UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9,290 lines • 371 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { d as asPositiveFiniteNumber, n as MAX_TIMER_TIMEOUT_MS } from "./number-coercion-D6u-4YD8.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { m as CONTEXT_OVERFLOW_ERROR_MESSAGE } from "./redact-Mj7pppxC.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./utils-C8YECn2Q.mjs";
import { d as sleepWithAbort, i as createAbortError, o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { a as captureAsyncWorkTracker, o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import "./gateway-request-scope-BvvDhs5D.mjs";
import { o as getGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs";
import { A as withTimeout } from "./fs-safe-BbWvmdVn.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { c as resolveOpenClawAgentSqlitePath, s as resolveIncognitoOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { B as resolvePersistedSessionStoreOwnerForTarget, C as resolveSessionAgentIds, a as resolveAgentDir, f as resolveAgentWorkspaceDir, w as resolveSessionAgentIdsStrict, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { t as classifyGatewayStorageFailure } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { r as emitDiagnosticEvent, t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs";
import { n as emitDiagnosticsTimelineEvent, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { d as normalizeUsage, n as deriveContextPromptTokens } from "./usage-CHLnzpJG.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as isStringOption } from "./string-readers-BtMVaphq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { t as redactIdentifier } from "./node-crypto-B6yuTjmm.mjs";
import { i as isSqliteTranscriptMutationConflict } from "./session-mutation-conflict-error-DsnM4Ef8.mjs";
import { t as SessionTranscriptWriterClaimReboundError } from "./session-transcript-writer-claim-error-DhmNAhcx.mjs";
import { t as AuthProfileAuthorizationError } from "./authorization-contract-CQ0hvliU.mjs";
import { I as OAUTH_REFRESH_CALL_TIMEOUT_MS, J as isEnvOnlyAuthProfileRuntime, K as getScopedSharedAuthStore, j as resolveProfilesUnavailableReason, w as isProfileInCooldown } from "./user-model-account-authority-CRj924IP.mjs";
import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs";
import { a as createNativeModelOwnedRuntimeModel, i as DEFAULT_PROVIDER, n as DEFAULT_MODEL, s as resolveNativeOwnedRuntimeModel, t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import { c as loadPluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { i as classifyAgentRunTerminalOutcome, r as AGENT_RUN_SUPERSEDED_STOP_REASON } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { T as retainQueuedAgentRunContext, _ as registerAgentRunContext, i as claimAgentRunContext, l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { C as withAgentRunLifecycleGeneration, a as emitAgentEvent, c as emitAgentEventIfCurrent, d as getAgentEventLifecycleGeneration, f as isAgentEventLifecycleGenerationCurrent, h as onAgentEventForRun, r as captureAgentRunLifecycleGeneration, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { d as runWithSessionSourceScope, f as sessionEntryCommitGuardOptions, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { v as requireActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { n as withPluginRetentionOwner } from "./plugin-retention-diagnostics-gj7JVNsM.mjs";
import { n as withPluginRuntimeGenerationScope, t as runOutsidePluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { r as resolveProviderPolicySurface } from "./provider-public-artifacts-CzxPvvri.mjs";
import { t as MODEL_APIS } from "./model-config-vocabulary-ByNYIDvQ.mjs";
import { n as OPENCLAW_AGENT_RUNTIME_ID } from "./agent-runtime-id-D8s1CaYB.mjs";
import { a as resolveProviderModelRoutes } from "./provider-model-routes-CbP035Gi.mjs";
import { d as isConfiguredKeyAuthSource, t as providerModelRouteAcceptsAuthMode } from "./provider-model-route-auth-dD2KD9io.mjs";
import { o as resolveProviderModelAuthPolicy } from "./model-runtime-policy-Cfudvy7O.mjs";
import { D as resolvePreparedModelThinkingCompat } from "./model-selection-shared-9Kz63Hhm.mjs";
import "./types.models-BRtCm3gx.mjs";
import { i as modelMatchesProviderModelRoute, r as isProviderModelRerouted } from "./provider-model-route-hB9HZIqE.mjs";
import { i as resolveModelFallbackAvailability } from "./model-selection-config-Bvf5WqHo.mjs";
import { a as resolveModelExtraParamSources, r as resolveAliasedParamValue } from "./model-extra-params-D2Glrj-b.mjs";
import { t as OPENAI_PROVIDER_ID } from "./openai-routing-Dakz1nVk.mjs";
import { l as resolveSecretSentinel, s as looksLikeSecretSentinel } from "./sentinel-BfPjneyJ.mjs";
import { f as isSafeToCopyOAuthIdentity, u as hasOAuthIdentity } from "./oauth-shared-gvo_ItCc.mjs";
import { F as recordRuntimeAuthMaterialization, I as revokeRuntimeAuthMaterializations } from "./runtime-snapshots-1lyYKb7Y.mjs";
import { n as SecretSurfaceUnavailableError } from "./runtime-degraded-state-BSnwk5PQ.mjs";
import "./backoff-B-fIQi7C.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import "./message-channel-normalize-CFHSufeo.mjs";
import { c as resolveMessageActionTurnCapabilityLifetime, l as revokeMessageActionTurnCapability, n as isTrustedMessageActionTurnIngress, r as mintMessageActionTurnCapability } from "./message-action-turn-capability-CQk0hiot.mjs";
import { t as sameSessionTranscriptStorePath } from "./transcript-store-identity-jolHcJiu.mjs";
import { n as captureSessionTranscriptTargetBinding } from "./transcript-target-binding-BvjuRqS9.mjs";
import { _ as resolvePreparedRunAdmission, g as resolveAdmittedRunActiveAssertion, h as readRunOperatorAuthority, l as getAdmittedRunDelegatedAuthority, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs";
import { o as isMarkdownCapableMessageChannel } from "./message-channel-DTYVLJT1.mjs";
import { o as resolveSessionStorePathForScope } from "./session-store-path-BIJyO4vM.mjs";
import { n as buildAgentRunTerminalOutcome, r as buildAgentRunTerminalOutcomeFromAttempt, u as projectAgentRunAttemptTerminal } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { d as isProviderRequestSizeCeilingError, h as isTimeoutErrorMessage } from "./message-patterns-xrpp7Aip.mjs";
import { a as MODEL_CHAT_REJECTED_CODE, c as getFailoverErrorCode, i as FailoverError, o as MODEL_CHAT_REJECTED_TEXT } from "./error-BCRqSFIY.mjs";
import { a as createAgentRunDirectAbortError, i as AGENT_RUN_SUPERSEDED_ERROR, m as resolveAgentRunErrorLifecycleFields } from "./run-termination-0Ig0-bk6.mjs";
import { t as isProviderRefusalAssistantError } from "./diagnostics-36a9D_mQ.mjs";
import { c as claimProviderReviewAttempt, d as readProviderReviewAcknowledgment, f as recordSessionProviderReview, i as resolveSessionWorkStartError, l as createSessionProviderReview, o as assertSessionProviderReviewWorkStart } from "./session-work-start-CFJs8WNp.mjs";
import { n as runWithoutOwnedSessionTranscriptWrites } from "./transcript-write-context-store-kFqld1UQ.mjs";
import { f as withExecRequestTurn, n as adoptExecRequestSession, o as captureExecRequestOwners } from "./exec-request-context-C8VKkMcB.mjs";
import { Dt as lifecycleAdmissionByOperation, E as readSessionControllerOperationState, I as acknowledgeReplySessionTransition, X as captureSessionTarget, b as markReplyOperationExecutionStarted, bt as isCurrentSessionControllerOperation, gt as assertSessionControllerOperation, z as getReplyOperationSessionReader } from "./session-controller.state-BApgK0mV.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { u as resolveEmbeddedRunTerminalToolFailure } from "./run-diagnostics-D33n4kQR.mjs";
import { i as isExecLikeToolName } from "./tool-error-summary-BTwB17cj.mjs";
import { o as hasReplyPayloadContent } from "./payload-Cab4FCxl.mjs";
import { C as markReplyPayloadForSourceSuppressionDelivery, D as retainSilentFinalPayloads, c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, 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, i as copyChannelSourceTurnContext, o as readChannelSourceTurnSameThreadRequired } from "./session-event-handoff-CC7Ui3SA.mjs";
import { a as resolveSessionPermissionExecMode } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { f as withGatewayToolCallerIdentity, r as createAdmittedGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { a as readSessionEntrySummariesInWorker, d as readSessionEntryInWorker, i as readSessionEntryReadOnlyInWorker, l as withSessionEntryReadOnlyInWorker, s as withSessionEntriesFromStoreInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { i as toDatabaseOptions, r as resolveSqliteSessionKey } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import { a as readCapturedSessionActorEntry, n as getSessionActorStorageBinding, o as runWithSessionActorStorage, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { n as captureMemoryExactSessionReader } from "./session-accessor.memory-exact-read-DXDGhyTq.mjs";
import { n as parseSqliteSessionFileMarker, t as formatSqliteSessionFileMarker } from "./legacy-sqlite-marker-D_RUp-nb.mjs";
import { o as resolveSqliteScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs";
import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { _ as prepareSessionRowPublicationScope, v as sessionChangeAffectsStoredRow } from "./session-actor-replica-pDCkqEFM.mjs";
import { a as prepareAgentRunTerminalReply, o as sanitizeAgentRunTerminalReply, t as filterAgentRunTerminalPayloadsForPresentation } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { t as assertSessionEntryCohortScope } from "./session-entry-cohort-scope-BPNP_A27.mjs";
import { t as captureSessionEntryNativeMutationWitness } from "./session-entry-read-ordered-DPv30g3R.mjs";
import { o as withSessionHistoryWorkerDatabase } from "./session-transcript-worker-runtime-DMpH3wlh.mjs";
import { t as renderAgentHarnessPreflightUserMessage } from "./user-facing-text-Dqp3fcZx.mjs";
import { C as renderRateLimitRetryExhaustion, o as formatBillingErrorMessage, p as renderAuthProfileFailoverCopy, x as renderRateLimitRecoveryStopped } from "./user-copy-DFvWpx47.mjs";
import { n as OAuthRefreshFailureError } from "./oauth-refresh-failure-DxrQiYzV.mjs";
import { a as parseImageDimensionError, i as isListedModelChatRejection, o as parseImageSizeError } from "./classify-core-Bs2jauQR.mjs";
import { n as isTransientNetworkError } from "./retryable-network-errors-D2gJmBqw.mjs";
import { a as failoverReasonFromClassification, o as inferSignalStatus } from "./classification-rules-DfXxEGkP.mjs";
import { a as renderAssistantRequestFailureCopy, u as renderStorageFailureSummary } from "./assistant-request-failure-copy-CDAkRIru.mjs";
import { t as AgentHarnessPreflightError } from "./errors-0Ou7CzqA.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { t as copyExplicitSkillSelectionFileHost } from "./skill-command-provenance-M2bVzkat.mjs";
import { t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs";
import { l as waitForSessionTranscriptProjection } from "./session-transcript-reconcile-CtdkqWN1.mjs";
import { t as beginSessionEffect } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { t as applySessionEntryOperation } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { h as resolveSessionPinnedHarnessId } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { g as withOwnedSessionTranscriptWrites } from "./transcript-write-context-_7rz2F7z.mjs";
import "./config-CMA-J084.mjs";
import { t as captureSessionManagerIncognitoBinding } from "./session-manager-incognito-scope-BRG0nvBK.mjs";
import { n as recordModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs";
import { a as resolveSessionTranscriptRuntimeTarget } from "./session-accessor.transcript-target-njOktg4F.mjs";
import { n as appendTranscriptMessage } from "./session-accessor.sqlite-transcript-write-C8dqprw-.mjs";
import "./sessions-D5Vvu3AE.mjs";
import "./lifecycle-BFcckgci.mjs";
import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs";
import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs";
import { a as withPreparedModelRuntimePluginGenerationScope, n as getPreparedModelRuntimePluginGeneration, r as runOutsidePreparedModelRuntimePluginGenerationScope, t as getPreparedModelRuntimeBorrowedSnapshot } from "./prepared-model-runtime-generation-scope-Dpvf6WHJ.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { l as withClaimingHookAdmission } from "./hooks-BiZpB_10.mjs";
import { n as getRegisteredAgentHarness } from "./registry-ubpieJjd.mjs";
import { a as resolveAgentHarnessPreparedRouteSupport, i as resolveAgentHarnessPreparedAuthSupport, t as assertPluginHarnessConversationToolPolicySupport } from "./support-LWqLDjUq.mjs";
import { c as isSetupCredentialAccessible, p as resolveSubscriptionAuthModeForProfiles } from "./order-jOvee2J6.mjs";
import { a as resolveLegacyInheritedAuthDir } from "./legacy-inherited-auth-dir-1Y-Cs3kS.mjs";
import { n as resolveAuthoredModelContextTokens } from "./context-resolution-DOFMNmJZ.mjs";
import { r as listModelCatalogObservedRoutes, t as createModelCatalogSnapshotView } from "./model-catalog-view-CsclLtvK.mjs";
import { a as resolveCandidateThinkingLevel } from "./thinking-runtime-BKWl4CUs.mjs";
import { n as CUSTOM_LOCAL_AUTH_MARKER, o as applyLocalNoAuthHeaderOverride } from "./model-auth-markers-4YSUG71a.mjs";
import { n as estimateAggregateUsageCost } from "./usage-format-BisQoUIV.mjs";
import { i as readSessionRuntimeOwnershipAsync } from "./session-utils-model-selection-BGYqZws_.mjs";
import { n as captureSessionEntrySourceAssertion } from "./session-entry-source-authority-Bxiv7qVT.mjs";
import { _ as attachProviderRequestAuth, a as getModelProviderRequestRouteFacts, g as attachProviderAuthAuthority, h as assertProviderAuthAuthority, o as getModelProviderRequestTransport, r as attachModelProviderRequestTransport, s as inheritModelProviderRequestRouteFacts, t as applyPreparedRuntimeAuthToModel, v as getProviderAuthAuthority } from "./provider-request-config-CCij-nof.mjs";
import { i as resolveProviderRequestCapabilities, n as resolveProviderEndpoint } from "./provider-attribution-DJbzqKsf.mjs";
import { c as resolveSafeTimeoutDelayMs } from "./timeouts-nwfOzsiL.mjs";
import { s as resolveContextEngineOwnerPluginId } from "./registry-BNPXTWdk.mjs";
import { t as PreparedModelRuntimeOwnerNotPublishedError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import { i as hasSyntheticLocalProviderAuthConfig, o as isConfigBackedInlineProviderApiKey, w as MissingProviderAuthError } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { n as getModelProviderLocalServiceReconciler } from "./provider-local-service-reconcile-DwxowFgX.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { l as resolveFastModeForElapsed, n as formatFastModeAutoProgressText, u as resolveFastModeModelAutoOnSeconds } from "./fast-mode-Dk3A3IUk.mjs";
import "./fast-mode-BcwTQ_IZ.mjs";
import { n as OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST } from "./host-compat-D2mUtPDd.mjs";
import { A as readAdmittedPublishedModelCatalog, a as acquireReadOnlyPreparedModelRuntime, j as readCapturedPreparedModelRuntimeCatalog, k as copyPreparedModelRuntimeSnapshotBindings, m as getPreparedModelRuntimeSnapshot, r as acquirePreparedModelRuntimeSnapshot, t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { d as resolveProviderRuntimePluginHandle, o as resolveProviderAuthProfileId, t as attachModelProviderRuntimePluginHandle } from "./provider-hook-runtime-CNiG8a3j.mjs";
import { L as prepareProviderRuntimeAuth, g as providerOwnsDynamicModelPreparation } from "./provider-runtime-BddjXkmv.mjs";
import { i as unwrapSecretSentinelsForProviderEgress } from "./provider-secret-egress-DZ6iOD2F.mjs";
import { o as getModelProviderLocalService } from "./provider-local-service-CoQj6xcb.mjs";
import { n as createAgentPluginRuntimeRefresh, t as captureAgentPluginRuntimeRefresh } from "./plugin-runtime-refresh-DCHb6kdS.mjs";
import { t as PreparedModelRuntimeInitialRunAdmissionError } from "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import { n as isLikelyContextOverflowError } from "./context-overflow-C7ex88b9.mjs";
import { a as isCompactionFailureError, i as extractObservedOverflowTokenCount, r as resolveModelCandidateChain } from "./model-fallback-candidates-CFJLuJlL.mjs";
import { o as prepareAgentWorkspaceAttachments } from "./workspace-access-CnjZBg1i.mjs";
import { n as registerAgentRunCapacityWait } from "./agent-run-capacity-wait-DDLM9V2q.mjs";
import { t as resolvePreferredSessionKeyForSessionIdMatches } from "./session-id-resolution-jexGZkIN.mjs";
import { n as classifyFailoverSignal, t as classifyFailoverReason } from "./classify-o7Whl-By.mjs";
import { t as isSessionTranscriptTurnMismatchErrorMessage } from "./transcript-turn-error-yJQy4oFe.mjs";
import { a as findCliTerminalStopError, c as hasRecordedModelFallbackStop, d as resolveFailoverClassificationFromError, f as resolveFailoverReasonFromError, i as describeFailoverError, l as isCliTerminalStopCode, p as resolveFailoverStatus, r as coerceToFailoverError, u as isNonProviderRuntimeCoordinationError } from "./failover-error-CbIiC30n.mjs";
import { a as resolveStoredSessionKeyForSessionId, i as resolveSessionKeyForRequestCore } from "./session-Cf7LaLt9.mjs";
import { i as resolveSessionSuspensionReason, t as captureSessionSuspension } from "./session-suspension-DpEUvu5N.mjs";
import { n as enqueueCommandInLane, o as isCommandLaneTaskTimeoutError, r as getCommandLaneSnapshot, t as CommandLaneTaskTimeoutError } from "./command-queue-BenRlAaO.mjs";
import { r as resolveCompactionTimeoutMs, t as compactContextEngineWithSafetyTimeout } from "./compaction-safety-timeout-Dm_4UNnX.mjs";
import { a as isRetryableProviderHttpStatus, i as hasOrganizationTpmRateLimitEvidence, o as resolveRetryAfterMs, r as hasLongWindowRateLimitEvidence, s as shouldRetryFailoverSignal, t as classifyRateLimitWindow } from "./retry-evidence-f1T47dhA.mjs";
import { n as recordAgentCleanupFailure, r as runAgentCleanupStep } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
import { n as markAuthProfileSuccess } from "./profiles-DbLHYG1P.mjs";
import { n as markAuthProfileFailure, r as markInlineProviderApiKeyFailure } from "./usage-wMHUW27k.mjs";
import { t as prepareCronRootSessionGeneration } from "./session-delivery-generation-CUS9yuZM.mjs";
import { n as isToolResultError } from "./tool-result-error-B2GHe83l.mjs";
import { t as buildContextEngineRuntimeSettings } from "./runtime-settings-Dsu1-5F4.mjs";
import { r as resolveLiveToolResultMaxChars } from "./tool-result-limits-BISboI8s.mjs";
import { t as createStageTimingTracker } from "./stage-timing-By2RFvzf.mjs";
import { n as createSessionControllerWatchdog } from "./session-controller.operation-BXBO7UKT.mjs";
import { t as withSessionTurn } from "./session-controller.admission-DDiE4tNx.mjs";
import { t as parseReplyDirectives } from "./reply-directives-BMfUGuku.mjs";
import { n as isTerminalAssistantError, t as isRetryableAssistantError } from "./retry-B3fOvo7T.mjs";
import { a as isFailoverAssistantError, i as isBillingAssistantError, n as classifyAssistantFailoverReason, o as isRateLimitAssistantError, r as isAuthAssistantError, t as buildAssistantFailoverSignal } from "./assistant-message-failures-Cv3Qnsh5.mjs";
import { o as isBenignCompactionSkipResult, r as classifyCompactionReason } from "./compact-reasons-DCGXQXOD.mjs";
import { t as resolveReplyFailoverFacts } from "./request-error-facts-Cc7KLiOY.mjs";
import { t as buildProviderAuthRecoveryHint } from "./provider-auth-recovery-hint-SMK7UCzs.mjs";
import { f as resolveReplyExpectation, i as isHostMissingReplyNoticeText, n as MISSING_REPLY_SIDE_EFFECT_NOTICE_TEXT, p as shouldDeliverMissingReplyNotice, r as createMissingReplyNotice, s as observeReplyDelivery, t as MISSING_REPLY_NOTICE_TEXT } from "./reply-completion-CrT6uEHT.mjs";
import { t as log$3 } from "./logger-DgCpB-Fs.mjs";
import { s as supersedeReplyRunByRunId } from "./session-controller-Bu0l-8-p.mjs";
import { r as waitForSessionMaintenance, t as beginForegroundSessionMaintenance } from "./coordinator-C4xk0qGg.mjs";
import { l as retireSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import "./agent-bundle-mcp-tools-CjrVbt71.mjs";
import { i as mergeAcceptedSessionSpawnsForRun, n as hasCompletionMessageSessionSpawn, t as hasAcceptedSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { t as emitAgentActivityEvent } from "./agent-activity-events-BvMnPRzr.mjs";
import "./auth-profiles-VRLhewIH.mjs";
import { r as getApiKeyForModelCore, t as applyAuthHeaderOverride } from "./model-auth-CEsyk_Yg.mjs";
import { n as resolveEmbeddedCliBackendDispatchEligibilityAsync } from "./cli-backend-dispatch-eligibility-CLVop73D.mjs";
import { a as fingerprintResolvedAuthProfileCredential, i as fingerprintOpaqueRuntimeOwner, n as fingerprintAuthProfileOwnerShape, o as fingerprintResolvedProviderAuth, r as fingerprintAwsSdkRuntimeOwner } from "./execution-auth-binding-DfJE1iEP.mjs";
import { t as ensureSelectedAgentHarnessPlugin } from "./runtime-plugin-Cug3vi2h.mjs";
import { r as withProviderRateLimitRetryDeadline } from "./provider-rate-limit-CuKCrLfX.mjs";
import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs";
import { i as withSessionManagerWrite, t as appendSessionTranscriptNote } from "./session-manager-write-admission-CUQ2naL2.mjs";
import { t as buildAgentRuntimeAuthPlan } from "./auth-DrOkaTvg.mjs";
import { d as markEmbeddedRunRecoveringTimeout, y as restoreEmbeddedRunTimeoutAbandonment } from "./runs-C1RO1Y6L.mjs";
import { n as resolveProcessToolScopeKey } from "./bash-process-scope-B7TaQfLU.mjs";
import { r as prepareDelegationCapability } from "./delegation-capability-BKV6nmg1.mjs";
import { h as sanitizeAssistantVisibleStreamText, s as extractAssistantVisibleText } from "./embedded-agent-utils-CRYA6mcb.mjs";
import { n as resolveSessionPlacementTurnSettlementAssertion, t as resolveSessionPlacementForcedTerminalSettlement } from "./session-placement-forced-terminal-settlement-RUb1C8PM.mjs";
import { r as captureAgentRunProviderReview } from "./session-lifecycle-state-YOgSt9Rr.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { n as resolveModelAsync, t as createEmptyAgentDiscoveryStores } from "./model-BmrpLWB9.mjs";
import { n as buildAgentHookContextIdentityFields, t as buildAgentHookContextChannelFields } from "./hook-agent-context-sUFGgK45.mjs";
import { i as LiveSessionModelSwitchError, r as shouldUseTransientCooldownProbeSlot } from "./failover-policy-BJz7cR8u.mjs";
import { r as readSourceReplyDeliveryRuntime } from "./source-reply-delivery-runtime-B-sqDs1R.mjs";
import { n as canRunPreparedAgentRuntimeAuthAttempt, r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs";
import { a as assertRequiredWorkerSelection } from "./required-worker-profile-BtG0rBjX.mjs";
import { t as protectPreparedProviderRuntimeAuth } from "./provider-runtime-auth-protection-CMR822Jv.mjs";
import { i as resolveCredentialScopedAuthAttemptModelDecision, n as hasPreparedAuthAttemptModelMetadata, r as providerUsesCredentialScopedModelMetadata, t as createPreparedRuntimeModelMaterializer } from "./credential-scoped-model-zYnbfp2r.mjs";
import { n as prepareAgentProviderRetryCount } from "./agent-project-settings-prepared-JbA7gqrJ.mjs";
import { a as declarePromptHistoryRewrite } from "./prompt-cache-observability-BBkCY6BX.mjs";
import { m as retainEmbeddedSessionPromptState } from "./session-prompt-state-H0jXFYE1.mjs";
import { r as buildUsageWithNoCost, t as buildAssistantMessage } from "./stream-message-shared-CBUzFwdv.mjs";
import { n as incrementCompactionCount } from "./session-updates-CAMM-3y9.mjs";
import { t as createTrajectoryRuntimeRecorder } from "./runtime-Bsp-rPbR.mjs";
import { h as resolveSourceReplyDelivery, i as hasCommittedMessagingToolDeliveryEvidence, l as hasMessagingToolDeliveryEvidence, m as resolveExplicitFinalSourceReplyDeliveryEvidence, u as hasOutboundDeliveryEvidence } from "./delivery-evidence-CqR4m_Hg.mjs";
import { a as buildCompletedAgentUsageMeta, i as resolveHookModelSelection, n as resolveAgentHarnessRunAdmissionError, o as mergeCompletedAgentUsage, r as resolveEmbeddedRuntimeModelPolicy, s as createAssistantErrorTranscript, t as buildBeforeModelResolveAttachments } from "./setup-BIn5eFVP.mjs";
import { n as resolveContextEngineCapabilities, t as runContextEngineMaintenance } from "./context-engine-maintenance-DsWc3w5M.mjs";
import { n as getCoreTtsAttemptResultMediaUrls, t as copyCoreTtsAttemptResultProvenance } from "./tts-tool-result-provenance-DWw-9hLr.mjs";
import { r as prepareAgentHarnessNativeToolPolicyRestricted, t as assertAgentHarnessExecutionEnvironment } from "./execution-environment-BrTopau0.mjs";
import { i as toNormalizedUsage, n as mergeAttemptRunStatsIntoAccumulator, r as mergeUsageIntoAccumulator, t as createUsageAccumulator } from "./usage-accumulator-CWIvkatR.mjs";
import { a as buildUsageAgentMetaFields, c as resolveEmbeddedAttemptBasePrompt, d as resolveFinalMessageRawText, f as resolveLatestCallUsage, i as buildErrorAgentMeta, l as resolveFinalAssistantRawText, m as resolveReportedModelRef, n as RUNTIME_AUTH_REFRESH_MIN_DELAY_MS, o as createRunRecoveryDiagId, p as resolveMaxRunRetryIterations, r as RUNTIME_AUTH_REFRESH_RETRY_MS, s as normalizeAssistantUsageForContext, t as RUNTIME_AUTH_REFRESH_MARGIN_MS, u as resolveFinalAssistantVisibleText } from "./helpers-W-meNuDY.mjs";
import { i as selectAgentHarnessForPreparedModelProviders, n as runAgentHarnessSettledTurnFinalization, r as selectAgentHarness, t as runAgentHarnessAttempt } from "./selection-Dmb46Mcc.mjs";
import { t as buildApiErrorObservationFields } from "./embedded-agent-error-observation-CgMe33_n.mjs";
import { t as forgetPromptBuildDrainCacheForRun } from "./plugin-turn-context-DWfKHRkT.mjs";
import { t as prepareAgentPromptProjects } from "./prompt-projects-DPH7_MHZ.mjs";
import { c as withRequiredSessionPlacement, d as settleFailedRequesterRun, f as settleRequesterRun, l as withSessionPlacementTurnAdmission } from "./session-placement-admission-CBCEtade.mjs";
import { i as shouldNoteLaneWait, n as resolveEmbeddedRunLaneTimeoutMs, r as resolveEmbeddedRunSessionLanePolicy, t as EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS } from "./lane-runtime-Amkf2D3O.mjs";
import { t as flushEmbeddedAttemptTrajectoryRecorder } from "./attempt-trajectory-flush-ChD2ftw_.mjs";
import { r as shouldSwitchToLiveModel, t as clearLiveModelSwitchPending } from "./live-model-switch-667ZwKej.mjs";
import { r as createAgentHarnessCompletionScope } from "./agent-harness-completion-scope-wzXWzRi4.mjs";
import { r as observeReplayMetadata, t as createEmbeddedRunReplayState } from "./replay-state-Amo8jvsa.mjs";
import { i as isEmbeddedRunReplaySafe, n as ReplaySafeTranscriptConflictError, t as ReplaySafeRunAbortError } from "./transcript-conflict-BirOVa3J.mjs";
import { n as resolveCyberAccessProgramForProvider } from "./model-catalog-access-programs-D76ru0cU.mjs";
import { n as buildAgentRuntimePlan } from "./build-1KVS3lgO.mjs";
import { n as isToolAuthoredSourceReplyForAssistant } from "./embedded-agent-tool-authored-source-reply-D2Px90_h.mjs";
import { t as listActiveProcessSessionReferences } from "./bash-process-references-BBxu9q4V.mjs";
import { t as resolveModelCallUrgency } from "./run-trigger-BlSheUsq.mjs";
import { t as buildEmbeddedCompactionRuntimeContext } from "./compaction-runtime-context-Cqy9zW9t.mjs";
import { r as declineBoundaryMaintenance, t as clearBoundaryMaintenance } from "./context-pressure-CRrtrfAa.mjs";
import { o as restoreCacheTtlToolResultProjections, s as sessionLikelyHasOversizedToolResults, u as truncateOversizedToolResultsInSessionManager } from "./tool-result-truncation-CpAX82MP.mjs";
import { n as projectEmbeddedMessageContext, r as projectTrajectorySessionTarget } from "./agent-end-context-CdOi9HMi.mjs";
import { n as resolveAgentLifecycleTerminalMetadata, t as createAgentLifecycleTerminalBackstop } from "./agent-lifecycle-terminal-DsT43SVO.mjs";
import { n as runBeforeAgentReplyForTurn, t as buildHandledBeforeAgentReplyPayloads } from "./before-agent-reply-B7qHTCot.mjs";
import { n as serializeAgentEventCallback, t as runBestEffortCallback } from "./embedded-agent-subscribe.callback-DQMmolWU.mjs";
import { t as redactRunIdentifier } from "./workspace-run-_jqMxJ_C.mjs";
import { r as stripOpenClawMcpToolPrefix } from "./tool-policy-bZXUEBo2.mjs";
import { a as resolveTieredModel, n as initializeReadOnlyRunModelCatalog, o as pickFallbackThinkingLevel, r as resolvePreparedRuntimeWorkspaces, s as resolveGlobalLane, t as bindRunToPreparedModelRuntime } from "./prepared-runtime-context-G3hnwl7-.mjs";
import { i as resolveCurrentSourceMessagingToolPartial, r as normalizeTextForComparison } from "./messaging-dedupe-ChHNHfTw.mjs";
import { i as resolveMessagingToolPayloadDedupe, n as filterMessagingToolReplyPayload, t as filterMessagingToolMediaDuplicates } from "./reply-payloads-dedupe-xQRy9T4a.mjs";
import { A as isStrictAgenticExecutionContractActive, C as classifyAssistantTurn, D as joinAssistantTexts, E as isIncompleteTerminalAssistantTurn, F as resolveCurrentAttemptAssistant, I as resolveCurrentAttemptErrorCode, L as shouldContinueInteractiveAcceptedSessionSpawns, M as hasAsyncActivity, N as hasAttemptTerminalState, O as TOOL_FAILURE_INSTRUCTION, P as isCurrentAttemptReplaySafe, S as shouldTreatEmptyAssistantReplyAsSilent, T as hasComposedVisibleAnswerAfterSettledTools, _ as isSettledTurnCutOffByOutputLimit, b as resolveSettledToolTerminalContinuation, g as isRejectedBeforeDispatch, k as sanitizeForConsole, t as createToolTerminalObserver, v as resolveNonVisibleTurnRetryInstructions, w as countSettledTurnDeliveryPayloads, x as shouldRetrySilentErrorAssistantTurn, y as resolveSettledToolBatchEvidence } from "./tool-terminal-outcome-I8TmHIh2.mjs";
import { n as mergeAttemptToolMediaPayloads, t as createPendingToolMediaCarry } from "./tool-media-payloads-PhnJJVdg.mjs";
import { i as formatUserFacingAssistantErrorText, r as formatAssistantErrorText, t as GENERIC_ASSISTANT_ERROR_TEXT } from "./error-text-mmb9Hrdz.mjs";
import { C as resolveEmbeddedRunAttemptTerminalState, S as resolveEmbeddedRunAttemptTerminalOutcome, b as isEmbeddedRunTerminalTimeout, d as outsideExecutionCapacity, f as withReleasableExecutionCapacity, h as markLastProviderPromptContextRejected, i as createAttemptCarryover, m as getProviderPromptState, n as resolveProviderRefusal, p as clearProviderPromptState, t as prepareEmbeddedAttemptPromptExecution, v as isEmbeddedRunTerminalAbort, x as isEmbeddedRunTimeoutFinal, y as isEmbeddedRunTerminalInterrupted } from "./prompt-image-preparation-BxsbSbTi.mjs";
import { i as resolveLegacyCompactionSessionKey, r as resolveContextEngineCompactionSuccessor, t as acceptCompactionSuccessor } from "./compaction-successor-hCQ2tiCH.mjs";
import { n as admitEmbeddedContextEngine, r as buildEmbeddedRunBlockedResult, t as prepareAttemptSystemPromptAdditions } from "./attempt-system-prompt-additions-BO5DyKLr.mjs";
import { t as resolveCompactionSuccessorTranscript } from "./types-BuiOsbhB.mjs";
import { n as resolveAgentRunSessionTarget, t as applyAgentRunSessionTargetIdentity } from "./run-session-target-b0y1C8K8.mjs";
import { n as publishClaimedSessionWriter, t as attachCompactionAccountingRecorder } from "./compaction-accounting-bridge-BYYhZqhH.mjs";
import { t as resolveEmbeddedSessionContextLimits } from "./session-context-limits-Dgvy6_uY.mjs";
import { r as runPostCompactionSideEffects } from "./compaction-hooks-CIs7VqLG.mjs";
import { c as createEmbeddedRunStageSummaryEmitter, g as preparePluginHarnessWorkspace, i as resolveAttemptDispatchSessionTarget, s as EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE, u as applyResolvedToolPromptFinalizer, v as resolveHarnessWorkspace, y as measureEmbeddedAgentPreparation } from "./attempt-transcript-helpers-D399v1wz.mjs";
import { t as resolveAuthProfileFailureReason } from "./auth-profile-failure-policy-Dh0jrfrG.mjs";
import { t as createEmbeddedRunPermissionChanges } from "./permission-change-BTpNBb78.mjs";
import { c as resizeExecApprovalContinuationPrompt } from "./bash-tools.exec-approval-output-Cb90XzcX.mjs";
import { n as agentHarnessExposesOpenClawTools, t as agentHarnessBuildsOpenClawTools } from "./tool-surface-BFxyaTMZ.mjs";
import { n as recordAdmittedModelRoutingDecision, t as resolveEmbeddedAttemptMemoryAudience } from "./attempt-memory-audience-EpNZCXem.mjs";
import { n as remapExplicitSkillSelectionPath, r as remapSkillReferencePaths } from "./sandbox-skills-B_GxuUqP.mjs";
import { n as preparePluginHarnessSkills } from "./skill-runtime-Cm3TP3Aa.mjs";
import { m as mapThinkingLevelForProvider } from "./replay-history-generic-mEncANYP.mjs";
import { a as resolveInitialEmbeddedRunModel, i as resolveEmbeddedRuntimePluginSelections, n as resolveAttemptTrajectoryAttribution, o as resolveInitialThinkLevel, r as resolveEmbeddedRuntimePluginPreparation, s as resolveRequestStreamTransportOverrides, t as CODEX_HARNESS_ID } from "./runtime-resolution-CrWh2XVu.mjs";
import { t as advanceAuthProfileCandidate } from "./advance-_THeLzhS.mjs";
import { t as captureAuthProfileAuthorization } from "./authorization-BCfvcvWl.mjs";
import { t as resolveExternalCliAuthOverlayScopeFromSelection } from "./external-cli-auth-selection-otqdrexE.mjs";
import { t as createUnrecordedScheduledAccountRefusal } from "./scheduled-unrecorded-account-DtjpvOWO.mjs";
import { t as applyPreparedReplyMedia } from "./reply-media-paths-B3zuAx71.mjs";
import { t as buildEmbeddedRunPayloads } from "./payloads-DgzHj3cB.mjs";
import { r as isBackgroundWorkLane } from "./background-work-CoZV6wmM.mjs";
import path from "node:path";
import { randomBytes } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { isResponsesOutputLimitToolCallError } from "@openclaw/ai/diagnostics";
import { hasOnlyAssistantReasoningContent } from "@openclaw/ai/internal/shared";
import { isContextOverflow } from "@openclaw/ai/internal/runtime";
import { CompactionReplayRefreshRequiredError, isCompactionReplayCheckpoint } from "@openclaw/ai/transports";
//#region src/agents/embedded-agent-runner/cli-backend-dispatch-transcript.ts
const log$2 = createSubsystemLogger("agents/embedded-cli-dispatch");
function createCliDispatchTranscriptRecorder(e) {
	let t = Promise.resolve();
	let n = "";
	let r = "";
	let i = false;
	let a = false;
	let o = 0;
	const s = {
		sessionId: e.sessionId,
		sessionKey: e.sessionKey,
		agentId: e.agentId,
		storePath: e.storePath,
		sessionFile: e.sessionFile,
		expectedLifecycleRevision: e.expectedLifecycleRevision,
		expectedWriterRunId: e.expectedWriterRunId
	};
	const c = captureSessionActorStorageOwner(s, {
		assertCurrent() {},
		authorize() {}
	});
	if (c) {
		s.agentId = c.agentId;
		s.storePath = c.path;
	}
	const l = acquireSessionActorStorage(s, {
		lifetime: {
			assertCurrent() {},
			assertReadable() {}
		},
		authority: {
			assertCurrent() {},
			authorize() {}
		}
	});
	l.catch(() => {});
	const enqueue = (n) => {
		t = t.then(async () => {
			const append = () => appendTranscriptMessage(s, {
				message: n(),
				config: e.config,
				cwd: e.cwd
			});
			const t = await l;
			if (c && !t) return;
			await (t ? runWithSessionActorStorage(t, append) : append());
		});
		t = t.catch((t) => {
			log$2.warn(`cli dispatch transcript append failed: runId=${e.runId} error=${String(t)}`);
		});
	};
	const u = {
		api: "cli",
		provider: e.provider,
		id: e.model ?? ""
	};
	const buildZeroUsageAssistantMessage = (e, t, n = a) => {
		const r = buildAssistantMessage({
			model: u,
			content: e,
			stopReason: t,
			usage: buildUsageWithNoCost({})
		});
		return n ? {
			...r,
			__openclaw: { turnTainted: true }
		} : r;
	};
	const appendAssistantSnapshot = (e, t) => {
		if (e && e !== r) {
			r = e;
			enqueue(() => buildZeroUsageAssistantMessage([{
				type: "text",
				text: e
			}], t));
		}
	};
	enqueue(() => ({
		role: "user",
		content: [{
			type: "text",
			text: e.prompt
		}],
		timestamp: Date.now(),
		...e.senderIsOwner !== void 0 ? { __openclaw: { senderIsOwner: e.senderIsOwner } } : {}
	}));
	return {
		noteToolEvent: (t) => {
			if (i) return;
			o += 1;
			const n = t.toolCallId?.trim() || `${e.runId}-tool-${String(o)}`;
			if (t.phase === "start") {
				const e = a;
				enqueue(() => buildZeroUsageAssistantMessage([{
					type: "toolCall",
					id: n,
					name: t.toolName,
					arguments: t.args ?? {}
				}], "toolUse", e));
				return;
			}
			a ||= t.resultContentSource === "network";
			enqueue(() => ({
				role: "toolResult",
				toolCallId: n,
				toolName: t.toolName,
				content: normalizeToolResultContent(t.result),
				details: asOptionalObjectRecord(asOptionalObjectRecord(t.result)?.details),
				isError: t.isError === true,
				timestamp: Date.now(),
				...t.resultContentSource ? { __openclaw: { resultContentSource: t.resultContentSource } } : {}
			}));
		},
		noteAssistantText: (e) => {
			if (!i && e.trim()) n = e;
		},
		flushAssistantSnapshot: () => {
			if (i) return;
			appendAssistantSnapshot(n.trim(), "aborted");
		},
		finalize: async (e) => {
			if (!i) {
				i = true;
				appendAssistantSnapshot(e?.trim() || n.trim(), "stop");
			}
			await t;
			await l.then((e) => e?.actor.release(), () => {});
		}
	};
}
/** Maps a sanitized CLI tool result onto transcript content blocks. */
function normalizeToolResultContent(e) {
	if (typeof e === "string") return e ? [{
		type: "text",
		text: e
	}] : [];
	const t = Array.isArray(e) ? e : asOptionalObjectRecord(e)?.content;
	if (!Array.isArray(t)) return [];
	return t.flatMap((e) => {
		if (typeof e === "string") return [{
			type: "text",
			text: e
		}];
		const t = asOptionalObjectRecord(e);
		if (!t) return [];
		const { type: n, text: r, data: i, mimeType: a } = t;
		if (n === "text" && typeof r === "string") return [{
			type: "text",
			text: r
		}];
		if (n === "image" && typeof i === "string" && typeof a === "string") return [{
			type: "image",
			data: i,
			mimeType: a
		}];
		return [];
	});
}
//#endregion
//#region src/agents/embedded-agent-runner/cli-backend-dispatch.ts
const log$1 = createSubsystemLogger("agents/embedded-cli-dispatch");
async function runEmbeddedAgentViaCliBackendIfEligible(e) {
	if (e.cliBackendDispatch !== "subscription-auth") return;
	if (e.sourceReplyDeliveryMode === "message_tool_only") return;
	const t = e.sessionFile?.trim();
	if (!t) return;
	if (e.disableTools || e.modelRun) return;
	if (!e.toolsAllow || e.toolsAllow.length === 0) return;
	const n = e.toolsAllow.map(normalizeToolPolicyName);
	if (n.some((e) => !e || e.includes("*"))) return;
	const r = [...new Set(n)];
	const i = await resolveEmbeddedCliBackendDispatchEligibilityAsync(e);
	if (!i) return;
	const { runCliAgent: a } = await import("./cli-runner.runtime.js");
	const o = await resolvePreparedRunAdmission({
		runId: e.runId,
		runtimeKind: "embedded",
		admittedRunContext: e.admittedRunContext,
		preparedRunAdmission: e.preparedRunAdmission
	});
	const s = {
		native: [],
		openClaw: r
	};
	const c = e.onAgentToolResult;
	const { storePath: l, expectedLifecycleRevision: u, expectedWriterRunId: d } = e.sessionTarget;
	const f = e.sessionManager || e.sessionPersistence === "detached" ? void 0 : createCliDispatchTranscriptRecorder({
		...e,
		storePath: l,
		sessionFile: t,
		provider: i.provider,
		cwd: e.cwd ?? e.workspaceDir,
		expectedLifecycleRevision: u,
		expectedWriterRunId: d
	});
	const p = onAgentEventForRun(e.runId, (e) => {
		if (e.stream === "assistant" && typeof e.data.text === "string") {
			f?.noteAssistantText(e.data.text);
			return;
		}
		if (e.stream !== "tool") return;
		const t = e.data.phase;
		if (t !== "start" && t !== "result") return;
		const n = typeof e.data.name === "string" ? e.data.name : "";
		if (!n) return;
		const r = normalizeToolPolicyName(stripOpenClawMcpToolPrefix(n));
		const i = typeof e.data.toolCallId === "string" ? e.data.toolCallId : void 0;
		if (t === "start") {
			f?.noteToolEvent({
				phase: t,
				toolName: r,
				toolCallId: i,
				args: isRecord(e.data.args) ? e.data.args : void 0
			});
			return;
		}
		const a = e.data.isError === true || isToolResultError(e.data.result);
		const o = e.data.resultContentSource === "network" ? "network" : void 0;
		f?.noteToolEvent({
			phase: t,
			toolName: r,
			toolCallId: i,
			result: e.data.result,
			isError: a,
			...o ? { resultContentSource: o } : {}
		});
		c?.({
			toolName: r,
			result: e.data.result,
			isError: a
		});
	});
	const flushOnAbort = () => f?.flushAssistantSnapshot();
	e.abortSignal?.addEventListener("abort", flushOnAbort, { once: true });
	log$1.info(`dispatching embedded run through CLI backend: runId=${e.runId} provider=${i.provider} model=${e.model ?? ""}`);
	let m;
	try {
		await e.onExecutionStarted?.(e.lifecycleGeneration !== void 0 ? { lifecycleGeneration: e.lifecycleGeneration } : void 0);
		const n = await a({
			admittedRunContext: o,
			sessionManager: e.sessionManager,
			disableTrajectory: e.disableTrajectory,
			sessionId: e.sessionId,
			sessionKey: e.sessionKey,
			sessionTarget: e.sessionTarget,
			expectedLifecycleRevision: u,
			expectedWriterRunId: d,
			chatType: e.chatType,
			agentId: e.agentId,
			storePath: l,
			trigger: e.trigger,
			sessionFile: t,
			workspaceDir: e.workspaceDir,
			agentDir: e.agentDir,
			config: e.config,
			prompt: e.prompt,
			imagePrompt: e.prompt,
			images: e.images,
			imageOrder: e.imageOrder,
			media: e.media,
			provider: i.provider,
			model: e.model,
			...e.requestedRouteResolution === "resolved" && e.provider && e.model ? { requesterModel: {
				provider: e.provider,
				model: e.model
			} } : {},
			authProfileId: e.authProfileId,
			modelHasVision: e.modelHasVision,
			contextWindow: e.contextWindow,
			thinkLevel: e.thinkLevel,
			fastMode: e.fastMode,
			fastModeStartedAtMs: e.fastModeStartedAtMs,
			fastModeAutoOnSeconds: e.fastModeAutoOnSeconds,
			timeoutMs: e.timeoutMs,
			runTimeoutOverrideMs: e.runTimeoutOverrideMs ?? e.timeoutMs,
			runId: e.runId,
			lifecycleGeneration: e.lifecycleGeneration,
			lane: e.lane,
			extraSystemPrompt: e.extraSystemPrompt,
			messageChannel: e.messageChannel,
			messageProvider: e.messageProvider,
			bootstrapContextMode: e.bootstrapContextMode,
			bootstrapContextRunKind: e.bootstrapContextRunKind,
			abortSignal: e.abortSignal,
			onBlockReply: e.onBlockReply,
			onPartialReply: e.onPartialReply,
			onExecutionPhase: e.onExecutionPhase,
			cliToolAvailability: s,
			disableCliLiveSession: true,
			cleanupCliLiveSessionOnRunEnd: true,
			runtimeFactsInTurn: true,
			requireExplicitMessageTarget: true,
			cleanupBundleMcpOnRunEnd: e.cleanupBundleMcpOnRunEnd
		});
		m = n.payloads?.find((e) => e.isReasoning !== true && typeof e.text === "string")?.text;
		const r = n.meta.agentMeta;
		if (!r?.cliSessionBinding && r?.clearCliSessionBinding !== true) return n;
		return {
			...n,
			meta: {
				...n.meta,
				agentMeta: {
					...r,
					cliSessionBinding: void 0,
					clearCliSessionBinding: void 0
				}
			}
		};
	} finally {
		e.abortSignal?.removeEventListener("abort", flushOnAbort);
		p();
		await f?.finalize(m);
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-delivery-state.ts
/** Project settled facts, retaining prior generations without collapsing repeated sends. */
function copyAttemptDeliveryState(e, t) {
	const append = (e, n) => t ? [...n ?? [], ...e].slice(-200) : e;
	return {
		latestMcpAppChannelView: e.latestMcpAppChannelView ?? t?.latestMcpAppChannelView,
		latestMcpConnectAction: e.latestMcpConnectAction ?? t?.latestMcpConnectAction,
		didSendViaMessagingTool: t?.didSendViaMessagingTool || e.didSendViaMessagingTool,
		sourceReplyDelivered: t?.sourceReplyDelivered || e.sourceReplyDelivered,
		sourceReplyDeliveryState: e.sourceReplyDeliveryState ?? t?.sourceReplyDeliveryState,
		didDeliverSourceReplyViaMessageTool: t?.didDeliverSourceReplyViaMessageTool === true || e.didDeliverSourceReplyViaMessageTool === true,
		didSendDeterministicApprovalPrompt: t?.didSendDeterministicApprovalPrompt || e.didSendDeterministicApprovalPrompt,
		messagingToolSentTexts: append(e.messagingToolSentTexts, t?.messagingToolSentTexts),
		messagingToolSentMediaUrls: append(e.messagingToolSentMediaUrls, t?.messagingToolSentMediaUrls),
		messagingToolSentTargets: append(e.messagingToolSentTargets, t?.messagingToolSentTargets),
		messagingToolSourceReplyPayloads: t ? append(e.messagingToolSourceReplyPayloads ?? [], t.messagingToolSourceReplyPayloads) : e.messagingToolSourceReplyPayloads,
		successfulCronAdds: t?.successfulCronAdds ? t.successfulCronAdds + (e.successfulCronAdds ?? 0) : e.successfulCronAdds,
		acceptedSessionSpawns: t ? [...t.acceptedSessionSpawns ?? [], ...e.acceptedSessionSpawns ?? []] : e.acceptedSessionSpawns,
		...t?.asyncWorkStarted || e.asyncWorkStarted || hasAsyncActivity(e.toolMetas) ? { asyncWorkStarted: true } : {}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/run-attempt-result.ts
function normalizeEmbeddedRunAttemptResult(e) {
	const t = e.runtimeContinuationStarted === true ? {
		hadPotentialSideEffects: true,
		replaySafe: false
	} : void 0;
	return copyCoreTtsAttemptResultProvenance(e, {
		...e,
		assistantTexts: e.assistantTexts ?? [],
		toolMetas: e.toolMetas ?? [],
		acceptedSessionSpawns: e.acceptedSessionSpawns ?? [],
		messagesSnapshot: e.messagesSnapshot ?? [],
		messagingToolSentTexts: e.messagingToolSentTexts ?? [],
		messagingToolSentMediaUrls: e.messagingToolSentMediaUrls ?? [],
		messagingToolSentTargets: e.messagingToolSentTargets ?? [],
		messagingToolSourceReplyPayloads: e.messagingToolSourceReplyPayloads ?? [],
		didDeliverSourceReplyViaMessageTool: e.didDeliverSourceReplyViaMessageTool === true,
		itemLifecycle: e.itemLifecycle ?? {
			startedCount: 0,
			completedCount: 0,
			activeCount: 0
		},
		replayMetadata: t ?? e.replayMetadata ?? {
			hadPotentialSideEffects: true,
			replaySafe: false
		},
		currentAttemptReplayMetadata: t ?? e.currentAttemptReplayMetadata
	});
}
function hasCompletedModelProgressForIdleBreaker(e) {
	return e.assistantTexts.some((e) => e.trim().length > 0) || e.toolMetas.length > 0 || (e.clientToolCalls?.length ?? 0) > 0 || hasOutboundDeliveryEvidence(e) || e.itemLifecycle.completedCount > 0;
}
function buildTraceToolSummary(e) {
	if (!e.toolMetas?.length) return;
	const t = normalizeUniqueTrimmedStringList(e.toolMetas.map((e) => e.toolName));
	const n = e.toolMetas.filter((e) => e.isError === true).length;
	return {
		calls: e.toolMetas.length,
		tools: t,
		failures: n || Number(Boolean(e.lastToolError)),
		...e.lastToolError ? { unresolvedError: { toolName: e.lastToolError.toolName } } : {}
	};
}
function resolveSuccessfulToolNames(e) {
	return normalizeUniqueTrimmedStringList([...e.toolMetas.filter((e) => e.isError === false).map((e) => e.toolName), ...normalizeUniqueTrimmedStringList(e.successfulNestedToolNames).toSorted()]);
}
//#endregion
//#region src/agents/embedded-agent-runner/plugin-runtime-refresh.ts
function continuationPrompt(e) {
	return e === "reload" ? "A plugin was reloaded while you were working. Continue the current task from the transcript; do not repeat completed actions or the original user request." : "The plugin runtime has been refreshed. Continue the current task from the transcript using the updated tools. Verify the requested change; do not repeat completed actions or the original user request.";
}
/** The embedded runner owns continuation data; tool controls never import its graph. */
function createEmbeddedAgentPluginRuntimeRefresh(e) {
	const t = createAgentPluginRuntimeRefresh();
	const n = createPendingToolMediaCarry();
	const r = /* @__PURE__ */ new Set();
	let i;
	let a;
	const closeGeneration = () => {
		a = void 0;
		t.close();
	};
	/** Called only after the attempt has persisted its completed tool results and released its tools. */
	function continueAfterAttempt(e, t, o) {
		if (e.dispatchedAttempt.rawAttempt.terminal.kind !== "ok" || !captureAgentPluginRuntimeRefresh().continuesAfterAttempt()) return;
		t();
		const s = normalizeEmbeddedRunAttemptResult(e.dispatchedAttempt.rawAttempt);
		for (const e of resolveSuccessfulToolNames(s)) r.add(e);
		i = copyAttemptDeliveryState(s);
		n.capture(s);
		const { runInput: c, sessionPromptState: l, usageAccumulator: u } = e;
		const d = c.runParams;
		a = {
			...d,
			sessionId: l.sessionId,
			sessionFile: l.sessionFile,
			sessionTarget: {
				...d.sessionTarget,
				...l.sessionTarget,
				...l.sessionWriterFence
			},
			initialTurnTainted: o(),
			preparedRunAdmission: void 0,
			pluginGeneration: void 0,
			pluginRuntimeRefreshContinuation: true,
			pluginRuntimeRefreshUserPrompt: d.pluginRuntimeRefreshUserPrompt ?? d.prompt,
			pluginRuntimeRefreshMessages: [
				...d.pluginRuntimeRefreshMessages ?? [],
				...l.continuation?.messages ?? [],
				...s.pluginRuntimeRefreshMessages ?? []
			],
			modelHasVision: void 0,
			modelThinkingCapability: void 0,
			modelFallbackAvailability: void 0,
			suppressNextUserMessagePersistence: true,
			prompt: continuationPrompt(captureAgentPluginRuntimeRefresh().requestSource())
		};
		return { meta: {
			durationMs: Date.now() - c.startedAtMs,
			terminalReply: { disposition: "empty" },
			agentMeta: {
				sessionId: l.sessionId,
				provider: e.provider,
				model: e.modelId,
				usage: toNormalizedUsage(u),
				assistantTurns: u.assistantTurns,
				...u.bridgeCalls ? { bridgeCalls: u.bridgeCalls } : {}
			}
		} };
	}
	return {
		run: (e) => {
			closeGeneration();
			return t.run(e);
		},
		continueAfterAttempt,
		mergeToolMedia: n.merge,
		applyDeliveryState: (e) => i ? Object.assign(e, copyAttemptDeliveryState(normalizeEmbeddedRunAttemptResult(e), i)) : e,
		withDeliveryCallbacks: (t) => {
			if (!i) return t;
			const n = i;
			const r = {
				config: t.config,
				messageProvider: t.messageChannel ?? t.messageProvider,
				originatingTo: t.messageTo ?? t.currentMessagingTarget ?? t.currentChannelId,
				originatingThreadId: t.messageThreadId ?? t.currentThreadTs,
				accountId: t.agentAccountId,
				messagingToolSentTargets: n.messagingToolSentTargets
			};
			const a = resolveMessagingToolPayloadDedupe(r);
			const o = a.shouldDedupePayloads ? a.matchingRoute && !a.useGlobalSentTextEvidenceFallback ? a.routeSentTexts : n.messagingToolSentTexts : [];
			const s = a.shouldDedupePayloads ? a.matchingRoute && !a.useGlobalSentMediaUrlEvidenceFallback ? a.routeSentMediaUrls : n.messagingToolSentMediaUrls : [];
			const c = {
				currentSourceMessagingToolHeldPartial: void 0,
				currentSourceMessagingToolSentTextsNormalized: o.map(normalizeTextForComparison)
			};
			const l = t.sourceReplyDeliveryMode === "message_tool_only" && (n.didDeliverSourceReplyViaMessageTool || (n.messagingToolSourceReplyPayloads?.length ?? 0) > 0);
			const filter = (e) => filterMessagingToolReplyPayload({
				...r,
				payload: e,
				sentTexts: n.messagingToolSentTexts,
				sentMediaUrls: n.messagingToolSentMediaUrls
			}).filter((t) => t === e || hasReplyPayloadContent(t));
			return {
				...t,
				onAssistantMessageStart: () => {
					c.currentSourceMessagingToolHeldPartial = void 0;
					return e.onAssistantMessageStart?.();
				},
				onPartialReply: e.onPartialReply ? (t) => {
					if (l) return false;
					const n = t.text ?? t.delta ?? "";
					const r = c.currentSourceMessagingToolHeldPartial;
					const i = resolveCurrentSourceMessagingToolPartial(c, {
						evtType: t.delta && !t.replace ? "text_delta" : "text_end",
						text: n,
						visibleDelta: t.delta ?? ""
					});
					if (i.hold && !t.mediaUrls?.length) return false;
					const a = {
						...t,
						text: i.hold ? void 0 : i.text,
						...r || i.text !== n || i.hold ? {
							delta: i.hold ? void 0 : i.text,
							replace: true
						} : {}
					};
					const o = filterMessagingToolMediaDuplicates({
						payloads: [a],
						sentMediaUrls: s
					})[0];
					return o && hasReplyPayloadContent(o) ? e.onPartialReply?.(o) : false;
				} : void 0,
				onBlockReply: e.onBlockReply ? async (t, n) => {
					const r = getReplyPayloadMetadata(t);
					if (r?.sourceReplyTranscriptMirror) {
						await e.onBlockReply?.(t, n);
						return;
					}
					if (l && !r?.deliverDespiteSourceReplySuppression) return;
					for (const r of filter(t)) await e.onBlockReply?.(copyReplyPayloadMetadata(t, r), n);
				} : void 0,
				onReasoningStream: e.onReasoningStream ? (t) => {
					if (!l) return e.onReasoningStream?.(t);
				} : void 0
			};
		},
		mergeTerminalReceipt: (e) => {
			const t = e.meta.agentMeta?.terminalReceipt;
			if (t && r.size > 0) t.successfulToolNames = [.../* @__PURE__ */ new Set([...r, ...t.successfulToolNames])];
		},
		takeContinuation: () => {
			const e = a;
			closeGeneration();
			return e;
		},
		close: () => {
			closeGeneration();
			i = void 0;
			n.clear();
			r.clear();
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/post-compaction-loop-guard.ts
/**
* Detects identical tool-call loops immediately after automatic compaction.
*
* The guard only observes a small post-compaction window; if compaction failed to break an
* identical args/result loop, the runner aborts before spending unbounded tokens.
*/
const log = createSubsystemLogger("agents/post-compaction-guard");
const DEFAULT_WINDOW_SIZE = 3;
const BASELINE_WINDOW_SIZE = 16;
const observationSignature = (e) => `${e.toolName}\0${e.argsHash}`;
function createPostCompactionLoopGuard(e) {
	const t = e?.enabled ?? true;
	const n = [];
	let r;
	let i;
	let a = [];
	const armPostCompaction = () => {
		i = t && n.length > 0 ? new Set(n.map(observationSignature)) : void 0;
		r = [];
		a = [];
		if (t) log.info(`post-compaction guard armed for ${DEFAULT_WINDOW_SIZE} attempts`);
	};
	const observe = (e) => {
		if (!t) return { shouldAbort: false };
		n.push(e);
		if (n.length > BASELINE_WINDOW_SIZE) n.shift();
		if (!r || r.length >= DEFAULT_WINDOW_SIZE) return { shouldAbort: false };
		if (i?.has(observationSignature(e))) a.push(e.toolName);
		r.push(e);
		const o = r.length < DEFAULT_WINDOW_SIZE;
		const s = r.filter((t) => t.toolName === e.toolName && t.argsHash === e.argsHash && t.resultHash === e.resultHash);
		if (s.length >= DEFAULT_WINDOW_SIZE) {
			log.error(`post-compaction loop persisted: tool=${e.toolName} repeated ${s.length} times with identical args+result post-compaction`);
			return {
				shouldAbort: true,
				detector: "compaction_loop_persisted",
				count: s.length,
				toolName: e.toolName,
				message: `CRITICAL: tool ${e.toolName} repeated ${s.length} times with identical arguments and identical results within ${DEFAULT_WINDOW_SIZE} attempts after auto-compaction. The compaction did not break the loop. Aborting to prevent runaway resource use.`
			};
		}
		if (!o) {
			const e = [...new Set(a)].sort().join(",");
			log.info(`post-compaction window closed: toolCalls=${r.length} preCompactionRepeats=${a.length}${e ? ` tools=${e}` : ""}`);
			i = void 0;
			a = [];
		}
		return { shouldAbort: false };
	};
	return {
		armPostCompaction,
		observe
	};
}
//#endregion
//#region src/plugins/provider-catalog-outcome.ts
/** True when the successful listing made with this exact credential returned the model id. */
function isModelInCredentialListing(e, t) {
	const n = normalizeProviderId(t.provider);
	return (e ?? []).some((e) => e.status === "ready" && e.profileId === t.profileId && normalizeProviderId(e.provider) === n && (e.listedModelIds ?? e.modelIdCatalog?.modelIds)?.includes(t.modelId));
}
//#endregion
//#region src/agents/embedded-agent-runner/run/failover-observation.ts
/** Capture sanitized attempt context before the decision and status are known. */
function createFailoverDecisionLogger(e) {
	const t = {
		...e,
		failoverReason: e.failoverReason ?? (e.timedOut ? "timeout" : null),
		profileFailureReason: e.profileFailureReason ?? (e.timedOut ? "timeout" : null)
	};
	const n = t.profileId ? redactIdentifier(t.profileId, { len: 12 }) : void 0;
	const r = sanitizeForConsole(t.runId) ?? "-";
	const i = sanitizeForConsole(t.provider) ?? "-";
	const a = sanitizeForConsole(t.model) ?? "-";
	const o = sanitizeForConsole(t.sourceProvider) ?? i;
	const s = sanitizeForConsole(t.sourceModel) ?? a;
	const c = n ?? "-";
	const l = t.failoverReason ?? "none";
	const u = o !== i || s !== a;
	return (e, d) => {
		const f = e === "continue_normal" ? "debug" : "warn";
		if (f === "debug" && !log$3.isEnabled(f)) return;
		const p = buildApiErrorObservationFields(t.rawError);
		const m = d?.retryCount ?? t.retryCount;
		const h = d?.profileRotationCount ?? t.profileRotationCount;
		log$3[f]("embedded run failover decision", {
			event: "embedded_run_failover_decision",
			tags: [
				"error_handling",
				"failover",
				t.stage,
				e
			],
			runId: t.runId,
			stage: t.stage,
			decision: e,
			failoverReason: t.failoverReason,
			profileFailureReason: t.profileFailureReason,
			provider: t.provider,
			model: t.model,
			sourceProvider: t.sourceProvider ?? t.provider,
			sourceModel: t.sourceModel ?? t.model,
			profileId: n,
			fallbackConfigured: t.fallbackConfigured,
			timedOut: t.timedOut,
			aborted: t.aborted,
			status: d?.status,
			retryCount: m,
			profileRotationCount: h,
			attemptCount: t.attemptCount,
			rawErrorHash: p.rawErrorHash,
			rawErrorFingerprint: p.rawErrorFingerprint,
			httpCode: p.httpCode,
			providerRuntimeFailureKind: p.providerRuntimeFailureKind,
			providerErrorType: p.providerErrorType,
			requestIdHash: p.requestIdHash,
			consoleMessage: `embedded run failover decision: runId=${r} stage=${t.stage} decision=${e} reason=${l} attempt=${t.attemptCount ?? "-"} retry=${m ?? "-"} rotations=${h ?? "-"} from=${o}/${s}${u ? ` to=${i}/${a}` : ""} profile=${c}`
		});
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/failover-policy.ts
function isTerminalFormatFailure(e) {
	return e.failoverFailure && e.failoverReason === "format" && e.allowFormatRetry !== true;
}
function isAssistantTimeoutFailure(e) {
	return e.terminal.kind === "timeout" && e.terminal.source !== "observation" && (e.terminal.source === "idle" || e.terminal.phase === "prompt");
}
function isConcreteNonTimeoutAssistantFailure(e) {
	return e.failoverFailure && Boolean(e.failoverReason) && e.failoverReason !== "timeout";
}
function shouldRotateAssistant(e) {
	const t = isAssistantTimeoutFailure(e);
	if (e.harnessOwnsTransport && (t || e.failoverReason === "timeout") && !isConcreteNonTimeoutAssistantFailure(e)) return false;
	return !(e.terminal.kind === "aborted" && e.terminal.source !== "yield_cleanup" || e.terminal.kind === "timeout" && e.terminal.source !== "observation" && e.terminal.aborted === true) && e.failoverFailure || t;
}
/** Preserves an existing retry reason unless the current attempt produced a stronger signal. */
function mergeRetryFailoverReason(e) {
	return e.failoverReason ?? e.previous ?? (e.timedOut ? "timeout" : null);
}
/**
* Chooses whether a run should rotate auth profile, switch model fallback,
* surface the error, continue normally, or return an error payload. Prompt,
* assistant, and retry-limit stages intentionally use different action sets.
*/
function resolveRunFailoverDecision(e) {
	if (e.stage === "retry_limit") {
		const t = e.failoverReason;
		if (e.fallbackConfigured && t && t !== "timeout" && t !== "format" && t !== "session_expired") return {
			action: "fallback_model",
			reason: t
		};
		return { action: "return_error_payload" };
	}
	const t = {
		action: "surface_error",
		reason: e.failoverReason
	};
	let n;
	let r;
	let i = e.failoverReason ?? "unknown";
	if (e.stage === "prompt") {
		if (isCliTerminalStopCode(e.failoverCode) || e.externalAbort || e.timedOutByRunBudget) return t;
		if (e.harnessOwnsTransport && e.failoverReason === "timeout") {
			if (e.promptTimeoutFallbackSafe === true && e.fallbackConfigured) return {
				action: "fallback_model",
				reason: "timeout"
			};
			return t;
		}
		r = e.failoverFailure && !isTerminalFormatFailure(e);
		n = r && e.failoverReason !== "timeout" && e.failoverReason !== "tls_certificate";
	} else {
		if (e.signalOwnedInterruption || (e.terminal.kind === "aborted" || e.terminal.kind === "timeout") && e.terminal.source === "external") return t;
		if (e.listedModelRejected) return e.fallbackConfigured ? {
			action: "fallback_model",
			reason: "format"
		} : {
			action: "surface_error",
			reason: "format"
		};
		if (isTerminalFormatFailure(e)) return t;
		if (e.terminal.kind === "timeout" && e.terminal.source === "run_budget") return e.terminal.phase === "prompt" && !e.harnessOwnsTransport && e.fallbackConfigured ? {
			action: "fallback_model",
			reason: "timeout"
		} : { action: "continue_normal" };
		if (e.failoverFailure && (e.failoverReason === "tls_certificate" || e.failoverReason === "model_not_found" && /\b(?:unknown model|invalid model|model[_\-\s]?not[_\-\s]?found|is not a valid model id|models?[/\s:].{0,120}?(?:not found|does not exist|retired|deprecated|no longer available)|[\w./:@-]+ was retired at \d{4}-\d{2}-\d{2}|no endpoints found for)\b/i.test(e.errorMessage ?? "") && !/\b(?:access|permissions?|accounts?|plans?|tiers?|subscriptions?|memberships?|entitlements?|unauthorized|forbidden)\b/i.test(e.errorMessage ?? ""))) return e.fallbackConfigured ? {
			action: "fallback_model",
			reason: i
		} : t;
		n = shouldRotateAssistant(e);
		if (!n) return { action: "continue_normal" };
		r = true;
		if (!isConcreteNonTimeoutAssistantFailure(e) && isAssistantTimeoutFailure(e)) i = "timeout";
	}
	if (!e.profileRotated && n) return {
		action: "rotate_profile",
		reason: e.failoverReason
	};
	return r && e.fallbackConfigured ? {
		action: "fallback_model",
		reason: i
	} : t;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/assistant-failure.ts
const MAX_EMPTY_ERROR_RETRIES = 3;
async function handleEmbeddedAssistantFailure(e) {
	const { runInput: t, preparedRuntime: n, normalizedAttempt: r, runtime: i } = e;
	const { attempt: a, terminalState: o, activeErrorContext: s } = r;
	const { attemptAssistant: c, currentAttemptAssistant: l } = r;
	const { provider: u, modelId: d, model: f } = n;
	const p = c?.stopReason === "error" ? c : void 0;
	const m = p?.errorMessage;
	if (p && log$3.isEnabled("debug")) log$3.debug("Assistant attempt failed", {
		provider: p.provider,
		model: p.model,
		runId: t.runParams.runId,
		responseId: p.responseId,
		code: p.errorCode,
		type: p.errorType
	});
	if (isSessionTranscriptTurnMismatchErrorMessage(m)) throw new Error(m);
	if (classifyGatewayStorageFailure(p)) return buildOutcome(e, {
		action: "proceed",
		assistantProfileFailureReason: null
	});
	const { aborted: h, externalAbort: g, idleTimedOut: _, promptError: v, timedOut: y } = projectAgentRunAttemptTerminal(a.terminal);
	const b = isEmbeddedRunTerminalInterrupted(o.outcome);
	const { signalOwnedInterruption: x } = o;
	const S = pickFallbackThinkingLevel({
		message: p?.errorMessage,
		attempted: n.attemptedThinking
	});
	const C = isAuthAssistantError(p);
	const w = isRateLimitAssistantError(p);
	const T = isBillingAssistantError(p);
	const E = isFailoverAssistantError(p);
	const D = classifyAssistantFailoverReason(p, { providerOwner: e.providerOwner });
	const O = Boolean(l?.provider) || o.outcome.providerStarted === true;
	const k = D ?? (O && (y || _) ? "timeout" : null);
	let A = e.failover.resolveAuthProfileFailureReason(k, {
		providerStarted: O,
		transientRateLimit: k === "rate_limit" && classifyRateLimitWindow(p?.errorMessage).kind === "short"
	});
	const j = isTerminalAssistantError(c);
	if (j || isEmbeddedRunTimeoutFinal(a) || !isCurrentAttemptReplaySafe(a)) return buildOutcome(e, {
		action: "proceed",
		assistantProfileFailureReason: j ? null : A
	});
	if (S && !b) {
		log$3.warn(`unsupported thinking level for ${u}/${d}; retrying with ${S}`);
		return buildOutcome(e, {
			action: "retry",
			thinkLevel: S,
			assistantProfileFailureReason: A
		});
	}
	const M = a.cloudCodeAssistFormatError;
	const N = parseImageDimensionError(p?.errorMessage ?? "");
	const P = D === null || D === "no_error_details" || D === "unclassified" || D === "unknown";
	const F = p ? buildAssistantFailoverSignal(p) : void 0;
	const I = F?.status;
	const L = F !== void 0 && isListedModelChatRejection(inferSignalStatus(F), F.message ?? "") && isModelInCredentialListing(e.providerOutcomes, {
		provider: u,
		modelId: d,
		profileId: i.lastProfileId
	});
	const R = F !== void 0 && I !== void 0 && I >= 400 && I < 500 && !isRetryableProviderHttpStatus(I) && !shouldRetryFailoverSignal({
		classification: null,
		signal: F
	});
	const z = !C && !w && !T && !M && !N && !b && !v && !R && shouldRetrySilentErrorAssistantTurn({
		attempt: a,
		assistant: p
	});
	if (z && P && e.emptyErrorRetries < MAX_EMPTY_ERROR_RETRIES) {
		const n = e.emptyErrorRetries + 1;
		log$3.warn(`[empty-error-retry] stopReason=error non-visible-output; resubmitting attempt=${n}/${MAX_EMPTY_ERROR_RETRIES} provider=${p?.provider ?? u} model=${p?.model ?? f.id} sessionKey=${t.runParams.sessionKey ?? t.runParams.sessionId}`);
		return buildOutcome(e, {
			action: "retry",
			emptyErrorRetries: n,
			assistantProfileFailureReason: A
		});
	}
	const B = t.fallbackConfigured && D === null && z && e.emptyErrorRetries >= MAX_EMPTY_ERROR_RETRIES;
	const V = B ? "unknown" : L ? "format" : D;
	const H = createFailoverDecisionLogger({
		stage: "assistant",
		runId: t.runParams.runId,
		rawError: p?.errorMessage?.trim(),
		failoverReason: V,
		profileFailureReason: A,
		provider: s.provider,
		model: s.model,
		sourceProvider: p?.provider ?? u,
		sourceModel: p?.model ?? d,
		profileId: i.lastProfileId,
		fallbackConfigured: t.fallbackConfigured,
		timedOut: y,
		aborted: h,
		retryCount: e.failover.transientRetryCount,
		profileRotationCount: e.overloadProfileRotations,
		attemptCount: e.traceAttempts.length + 1
	});
	if (!x && C && !L && await n.maybeRefreshRuntimeAuthForAuthError(p?.errorMessage ?? "", e.runtimeAuthRetry)) return buildOutcome(e, {
		action: "retry",
		authRetryPending: true,
		assistantProfileFailureReason: A
	});
	if (N && i.lastProfileId) {
		const e = [
			N.messageIndex !== void 0 ? `message=${N.messageIndex}` : null,
			N.contentIndex !== void 0 ? `content=${N.contentIndex}` : null,
			N.maxDimensionPx !== void 0 ? `limit=${N.maxDimensionPx}px` : null
		].filter(Boolean).join(" ");
		log$3.warn(`Profile ${i.lastProfileId} rejected image payload${e ? ` (${e})` : ""}.`);
	}
	const resolveDecision = (e) => resolveRunFailoverDecision({
		stage: "assistant",
		allowFormatRetry: M,
		terminal: a.terminal,
		signalOwnedInterruption: x,
		fallbackConfigured: t.fallbackConfigured,
		failoverFailure: E,
		failoverReason: D,
		errorMessage: p?.errorMessage,
		harnessOwnsTransport: i.pluginHarnessOwnsTransport,
		listedModelRejected: L,
		profileRotated: e
	});
	const U = B ? {
		action: "fallback_model",
		reason: "unknown"
	} : resolveDecision(false);
	const W = i.lastProfileId ? n.attemptAuthProfileStore.profiles?.[i.lastProfileId]?.type : void 0;
	const G = o.outcome;
	const K = g || x;
	let q = e.overloadProfileRotations;
	let J = U;
	const logDecision = (t, n) => H(t, {
		...n,
		retryCount: e.failover.transientRetryCount,
		profileRotationCount: q
	});
	const recordTrace = (t, n) => {
		e.traceAttempts.push({
			provider: s.provider,
			model: s.model,
			result: V === "timeout" ? "timeout" : t,
			...V ? { reason: V } : {},
			stage: "assistant",
			...n !== void 0 ? { status: n } : {}
		});
	};
	const throwFailure = (n) => {
		if (J.action === "surface_error" && n.reason === "format") recordModelFallbackStop(n);
		recordTrace(U.action === "fallback_model" ? "fallback_model" : "error", n.status);
		if (n.suspend) t.suspendForFailure({
			cfg: t.runParams.config,
			agentDir: t.agentDir,
			sessionId: e.suspensionSessionId,
			reason: resolveSessionSuspensionReason(n.reason),
			failedProvider: n.provider ?? u,
			failedModel: n.model ?? d
		});
		throw n;
	};
	if (J.action === "rotate_profile") {
		const n = i.lastProfileId;
		const markFailedProfile = async () => {
			if (!A) return;
			try {
				await e.failover.maybeMarkAuthProfileFailure({
					profileId: n,
					reason: A,
					modelId: d,
					retryAfterMs: F?.retryAfterMs
				});
			} catch (e) {
				log$3.warn(`profile failure mark failed: ${String(e)}`);
			}
		};
		if (D === "overloaded") {
			q += 1;
			if (q > e.failover.overloadProfileRotationLimit && t.fallbackConfigured) {
				const e = I ?? resolveFailoverStatus("overloaded");
				log$3.warn(`overload profile rotation cap reached for ${sanitizeForLog(u)}/${sanitizeForLog(d)} after ${q} rotations; escalating to model fallback`);
				await markFailedProfile();
				logDecision("fallback_model", { status: e });
				throwFailure(new FailoverError("The AI service is temporarily overloaded. Please try again in a moment.", {
					reason: "overloaded",
					provider: s.provider,
					model: s.model,
					profileId: i.lastProfileId,
					status: e,
					rawError: p?.errorMessage?.trim()
				}));
			}
		}
		const r = await e.failover.advanceAuthProfile(D, {
			failoverProvider: s.provider,
			failoverModel: s.model,
			logFallbackDecision: H
		});
		if (A === "timeout" && !r && !t.fallbackConfigured) A = null;
		const a = markFailedProfile();
		if (y && !t.isProbeSession && n) {
			const e = _ ? "idle timeout (model silent)" : "timed out";
			const i = r ? "Trying next account..." : t.fallbackConfigured ? "No further authorized account for this provider; trying the next configured model." : A ? "No further authorized account for this provider; create a backup auth profile and add its id to auth.order to enable failover." : "No failover target is available; leaving the profile available for the next turn.";
			log$3.warn(`Profile ${n} ${e}. ${i}`);
		}
		if (M && n) log$3.warn(`Profile ${n} hit Cloud Code Assist format error. Tool calls will be sanitized on retry.`);
		if (r) {
			logDecision("rotate_profile");
			recordTrace("rotate_profile");
			return buildOutcome(e, {
				action: "retry",
				thinkLevel: e.getThinkLevel(),
				overloadProfileRotations: q,
				lastRetryFailoverReason: mergeRetryFailoverReason({
					previous: e.previousRetryFailoverReason,
					failoverReason: D,
					timedOut: y
				}),
				assistantProfileFailureReason: A
			});
		}
		await a;
		J = resolveDecision(true);
	}
	if (J.action === "surface_error") logDecision("surface_error");
	if (J.action === "fallback_model" || J.action === "surface_error" && !K && !y && (E || L)) {
		const n = (L ? "The provider lists this model but rejected a chat request. It may not be a chat model, or it isn't enabled for this account. Choose another model." : void 0) || (p ? formatUserFacingAssistantErrorText(p, {
			cfg: t.runParams.config,
			sessionKey: t.runParams.sessionKey ?? t.runParams.sessionId,
			agentId: t.runParams.agentId,
			provider: s.provider,
			providerOwner: e.providerOwner,
			model: s.model,
			authMode: W
		}) : void 0) || p?.errorMessage?.trim() || (y ? "LLM request timed out." : w ? "LLM request rate limited." : T ? formatBillingErrorMessage(s.provider, s.model, W) : C ? "LLM request unauthorized." : "LLM request failed.");
		const r = J.reason ?? (T ? "billing" : C ? "auth" : w ? "rate_limit" : "unknown");
		const a = I ?? resolveFailoverStatus(r) ?? (isTimeoutErrorMessage(n) ? 408 : void 0);
		if (J.action === "fallback_model") logDecision("fallback_model", { status: a });
		throwFailure(new FailoverError(renderRateLimitRetryExhaustion(e.rateLimitRetriesExhausted) ?? n, {
			reason: r,
			rateLimitRetriesExhausted: e.rateLimitRetriesExhausted,
			provider: s.provider,
			model: s.model,
			profileId: i.lastProfileId,
			authMode: W,
			status: a,
			code: L ? MODEL_CHAT_REJECTED_CODE : p?.errorCode,
			rawError: p?.errorMessage?.trim(),
			timeout: G.status === "timeout" ? {
				timeoutPhase: G.timeoutPhase,
				providerStarted: G.providerStarted
			} : void 0,
			suspend: Boolean(t.runParams.sessionKey ?? t.runParams.sessionId) && (r === "rate_limit" || r === "billing")
		}));
	}
	logDecision("continue_normal");
	return buildOutcome(e, {
		action: "proceed",
		overloadProfileRotations: q,
		assistantProfileFailureReason: A
	});
}
function buildOutcome(e, t) {
	return {
		action: t.action,
		thinkLevel: t.thinkLevel ?? e.runtime.thinkLevel,
		authRetryPending: t.authRetryPending ?? false,
		emptyErrorRetries: t.emptyErrorRetries ?? e.emptyErrorRetries,
		overloadProfileRotations: t.overloadProfileRotations ?? e.overloadProfileRotations,
		lastRetryFailoverReason: t.lastRetryFailoverReason ?? e.previousRetryFailoverReason,
		assistantProfileFailureReason: t.assistantProfileFailureReason
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/idle-timeout-breaker.ts
const MAX_CONSECUTIVE_IDLE_TIMEOUTS_BEFORE_OUTPUT = 5;
function stepIdleTimeoutBreaker(e, t) {
	if (t.idleTimedOut && !t.completedModelProgress) e.consecutiveIdleTimeoutsBeforeOutput += 1;
	else if (t.completedModelProgress) e.consecutiveIdleTimeoutsBeforeOutput = 0;
	return {
		consecutive: e.consecutiveIdleTimeoutsBeforeOutput,
		tripped: e.consecutiveIdleTimeoutsBeforeOutput >= 5
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts
/**
* Builds the user-visible incomplete-turn warning when a terminal attempt did
* not produce a safe final assistant response and no committed delivery/progress
* already completed the task.
*/
function resolveIncompleteTurnPayloadText(e) {
	const t = e.terminalFailure?.prepared.payloadsForVisibleCompletion;
	const n = e.attempt.terminal.kind === "ok" && e.attempt.lastToolError ? t?.find((e) => getReplyPayloadMetadata(e)?.toolErrorWarning) : void 0;
	const r = n ? countSettledTurnDeliveryPayloads({
		payloads: t,
		attempt: e.attempt
	}) : e.payloadCount;
	const i = classifyAssistantTurn({
		...e,
		payloadCount: r
	});
	const a = e.attempt.textToolCallAttempt === true;
	const o = i.assistant;
	const s = {
		...e.attempt,
		messagingToolSourceReplyPayloads: e.attempt.messagingToolSourceReplyPayloads?.filter((e) => !e.toolAuthored || isToolAuthoredSourceReplyForAssistant(e, o))
	};
	const c = hasAttemptTerminalState(s);
	const l = isIncompleteTerminalAssistantTurn({
		hasAssistantVisibleText: r > 0,
		hasTerminalOutput: c,
		lastAssistant: o
	});
	const u = r !== 0 && e.attempt.keptAnswer === void 0 && !i.visibleText.length && !o?.openclawDelivery?.tts?.text?.trim() && !c && Boolean(o && hasOnlyAssistantReasoningContent(o));
	const d = (e.rawPayloadCount ?? e.payloadCount) > r;
	if (r !== 0 && !l && !u && !a || e.aborted && e.externalAbort || e.timedOut || e.attempt.clientToolCalls || e.attempt.yieldDetected || e.attempt.didSendDeterministicApprovalPrompt || n && c || e.attempt.lastToolError && !n || e.hasIntentionalTerminalCompletion || e.attempt.hasToolMediaBlockReply || resolveSourceReplyDelivery(s) !== "missing" || s.messagingToolSourceReplyPayloads?.some((e) => e.toolAuthored === true) || hasCompletionMessageSessionSpawn(e.attempt.acceptedSessionSpawns)) return null;
	if (hasAsyncActivity(e.attempt.toolMetas) || !e.aborted && o?.stopReason === "stop" && (e.attempt.itemLifecycle.activeCount > 0 || e.attempt.itemLifecycle.completedCount < e.attempt.itemLifecycle.startedCount)) return null;
	const f = a ? "⚠️ The model wrote a tool call as text instead of calling the tool. No tool ran for that call." : void 0;
	const p = o?.stopReason;
	if (!a && !l && !i.reasoningOnly && !u && !d && !i.emptyResponse && p !== "error") return null;
	if (n?.text) return n.text;
	const { promptError: m } = projectAgentRunAttemptTerminal(e.attempt.terminal);
	if (!m && o?.stopReason === "error" && o.errorCode === "incomplete_tool_call") return formatUserFacingAssistantErrorText(o);
	const h = renderAgentHarnessPreflightUserMessage(m);
	const g = m && h === void 0 ? resolveReplyFailoverFacts(m, formatErrorMessage(m)) : void 0;
	const _ = f ?? h ?? (g ? g.providerRequestError?.userMessage ?? g.requestFailureText ?? renderAssistantRequestFailureCopy({
		reason: g.reason,
		status: g.status,
		code: g.code
	}) : void 0);
	if (e.hadPotentialSideEffects || e.attempt.replayMetadata.hadPotentialSideEffects) return _ ? `${_} Note: some tool actions may have already been executed — please verify before retrying.` : MISSING_REPLY_SIDE_EFFECT_NOTICE_TEXT;
	if (f) return `${f} Please try again or use a model with native tool calling.`;
	if (h !== void 0) return h;
	if (o && isProviderRefusalAssistantError(o)) return formatUserFacingAssistantErrorText(o);
	const v = e.terminalFailure;
	const y = v?.assistantProfileFailureReason;
	if (v && (y === "auth" || y === "auth_permanent")) return renderAuthProfileFailoverCopy({
		reason: y,
		provider: v.provider,
		allInCooldown: false,
		recoveryHint: buildProviderAuthRecoveryHint({
			provider: v.provider,
			config: v.runParams.config,
			workspaceDir: v.runParams.workspaceDir,
			env: process.env
		})
	});
	return _ ?? (p === "length" ? "⚠️ The model reached its output token limit before generating an answer. Please try again." : "No answer was returned. Ask again if you still need one.");
}
/**
* Allows one retry when the provider returned no assistant turn at all and the
* attempt has no side effects, active lifecycle items, delivery, or terminal
* assistant/tool state.
*/
function shouldRetryMissingAssistantTurn(e) {
	return !(e.payloadCount !== 0 || e.aborted || e.promptError || e.timedOut || e.attempt.clientToolCalls || resolveCurrentAttemptAssistant(e.attempt) || e.attempt.yieldDetected || e.attempt.didSendDeterministicApprovalPrompt || e.attempt.lastToolError || joinAssistantTexts(e.attempt.assistantTexts).length > 0 || hasCommittedMessagingToolDeliveryEvidence(e.attempt) || hasAcceptedSessionSpawn(e.attempt.acceptedSessionSpawns) || hasAsyncActivity(e.attempt.toolMetas) || (e.attempt.itemLifecycle?.startedCount ?? 0) > 0 || (e.attempt.itemLifecycle?.activeCount ?? 0) > 0 || e.attempt.replayMetadata.hadPotentialSideEffects);
}
/** Same-attempt work that can resume execution or deliver its completion. */
function hasRunContinuationEvidence(e) {
	return (e.clientToolCalls?.length ?? 0) > 0 || e.didSendDeterministicApprovalPrompt === true || hasCompletionMessageSessionSpawn(e.acceptedSessionSpawns) || e.runtimeContinuationStarted === true || e.yieldMessageWaitRegistered === true || hasAsyncActivity(e.toolMetas);
}
/**
* A deliberate yield can also leave accepted work or already-sent output. A waiting
* acknowledgment is kept only for an armed completion, so that wake is its continuation.
*/
function hasYieldContinuationEvidence(e) {
	return Boolean(e.yieldAcknowledgment?.trim()) || hasAcceptedSessionSpawn(e.acceptedSessionSpawns) || hasCommittedMessagingToolDeliveryEvidence(e) || (e.successfulCronAdds ?? 0) > 0 || hasRunContinuationEvidence(e);
}
const YIELD_DIAGNOSTIC_TEXT = "⚠️ Turn yielded without a continuation source. Send a message to resume.";
const TRUNCATED_REPLY_NOTICE_TEXT = "⚠️ Reply truncated at the model's output token limit. The text above is partial — ask to continue it.";
const CUT_OFF_SUMMARY_NOTICE_TEXT = "⚠️ The model was cut off at its output token limit, so the summary above was written afterwards without tools. Some work may be unfinished — check before relying on it.";
/**
* Marks replay invalid whenever the recorded attempt might not be safe to
* replay or the current run ended in a compaction/incomplete-turn state that
* needs a fresh prompt boundary.
*/
function resolveReplayInvalidFlag(e) {
	const t = projectAgentRunAttemptTerminal(e.attempt.terminal);
	const n = e.attempt.replayMetadata.replaySafe && isProviderRefusalAssistantError(resolveCurrentAttemptAssistant(e.attempt));
	return !e.attempt.replayMetadata.replaySafe || t.promptErrorSource === "compaction" || t.timedOutDuringCompaction || Boolean(e.incompleteTurnText) && !n;
}
/** Classifies the persisted run state used by session recovery and resume logic. */
function resolveRunLivenessState(e) {
	if (e.incompleteTurnText) return "abandoned";
	const t = projectAgentRunAttemptTerminal(e.attempt.terminal);
	if (!t.timedOutDuringToolExecution && (t.promptErrorSource === "compaction" || t.timedOutDuringCompaction)) return "paused";
	if ((e.aborted || e.timedOut) && e.payloadCount === 0) return "blocked";
	if (resolveCurrentAttemptAssistant(e.attempt)?.stopReason === "error") return "blocked";
	return "working";
}
//#endregion
//#region src/agents/embedded-agent-runner/run/retry-limit.ts
function handleRetryLimitExhaustion(e) {
	if (e.decision.action === "fallback_model") throw new FailoverError(e.message, {
		reason: e.decision.reason,
		provider: e.provider,
		model: e.model,
		profileId: e.profileId,
		status: resolveFailoverStatus(e.decision.reason)
	});
	const t = "Request failed after repeated internal retries. Please try again, or use /new to start a fresh session.";
	return {
		payloads: [{
			text: t,
			isError: true
		}],
		meta: {
			durationMs: e.durationMs,
			agentMeta: e.agentMeta,
			terminalReply: sanitizeAgentRunTerminalReply(t),
			finalAssistantVisibleText: t,
			...e.replayInvalid ? { replayInvalid: true } : {},
			livenessState: "blocked",
			error: {
				kind: "retry_limit",
				message: e.message
			}
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-normalization.ts
async function normalizeEmbeddedRunAttempt(e) {
	const { runInput: t, preparedRuntime: n, dispatchedAttempt: r, sessionPromptState: i, provider: a, modelId: o } = e;
	const s = t.runParams;
	const c = n.snapshot();
	const l = normalizeEmbeddedRunAttemptResult(r.rawAttempt);
	const assertNotAborted = () => {
		try {
			t.laneController.throwIfAborted();
		} catch (t) {
			if (t instanceof Error && isAbortError(t) && !s.pluginRuntimeRefreshContinuation && isEmbeddedRunReplaySafe(e.replayState, l)) throw new ReplaySafeRunAbortError(t);
			throw t;
		}
	};
	const u = Math.max(0, l.compactionCount ?? 0);
	const d = e.recordedCompactionCount ?? 0;
	e.contextRecoveryState.autoCompactionCount += Math.max(0, u - d);
	if (u > d) e.contextRecoveryState.currentContextSnapshot = { tokens: void 0 };
	if ((d === 0 || u > d) && typeof l.compactionTokensAfter === "number" && Number.isFinite(l.compactionTokensAfter) && l.compactionTokensAfter >= 0) e.contextRecoveryState.lastCompactionTokensAfter = Math.floor(l.compactionTokensAfter);
	await i.waitForCurrentUserMessagePersistence();
	i.suppressNextUserMessagePersistence = i.activePrompt.persisted;
	assertNotAborted();
	const { terminal: f, preflightRecovery: p, sessionIdUsed: m, sessionFileUsed: h, lastAssistant: g, currentAttemptAssistant: _, currentAttemptCompletedAssistant: v } = l;
	const { idleTimedOut: y, promptError: b } = projectAgentRunAttemptTerminal(f);
	const x = resolveCurrentAttemptAssistant(l);
	const S = resolveEmbeddedRunAttemptTerminalState({
		attempt: l,
		assistant: x,
		abortSignal: s.abortSignal
	});
	const { outcome: C, signalOwnedInterruption: w } = S;
	const T = isEmbeddedRunTerminalAbort(C);
	const E = isEmbeddedRunTerminalTimeout(C);
	const D = isEmbeddedRunTerminalInterrupted(C);
	const setTerminalLifecycleMeta = (e) => {
		const { stopReason: t, ...n } = e;
		const r = D ? C.stopReason : t;
		l.setTerminalLifecycleMeta?.({
			...n,
			...r ? { stopReason: r } : {},
			aborted: T
		});
	};
	if (s.sessionPersistence !== "detached") {
		const e = i.sessionId;
		const t = i.sessionFile;
		const n = i.sessionTarget ? { ...i.sessionTarget } : void 0;
		const assertCurrent = () => {
			assertNotAborted();
			if (i.sessionId !== e || i.sessionFile !== t || i.sessionTarget?.agentId !== n?.agentId || i.sessionTarget?.sessionId !== n?.sessionId || i.sessionTarget?.sessionKey !== n?.sessionKey || i.sessionTarget?.storePath !== n?.storePath) throw new Error("Legacy context-engine successor target changed the active session binding");
		};
		assertCurrent();
		let r = m;
		const a = Boolean(h && h !== i.sessionFile);
		let o = i.sessionTarget;
		if (h && a) {
			const t = parseSqliteSessionFileMarker(h);
			if (t) {
				const n = i.sessionTarget?.sessionKey;
				const a = await readSessionEntrySummariesInWorker({
					agentId: t.agentId,
					storePath: t.storePath
				});
				assertCurrent();
				const s = n ? resolveSqliteSessionKey(n, t.agentId) : void 0;
				const c = resolveLegacyCompactionSessionKey(a, t.sessionId, {
					sessionId: e,
					sessionKey: n
				}, s);
				if (t.sessionId !== m && m !== e || !c || t.agentId !== i.sessionTarget?.agentId) throw new Error("Legacy context-engine successor identity is inconsistent");
				r = t.sessionId;
				o = {
					...t,
					sessionKey: c
				};
			} else if (h.startsWith("agent:") && i.sessionTarget && resolveAgentIdFromSessionKey(h) === i.sessionTarget.agentId) {
				const e = await readSessionEntryReadOnlyInWorker({
					agentId: i.sessionTarget.agentId,
					sessionKey: h,
					storePath: i.sessionTarget.storePath
				}, assertCurrent);
				assertCurrent();
				if (!e?.sessionId || e.sessionId !== m) throw new Error("Legacy context-engine successor identity is inconsistent");
				o = {
					...i.sessionTarget,
					sessionId: m,
					sessionKey: h
				};
			} else throw new Error("Legacy context-engine successor files are unsupported; return a structured sessionTarget");
		} else if (m && m !== e) o = i.sessionTarget ? {
			...i.sessionTarget,
			sessionId: m
		} : void 0;
		if (a && o && i.sessionTarget && (!o.agentId || !o.sessionKey || !o.storePath || !i.sessionTarget.agentId || !i.sessionTarget.sessionKey || !i.sessionTarget.storePath || o.agentId !== i.sessionTarget.agentId || o.sessionKey !== i.sessionTarget.sessionKey || path.resolve(o.storePath) !== path.resolve(i.sessionTarget.storePath))) throw new Error("Legacy context-engine successor target changed the active session binding");
		assertCurrent();
		i.adoptSessionId(r);
		if (h && a) i.sessionFile = h;
		else if (r !== e && o) {
			const e = parseSqliteSessionFileMarker(i.sessionFile);
			if (e) i.sessionFile = formatSqliteSessionFileMarker({
				agentId: o.agentId ?? e.agentId,
				sessionId: o.sessionId ?? e.sessionId,
				storePath: o.storePath ?? e.storePath
			});
		}
		i.sessionTarget = o;
	}
	assertNotAborted();
	const O = l.bootstrapPromptWarningSignaturesSeen ?? (l.bootstrapPromptWarningSignature ? Array.from(/* @__PURE__ */ new Set([...e.bootstrapPromptWarningSignaturesSeen, l.bootstrapPromptWarningSignature])) : e.bootstrapPromptWarningSignaturesSeen);
	const k = normalizeAssistantUsageForContext(g);
	const A = normalizeAssistantUsageForContext(_);
	const j = normalizeUsage(l.promptCache?.lastCallUsage);
	const M = resolveLatestCallUsage({
		currentAttemptCandidates: [
			l.attemptUsage?.contextUsage ? l.attemptUsage : void 0,
			A,
			j
		],
		carriedUsage: e.lastRunPromptUsage,
		transcriptFallback: k
	});
	const N = l.attemptUsage ?? M.currentAttempt;
	mergeUsageIntoAccumulator(e.usageAccumulator, N);
	mergeAttemptRunStatsIntoAccumulator(e.usageAccumulator, l);
	if (isSqliteTranscriptMutationConflict(b)) {
		if (b instanceof Error && isEmbeddedRunReplaySafe(e.replayState, l)) throw new ReplaySafeTranscriptConflictError(b);
		throw b;
	}
	const P = p?.handled === true && p.source === "mid-turn" && (p.truncatedCount ?? 0) > 0 ? { contextUsage: { state: "unavailable" } } : M.latest;
	const F = stepIdleTimeoutBreaker(e.idleTimeoutBreakerState, {
		idleTimedOut: E && y,
		completedModelProgress: hasCompletedModelProgressForIdleBreaker(l)
	});
	if (F.tripped) {
		const r = `Idle-timeout cost-runaway breaker tripped: ${F.consecutive} consecutive idle timeouts without completed model progress (cap=${5}). Halting further attempts to bound paid model calls. See issue #76293.`;
		log$3.error(`[idle-timeout-circuit-breaker-tripped] sessionKey=${s.sessionKey ?? s.sessionId} provider=${a}/${o} consecutive=${F.consecutive} cap=${5}`);
		const u = handleRetryLimitExhaustion({
			message: r,
			decision: resolveRunFailoverDecision({
				stage: "retry_limit",
				fallbackConfigured: t.fallbackConfigured,
				failoverReason: e.lastRetryFailoverReason
			}),
			provider: a,
			model: o,
			profileId: c.lastProfileId,
			durationMs: Date.now() - t.startedAtMs,
			agentMeta: buildErrorAgentMeta({
				sessionId: i.sessionId,
				sessionFile: i.sessionFile,
				provider: a,
				model: n.model.id,
				credentialSource: l.modelAttempt?.credentialSource,
				...c.outerContextTokenMeta,
				usageAccumulator: e.usageAccumulator,
				lastRunPromptUsage: P
			}),
			replayInvalid: e.replayState.replayInvalid ? true : void 0
		});
		u.meta.modelFallbackStopReason = "idle_timeout_circuit_breaker";
		return {
			action: "complete",
			result: u
		};
	}
	if (l.contextBudgetStatus) e.contextRecoveryState.lastContextBudgetStatus = l.contextBudgetStatus;
	const I = resolveReportedModelRef({
		provider: a,
		model: o,
		assistant: x
	});
	let L = e.replayState;
	const resolveReplayInvalidForAttempt = (e) => L.replayInvalid || resolveReplayInvalidFlag({
		attempt: l,
		incompleteTurnText: e
	});
	if (resolveReplayInvalidForAttempt(null)) L.replayInvalid = true;
	L = observeReplayMetadata(L, l.replayMetadata);
	const R = x ? formatAssistantErrorText(x, {
		cfg: s.config,
		sessionKey: t.resolvedSessionKey ?? s.sessionId,
		agentId: s.agentId,
		provider: I.provider,
		providerOwner: c.providerRuntimeHandle?.plugin,
		model: I.model,
		authMode: c.lastProfileId ? n.attemptAuthProfileStore.profiles?.[c.lastProfileId]?.type : void 0
	}) : void 0;
	const z = x?.stopReason === "error" ? x.errorMessage?.trim() || R : void 0;
	if (!w && !n.nativeModelOwned && p?.handled) {
		const e = p.source === "mid-turn";
		log$3.info(`[context-overflow-precheck] early recovery route=${p.route} completed for ${a}/${o}; ` + (e ? "retrying from current transcript" : "retrying prompt"));
		if (e) {
			if ((p.truncatedCount ?? 0) > 0) i.markOwnedTranscriptRetry();
			i.continueFromCurrentTranscript({ replayCurrentUserTurn: true });
		}
		return {
			action: "retry",
			retryKind: "recovery",
			bootstrapPromptWarningSignaturesSeen: O,
			lastRunPromptUsage: P,
			replayState: L
		};
	}
	return {
		action: "proceed",
		bootstrapPromptWarningSignaturesSeen: O,
		lastRunPromptUsage: P,
		replayState: L,
		attempt: l,
		sessionIdUsed: m,
		sessionFileUsed: h,
		currentAttemptAssistant: _,
		currentAttemptCompletedAssistant: v,
		attemptAssistant: x,
		terminalState: S,
		setTerminalLifecycleMeta,
		attemptCompactionCount: u,
		activeErrorContext: I,
		resolveReplayInvalidForAttempt,
		assistantErrorText: z,
		canRestartForLiveSwitch: !hasOutboundDeliveryEvidence(l) && !l.didSendDeterministicApprovalPrompt && !l.lastToolError && (l.toolMetas?.length ?? 0) === 0 && (l.assistantTexts?.length ?? 0) === 0
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/codex-app-server-recovery.ts
function hasCodexAppServerRecoveryRetryBudget(e) {
	return !e.alreadyRetried && e.runLoopIterations < e.maxRunLoopIterations;
}
/**
* Decides whether a Codex app-server failure can be retried by replaying the
* same turn. The retry is intentionally narrow: stdio-only, replay-safe, once
* per run, and only before any assistant/tool/item side effects escape.
*/
function resolveCodexAppServerRecoveryRetry(e) {
	const t = e.attempt.codexAppServerFailure;
	if (!t) return {
		retry: false,
		reason: "not_codex_app_server_failure"
	};
	if (t.kind !== "client_closed_before_turn_completed" && t.kind !== "turn_completion_idle_timeout") return {
		retry: false,
		reason: t.kind
	};
	if (t.kind === "turn_completion_idle_timeout" && t.turnWatchTimeoutKind !== "completion") return {
		retry: false,
		reason: t.turnWatchTimeoutKind ?? "unknown_turn_watch_timeout"
	};
	if (t.transport !== "stdio") return {
		retry: false,
		reason: "non_stdio_transport"
	};
	if (!e.retryAvailable) return {
		retry: false,
		reason: "retry_exhausted"
	};
	if (!t.replaySafe || !e.attempt.replayMetadata.replaySafe) return {
		retry: false,
		reason: t.replayBlockedReason ?? "replay_unsafe"
	};
	if (e.attempt.assistantTexts.some((e) => e.trim().length > 0)) return {
		retry: false,
		reason: "assistant_output"
	};
	if (e.attempt.toolMetas.length > 0 || e.attempt.clientToolCalls || e.attempt.lastToolError || e.attempt.didSendDeterministicApprovalPrompt) return {
		retry: false,
		reason: "tool_activity"
	};
	if (e.attempt.itemLifecycle.startedCount > 0 || e.attempt.itemLifecycle.activeCount > 0) return {
		retry: false,
		reason: "active_item"
	};
	return { retry: true };
}
//#endregion
//#region src/agents/embedded-agent-runner/run/compaction-live-model-selection.ts
function resolveCompactionLiveModelSelection(e) {
	const { current: t, requested: n } = e;
	if (!n) return t;
	const r = {
		provider: n.provider,
		model: n.model
	};
	if (n.authProfileId) return {
		...r,
		authProfileId: n.authProfileId,
		authProfileIdSource: n.authProfileIdSource ?? "auto"
	};
	if (normalizeProviderId(n.provider) === normalizeProviderId(t.provider)) return {
		...t,
		...r
	};
	return {
		...r,
		authProfileIdSource: "auto"
	};
}
//#endregion
//#region src/config/sessions/session-entry-presence-read.ts
/** Capture the exact metadata owner before initial-writer admission can wait. */
function prepareSessionEntryPresenceRead(e) {
	const t = captureMemoryExactSessionReader(e);
	if (t) {
		const n = resolveSqliteSessionKey(e.sessionKey, t.agentId);
		const r = {
			agentId: t.agentId,
			storePath: t.path,
			sessionKey: n,
			sessionActor: getSessionActorStorageBinding({})
		};
		return {
			sessionKey: n,
			storePath: t.path,
			read: async () => Boolean(captureMemoryExactSessionReader(r)?.read(n))
		};
	}
	const n = { ...e.env ?? process.env };
	n.OPENCLAW_STATE_DIR = resolveStateDir(n);
	const r = resolveSessionStorePathForScope({
		...e,
		env: n
	});
	const i = resolveSqliteScope({
		...e,
		storePath: r,
		env: n
	});
	const a = toDatabaseOptions(i);
	const o = resolveOpenClawAgentSqlitePath(a);
	const s = {
		agentId: i.agentId,
		sessionKey: i.sessionKey,
		storePath: o,
		databaseAgentId: a.agentId,
		env: n
	};
	return {
		sessionKey: i.sessionKey,
		storePath: r,
		read: async () => await withSessionHistoryWorkerDatabase(a, async (e) => await e.readEntryPresence(s))
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/session-writer-revocation.ts
async function revokeAgentSessionWriterClaim(e) {
	if (!e.isCurrent()) return false;
	const assertCurrent = () => {
		if (!e.isCurrent()) throw new Error("Session writer cleanup owner changed");
	};
	const revoke = () => applySessionEntryOperation({
		...e.snapshot.agentId ? { agentId: e.snapshot.agentId } : {},
		sessionKey: e.snapshot.sessionKey,
		storePath: e.snapshot.storePath
	}, {
		kind: "writer-revoke",
		runId: e.runId,
		...e.persistTerminal ? { terminalAtMs: Date.now() } : {},
		expected: {
			sessionId: e.sessionId,
			lifecycleRevision: e.snapshot.entry.lifecycleRevision,
			activeWriterRunId: e.runId
		}
	}, {
		preserveActivity: true,
		skipMaintenance: true,
		workerGuard: { assertCurrent }
	});
	let t;
	try {
		t = await e.memory?.acquire(false, {
			assertCurrent,
			assertReadable: assertCurrent
		});
		if (e.memory && !t) return false;
		const n = e.memory && t ? await runWithSessionActorStorage({
			actor: t,
			agentId: e.memory.database.agentId,
			path: e.memory.database.path,
			authority: {
				assertCurrent,
				authorize: assertCurrent
			}
		}, revoke) : await revoke();
		return n?.sessionId === e.sessionId && n.lifecycleRevision === e.snapshot.entry.lifecycleRevision && n.activeWriterRunId === void 0;
	} catch (t) {
		if (!e.isCurrent()) return false;
		throw t;
	} finally {
		await t?.release();
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/session-bootstrap.ts
const NO_REAL_CONVERSATION_MESSAGES_REASON = "no real conversation messages";
function resolveSessionTargetAgentId(e, t, n) {
	const r = normalizeOptionalString(e.sessionTarget?.agentId);
	const i = normalizeOptionalString(e.sessionTarget?.storePath);
	const a = resolvePersistedSessionStoreOwnerForTarget({
		config: e.config ?? {},
		sessionKey: t,
		storePath: i
	});
	if (r && i && !parseAgentSessionKey(t)?.agentId && a.kind === "none") return r;
	return n ?? resolveSessionAgentId({
		agentId: r ?? e.agentId,
		config: e.config,
		sessionKey: t
	});
}
async function buildContextEngineCompactionSessionTarget(e) {
	const t = normalizeOptionalString(e.sessionTarget?.agentId);
	const n = normalizeOptionalString(e.sessionTarget?.sessionId);
	const r = normalizeOptionalString(e.sessionTarget?.sessionKey);
	const i = normalizeOptionalString(e.sessionTarget?.storePath);
	const a = Boolean(t && n && r && i);
	const o = a ? void 0 : parseSqliteSessionFileMarker(e.sessionFile);
	const s = normalizeOptionalString(e.sessionKey);
	const c = r ?? s;
	const l = parseAgentSessionKey(c)?.agentId;
	const u = o ? await readSessionEntrySummariesInWorker({
		agentId: o.agentId,
		storePath: o.storePath
	}) : [];
	const d = u.find(({ sessionKey: e }) => o && c && e === resolveSqliteSessionKey(c, o.agentId))?.entry;
	const f = u.filter(({ entry: e }) => e.sessionId === o?.sessionId);
	const p = o ? resolvePreferredSessionKeyForSessionIdMatches(f.map(({ sessionKey: e, entry: t }) => [e, t]), o.sessionId) : void 0;
	const m = o ? d?.sessionId === o.sessionId || c && !d ? c : p : void 0;
	if (o && f.length > 0 && !m) throw new Error("Legacy compaction transcript identity is ambiguous");
	if (o && (t && t !== o.agentId || n && n !== o.sessionId || l && l !== o.agentId || i && path.resolve(i) !== path.resolve(o.storePath) || c && d && d.sessionId !== o.sessionId)) throw new Error("Legacy compaction transcript identity is inconsistent");
	const h = a ? r : o ? m : r ?? s;
	const g = resolveSessionTargetAgentId(e, h, o?.agentId);
	const _ = i ?? o?.storePath ?? resolveSessionStorePathCore(e.config?.session?.store, { agentId: g });
	return {
		agentId: g,
		sessionId: n ?? o?.sessionId ?? e.sessionId,
		...h ? { sessionKey: h } : {},
		..._ ? { storePath: _ } : {},
		...e.sessionTarget?.threadId !== void 0 ? { threadId: e.sessionTarget.threadId } : {}
	};
}
function isNoRealConversationCompactionNoop(e) {
	return e.ok === true && e.compacted === false && e.reason === NO_REAL_CONVERSATION_MESSAGES_REASON;
}
async function resetNoRealConversationTokenSnapshot(e) {
	if (!e.sessionTarget || e.sessionPersistence === "detached") return;
	e.assertActive();
	try {
		await applySessionEntryOperation(e.sessionTarget, {
			kind: "fields",
			patch: {
				totalTokens: 0,
				totalTokensFresh: true,
				totalTokensVersion: 1,
				inputTokens: void 0,
				outputTokens: void 0,
				cacheRead: void 0,
				cacheWrite: void 0,
				contextBudgetStatus: void 0,
				updatedAt: Date.now()
			}
		}, {
			result: "none",
			skipMaintenance: true,
			takeCacheOwnership: true,
			...sessionEntryCommitGuardOptions(e.assertActive)
		});
		e.assertActive();
	} catch (t) {
		e.assertActive();
		log$3.warn(`[context-overflow-precheck] failed to reset stale context snapshot for ${e.sessionTarget.sessionKey}: ${String(t)}`);
	}
}
/** Best-effort identity lookup retains the agent that owns an unqualified stored key. */
async function backfillSessionIdentity(e) {
	const t = normalizeOptionalString(e.sessionKey);
	if (t) return { sessionKey: t };
	if (e.sessionPersistence === "detached" || !e.config || !e.sessionId) return {};
	try {
		const t = normalizeOptionalString(e.agentId) ? await resolveStoredSessionKeyForSessionId({
			cfg: e.config,
			sessionId: e.sessionId,
			agentId: e.agentId
		}) : await resolveSessionKeyForRequestCore({
			cfg: e.config,
			sessionId: e.sessionId
		});
		return {
			sessionKey: normalizeOptionalString(t.sessionKey),
			agentId: normalizeOptionalString(e.agentId) ?? normalizeOptionalString(t.agentId)
		};
	} catch (t) {
		log$3.warn(`[backfillSessionIdentity] Failed to resolve sessionKey for sessionId=${redactRunIdentifier(sanitizeForLog(e.sessionId))}: ${formatErrorMessage(t)}`);
		return {};
	}
}
/** Prepare canonical session identity without acquiring execution or placement ownership. */
async function prepareEmbeddedRunSession(e) {
	const t = normalizeOptionalString(e.sessionTarget?.agentId) ?? normalizeOptionalString(e.agentId);
	const n = getAgentEventLifecycleGeneration();
	const r = applyAgentRunSessionTargetIdentity(e);
	const i = {
		...r,
		...await backfillSessionIdentity(r)
	};
	let a;
	const assertWorkerSelection = () => assertRequiredWorkerSelection(i.config ?? {}, { agentRuntime: i.agentHarnessId ?? i.agentHarnessRuntimeOverride });
	const o = i.sessionPersistence !== "detached" ? getReplyOperationSessionReader(i.replyOperation) : void 0;
	const s = i.admittedRunContext ? resolveAdmittedRunActiveAssertion(i.admittedRunContext, i.abortSignal) : void 0;
	const c = o ? async (e) => {
		a = await assertAgentHarnessRunAdmission(i, e);
		assertWorkerSelection();
		return {
			target: a?.runtimeTarget ?? await resolveSessionTranscriptRuntimeTarget(e),
			assertCurrent: () => {
				i.abortSignal?.throwIfAborted();
				s?.();
				o.assertCurrent();
			}
		};
	} : void 0;
	if (!c) {
		a = await assertAgentHarnessRunAdmission(i);
		assertWorkerSelection();
	}
	const l = await resolveAgentRunSessionTarget({
		...i,
		missingSessionKey: "create"
	}, c);
	return {
		params: {
			...i,
			agentId: l.agentId,
			sessionId: l.sessionId,
			sessionKey: l.sessionKey,
			sessionTarget: l,
			sessionFile: l.sessionKey
		},
		runSessionTarget: l,
		sessionAdmission: a,
		contextEngineAgentId: t,
		queuedLifecycleGeneration: n
	};
}
/** Reserves only a missing row's first writer; no row or claim exists until lazy persistence. */
async function prepareInitialSessionWriter(e) {
	const { runParams: t, target: n } = e;
	if (t.sessionPersistence === "detached" || t.sessionManager && !t.sessionManager.getSessionTarget() || t.sessionTarget?.expectedWriterRunId || !n?.agentId || !n.sessionId || !n.sessionKey || !n.storePath) return;
	const r = t.abortSignal;
	const i = t.admittedRunContext && resolveAdmittedRunActiveAssertion(t.admittedRunContext, r);
	if (!i) return;
	const a = {
		agentId: n.agentId,
		sessionId: n.sessionId,
		sessionKey: n.sessionKey,
		storePath: n.storePath
	};
	const o = prepareSessionEntryPresenceRead(a);
	let s;
	const assertActive = () => {
		r?.throwIfAborted();
		if (s) throw s;
		i();
	};
	const assertAbsent = async () => {
		assertActive();
		const e = await o.read();
		assertActive();
		if (e) throw new SessionTranscriptWriterClaimReboundError();
	};
	await assertAbsent();
	const c = await beginSessionEffect({
		agentId: a.agentId,
		scope: o.storePath,
		identities: [
			a.sessionKey,
			o.sessionKey,
			a.sessionId
		],
		signal: r,
		assertAllowed: assertAbsent,
		onInterrupt: (t) => {
			s ??= t ?? /* @__PURE__ */ new Error("Initial session writer interrupted by lifecycle change");
			e.onInterrupt(s);
		}
	});
	const l = t.runId;
	const u = new AsyncWorkScope();
	let d;
	let f = false;
	let p;
	return {
		writer: Object.freeze({
			writerRunId: l,
			get committedFence() {
				return d;
			},
			assertActive: () => {
				assertActive();
				if (!d && (f || !c.isActive())) throw new SessionTranscriptWriterClaimReboundError();
			},
			recordCommitted: (e) => {
				d = Object.freeze({ ...e });
				c.release();
			},
			withTranscriptWrite: (e) => c.run(() => u.track(e))
		}),
		run: c.run,
		close: () => p ??= (async () => {
			try {
				await AsyncWorkScope.runWhenAllIdle(() => [u], () => u.drain());
			} finally {
				f = true;
				c.release();
			}
		})()
	};
}
async function assertAgentHarnessRunAdmission(e, t) {
	if (e.sessionPersistence === "detached") return;
	const n = normalizeOptionalString(e.sessionKey);
	if (!n) return;
	const r = normalizeOptionalString(e.sessionTarget?.storePath);
	const i = resolveSessionTargetAgentId(e, n);
	const a = r ?? resolveSessionStorePathCore(e.config?.session?.store, { agentId: i });
	const o = e.admittedRunContext ? resolveAdmittedRunActiveAssertion(e.admittedRunContext, e.abortSignal) : void 0;
	o?.();
	const s = {
		agentId: i,
		sessionKey: n,
		storePath: a,
		readConsistency: "latest"
	};
	const assertCurrent = () => {
		o?.();
		e.abortSignal?.throwIfAborted();
	};
	const consume = (r, i) => {
		assertCurrent();
		const c = resolveAgentHarnessRunAdmissionError({
			agentHarnessId: e.agentHarnessId,
			entry: r,
			modelSelectionLocked: e.modelSelectionLocked,
			sessionId: e.sessionId,
			sessionKey: n
		});
		if (c) throw new Error(c);
		return r ? {
			...s,
			entry: r,
			assertActive: o,
			...i && t ? { runtimeTarget: {
				...i,
				storePath: t.storePath ?? a
			} } : {}
		} : void 0;
	};
	const c = getReplyOperationSessionReader(e.replyOperation);
	if (c) {
		const e = assertSessionEntryCohortScope(c, s);
		const r = t?.agentId === i && t.sessionKey.trim() === n && t.storePath && path.resolve(t.storePath) === path.resolve(a) ? {
			agentId: i,
			sessionId: t.sessionId,
			sessionKey: e
		} : void 0;
		return c.withRead({
			sessionKeys: [e],
			...r ? { runtimeTarget: r } : {}
		}, assertCurrent, (t) => consume(t.entries.find((t) => t.sessionKey === e)?.entry, t.runtimeTarget));
	}
	return consume(await readSessionEntryInWorker(s, assertCurrent));
}
async function claimPersistedAgentSessionWriter(e, t) {
	const n = e.sessionId;
	const r = t.entry.lifecycleRevision;
	const i = getAgentEventLifecycleGeneration();
	const a = e.replyOperation;
	const o = captureSessionManagerIncognitoBinding({
		agentId: t.agentId ?? resolveSessionTargetAgentId(e, t.sessionKey),
		sessionId: n,
		sessionKey: t.sessionKey,
		storePath: t.storePath
	}, e.sessionManager);
	if (t.entry.sessionId !== n) throw new Error(`Session changed before writer admission: ${t.sessionKey}`);
	const s = normalizeOptionalString(t.entry.activeWriterRunId);
	const c = a && lifecycleAdmissionByOperation.get(a)?.adoptInput;
	let l;
	if (c) l = await runWithSessionSourceScope(t.assertActive, () => c({
		runId: e.runId,
		assertCurrent: t.assertActive
	}), { checkAfter: false });
	else {
		l = await applySessionEntryOperation({
			...t.agentId ? { agentId: t.agentId } : {},
			sessionKey: t.sessionKey,
			storePath: t.storePath
		}, {
			kind: "fields",
			expected: {
				sessionId: n,
				lifecycleRevision: r
			},
			patch: { activeWriterRunId: e.runId }
		}, {
			skipMaintenance: true,
			preserveActivity: true,
			...sessionEntryCommitGuardOptions(t.assertActive)
		});
		if (l && (l.sessionId !== n || l.lifecycleRevision !== r)) throw new Error(`Session changed before writer claim commit: ${t.sessionKey}`);
		if (!l || l.activeWriterRunId !== e.runId) throw new Error(`Session writer claim was not persisted: ${t.sessionKey}`);
	}
	if (s && s !== e.runId) {
		if (supersedeReplyRunByRunId(s, () => {
			const e = getAgentRunContext(s)?.lifecycleGeneration;
			if (!emitAgentEventIfCurrent({
				runId: s,
				...e ? { lifecycleGeneration: e } : {},
				stream: "lifecycle",
				sessionKey: t.sessionKey,
				sessionId: n,
				...t.agentId ? { agentId: t.agentId } : {},
				data: {
					phase: "end",
					aborted: true,
					status: "superseded",
					stopReason: "superseded",
					error: "agent run superseded by a newer session writer",
					endedAt: Date.now()
				}
			})) throw new Error(`Could not record superseded writer outcome: ${s}`);
		})) log$3.warn(`[session-writer] replacing claim session=${sanitizeForLog(t.sessionKey)} previousRunId=${redactRunIdentifier(sanitizeForLog(s))} nextRunId=${redactRunIdentifier(sanitizeForLog(e.runId))} live=true`);
	}
	return {
		expectedLifecycleRevision: r,
		expectedWriterRunId: e.runId,
		entry: l,
		revoke: (r, s) => revokeAgentSessionWriterClaim({
			snapshot: t,
			sessionId: n,
			runId: e.runId,
			memory: o,
			persistTerminal: s?.persistTerminal,
			isCurrent: () => (r?.() ?? true) && getAgentEventLifecycleGeneration() === i && (!a || isCurrentSessionControllerOperation(a))
		})
	};
}
async function claimAgentSessionWriter(e) {
	const t = await assertAgentHarnessRunAdmission(e);
	return t ? claimPersistedAgentSessionWriter(e, t) : void 0;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/compaction-runtime.ts
/** The host owns recovery progress even when the engine produces no hook notices. */
async function compactEmbeddedRunForRecovery(e, t) {
	const n = e.prepareRecoveryOwner();
	const emitProgress = (n, r) => {
		const i = {
			stream: "compaction",
			data: {
				phase: n,
				itemId: t.diagId,
				...r === void 0 ? {} : { completed: r }
			},
			...e.runParams.sessionKey ? { sessionKey: e.runParams.sessionKey } : {}
		};
		emitAgentEvent({
			runId: e.runParams.runId,
			...i
		});
		runBestEffortCallback({
			label: "recovery compaction progress",
			log: log$3,
			callback: () => e.runParams.onAgentEvent?.(i)
		});
	};
	let r = false;
	emitProgress("start");
	try {
		if (t.trigger === "overflow") {
			let r;
			try {
				const i = e.runParams.beforeRecoveryCompaction;
				r = i ? await outsideExecutionCapacity(() => i({
					sessionId: n.session.id,
					...e.modelSelection,
					contextTokenBudget: t.tokenBudget
				})) : "skipped: no reply-owned memory checkpoint";
			} catch {
				n.assertActive();
				log$3.warn("Overflow memory checkpoint failed; continuing compaction");
				r = "failed";
			}
			n.assertActive();
			log$3.info(`[memory-flush] overflow checkpoint ${r}`);
		}
		const i = await executeRecoveryCompaction(e, t, n);
		r = i.result.ok && i.result.compacted;
		return i;
	} finally {
		emitProgress("end", r);
	}
}
/** Preserve one prepared owner snapshot throughout context and timeout recovery. */
async function executeRecoveryCompaction(e, t, n) {
	const { runParams: r } = e;
	const i = n.session;
	const a = r.userTurnTranscriptRecorder?.getAdmissionReceipt();
	const o = a?.agentId === e.sessionAgentId && a.sessionKey === e.resolvedSessionKey && sameSessionTranscriptStorePath(a.storePath, i.target?.storePath) ? a.entryId : void 0;
	const s = {
		...r,
		sessionId: i.id,
		sessionKey: e.resolvedSessionKey
	};
	const c = t.trigger === "timeout_recovery" ? "timeout" : t.trigger;
	const l = `${c === "budget" ? "context budget" : c} recovery`;
	await e.runOwnsCompactionBeforeHook(l);
	n.assertActive();
	const u = {
		...buildEmbeddedCompactionRuntimeContext({
			...r,
			modelCallUrgency: resolveModelCallUrgency(r),
			authProfileId: e.modelSelection.authProfileId,
			authProfileIdSource: e.modelSelection.authProfileIdSource,
			runtimeAuthPlan: e.runtimeAuthPlan,
			workspaceDir: e.workspaceDir,
			agentDir: e.agentDir,
			provider: e.modelSelection.provider,
			modelId: e.modelSelection.model,
			harnessRuntime: e.harnessRuntime,
			thinkLevel: e.thinkLevel,
			activeProcessSessions: listActiveProcessSessionReferences({ scopeKey: resolveProcessToolScopeKey({
				sessionKey: r.sessionKey,
				sessionId: i.id,
				agentId: e.sessionAgentId
			}) })
		}, "recovery"),
		...resolveContextEngineCapabilities({
			config: r.config,
			sessionKey: r.sessionKey,
			explicitAgentId: e.contextEngineAgentId,
			contextEnginePluginId: e.resolveContextEnginePluginId(),
			purpose: c === "budget" ? "context-engine.compaction" : `context-engine.${c}-compaction`
		}),
		onCompactionHookMessages: e.onCompactionHookMessages,
		...e.attempt.promptCache ? { promptCache: e.attempt.promptCache } : {},
		runId: r.runId,
		trigger: t.trigger,
		...t.currentTokenCount !== void 0 ? { currentTokenCount: t.currentTokenCount } : {},
		diagId: t.diagId,
		attempt: t.attempt,
		maxAttempts: t.maxAttempts
	};
	let d = 0;
	const f = e.buildRuntimeSettings({
		tokenBudget: t.tokenBudget,
		...t.trigger === "overflow" ? { degradedReason: "context_overflow" } : {}
	});
	const p = {
		sessionId: i.id,
		sessionKey: e.resolvedSessionKey,
		agentId: e.sessionAgentId,
		sessionTarget: await buildContextEngineCompactionSessionTarget({
			agentId: e.sessionAgentId,
			config: r.config,
			sessionFile: i.file,
			sessionId: i.id,
			sessionKey: e.resolvedSessionKey,
			sessionTarget: i.target
		}),
		tokenBudget: t.tokenBudget,
		...t.currentTokenCount !== void 0 ? { currentTokenCount: t.currentTokenCount } : {},
		force: true,
		compactionTarget: "budget",
		runtimeContext: u,
		runtimeSettings: f
	};
	let m;
	try {
		m = await compactContextEngineWithSafetyTimeout({
			info: e.contextEngine.info,
			compact: (r) => n.withTranscriptWrites(r.abortSignal, () => {
				if (r.runtimeContext) attachCompactionAccountingRecorder(r.runtimeContext, {
					requestBudget: e.state.compactionRequestBudget,
					requestFromEntryId: o,
					pendingRequestState: t.trigger === "timeout_recovery" ? void 0 : "unresolved",
					memoryTranscript: n.sessionManager ? {
						sessionManager: n.sessionManager,
						sessionTarget: i.target,
						assertActive: () => {
							r.abortSignal?.throwIfAborted();
							n.assertActive();
						}
					} : void 0,
					recordUsage: (t) => mergeUsageIntoAccumulator(e.usageAccumulator, t),
					recordCompaction: ({ tokensAfter: t }) => {
						declarePromptHistoryRewrite({
							...s,
							reason: "compaction"
						});
						d += 1;
						e.state.observeContextAccounting({
							kind: "compaction",
							tokensAfter: t
						});
					}
				});
				return e.contextEngine.compact(r);
			})
		}, p, resolveCompactionTimeoutMs(r.config), r.abortSignal);
	} catch (t) {
		n.assertActive();
		log$3.warn(`contextEngine.compact() threw during ${l} for ${e.modelSelection.provider}/${e.modelSelection.model}: ${String(t)}`);
		m = {
			ok: false,
			compacted: false,
			reason: String(t)
		};
	}
	if (d > 0 && !m.compacted) m = {
		ok: m.ok,
		compacted: true,
		reason: m.reason
	};
	const h = resolveCompactionSuccessorTranscript(m);
	const g = m.result?.sessionTarget;
	const _ = (!h.sessionId || h.sessionId === i.id) && (!h.sessionFile || h.sessionFile === i.file) && (!g?.agentId || g.agentId === i.target?.agentId) && (!g?.sessionKey || g.sessionKey === i.target?.sessionKey) && (!g?.storePath || sameSessionTranscriptStorePath(g.storePath, i.target?.storePath));
	const v = m.result?.tokensAfter;
	const y = typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : void 0;
	const recordTokensAfter = () => {
		e.state.lastCompactionTokensAfter = y;
		e.state.currentContextSnapshot = { tokens: y };
	};
	if (m.compacted && d === 0) e.state.observeContextAccounting({
		kind: "compaction",
		tokensAfter: _ ? y : void 0
	});
	n.assertActive();
	const b = n.sessionManager && _ && (g?.threadId === void 0 || g.threadId === i.target.threadId);
	const x = m.compacted && !b ? await e.adoptCompactionTranscript(m, _ ? void 0 : recordTokensAfter) : void 0;
	e.assertRecoveryActive();
	if (m.compacted && d === 0) declarePromptHistoryRewrite({
		...s,
		reason: "compaction"
	});
	return {
		result: m,
		runtimeContext: u,
		runtimeSettings: f,
		previousSessionId: x
	};
}
function createEmbeddedRunCompactionRuntime(e) {
	const { runParams: t, contextEngine: n, hookRunner: r, hookContext: i, sessionPromptState: a } = e;
	const o = t.abortSignal;
	const s = t.admittedRunContext ? resolveAdmittedRunActiveAssertion(t.admittedRunContext) : void 0;
	const c = t.runId;
	const l = t.sessionManager && !t.sessionManager.getSessionTarget() ? t.sessionManager : void 0;
	const u = t.sessionPersistence === "detached";
	const d = a.sessionTarget;
	const f = !l && !u && d ? captureSessionActorStorageOwner(d, {
		assertCurrent() {
			o?.throwIfAborted();
			s?.();
		},
		authorize() {}
	}) : void 0;
	const p = composeSessionSourceAssertion([s], (e) => {
		o?.throwIfAborted();
		if (!s) throw new Error("compaction recovery requires an active admitted run");
		e();
	});
	const assertRecoveryTarget = (e, t = a.sessionId, n = a.sessionWriterFence) => {
		p();
		if (l || u) return;
		if (f && (e?.agentId !== d?.agentId || !sameSessionTranscriptStorePath(e?.storePath, d?.storePath))) throw new SessionTranscriptWriterClaimReboundError();
		if (!n || n.expectedWriterRunId !== c) throw new SessionTranscriptWriterClaimReboundError();
		if (f) {
			const r = e?.sessionKey && e.storePath ? readCapturedSessionActorEntry(f, e.sessionKey) : void 0;
			if (r?.sessionId !== t || r.lifecycleRevision !== n.expectedLifecycleRevision || r.activeWriterRunId !== n.expectedWriterRunId) throw new SessionTranscriptWriterClaimReboundError();
		}
	};
	const assertRecoveryActive = () => assertRecoveryTarget(a.sessionTarget);
	const getPreparedTarget = () => {
		const e = a.sessionTarget;
		if (!e?.agentId || !e.sessionKey || !e.storePath) throw new Error("compaction recovery requires a complete transcript target");
		return {
			...e,
			agentId: e.agentId,
			sessionId: a.sessionId,
			sessionKey: e.sessionKey,
			storePath: e.storePath
		};
	};
	const prepareRecoveryOwner = () => {
		assertRecoveryActive();
		const e = a.sessionId;
		const t = a.sessionFile;
		const n = a.sessionWriterFence;
		const r = {
			...getPreparedTarget(),
			...n
		};
		const i = !l && !u ? captureSessionEntrySourceAssertion({
			scope: r,
			expected: {
				sessionId: e,
				lifecycleRevision: n?.expectedLifecycleRevision,
				activeWriterRunId: n?.expectedWriterRunId
			},
			fields: [
				"sessionId",
				"lifecycleRevision",
				"activeWriterRunId"
			],
			assertCurrent: () => assertRecoveryTarget(r, e, n),
			assertHostCurrent: () => {
				if (!n || n.expectedWriterRunId !== c) throw new SessionTranscriptWriterClaimReboundError();
			},
			refuse: () => {
				throw new SessionTranscriptWriterClaimReboundError();
			}
		}) : void 0;
		const o = composeSessionSourceAssertion([p, i], (n) => {
			n();
			const i = a.sessionTarget;
			if (a.sessionId !== e || a.sessionFile !== t || i?.agentId !== r.agentId || i?.sessionKey !== r.sessionKey || !sameSessionTranscriptStorePath(i?.storePath, r.storePath)) throw new Error("active session changed after recovery transcript preparation");
		});
		return {
			session: {
				id: e,
				file: t,
				target: r
			},
			...l ? { sessionManager: l } : {},
			assertActive: o,
			withTranscriptWrites: (e, t) => {
				const n = composeSessionSourceAssertion([o], (t) => {
					e?.throwIfAborted();
					t();
				});
				const i = composeSessionSourceAssertion([n], (e) => {
					e();
					if (u || l) throw new Error("detached recovery cannot persist a session transcript");
				});
				return withOwnedSessionTranscriptWrites({
					sessionTarget: r,
					assertCommitAllowed: i,
					withTranscriptWrite: async (e) => await e()
				}, async () => {
					n();
					return await t();
				});
			}
		};
	};
	const prepareRecoverySession = async (e) => {
		const n = prepareRecoveryOwner();
		const r = l ?? (u ? void 0 : await SessionManager.openAsync(n.session.target, t.workspaceDir, resolveEmbeddedSessionContextLimits({ contextTokenBudget: e })));
		n.assertActive();
		return {
			sessionManager: r,
			assertActive: n.assertActive,
			withSessionManagerRewriteLock: (e) => n.withTranscriptWrites(void 0, async () => {
				if (!r) throw new Error("detached recovery has no caller-owned transcript to rewrite");
				await r.reloadPersistedTranscriptAsync();
				n.assertActive();
				return await e();
			})
		};
	};
	const resolveActiveHookContext = () => ({
		...i,
		sessionId: a.sessionId
	});
	const adoptCompactionTranscript = async (e, n) => {
		assertRecoveryActive();
		const r = getPreparedTarget();
		if (l || u) {
			const i = await resolveContextEngineCompactionSuccessor({
				config: t.config,
				currentSessionFile: a.sessionFile,
				currentTarget: r,
				result: e
			});
			p();
			a.capturePreparedCompactionTarget(i);
			try {
				n?.();
				a.notifyCompactionSessionAdopted(r.sessionId);
				p();
				return i.sessionId !== r.sessionId ? r.sessionId : void 0;
			} finally {
				if (i.sessionId !== r.sessionId) await retireSessionMcpRuntime({
					sessionId: r.sessionId,
					reason: "compaction-session-end",
					retainAcrossReuse: true,
					preserveActiveLeases: true
				});
			}
		}
		const i = a.sessionWriterFence;
		const recordAccepted = (e) => {
			a.recordCommittedCompactionSuccessor(e);
			n?.();
		};
		const o = await acceptCompactionSuccessor({
			config: t.config,
			currentSessionFile: a.sessionFile,
			currentTarget: r,
			result: e,
			expectedEntry: {
				sessionId: r.sessionId,
				lifecycleRevision: i?.expectedLifecycleRevision,
				activeWriterRunId: i?.expectedWriterRunId
			},
			assertActive: p,
			onCommitted: recordAccepted
		});
		if (!o.previousSessionId) recordAccepted(o);
		if (t.replyOperation && o.admissionTransition) {
			p();
			await acknowledgeReplySessionTransition(t.replyOperation, o.admissionTransition);
		}
		assertRecoveryActive();
		a.notifyCompactionSessionAdopted(o.previousSessionId);
		assertRecoveryActive();
		return o.previousSessionId;
	};
	const onCompactionHookMessages = (e) => {
		const n = e.messages.filter((e) => e.trim().length > 0);
		if (n.length === 0) return;
		assertRecoveryActive();
		runBestEffortCallback({
			label: "compaction hook notice",
			log: log$3,
			callback: () => t.onAgentEvent?.({
				stream: "compaction",
				data: {
					phase: "notice",
					messages: n
				},
				...t.sessionKey ? { sessionKey: t.sessionKey } : {}
			})
		});
	};
	const runOwnsCompactionHook = async (e, t, i) => {
		assertRecoveryActive();
		const o = t ? "after_compaction" : "before_compaction";
		if (n.info.ownsCompaction !== true || t && !t.ok || !r?.hasHooks(o)) return;
		try {
			if (t) await r.runAfterCompaction({
				messageCount: -1,
				compactedCount: t.compacted ? -1 : 0,
				tokenCount: t.result?.tokensAfter,
				sessionFile: resolveCompactionSuccessorTranscript(t).sessionFile ?? a.sessionFile,
				...i ? { previousSessionId: i } : {}
			}, resolveActiveHookContext());
			else await r.runBeforeCompaction({
				messageCount: -1,
				sessionFile: a.sessionFile
			}, resolveActiveHookContext());
		} catch (t) {
			assertRecoveryActive();
			log$3.warn(`${o} hook failed during ${e}: ${String(t)}`);
		}
		assertRecoveryActive();
	};
	return {
		assertRecoveryActive,
		prepareRecoveryOwner,
		prepareRecoverySession,
		adoptCompactionTranscript,
		onCompactionHookMessages,
		runOwnsCompactionBeforeHook: (e) => runOwnsCompactionHook(e),
		runOwnsCompactionAfterHook: (e, t, n) => runOwnsCompactionHook(e, t, n)
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/overflow-context-recovery.ts
function renderRecoverySideEffectCaution(e) {
	return (e.currentAttemptReplayMetadata ?? e.replayMetadata).hadPotentialSideEffects ? " Completed tool actions were not replayed; verify their effects before retrying." : "";
}
async function recoverEmbeddedRunOverflow(e) {
	const t = e.attempt.preflightRecovery?.pressure === "maintenance" && projectAgentRunAttemptTerminal(e.attempt.terminal).promptErrorSource === "precheck";
	const n = await recoverContextPressure(e, t);
	if (!t || e.aborted || e.signalOwnedInterruption || n.action === "retry") return n;
	e.assertRecoveryActive();
	declineBoundaryMaintenance(e.runParams.runId);
	log$3.warn("[context-maintenance] continuing the turn without maintenance; the request still fits");
	e.markOwnedTranscriptRetry();
	if (e.attempt.preflightRecovery?.source === "mid-turn" || !isCurrentAttemptReplaySafe(e.attempt)) e.prepareCurrentTranscriptRetry();
	return { action: "retry" };
}
async function recoverContextPressure(e, t) {
	const n = e.assistantOverflowCandidate?.message;
	const r = e.assistantOverflowCandidate?.classification;
	const i = !e.aborted && !e.signalOwnedInterruption ? (() => {
		if (e.promptError) {
			const n = formatErrorMessage(e.promptError);
			if (t || isLikelyContextOverflowError(n)) return {
				text: n,
				source: "promptError"
			};
			return null;
		}
		if (isProviderRefusalAssistantError(n)) return null;
		if (n?.stopReason === "error" && r?.kind === "reason") return null;
		if (n && (r?.kind === "context_overflow" || e.contextTokenBudget !== void 0 && isContextOverflow(n, e.contextTokenBudget))) return {
			text: n.errorMessage?.trim() || "Context window exceeded",
			source: "assistantError"
		};
		if (n?.stopReason === "length") return null;
		if (e.assistantErrorText && isLikelyContextOverflowError(e.assistantErrorText)) return {
			text: e.assistantErrorText,
			source: "assistantError"
		};
		return null;
	})() : null;
	if (!i || !e.genericCompactionRecoveryAllowed || e.contextTokenBudget === void 0) return { action: "none" };
	e.assertRecoveryActive();
	const a = e.contextTokenBudget;
	const o = projectAgentRunAttemptTerminal(e.attempt.terminal);
	const s = o.promptErrorSource === "precheck";
	const c = s ? "budget" : "overflow";
	const l = s ? "context budget recovery" : "overflow recovery";
	const u = s ? "predicted context pressure" : "context overflow";
	const d = i.source === "assistantError" || o.promptErrorSource === "prompt" ? markLastProviderPromptContextRejected(getProviderPromptState(e.runParams.runId)) : void 0;
	const f = e.runParams;
	const p = createRunRecoveryDiagId();
	const m = i.text;
	const h = extractObservedOverflowTokenCount(m);
	const g = e.attempt.preflightRecovery;
	const _ = g?.source === "mid-turn" || !isCurrentAttemptReplaySafe(e.attempt);
	if ((e.state.compactionRequestBudget?.fixedTokens ?? 0) >= a) return {
		action: "surface",
		kind: "context_overflow",
		errorText: m,
		userText: "Context overflow: the system prompt, injected context, or tool definitions exceed the model's context window before chat history. Reduce plugin-provided system context or other fixed instructions (inspect /context detail), or use a larger-context model. Resetting the session will not shrink this context." + renderRecoverySideEffectCaution(e.attempt)
	};
	if (!_ && (e.state.compactionRequestBudget?.pendingTokens ?? 0) >= a) return {
		action: "surface",
		kind: "context_overflow",
		errorText: m,
		userText: "This message exceeds the model's context window on its own. Send a smaller message or use a larger-context model." + renderRecoverySideEffectCaution(e.attempt)
	};
	const retryCurrentTranscript = () => {
		if (_) e.prepareCurrentTranscriptRetry();
		return { action: "retry" };
	};
	const truncateToolResults = async () => {
		const { sessionManager: t, assertActive: n } = await e.prepareRecoverySession(a);
		if (!t) return {
			truncated: false,
			truncatedCount: 0,
			reason: "detached recovery has no caller-owned transcript"
		};
		return await withSessionManagerWrite(t, async () => {
			try {
				var r = _usingCtx();
				const i = t.getSessionTarget();
				n();
				const o = r.u(retainEmbeddedSessionPromptState(e.getActiveSession().id)).state.toolResults;
				restoreCacheTtlToolResultProjections(o, t.getToolResultProjectionEntries());
				const c = await truncateOversizedToolResultsInSessionManager({
					sessionManager: t,
					contextWindowTokens: a,
					maxCharsOverride: resolveLiveToolResultMaxChars({ contextWindowTokens: a }),
					protectTrailingToolResults: !s && g?.route === "compact_then_truncate",
					preserveSentToolResults: s,
					projectionState: o,
					...i
				});
				n();
				return c;
			} catch (e) {
				r.e = e;
			} finally {
				r.d();
			}
		});
	};
	const v = s ? asPositiveFiniteNumber(g?.promptBudgetBeforeReserve) : void 0;
	const y = s ? asPositiveFiniteNumber(g?.estimatedPromptTokens) : void 0;
	const b = v === void 0 ? void 0 : Math.floor(v);
	const x = y === void 0 ? void 0 : Math.ceil(y);
	const S = h ?? x ?? (e.contextTokenBudget > 0 ? e.contextTokenBudget + 1 : void 0);
	const C = e.getActiveSession();
	log$3.warn(`[context-overflow-diag] sessionKey=${f.sessionKey ?? f.sessionId} provider=${e.modelSelection.provider}/${e.modelSelection.model} source=${i.source} trigger=${c} messages=${e.attempt.messagesSnapshot.length} sessionFile=${C.file} diagId=${p} compactionAttempts=${e.state.overflowCompactionAttempts} observedTokens=${h ?? "unknown"} preflightEstimatedTokens=${x ?? "unknown"} compactionTokens=${S ?? "unknown"} providerPayloadBytes=${d?.byteWeight ?? "unknown"} error=${truncateUtf16Safe(m, 200)}`);
	const w = isCompactionFailureError(m);
	if (isProviderRequestSizeCeilingError(m)) {
		log$3.warn(`[context-overflow-recovery] provider request-size ceiling for ${e.modelSelection.provider}/${e.modelSelection.model}; livenessState=blocked suggestedAction=reset_or_new kind=${w ? "compaction_failure" : "context_overflow"} compaction=skipped retry=skipped`);
		return {
			action: "surface",
			kind: w ? "compaction_failure" : "context_overflow",
			errorText: m,
			userText: CONTEXT_OVERFLOW_ERROR_MESSAGE + renderRecoverySideEffectCaution(e.attempt)
		};
	}
	let T = false;
	let E;
	let D = false;
	if (!w && e.attemptCompactionCount > 0 && e.state.overflowCompactionAttempts < 3) {
		e.markOwnedTranscriptRetry();
		e.state.overflowCompactionAttempts += 1;
		log$3.warn(`${u} persisted after in-attempt compaction (attempt ${e.state.overflowCompactionAttempts}/${3}); retrying prompt without additional compaction for ${e.modelSelection.provider}/${e.modelSelection.model}`);
		return retryCurrentTranscript();
	}
	if (!w && e.attemptCompactionCount === 0 && e.state.overflowCompactionAttempts < 3) {
		e.state.overflowCompactionAttempts += 1;
		log$3.warn(`${u} detected (attempt ${e.state.overflowCompactionAttempts}/${3}); attempting auto-compaction for ${e.modelSelection.provider}/${e.modelSelection.model}`);
		const n = await compactEmbeddedRunForRecovery(e, {
			tokenBudget: b ?? e.contextTokenBudget,
			trigger: c,
			diagId: p,
			attempt: e.state.overflowCompactionAttempts,
			maxAttempts: 3,
			currentTokenCount: S
		});
		const { result: r, previousSessionId: i } = n;
		e.assertRecoveryActive();
		if (r.ok && r.compacted) {
			const t = e.getActiveSession();
			T = i !== void 0 && _ && e.attempt.toolMetas.some((e) => e.codeModeSuspended === true);
			if (T) log$3.warn(`[context-overflow-recovery] compaction rotated ${i} -> ${t.id} while nested tool work was parked; not continuing mid-turn for ${e.modelSelection.provider}/${e.modelSelection.model}`);
			if (e.contextEngine.maintain) {
				const r = await e.prepareRecoverySession(a);
				await runContextEngineMaintenance({
					...r,
					contextEngine: e.contextEngine,
					sessionId: t.id,
					sessionKey: f.sessionKey,
					sessionTarget: t.target,
					sessionFile: t.file,
					reason: "compaction",
					runtimeContext: n.runtimeContext,
					runtimeSettings: n.runtimeSettings,
					config: f.config,
					agentId: e.sessionAgentId,
					contextEngineAgentId: e.contextEngineAgentId,
					abortSignal: f.abortSignal
				});
				e.assertRecoveryActive();
			}
		}
		await e.runOwnsCompactionAfterHook(l, r, i);
		e.assertRecoveryActive();
		if (g && isNoRealConversationCompactionNoop(r)) {
			e.state.lastCompactionTokensAfter = void 0;
			e.state.lastContextBudgetStatus = void 0;
			const t = await e.prepareRecoverySession(a);
			await resetNoRealConversationTokenSnapshot({
				sessionTarget: t.sessionManager?.getSessionTarget(),
				sessionPersistence: f.sessionPersistence,
				assertActive: t.assertActive
			});
			e.assertRecoveryActive();
			log$3.info(`[context-overflow-precheck] stale token state had no real conversation messages for ${e.modelSelection.provider}/${e.modelSelection.model}; resetting the context snapshot and retrying prompt`);
			return retryCurrentTranscript();
		}
		if (r.compacted) {
			const n = r.result?.tokensBefore;
			const i = r.result?.tokensAfter;
			const a = typeof n === "number" && Number.isFinite(n) && typeof i === "number" && Number.isFinite(i) && i >= n;
			const o = a ? "auto-compaction removed nothing" : "auto-compaction succeeded";
			if (t && a) declineBoundaryMaintenance(f.runId);
			if (g?.route === "compact_then_truncate") {
				const t = await truncateToolResults();
				if (t.truncated) log$3.info(`[context-overflow-precheck] post-compaction tool-result truncation succeeded for ${e.modelSelection.provider}/${e.modelSelection.model}; truncated ${t.truncatedCount} tool result(s)`);
				else log$3.warn(`[context-overflow-precheck] post-compaction tool-result truncation did not help for ${e.modelSelection.provider}/${e.modelSelection.model}: ${t.reason ?? "unknown"}`);
			}
			e.assertRecoveryActive();
			e.runParams.onAutoCompactionSucceeded?.(e.state.autoCompactionCount);
			e.assertRecoveryActive();
			e.armPostCompactionGuard();
			if (T) log$3.warn(`${o} for ${e.modelSelection.provider}/${e.modelSelection.model}, but parked nested tool work cannot follow the rotated session; surfacing overflow guidance`);
			else {
				log$3.info(`${o} for ${e.modelSelection.provider}/${e.modelSelection.model}; retrying prompt`);
				e.markOwnedTranscriptRetry();
				if (_) e.prepareCurrentTranscriptRetry();
				else {
					await e.prepareCompactedTranscriptRetry(e.assertRecoveryActive);
					e.assertRecoveryActive();
				}
				return { action: "retry" };
			}
		} else {
			E = formatErrorMessage(r.reason ?? "nothing to compact");
			D = isBenignCompactionSkipResult(r);
			log$3.warn(`auto-compaction failed for ${e.modelSelection.provider}/${e.modelSelection.model}: ${E}`);
		}
	}
	if (!T && !e.state.toolResultTruncationAttempted) {
		const t = resolveLiveToolResultMaxChars({ contextWindowTokens: e.contextTokenBudget });
		if (sessionLikelyHasOversizedToolResults({
			messages: e.attempt.messagesSnapshot,
			contextWindowTokens: e.contextTokenBudget,
			maxCharsOverride: t,
			preserveSentToolResults: s
		})) {
			e.state.toolResultTruncationAttempted = true;
			log$3.warn(`[context-overflow-recovery] Attempting tool result truncation for ${e.modelSelection.provider}/${e.modelSelection.model} (contextWindow=${e.contextTokenBudget} tokens)`);
			const t = await truncateToolResults();
			if (t.truncated) {
				e.markOwnedTranscriptRetry();
				log$3.info(`[context-overflow-recovery] Truncated ${t.truncatedCount} tool result(s); retrying prompt`);
				return retryCurrentTranscript();
			}
			log$3.warn(`[context-overflow-recovery] Tool result truncation did not help: ${t.reason ?? "unknown"}`);
		}
	}
	const O = E !== void 0 && (s || !D);
	const k = classifyCompactionReason(E);
	const A = k === "unshrinkable_request";
	const j = O || A;
	const M = w || j ? "compaction_failure" : "context_overflow";
	const N = s ? "before the next model request" : "after the provider rejected the prompt";
	const P = j ? `Auto-compaction failed ${N}: ${E}` : m;
	const F = A ? `${E}` + renderRecoverySideEffectCaution(e.attempt) : O ? `${k === "timeout" ? "Auto-compaction timed out" : "Auto-compaction failed"} ${N}. Try again or run /compact.` + renderRecoverySideEffectCaution(e.attempt) : CONTEXT_OVERFLOW_ERROR_MESSAGE + renderRecoverySideEffectCaution(e.attempt);
	if (!t) log$3.warn(`[context-overflow-recovery] exhausted ${s ? "context budget" : "provider overflow"} recovery for ${e.modelSelection.provider}/${e.modelSelection.model}; livenessState=blocked suggestedAction=${A ? "reduce_context" : O ? "retry_or_compact" : "reset_or_new"} kind=${M}`);
	return {
		action: "surface",
		kind: M,
		errorText: P,
		userText: F
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/prompt-failure.ts
async function handleEmbeddedPromptFailure(e) {
	const { runInput: t, preparedRuntime: n, normalizedAttempt: r, runtime: i, terminal: a } = e;
	if (isNonProviderRuntimeCoordinationError(a.promptError) || hasRecordedModelFallbackStop(a.promptError)) throw a.promptError;
	if (a.promptErrorSource === "precheck" && a.promptError instanceof CompactionReplayRefreshRequiredError) {
		const t = new CompactionReplayRefreshRequiredError().message;
		return completeBlockedPromptFailure(e, {
			text: t,
			errorKind: "compaction_replay_refresh_required",
			errorMessage: t
		});
	}
	const o = i.lastProfileId ? n.attemptAuthProfileStore.profiles?.[i.lastProfileId]?.type : void 0;
	const s = buildAgentRunTerminalOutcomeFromAttempt({
		terminal: r.attempt.terminal,
		promptTimeoutOutcome: r.attempt.promptTimeoutOutcome
	});
	const c = {
		provider: r.activeErrorContext.provider,
		model: r.activeErrorContext.model,
		profileId: i.lastProfileId,
		authMode: o,
		sessionId: r.sessionIdUsed,
		lane: t.globalLane,
		timeout: s.status === "timeout" ? {
			timeoutPhase: s.timeoutPhase,
			providerStarted: s.providerStarted
		} : void 0
	};
	const l = coerceToFailoverError(a.promptError, c);
	const u = describeFailoverError(l ?? a.promptError);
	if (l?.suspend) t.suspendForFailure({
		cfg: t.runParams.config,
		agentDir: t.agentDir,
		sessionId: e.suspensionSessionId,
		reason: resolveSessionSuspensionReason(l.reason),
		failedProvider: l.provider ?? n.provider,
		failedModel: l.model ?? n.modelId
	});
	const d = u.message || formatErrorMessage(a.promptError);
	const f = isCliTerminalStopCode(u.code);
	if (!f && await n.maybeRefreshRuntimeAuthForAuthError(d, e.runtimeAuthRetry)) return {
		action: "retry",
		thinkLevel: i.thinkLevel,
		authRetryPending: true,
		lastRetryFailoverReason: e.previousRetryFailoverReason
	};
	const p = f ? void 0 : resolveBlockedPromptResult(e, d);
	if (p) return p;
	const m = u.reason ?? classifyFailoverReason(d, { provider: n.provider });
	const h = e.failover.resolveAuthProfileFailureReason(m, {
		providerStarted: a.promptErrorSource === "prompt",
		transientRateLimit: m === "rate_limit" && classifyRateLimitWindow(d).kind === "short"
	});
	const g = a.promptErrorSource === "prompt" && m === "timeout" && !r.attempt.codexAppServerFailure && r.attempt.promptTimeoutOutcome?.replayInvalid !== true && r.attempt.replayMetadata.replaySafe;
	const _ = i.lastProfileId;
	const v = createFailoverDecisionLogger({
		stage: "prompt",
		runId: t.runParams.runId,
		rawError: d,
		failoverReason: m,
		profileFailureReason: h,
		provider: n.provider,
		model: n.modelId,
		sourceProvider: n.provider,
		sourceModel: n.modelId,
		profileId: _,
		fallbackConfigured: t.fallbackConfigured,
		aborted: a.aborted,
		retryCount: e.failover.transientRetryCount,
		attemptCount: e.traceAttempts.length + 1
	});
	const recordFailoverDecision = (t, r = m, i) => {
		e.traceAttempts.push({
			provider: n.provider,
			model: n.modelId,
			result: m === "timeout" ? "timeout" : t,
			...r ? { reason: r } : {},
			stage: "prompt",
			...i !== void 0 ? { status: i } : {}
		});
		v(t, {
			...t === "fallback_model" ? { status: i } : {},
			retryCount: e.failover.transientRetryCount,
			profileRotationCount: t === "rotate_profile" ? 1 : 0
		});
	};
	const resolveDecision = (e) => resolveRunFailoverDecision({
		stage: "prompt",
		externalAbort: a.externalAbort,
		fallbackConfigured: t.fallbackConfigured,
		failoverCode: u.code,
		failoverFailure: m !== null,
		failoverReason: m,
		harnessOwnsTransport: i.pluginHarnessOwnsTransport,
		promptTimeoutFallbackSafe: g,
		timedOutByRunBudget: a.timedOutByRunBudget,
		profileRotated: e
	});
	let y = resolveDecision(false);
	let b = false;
	if (y.action === "rotate_profile") {
		b = await e.failover.advanceAuthProfile(m, {
			failoverProvider: n.provider,
			failoverModel: n.modelId,
			logFallbackDecision: v
		});
		if (!b) y = resolveDecision(true);
	}
	const x = h ? e.failover.maybeMarkAuthProfileFailure({
		profileId: _,
		reason: h,
		modelId: n.modelId,
		retryAfterMs: resolveRetryAfterMs(formatErrorMessage(a.promptError), Date.now(), a.promptError)
	}).catch((e) => {
		log$3.warn(`prompt profile failure mark failed: ${String(e)}`);
	}) : void 0;
	if (b) {
		recordFailoverDecision("rotate_profile");
		const t = mergeRetryFailoverReason({
			previous: e.previousRetryFailoverReason,
			failoverReason: m
		});
		return {
			action: "retry",
			thinkLevel: e.getThinkLevel(),
			authRetryPending: false,
			lastRetryFailoverReason: t
		};
	}
	if (x) await x;
	const S = f ? void 0 : pickFallbackThinkingLevel({
		message: d,
		attempted: n.attemptedThinking
	});
	if (S) {
		log$3.warn(`unsupported thinking level for ${n.provider}/${n.modelId}; retrying with ${S}`);
		v("retry_thinking_level", { retryCount: e.failover.transientRetryCount });
		return {
			action: "retry",
			thinkLevel: S,
			authRetryPending: false,
			lastRetryFailoverReason: e.previousRetryFailoverReason
		};
	}
	const C = e.rateLimitRetriesExhausted !== void 0 && m === "rate_limit" ? coerceToFailoverError(l ?? a.promptError, {
		...c,
		rateLimitRetriesExhausted: e.rateLimitRetriesExhausted
	}) : void 0;
	if (y.action === "fallback_model") {
		const e = y.reason;
		const t = resolveFailoverStatus(e, u.code);
		recordFailoverDecision("fallback_model", e, t);
		throw C ?? (l?.reason === e ? l : null) ?? new FailoverError(d, {
			...c,
			reason: e,
			provider: n.provider,
			model: n.modelId,
			status: t
		});
	}
	if (y.action === "surface_error") recordFailoverDecision("surface_error");
	if (c.timeout) throw l ?? new FailoverError(d, {
		...c,
		reason: "timeout",
		cause: a.promptError
	});
	throw C ?? toErrorObject(a.promptError, "Prompt failed");
}
function resolveBlockedPromptResult(e, t) {
	let n;
	let r;
	if (/incorrect role information|roles must alternate/i.test(t)) {
		n = "Message ordering conflict - please try again. If this persists, use /new to start a fresh session.";
		r = "role_ordering";
	} else {
		const e = parseImageSizeError(t);
		if (!e) return;
		const i = e.maxMb;
		const a = Number.isFinite(i) ? `${i}` : null;
		n = `Image too large for the model${a ? ` (max ${a}MB)` : ""}. Please compress or resize the image and try again.`;
		r = "image_size";
	}
	return completeBlockedPromptFailure(e, {
		text: n,
		errorKind: r,
		errorMessage: t
	});
}
function completeBlockedPromptFailure(e, t) {
	const n = e.normalizedAttempt.resolveReplayInvalidForAttempt();
	e.normalizedAttempt.setTerminalLifecycleMeta({
		replayInvalid: n,
		livenessState: "blocked"
	});
	return {
		action: "complete",
		result: buildEmbeddedRunBlockedResult({
			...t,
			durationMs: Date.now() - e.runInput.startedAtMs,
			agentMeta: e.buildErrorAgentMeta(),
			attempt: e.normalizedAttempt.attempt,
			replayInvalid: n,
			finalPromptText: e.normalizedAttempt.attempt.finalPromptText
		})
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/timeout-context-recovery.ts
const MAX_TIMEOUT_COMPACTION_ATTEMPTS = 2;
async function recoverEmbeddedRunTimeout(e) {
	if (!e.genericCompactionRecoveryAllowed || e.contextTokenBudget === void 0 || !e.timedOut || e.signalOwnedInterruption || e.timedOutDuringCompaction || e.timedOutDuringToolExecution || e.timedOutByRunBudget) return false;
	const t = deriveContextPromptTokens({ lastCallUsage: e.lastRunPromptUsage });
	const n = t != null && e.contextTokenBudget > 0 ? t / e.contextTokenBudget : 0;
	if (e.state.timeoutCompactionAttempts >= MAX_TIMEOUT_COMPACTION_ATTEMPTS) {
		log$3.warn(`[timeout-compaction] already attempted timeout compaction ${e.state.timeoutCompactionAttempts} time(s); falling through to failover rotation`);
		return false;
	}
	if (n <= .65) return false;
	e.assertRecoveryActive();
	const r = markEmbeddedRunRecoveringTimeout({
		sessionId: e.getActiveSession().id,
		runId: e.runParams.runId,
		operation: e.runParams.replyOperation
	});
	try {
		const t = createRunRecoveryDiagId();
		e.state.timeoutCompactionAttempts += 1;
		log$3.warn(`[timeout-compaction] LLM timed out with high prompt token usage (${Math.round(n * 100)}%); attempting compaction before retry (attempt ${e.state.timeoutCompactionAttempts}/${MAX_TIMEOUT_COMPACTION_ATTEMPTS}) diagId=${t}`);
		const { result: i, previousSessionId: a } = await compactEmbeddedRunForRecovery(e, {
			tokenBudget: e.contextTokenBudget,
			trigger: "timeout_recovery",
			diagId: t,
			attempt: e.state.timeoutCompactionAttempts,
			maxAttempts: MAX_TIMEOUT_COMPACTION_ATTEMPTS
		});
		e.assertRecoveryActive();
		await e.runOwnsCompactionAfterHook("timeout recovery", i, a);
		e.assertRecoveryActive();
		if (!i.compacted) {
			if (r) restoreEmbeddedRunTimeoutAbandonment(r);
			log$3.warn(`[timeout-compaction] compaction did not reduce context for ${e.modelSelection.provider}/${e.modelSelection.model}; falling through to normal handling`);
			return false;
		}
		e.runParams.onAutoCompactionSucceeded?.(e.state.autoCompactionCount);
		e.assertRecoveryActive();
		if (i.ok && e.contextEngine.info.ownsCompaction === true && e.runParams.sessionPersistence !== "detached") {
			const t = e.getActiveSession();
			await runPostCompactionSideEffects({
				config: e.runParams.config,
				sessionKey: e.runParams.sessionKey,
				sessionId: t.id,
				agentId: e.sessionAgentId,
				memoryAudience: e.runInput?.hookContext.memoryAudience,
				sandboxed: e.runInput?.hookContext.sandboxed,
				sessionFile: t.file,
				assertActive: e.assertRecoveryActive
			});
			e.assertRecoveryActive();
		}
		log$3.info(`[timeout-compaction] compaction succeeded for ${e.modelSelection.provider}/${e.modelSelection.model}; retrying prompt`);
		e.armPostCompactionGuard();
		await e.prepareCompactedTranscriptRetry(e.assertRecoveryActive);
		e.assertRecoveryActive();
		if (r) e.state.retainTimeoutRecoveryMarker(r);
		return true;
	} catch (e) {
		if (r) restoreEmbeddedRunTimeoutAbandonment(r);
		throw e;
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-recovery.ts
async function recoverEmbeddedRunAttempt(e) {
	const { runInput: t, preparedRuntime: n, normalizedAttempt: r, runtimePlan: i, sessionPromptState: a, failoverRetryController: o, compactionRuntime: s } = e;
	const c = t.runParams;
	const l = n.snapshot();
	const { attempt: u, sessionIdUsed: d, attemptAssistant: f, currentAttemptAssistant: p, currentAttemptCompletedAssistant: m, terminalState: h, setTerminalLifecycleMeta: g, attemptCompactionCount: _, resolveReplayInvalidForAttempt: v, assistantErrorText: y, canRestartForLiveSwitch: b } = r;
	const x = projectAgentRunAttemptTerminal(u.terminal);
	const { aborted: S, externalAbort: C, promptError: w, promptErrorSource: T, timedOut: E, timedOutDuringCompaction: D, timedOutDuringToolExecution: O, timedOutByRunBudget: k, idleTimedOut: A } = x;
	const j = isEmbeddedRunTerminalInterrupted(h.outcome);
	const M = isCurrentAttemptReplaySafe(u);
	const N = T === "precheck" && u.preflightRecovery?.source === "mid-turn";
	const P = resolveSettledToolBatchEvidence(u, { midTurn: N });
	const F = T === "precheck" && u.preflightRecovery?.pressure === "maintenance";
	const recordRecoveryDecision = (e, t) => {
		emitDiagnosticsTimelineEvent({
			type: "mark",
			name: "model.recovery.decision",
			runId: c.runId,
			attributes: {
				decision: e,
				reason: t,
				replaySafe: M,
				allToolCallsRecorded: P.allToolCallsRecorded,
				allToolsProvenSettled: P.allToolsProvenSettled,
				parkedCodeModeRun: P.parkedCodeModeRun,
				intentionalTermination: P.intentionalTermination
			}
		}, { config: c.config });
	};
	const I = hasAsyncActivity(u.toolMetas);
	const L = !P.intentionalTermination && !I && !u.didSendDeterministicApprovalPrompt;
	const R = m ?? f;
	const z = R?.stopReason === "length" && !isCompactionReplayCheckpoint(R.providerReplay) && R.content.length === 0 && !isContextOverflow(R, l.contextTokenBudget) && !u.lastToolError && !hasAttemptTerminalState(u) && !hasComposedVisibleAnswerAfterSettledTools(u);
	const B = z && resolveSourceReplyDelivery(u, await observeReplyDelivery(c.resolveReplyDelivery, (u.answerSegments?.at(-1)?.messageEnd ?? -1) + 1, (e) => log$3.warn(`reply delivery observation failed; retaining custody: ${formatErrorMessage(e)}`))) === "missing";
	if (z) t.laneController.throwIfAborted();
	const V = Boolean(R && (isResponsesOutputLimitToolCallError(R) || B));
	const H = c.modelRun !== true && c.promptMode !== "none" && !l.pluginHarnessOwnsTransport && !j && !w && (M || P.allToolsProvenSettled) && u.itemLifecycle.activeCount === 0 && L;
	const U = A && P.allToolsProvenSettled && L;
	const W = P.allToolsProvenSettled || P.parkedCodeModeRun;
	const G = N && W && !I;
	const K = !l.pluginHarnessOwnsTransport && !j && (!w || T === "prompt") && P.allToolsProvenSettled && L && !u.yieldDetected && !u.clientToolCalls;
	const { signalOwnedInterruption: q } = h;
	const J = R?.stopReason === "error" || R?.stopReason === "length" ? R : void 0;
	const retry = (t) => ({
		action: "retry",
		authRetryPending: t?.authRetryPending ?? false,
		codexAppServerRecoveryRetries: t?.codexAppServerRecoveryRetries ?? e.codexAppServerRecoveryRetries,
		lastRetryFailoverReason: t?.lastRetryFailoverReason === void 0 ? e.lastRetryFailoverReason : t.lastRetryFailoverReason,
		thinkLevel: t?.thinkLevel ?? l.thinkLevel
	});
	const buildAttemptErrorMeta = () => buildErrorAgentMeta({
		sessionId: d,
		sessionFile: a.sessionFile,
		provider: n.provider,
		model: n.model.id,
		credentialSource: u.modelAttempt?.credentialSource,
		...l.outerContextTokenMeta,
		usageAccumulator: e.usageAccumulator,
		lastRunPromptUsage: e.lastRunPromptUsage,
		currentAttemptAssistant: p
	});
	const completeBlocked = (e, n, r = n, i) => {
		const a = v();
		g({
			replayInvalid: a,
			livenessState: "blocked"
		});
		return {
			action: "complete",
			result: buildEmbeddedRunBlockedResult({
				text: r,
				errorKind: e,
				errorMessage: n,
				durationMs: Date.now() - t.startedAtMs,
				agentMeta: buildAttemptErrorMeta(),
				attempt: u,
				replayInvalid: a,
				finalPromptText: i
			})
		};
	};
	if (T === "hook:before_agent_run" && !j) {
		recordRecoveryDecision("rejected", "hook_block");
		return completeBlocked("hook_block", formatErrorMessage(w));
	}
	const Y = await shouldSwitchToLiveModel({
		cfg: c.config,
		sessionPersistence: c.sessionPersistence,
		sessionKey: t.resolvedSessionKey,
		agentId: c.agentId,
		defaultProvider: DEFAULT_PROVIDER,
		defaultModel: DEFAULT_MODEL,
		currentProvider: n.provider,
		currentModel: n.modelId,
		currentAgentRuntimeOverride: c.agentHarnessRuntimeOverride,
		currentAuthProfileId: n.preferredProfileId,
		currentAuthProfileIdSource: c.authProfileIdSource
	});
	if (M && !q && Y && b) {
		await clearLiveModelSwitchPending({
			cfg: c.config,
			sessionKey: t.resolvedSessionKey,
			agentId: c.agentId,
			defaultProvider: DEFAULT_PROVIDER,
			defaultModel: DEFAULT_MODEL,
			expectedSelection: Y
		});
		log$3.info(`live session model switch requested during active attempt for ${c.sessionId}: ${n.provider}/${n.modelId} -> ${Y.provider}/${Y.model}`);
		recordRecoveryDecision("accepted", "live_model_switch");
		throw new LiveSessionModelSwitchError(Y);
	}
	const X = f?.stopReason === "error" ? buildAssistantFailoverSignal(f) : void 0;
	const ee = X ? classifyFailoverSignal(X, { providerPlugin: l.providerRuntimeHandle?.plugin }) : null;
	const te = J === f ? ee : J?.stopReason === "error" ? classifyFailoverSignal(buildAssistantFailoverSignal(J), { providerPlugin: l.providerRuntimeHandle?.plugin }) : null;
	const Z = w ? resolveFailoverClassificationFromError(w, n.provider) : ee;
	const ne = f?.diagnostics?.some((e) => e.type === "provider_transport_failure");
	const re = w ? failoverReasonFromClassification(Z) : ee?.kind === "reason" ? ee.reason : A || f && isRetryableAssistantError(f) && ne ? "timeout" : null;
	const ie = resolveCompactionLiveModelSelection({
		current: {
			provider: n.provider,
			model: n.modelId,
			authProfileId: l.lastProfileId,
			authProfileIdSource: c.authProfileBinding ? c.authProfileIdSource ?? "auto" : l.lastProfileId && l.lastProfileId === n.lockedProfileId ? "user" : "auto"
		},
		requested: M ? Y : void 0
	});
	const ae = {
		runInput: t,
		runParams: c,
		state: e.contextRecoveryState,
		contextEngine: e.contextEngine,
		contextTokenBudget: l.contextTokenBudget,
		genericCompactionRecoveryAllowed: n.genericCompactionRecoveryAllowed,
		attempt: u,
		runtimeAuthPlan: i.auth,
		resolvedSessionKey: t.resolvedSessionKey,
		sessionAgentId: e.sessionAgentId,
		contextEngineAgentId: t.contextEngineAgentId,
		agentDir: t.agentDir,
		workspaceDir: t.workspaceDir,
		modelSelection: ie,
		harnessRuntime: l.agentHarness.id,
		thinkLevel: l.thinkLevel,
		resolveContextEnginePluginId: e.resolveContextEnginePluginId,
		buildRuntimeSettings: e.buildRuntimeSettings,
		...s,
		getActiveSession: () => ({
			id: a.sessionId,
			file: a.sessionFile,
			target: a.sessionTarget
		}),
		prepareCompactedTranscriptRetry: a.prepareCompactedTranscriptRetry,
		armPostCompactionGuard: e.armPostCompactionGuard,
		usageAccumulator: e.usageAccumulator
	};
	if ((M || G) && await recoverEmbeddedRunTimeout({
		...ae,
		timedOut: E,
		signalOwnedInterruption: q,
		timedOutDuringCompaction: D,
		timedOutDuringToolExecution: O,
		timedOutByRunBudget: k,
		lastRunPromptUsage: e.lastRunPromptUsage
	})) {
		recordRecoveryDecision("accepted", "timeout_recovery");
		return retry();
	}
	const oe = V ? "output_limit" : re;
	const se = w ? getFailoverErrorCode(w) : X?.code;
	const ce = w ? formatErrorMessage(w) : X?.message;
	if (!F && !C && !h.signalOwnedInterruption && !k && !D && !O && (!j || !l.pluginHarnessOwnsTransport && (M || U)) && !u.yieldDetected && !u.clientToolCalls && !u.codexAppServerFailure && !findCliTerminalStopError(w) && (!w || T === "prompt") && !isTerminalAssistantError(f) && (!V || H) && oe && await o.maybeRetryTransient({
		reason: oe,
		sameModelRetry: Z?.kind === "reason" ? Z.sameModelRetry : void 0,
		code: se,
		message: ce,
		retryAfterMs: w ? resolveRetryAfterMs(formatErrorMessage(w), Date.now(), w) : X?.retryAfterMs,
		maxRetryDelayMs: u.providerRetryMaxDelayMs,
		failoverEligible: M,
		onRetry: async ({ attempt: e, maxRetries: t, delayMs: n, reason: r }) => {
			const i = {
				stream: "run_status",
				data: {
					phase: "retrying",
					message: r === "rate_limit" ? `Waiting for rate limit… ${Math.ceil(n / 1e3)}s (attempt ${e + 1}/${t + 1}).` : r === "output_limit" ? `Retrying… ${e + 1}/${t + 1}` : `Provider temporarily unavailable. Retrying in ${Math.ceil(n / 1e3)}s (${e}/${t}).`,
					retryAttempt: e,
					maxRetries: t,
					delayMs: n,
					retryAt: Date.now() + n,
					attempt: e + 1,
					maxAttempts: t + 1,
					reason: r
				}
			};
			emitAgentEvent({
				runId: c.runId,
				sessionKey: c.sessionKey,
				...i
			});
			await c.onAgentEvent?.(i);
		}
	})) {
		t.laneController.throwIfAborted();
		if (ne || isTransientNetworkError(w ?? {
			code: se,
			message: ce
		})) {
			await n.refreshTransportForConnectionError();
			t.laneController.throwIfAborted();
		}
		if (V) {
			a.markOwnedTranscriptRetry();
			await a.settleOwnedTranscriptProjection(a.sessionTarget, c.abortSignal);
			t.laneController.throwIfAborted();
			const e = (R?.diagnostics?.find((e) => e.type === "openai_responses_terminal")?.details)?.incompleteToolCallId;
			await a.withSessionWriterContext(() => a.recordOutputLimitNotice(typeof e === "string" ? e : void 0));
			t.laneController.throwIfAborted();
		}
		const r = !l.pluginHarnessOwnsTransport && !w && !V && f?.stopReason === "error" && f.content.length === 0 && (M || P.allToolsProvenSettled) && u.itemLifecycle.activeCount === 0 && L;
		a.markOwnedTranscriptRetry();
		a.continueFromCurrentTranscript({
			includeToolFailureInstruction: Boolean(u.lastToolError),
			messages: l.pluginHarnessOwnsTransport ? u.messagesSnapshot : void 0,
			...r ? { replayCurrentUserTurn: true } : {}
		});
		recordRecoveryDecision("accepted", "transient_retry");
		return retry({ lastRetryFailoverReason: V ? e.lastRetryFailoverReason : re });
	}
	if (!F && !M && !G && !K) {
		recordRecoveryDecision("rejected", "replay_unsafe");
		return { action: "proceed" };
	}
	const le = await recoverEmbeddedRunOverflow({
		...ae,
		aborted: S,
		signalOwnedInterruption: q,
		promptError: w,
		assistantErrorText: m !== void 0 ? J?.errorMessage : y,
		assistantOverflowCandidate: J ? {
			message: J,
			classification: te
		} : void 0,
		attemptCompactionCount: _,
		prepareCurrentTranscriptRetry: a.continueFromCurrentTranscript,
		markOwnedTranscriptRetry: a.markOwnedTranscriptRetry
	});
	if (le.action === "retry") {
		recordRecoveryDecision("accepted", F ? "boundary_maintenance" : "overflow_recovery");
		return retry();
	}
	if (le.action === "surface") {
		recordRecoveryDecision("rejected", "overflow_unrecoverable");
		return completeBlocked(le.kind, le.errorText, le.userText, u.finalPromptText);
	}
	if (!M) {
		recordRecoveryDecision("rejected", "replay_unsafe");
		return { action: "proceed" };
	}
	const Q = Boolean(u.codexAppServerFailure && (u.promptTimeoutOutcome || isEmbeddedRunTimeoutFinal(u)));
	if (w && T !== "compaction" && u.codexAppServerFailure) {
		if (resolveCodexAppServerRecoveryRetry({
			attempt: u,
			retryAvailable: e.codexAppServerRecoveryRetryAvailable
		}).retry) {
			t.laneController.throwIfAborted();
			a.suppressNextUserMessagePersistence = true;
			log$3.warn(`codex app-server replay-safe failure; retrying once failureKind=${u.codexAppServerFailure?.kind} runId=${c.runId} sessionId=${c.sessionId}`);
			recordRecoveryDecision("accepted", "harness_retry");
			return retry({ codexAppServerRecoveryRetries: e.codexAppServerRecoveryRetries + 1 });
		}
		if (!Q) {
			recordRecoveryDecision("rejected", "harness_retry_unavailable");
			throw toErrorObject(w, "Prompt failed");
		}
	}
	if (w && !j && T !== "compaction" && !Q) {
		const i = await handleEmbeddedPromptFailure({
			runInput: t,
			preparedRuntime: n,
			normalizedAttempt: r,
			runtime: l,
			terminal: x,
			suspensionSessionId: a.sessionId ?? c.sessionId,
			runtimeAuthRetry: e.runtimeAuthRetry,
			buildErrorAgentMeta: buildAttemptErrorMeta,
			failover: o,
			rateLimitRetriesExhausted: o.rateLimitRetriesExhausted,
			getThinkLevel: () => n.snapshot().thinkLevel,
			traceAttempts: e.traceAttempts,
			previousRetryFailoverReason: e.lastRetryFailoverReason
		});
		if (i.action === "complete") {
			recordRecoveryDecision("rejected", "prompt_failure");
			return {
				action: "complete",
				result: i.result
			};
		}
		n.setThinkLevel(i.thinkLevel);
		recordRecoveryDecision("accepted", "prompt_recovery");
		return retry({
			authRetryPending: i.authRetryPending,
			lastRetryFailoverReason: i.lastRetryFailoverReason,
			thinkLevel: i.thinkLevel
		});
	}
	recordRecoveryDecision("rejected", "no_recovery");
	return { action: "proceed" };
}
//#endregion
//#region src/agents/embedded-agent-runner/run/context-recovery-state.ts
function createEmbeddedRunContextRecoveryState() {
	let e;
	const t = {
		autoCompactionCount: 0,
		compactionRequestBudget: void 0,
		lastCompactionTokensAfter: void 0,
		currentContextSnapshot: void 0,
		lastContextBudgetStatus: void 0,
		overflowCompactionAttempts: 0,
		timeoutCompactionAttempts: 0,
		toolResultTruncationAttempted: false,
		observeContextAccounting(e) {
			const n = e.kind === "compaction" ? e.tokensAfter : e.contextTokens;
			t.currentContextSnapshot = { tokens: n };
			if (e.kind === "compaction") {
				t.autoCompactionCount += 1;
				t.lastCompactionTokensAfter = n;
			} else if (e.successful) {
				t.overflowCompactionAttempts = 0;
				t.toolResultTruncationAttempted = false;
			}
		},
		retainTimeoutRecoveryMarker(t) {
			e = t;
		},
		restoreTimeoutRecoveryAbandonment() {
			const t = e;
			e = void 0;
			return t ? restoreEmbeddedRunTimeoutAbandonment(t) : false;
		},
		beginAttempt(e, n) {
			let r = true;
			const i = {
				recordedCompactionCount: 0,
				onCompactionRequestBudget: (i) => {
					if (!r || e?.aborted) return;
					t.compactionRequestBudget = i;
					n?.(i);
				},
				onContextAccountingEvent: (e) => {
					if (e.kind === "compaction") i.recordedCompactionCount += 1;
					t.observeContextAccounting(e);
				},
				close() {
					r = false;
				}
			};
			t.compactionRequestBudget = void 0;
			n?.(void 0);
			return i;
		}
	};
	return t;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/failover-retry-controller.ts
const MAX_TRANSIENT_RETRIES = 8;
const MAX_OUTPUT_LIMIT_RETRIES = 1;
const MAX_TRANSIENT_RETRY_TIME_MS = 9e4;
const TRANSIENT_RETRY_BASE_DELAY_MS = 1e3;
const TRANSIENT_RETRY_MAX_DELAY_MS = 3e4;
const RATE_LIMIT_RETRY_MAX_DELAY_MS = 6e4;
const SHARED_TPM_FALLBACK_MAX_RETRIES = 2;
const SHARED_TPM_FALLBACK_RETRY_TIME_MS = 15e3;
function resolveTransientRetryDelayMs(e) {
	const t = e.elapsedMs === void 0 ? Infinity : (e.maxElapsedMs ?? MAX_TRANSIENT_RETRY_TIME_MS) - Math.max(0, e.elapsedMs);
	if (t <= 0 || e.retryAfterMs === Infinity) return;
	const n = e.rateLimit ? RATE_LIMIT_RETRY_MAX_DELAY_MS : TRANSIENT_RETRY_MAX_DELAY_MS;
	const r = Math.min(n, TRANSIENT_RETRY_BASE_DELAY_MS * 2 ** Math.max(0, e.retryNumber - 1));
	const i = Math.min(n, Math.round(r * (.5 + Math.random())));
	const a = Number.isFinite(e.retryAfterMs) ? Math.max(0, Math.ceil(e.retryAfterMs ?? 0)) : 0;
	const o = Math.max(i, a);
	return o <= t ? o : void 0;
}
const MAX_OVERLOAD_PROFILE_ROTATIONS = 1;
const MAX_RATE_LIMIT_PROFILE_ROTATIONS = 1;
const RETRY_SLEEP_CHUNK_MS = 864e5;
function createEmbeddedRunFailoverRetryController(e) {
	const { runInput: t, preparedRuntime: n } = e;
	const { runParams: r, globalLane: i, agentDir: a, fallbackConfigured: o } = t;
	const s = o ? monotonicNow() - (Date.now() - t.startedAtMs) : 0;
	const { provider: c, modelId: l } = n;
	const u = n.advanceAttemptAuthProfile;
	let d = 0;
	let f = 0;
	let p = 0;
	let m = false;
	let h = false;
	let g;
	let _ = false;
	let v;
	let y = null;
	const resolveProfileFailureReason = (e, t) => resolveAuthProfileFailureReason({
		failoverReason: e,
		providerStarted: t?.providerStarted,
		transientRateLimit: t?.transientRateLimit,
		policy: r.authProfileFailurePolicy
	});
	const maybeMarkAuthProfileFailure = async (e) => {
		const { profileId: t, reason: i } = e;
		if (n.snapshot().pluginHarnessOwnsTransport && (i === "auth" || i === "auth_permanent")) revokeRuntimeAuthMaterializations({
			agentDir: a,
			provider: c,
			runtimeOwnerId: n.snapshot().agentHarness.id
		});
		if (r.authProfileStateMode === "read-only" || !i) return;
		if (n.snapshot().pluginHarnessOwnsTransport && i === "timeout") return;
		const o = {
			store: n.profileFailureStore,
			reason: i,
			cfg: n.snapshot().transportConfig ?? r.config,
			agentDir: a,
			runId: r.runId,
			modelId: e.modelId,
			retryAfterMs: e.retryAfterMs
		};
		if (t) {
			await markAuthProfileFailure({
				...o,
				profileId: t
			});
			return;
		}
		const s = n.getApiKeyInfo();
		if (s?.mode !== "api-key" || !isConfigBackedInlineProviderApiKey({
			cfg: n.snapshot().transportConfig ?? r.config,
			provider: c,
			source: s.source,
			store: n.profileFailureStore
		})) return;
		await markInlineProviderApiKeyFailure({
			...o,
			provider: c
		});
	};
	const advanceRateLimitAuthProfile = async (t) => {
		if (h) return false;
		if (d >= MAX_RATE_LIMIT_PROFILE_ROTATIONS && o) {
			const r = resolveFailoverStatus("rate_limit");
			log$3.warn(`rate-limit profile rotation cap reached for ${sanitizeForLog(c)}/${sanitizeForLog(l)} after ${d} rotations; escalating to model fallback`);
			t.logFallbackDecision("fallback_model", { status: r });
			throw new FailoverError(renderRateLimitRetryExhaustion(v) ?? "The AI service is temporarily rate-limited. Please try again in a moment.", {
				reason: "rate_limit",
				rateLimitRetriesExhausted: v,
				provider: t.failoverProvider,
				model: t.failoverModel,
				profileId: n.snapshot().lastProfileId,
				sessionId: e.getSessionId(),
				lane: i,
				status: r
			});
		}
		const r = await n.advanceAttemptAuthProfile();
		if (r) d += 1;
		return r;
	};
	return {
		overloadProfileRotationLimit: MAX_OVERLOAD_PROFILE_ROTATIONS,
		get transientRetryCount() {
			return f;
		},
		get rateLimitRetriesExhausted() {
			return v;
		},
		get sharedTpmRetryDeadline() {
			return h && y !== null ? y + SHARED_TPM_FALLBACK_RETRY_TIME_MS : void 0;
		},
		observeAttempt: (e) => {
			g = e.providerRetryMaxRetries;
			_ = e.providerRequestTimeoutExplicit === true;
			v = void 0;
			if (e.hasSuccessfulModelResponse) {
				f = 0;
				m = false;
				h = false;
				y = null;
			}
		},
		advanceAuthProfile: (e, t) => {
			if (r.retryTransientErrors === false && (e === "rate_limit" || e === "overloaded" || e === "server_error" || e === "timeout")) return Promise.resolve(false);
			return e === "rate_limit" ? advanceRateLimitAuthProfile(t) : u();
		},
		maybeMarkAuthProfileFailure,
		resolveAuthProfileFailureReason: resolveProfileFailureReason,
		recoverThrownHarnessAuthFailure: async (e) => {
			if (!n.snapshot().pluginHarnessOwnsTransport) return null;
			const t = resolveFailoverReasonFromError(e, c);
			if (t !== "auth" && t !== "auth_permanent") return null;
			const i = n.snapshot().lastProfileId;
			const a = resolveProfileFailureReason(t);
			const o = r.authProfileIdSource === "user" && i === r.authProfileId ? false : await n.advanceAttemptAuthProfile();
			try {
				await maybeMarkAuthProfileFailure({
					profileId: i,
					reason: a,
					modelId: l
				});
			} catch (e) {
				log$3.warn(`profile failure mark failed: ${String(e)}`);
			}
			return o ? {
				provider: c,
				model: l,
				result: "rotate_profile",
				reason: t,
				stage: "prompt"
			} : null;
		},
		maybeRetryTransient: async (t) => {
			r.abortSignal?.throwIfAborted();
			v = void 0;
			const recordDecision = (e, t) => emitDiagnosticsTimelineEvent({
				type: "mark",
				name: "model.retry.decision",
				runId: r.runId,
				attributes: {
					decision: e,
					reason: t,
					retryCount: f
				}
			}, { config: r.config });
			if (r.retryTransientErrors === false && t.reason !== "output_limit") {
				recordDecision("rejected", "transient_retry_disabled");
				return false;
			}
			if (r.retryConnectionErrors === false && t.code !== void 0 && [
				"ECONNREFUSED",
				"ENOTFOUND",
				"EHOSTUNREACH",
				"ENETUNREACH"
			].includes(t.code)) {
				recordDecision("rejected", "connection_retry_disabled");
				return false;
			}
			if (t.reason !== "rate_limit" && t.reason !== "overloaded" && t.reason !== "server_error" && t.reason !== "timeout" && t.reason !== "output_limit") {
				recordDecision("rejected", "non_transient");
				return false;
			}
			const i = t.reason === "rate_limit";
			h = i && o && r.isFinalFallbackAttempt !== true && t.failoverEligible !== false && (h || hasOrganizationTpmRateLimitEvidence(t.message));
			if (i && hasLongWindowRateLimitEvidence(t.message)) {
				recordDecision("rejected", "long_window_rate_limit");
				return false;
			}
			if (t.sameModelRetry === false) {
				recordDecision("rejected", "non_transient");
				return false;
			}
			const a = t.maxRetryDelayMs !== void 0 && Number.isFinite(t.maxRetryDelayMs) && t.maxRetryDelayMs > 0 ? t.maxRetryDelayMs : void 0;
			if (i && a !== void 0 && t.retryAfterMs !== void 0 && t.retryAfterMs > a) {
				recordDecision("rejected", "retry_delay_exceeds_cap");
				log$3.warn(`rate-limit retry floor ${t.retryAfterMs === Infinity ? "exceeds representable time" : `${t.retryAfterMs}ms`} exceeds retry.provider.maxRetryDelayMs=${a} for ${sanitizeForLog(c)}/${sanitizeForLog(l)}; ${t.failoverEligible === false ? "ending replay-unsafe attempt" : "failing over"}`);
				return false;
			}
			m ||= i;
			const u = f;
			const d = Math.min(g ?? (i ? 15 : MAX_TRANSIENT_RETRIES), m ? 15 : Infinity, h ? SHARED_TPM_FALLBACK_MAX_RETRIES : Infinity);
			if (u >= d || t.reason === "output_limit" && p >= MAX_OUTPUT_LIMIT_RETRIES) {
				if (i) v = d === 0 ? 0 : u;
				recordDecision("rejected", "retry_budget_exhausted");
				log$3.error("same-model retries exhausted", {
					provider: c,
					model: l,
					reason: t.reason,
					retries: u,
					runId: r.runId
				});
				return false;
			}
			const b = monotonicNow();
			const x = y ?? b;
			if (t.reason !== "output_limit") y = x;
			const S = resolveTransientRetryDelayMs({
				retryNumber: u + 1,
				retryAfterMs: t.retryAfterMs,
				rateLimit: i,
				maxElapsedMs: h ? SHARED_TPM_FALLBACK_RETRY_TIME_MS : void 0,
				elapsedMs: i && !h || t.reason === "output_limit" ? void 0 : b - x
			});
			const C = o && r.isFinalFallbackAttempt !== true && t.failoverEligible !== false && t.reason !== "output_limit" && g === void 0 && !_ && !n.snapshot().pluginHarnessOwnsTransport && r.timeoutMs > 0 && r.timeoutMs < 2147e6 ? r.timeoutMs / 2 - (b - s) : Infinity;
			if (S === void 0 || S >= C) {
				recordDecision("rejected", "retry_delay_unavailable");
				log$3.warn(`transient retry ${t.retryAfterMs === Infinity ? "floor exceeds representable time" : "window elapsed"} for ${sanitizeForLog(c)}/${sanitizeForLog(l)} after ${f}/${d} retries; stopping same-model retries`);
				return false;
			}
			if (i) try {
				await maybeMarkAuthProfileFailure({
					profileId: n.snapshot().lastProfileId,
					reason: resolveProfileFailureReason("rate_limit", { transientRateLimit: true }),
					modelId: l,
					retryAfterMs: t.retryAfterMs
				});
			} catch (e) {
				log$3.warn(`profile failure mark failed: ${String(e)}`);
			}
			r.abortSignal?.throwIfAborted();
			const w = t.reason === "output_limit";
			const T = (w ? p : u) + 1;
			const E = w ? Math.min(d, MAX_OUTPUT_LIMIT_RETRIES) : d;
			if (w || log$3.isEnabled("debug")) log$3[w ? "warn" : "debug"](`${w ? "output-limit continuation" : "transient same-model retry"} ${T}/${E} for ${sanitizeForLog(c)}/${sanitizeForLog(l)} reason=${t.reason}: delayMs=${S} runId=${JSON.stringify(r.runId)} sessionId=${JSON.stringify(e.getSessionId())}`);
			try {
				await t.onRetry?.({
					attempt: T,
					maxRetries: E,
					delayMs: S,
					reason: t.reason
				});
			} catch {
				log$3.warn("transient retry status callback failed; continuing retry");
			}
			r.abortSignal?.throwIfAborted();
			const D = r.onRetryWait?.(Date.now() + S, r.abortSignal, i ? { rateLimitStopMessage: renderRateLimitRecoveryStopped(u) } : void 0);
			let O = false;
			try {
				let e = S;
				while (e > 0) {
					const t = Math.min(e, RETRY_SLEEP_CHUNK_MS);
					try {
						await sleepWithAbort(t, r.abortSignal);
					} catch (e) {
						r.abortSignal?.throwIfAborted();
						throw e;
					}
					e -= t;
				}
				O = true;
			} finally {
				if (!O) recordDecision("rejected", "wait_interrupted");
				D?.(O);
			}
			recordDecision("accepted", "backoff_completed");
			f += 1;
			if (t.reason === "output_limit") p += 1;
			return true;
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/provider-review-run.ts
/** Owns review admission, one physical attempt, and refusal recording for the logical run. */
function createProviderReviewRun(e) {
	const { run: t, runtime: n, session: r } = e;
	const i = t.runParams;
	const a = i.providerReviewAcknowledgment;
	function stop(e) {
		recordModelFallbackStop(e);
		throw e;
	}
	const target = (n) => {
		const i = r.sessionTarget;
		if (!i?.agentId || !i.sessionKey || !i.storePath || !e.assertCurrent) return stop(/* @__PURE__ */ new Error("Provider precaution requires current run authority and session identity"));
		return {
			agentId: i.agentId,
			sessionKey: i.sessionKey,
			storePath: i.storePath,
			sessionId: n,
			lifecycleRevision: r.sessionWriterFence?.expectedLifecycleRevision ?? t.sessionAdmission?.entry.lifecycleRevision
		};
	};
	const assertCurrent = () => {
		if (!e.assertCurrent) stop(/* @__PURE__ */ new Error("Provider precaution requires current run authority"));
		e.assertCurrent();
	};
	const failure = (e) => {
		if (!a) return;
		let t = e instanceof Error ? e : e === void 0 ? void 0 : new Error("Provider continuation failed", { cause: e });
		try {
			readProviderReviewAcknowledgment(a);
		} catch (e) {
			t ??= new Error("Provider continuation stopped; review the current findings before trying again", { cause: e });
		}
		if (t) stop(t);
	};
	return {
		async admit() {
			const e = t.sessionAdmission?.entry;
			const o = e?.providerReview && resolveSessionWorkStartError(t.resolvedSessionKey, e, {
				providerReviewAcknowledgment: a,
				runId: i.runId
			});
			if (o) stop(new Error(o));
			if (!a) return;
			const s = n.snapshot();
			try {
				await assertSessionProviderReviewWorkStart({
					target: target(r.sessionId),
					acknowledgment: a,
					runId: i.runId,
					provider: n.provider,
					model: n.modelId,
					runtimeId: s.agentHarness.id,
					api: s.effectiveModel.api,
					assertCurrent
				});
			} catch (e) {
				stop(new Error("Provider review continuation is no longer admitted", { cause: e }));
			}
		},
		beginAttempt() {
			if (a) try {
				claimProviderReviewAttempt(a, i.runId);
			} catch (e) {
				stop(new Error("Provider review continuation cannot start another attempt", { cause: e }));
			}
		},
		failure,
		async settle(e) {
			const t = e.currentAttemptCompletedAssistant ?? e.currentAttemptAssistant;
			const o = resolveProviderRefusal(t);
			if (o?.category === "misalignment" && t?.stopReason === "error" && i.sessionPersistence !== "detached") {
				const t = target(e.sessionIdUsed);
				const a = n.snapshot();
				try {
					const s = {
						target: t,
						refusal: {
							runId: i.runId,
							...e.runtimeModelSelection ?? {
								provider: n.provider,
								model: n.modelId
							},
							runtimeId: a.agentHarness.id,
							api: a.effectiveModel.api,
							review: o.review,
							nativeThreadId: o.nativeThreadId,
							nativeTurnId: o.nativeTurnId
						},
						assertCurrent
					};
					if (isIncognitoSessionKey(t.sessionKey)) captureAgentRunProviderReview({
						runId: i.runId,
						target: t,
						review: createSessionProviderReview({
							sessionId: t.sessionId,
							refusal: s.refusal
						}),
						expectedWriterRunId: r.sessionWriterFence?.expectedWriterRunId ?? i.runId,
						assertCurrent
					});
					else await recordSessionProviderReview(s);
					assertCurrent();
				} catch (e) {
					stop(new Error("The provider paused this session, but its findings could not be saved", { cause: e }));
				} finally {
					try {
						const { clearSessionQueues: n } = await import("./cleanup-9UV9K0EX.mjs");
						const { getExistingFollowupQueue: r } = await import("./state-BGjelZzI.mjs");
						assertCurrent();
						const i = [t.sessionKey, e.sessionIdUsed];
						const a = captureSessionTarget({
							storeScope: t.storePath,
							sessionKey: t.sessionKey,
							aliases: i,
							agentId: t.agentId,
							incarnation: t.sessionId
						});
						n(i, a, [...new Set(i.flatMap((e) => r(e, a)?.entries.filter((e) => !e.claim || e.claim.released) ?? []))]);
					} catch (e) {
						stop(new Error("Provider precaution queue settlement did not complete", { cause: e }));
					}
				}
			}
			if (a) {
				const n = resolveEmbeddedRunAttemptTerminalOutcome({
					attempt: e,
					assistant: t,
					abortSignal: i.abortSignal
				});
				const r = classifyAgentRunTerminalOutcome(n);
				const a = r === "success" ? void 0 : i.abortSignal?.aborted && i.abortSignal.reason instanceof Error ? i.abortSignal.reason : r === "cancellation" ? createAgentRunDirectAbortError() : r === "timeout" ? new FailoverError(n.error ?? "Provider continuation timed out", {
					reason: "timeout",
					timeout: {
						timeoutPhase: n.timeoutPhase,
						providerStarted: n.providerStarted
					}
				}) : /* @__PURE__ */ new Error("Provider continuation failed; review its result before trying again");
				failure(a);
			}
			return o;
		},
		finish(e) {
			return a ? {
				...e,
				meta: {
					...e.meta,
					modelFallbackStopReason: e.meta.modelFallbackStopReason ?? "provider_review_continuation"
				}
			} : e;
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/retry-budget.ts
function createRunRetryBudget(e) {
	return {
		attemptsDispatched: 0,
		attemptsCounted: 0,
		maxAttempts: e
	};
}
function isRunRetryBudgetExhausted(e) {
	return e.attemptsCounted >= e.maxAttempts;
}
function beginRunAttempt(e) {
	e.attemptsDispatched += 1;
	e.attemptsCounted += 1;
}
function recordRunModelProgress(e) {
	e.attemptsCounted = 1;
}
function recordRunRetry(e, t) {
	if (t === "progress_continuation") e.attemptsCounted = Math.max(0, e.attemptsCounted - 1);
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-continuation-retry.ts
/** Capture one native owner's admitted local settings before execution, then project once. */
function createAttemptContinuationRetryCount(e, t, n, r) {
	let i;
	let a;
	const prepareContinuationRetryCount = ({ cwd: o }) => {
		r();
		if (a !== void 0) {
			if (a !== o) throw new Error("Native execution cwd changed after continuation retry preparation");
			return;
		}
		i = prepareAgentProviderRetryCount({
			...n,
			cwd: o,
			cfg: e.config,
			pluginMetadataSnapshot: t.pluginMetadataSnapshot
		});
		a = o;
	};
	return {
		capability: t.pluginHarnessOwnsTransport ? { prepareContinuationRetryCount } : {},
		applyTo: (e) => {
			if (i !== void 0) e.providerRetryMaxRetries = i;
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-gateway-tools.ts
/** Prepare Gateway tools once at the shared dispatch boundary, including internal continuations. */
function withPreparedEmbeddedGatewayTools(e, t) {
	const n = createAdmittedGatewayToolCallerIdentity({
		admittedRunContext: e.admittedRunContext,
		cronAuthorityCheck: e.cronCreatorAuthorityCapability?.isCurrent,
		agentId: e.agentId,
		sessionKey: e.sessionKey,
		turnSourceChannel: e.messageChannel ?? e.messageProvider,
		turnSourceLocal: !e.messageChannel && !e.messageProvider && e.cronCreatorAuthorityCapability?.callerOrigin.kind === "local" || void 0,
		turnSourceTo: e.currentMessagingTarget ?? e.currentChannelId,
		turnSourceAccountId: e.agentAccountId,
		turnSourceThreadId: e.currentThreadTs
	});
	return withGatewayToolCallerIdentity(n, () => {
		const n = getGatewayContextResolver(e.admittedRunContext)?.();
		if (!e.disableTools && e.sessionPersistence !== "detached" && agentHarnessExposesOpenClawTools(e.agentHarnessId) && n && !n.localEmbedded) e.githubPublicationAvailable = true;
		return t();
	});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-trajectory.ts
async function prepareEmbeddedHarnessTrajectory(e) {
	const { attempt: t } = e;
	const n = resolveAttemptTrajectoryAttribution(e);
	if (e.harnessId !== "codex" || t.disableTrajectory || t.sessionPersistence === "detached") return;
	return await createTrajectoryRuntimeRecorder({
		cfg: t.config,
		env: process.env,
		runId: t.runId,
		sessionId: e.sessionId,
		sessionKey: e.sessionKey,
		sessionFile: e.sessionFile,
		...projectTrajectorySessionTarget(e.sessionTarget, true),
		provider: n.provider,
		modelId: n.modelId,
		modelApi: n.modelApi,
		workspaceDir: e.workspaceDir
	});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-store.ts
function resolveAttemptDispatchApiKey(e) {
	if (e.runtimeAuthState) return e.pluginHarnessOwnsTransport ? e.runtimeAuthState.sourceApiKey : void 0;
	return e.apiKeyInfo?.apiKey;
}
function createScopedAuthProfileStore(e, t) {
	const n = e.profiles ?? {};
	const r = t.map((e) => e.trim()).filter(Boolean);
	const i = Object.fromEntries(r.flatMap((e) => {
		const t = n[e];
		return t ? [[e, t]] : [];
	}));
	const filterProfiles = (e) => (e ?? []).filter((e) => i[e]);
	const a = filterProfiles(e.runtimeExternalProfileIds);
	const o = filterProfiles(e.runtimePersistedProfileIds);
	return Object.keys(i).length > 0 ? {
		version: e.version,
		profiles: i,
		...o.length > 0 ? { runtimePersistedProfileIds: o } : {},
		...a.length > 0 || e.runtimeExternalProfileIdsAuthoritative === true ? { runtimeExternalProfileIds: a } : {},
		...e.runtimeExternalProfileIdsAuthoritative === true ? { runtimeExternalProfileIdsAuthoritative: true } : {}
	} : {
		version: 1,
		profiles: {}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/backend.ts
/** Replaces backend-retained provenance with the exact prepared request fact. */
function resolveRuntimeModelAttempt(e) {
	const t = e?.auth.credentialSource;
	return t ? {
		provider: e.resolvedRef.provider,
		model: e.resolvedRef.modelId,
		credentialSource: t
	} : void 0;
}
async function runEmbeddedAttemptWithBackend(e, t, n = e.media) {
	const r = e.admittedRunContext ? resolveAdmittedRunActiveAssertion(e.admittedRunContext, e.abortSignal) : void 0;
	const i = await prepareAgentWorkspaceAttachments({
		workspaceDir: e.workspaceDir,
		turn: {
			config: e.config,
			media: n,
			timeoutMs: e.timeoutMs,
			abortSignal: e.abortSignal,
			userTurnTranscriptRecorder: e.userTurnTranscriptRecorder
		},
		assertCurrent: () => {
			if (!r) throw new Error("Workspace attachment preparation requires active admitted run authority");
			r();
			e.hostCapabilities?.assertActive();
		}
	});
	const a = n?.length ? {
		...e,
		inputAttachmentMedia: n
	} : e;
	const o = await runAgentHarnessAttempt(i ? {
		...a,
		prompt: `${e.prompt}\n\n${i}`,
		transcriptPrompt: e.transcriptPrompt ?? e.prompt
	} : a, t);
	const { modelAttempt: s, runtimeModelSelection: c, requesterContinuationSettled: l, ...u } = o;
	const d = resolveRuntimeModelAttempt(e.runtimePlan);
	const f = mergeAcceptedSessionSpawnsForRun(e.admittedRunContext.operationalRunInstance, o.acceptedSessionSpawns);
	return copyCoreTtsAttemptResultProvenance(o, {
		...u,
		...f.length ? { acceptedSessionSpawns: f } : {},
		...d ? { modelAttempt: d } : {},
		...t && c ? { runtimeModelSelection: {
			provider: c.provider,
			model: c.model
		} } : {}
	});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/terminal-retry-state.ts
function createEmbeddedRunTerminalRetryState() {
	return {
		completionCheck: {
			unfinishedPlan: false,
			checked: false
		},
		reasoningOnlyAttempts: 0,
		emptyResponseAttempts: 0,
		textToolCallAttempts: 0,
		missingAssistantAttempts: 0,
		compactionContinuationAttempts: 0,
		beforeFinalizeRevisionAttempts: 0
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/run-attempt-dispatch.ts
/** Prepares the selected runtime and dispatches an attempt under its admitted lifecycle. */
async function prepareAndDispatchEmbeddedRunAttempt(e, t) {
	try {
		var n = _usingCtx();
		const { runInput: r, preparedRuntime: i, contextEngine: a, sessionPromptState: o, terminalRetryState: s } = e;
		const c = r.runParams;
		const { workspaceResolution: l, workspaceDir: u, bootstrapWorkspaceDir: d, isCanonicalWorkspace: f, agentDir: p, resolvedSessionKey: m, resolvedToolResultFormat: h, startupStages: g, emitStartupStageSummary: _, lifecycleGeneration: v } = r;
		const { fastModeAutoOnSeconds: y, fastModeAutoProgressState: b, fastModeStartedAtMs: x, maybeAnnounceFastModeAutoOff: S, notifyExecutionPhase: C, notifyRunProgress: w, resolveAttemptFastModeParam: T } = r.progressController;
		const { createAttemptControls: E } = r.laneController;
		const { provider: D, modelId: O, requestedModelId: k, expectedHarnessArtifact: A, nativeModelOwned: j, authStorage: M, modelRegistry: N, attemptAuthProfileStore: P, lockedProfileId: F, resolveRunAttemptAuthProfileStore: I } = i;
		const L = i.snapshot();
		const R = attachModelProviderRuntimePluginHandle(L.effectiveModel, L.providerRuntimeHandle);
		c.assertModelInput?.(R);
		if (!e.startupStagesEmitted) g.mark(EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE.workspace);
		const z = o.activePrompt.override ?? resolveEmbeddedAttemptBasePrompt({
			provider: D,
			prompt: c.prompt
		});
		const B = resolveAttemptDispatchApiKey({
			apiKeyInfo: L.apiKeyInfo,
			runtimeAuthState: L.runtimeAuthState,
			pluginHarnessOwnsTransport: L.pluginHarnessOwnsTransport
		});
		const V = T();
		const H = { ...o.sessionTarget };
		const U = await resolveAttemptDispatchSessionTarget({
			agentId: l.agentId,
			config: c.config,
			sessionKey: m,
			promptState: o
		});
		await o.settleOwnedTranscriptProjection(U, c.abortSignal);
		if (!e.startupStagesEmitted) g.mark(EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE.prompt);
		const W = buildAgentRuntimePlan({
			provider: D,
			modelId: O,
			model: R,
			modelApi: R.api,
			harnessId: L.agentHarness.id,
			harnessRuntime: L.agentHarness.id,
			preparedAuthPlan: L.activePreparedAuthPlan,
			transportConfig: L.transportConfig,
			metadataSnapshot: L.pluginMetadataSnapshot,
			providerRuntimeHandle: L.providerRuntimeHandle,
			config: c.config,
			workspaceDir: u,
			agentDir: p,
			agentId: l.agentId,
			thinkingLevel: mapThinkingLevelForProvider(L.thinkLevel, R),
			extraParamsOverride: {
				...c.streamParams,
				fastMode: V
			}
		});
		if (!c.admittedRunContext) throw new Error("embedded attempt reached dispatch without an admitted run context");
		const G = c.admittedRunContext;
		const requireActiveAssertion = (e) => {
			const t = resolveAdmittedRunActiveAssertion(G, e);
			if (!t) throw new Error("embedded attempt reached dispatch without an active admitted run");
			return t;
		};
		const K = requireActiveAssertion(c.abortSignal);
		const q = await prepareEmbeddedHarnessTrajectory({
			attempt: c,
			harnessId: L.agentHarness.id,
			model: R,
			modelId: O,
			provider: D,
			runtimePlan: W,
			sessionId: o.sessionId,
			sessionKey: m,
			sessionFile: U?.sessionKey ?? o.sessionFile,
			sessionTarget: U,
			workspaceDir: u
		});
		K();
		if (!e.startupStagesEmitted) {
			g.mark(EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE.runtimePlan);
			g.mark(EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE.dispatch);
			C("attempt_dispatch", {
				provider: D,
				model: O
			});
			_(EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE.dispatch);
		}
		const J = e.resolveRuntimeFallbackReason();
		const Y = Boolean(L.lastProfileId && L.lastProfileId === F);
		recordAdmittedModelRoutingDecision({
			admittedRunContext: c.admittedRunContext,
			abortSignal: c.abortSignal,
			requestedProvider: c.modelRoutingProvenance?.requestedProvider ?? r.provider,
			requestedModel: c.modelRoutingProvenance?.requestedModel ?? k ?? r.modelId,
			selectedProvider: D,
			selectedModel: O,
			selectionMode: Y ? "explicit" : "automatic",
			credentialProfileId: L.lastProfileId,
			fallbackSelected: c.modelRoutingProvenance?.stage === "fallback" || Boolean(J),
			fallbackReason: c.modelRoutingProvenance?.fallbackReason
		});
		const { sessionId: X, sessionFile: ee, suppressNextUserMessagePersistence: te } = o;
		const Z = o.activePrompt.internal;
		const { sessionManager: ne } = c;
		const { nativeSessionRuntime: re } = i;
		const ie = I();
		const ae = Boolean(c.onSuccessfulAuthBinding || A);
		const oe = O !== k || c.modelRoutingProvenance?.stage === "fallback" || Boolean(J);
		const se = j && a?.info.id === "legacy" ? void 0 : a;
		const ce = {
			prompt: z,
			transcriptPrompt: c.transcriptPrompt
		};
		const le = c.execApprovalContinuationPromptRange;
		if (le) {
			const e = Math.max(1, Math.floor(L.contextTokenBudget ?? R.contextWindow ?? R.maxTokens ?? 2e5));
			const t = resolveLiveToolResultMaxChars({ contextWindowTokens: e });
			const resize = (e, n = le) => resizeExecApprovalContinuationPrompt({
				prompt: e,
				range: n,
				maxOutputUtf16Units: t
			});
			ce.prompt = resize(z);
			ce.transcriptPrompt = c.transcriptPrompt === void 0 ? void 0 : resize(c.transcriptPrompt, c.execApprovalContinuationTranscriptPromptRange ?? le);
			c.userTurnTranscriptRecorder?.replaceTextBeforePersistence?.(ce.transcriptPrompt ?? ce.prompt);
		}
		const Q = requireActiveAssertion(c.abortSignal);
		Q();
		if (L.pluginHarnessOwnsTransport) {
			await c.awaitSessionDiffBaseline?.();
			Q();
		}
		const ue = n.u(L.pluginHarnessOwnsTransport ? await preparePluginHarnessWorkspace({
			...c,
			agentId: l.agentId,
			cwd: void 0,
			sessionId: X,
			sessionKey: m,
			workspaceDir: u
		}) : null);
		Q();
		const de = ue?.workspace;
		const fe = createAttemptContinuationRetryCount(c, L, {
			sessionId: X,
			agentDir: p
		}, Q);
		const pe = de ? await prepareEmbeddedAttemptPromptExecution({
			attempt: {
				...c,
				model: R
			},
			mediaOwnerAgentId: de.sessionAgentId,
			effectiveFsWorkspaceOnly: de.effectiveFsWorkspaceOnly,
			effectiveWorkspace: de.effectiveWorkspace,
			prompt: "",
			sandbox: de.sandbox,
			skipPromptSubmission: false,
			pluginHarness: true
		}) : {
			images: c.images,
			imageOrder: c.imageOrder,
			media: c.media
		};
		const me = L.pluginHarnessOwnsTransport && c.finalizePromptForResolvedTools ? applyResolvedToolPromptFinalizer({
			prompt: ce.prompt,
			activeToolNames: [],
			finalize: c.finalizePromptForResolvedTools
		}) : void 0;
		const he = ue?.sandbox ?? de?.sandbox;
		if (c.permissionMode) {
			c.execOverrides ??= {};
			c.execOverrides.mode = resolveSessionPermissionExecMode({ mode: c.permissionMode });
		}
		const { extraSystemPrompt: ge, gitCoauthorPrompt: _e } = await prepareAttemptSystemPromptAdditions({
			agentId: l.agentId,
			authProfileId: L.lastProfileId,
			config: c.config,
			extraSystemPrompt: c.extraSystemPrompt,
			modelId: O,
			provider: D,
			sessionId: X,
			sessionKey: c.sessionKey,
			storePath: c.sessionTarget?.storePath,
			toolsAllow: c.toolsAllow
		});
		Q();
		const { skillsSnapshot: ve, skillReferencePaths: ye } = await preparePluginHarnessSkills({
			assertCurrent: Q,
			attempt: {
				bootstrapWorkspaceDir: d,
				config: c.config,
				contextTokenBudget: L.contextTokenBudget,
				skillsSnapshot: c.skillsSnapshot,
				toolExecutionAllow: c.toolExecutionAllow
			},
			effectiveWorkspace: u,
			sandbox: he,
			sessionAgentId: l.agentId
		});
		const be = await prepareDelegationCapability({
			fallbackActive: oe,
			run: c,
			sessionKey: m,
			sessionId: X,
			modelProvider: D,
			modelId: O
		});
		Q();
		const { memoryAudience: xe, release: Se } = await resolveEmbeddedAttemptMemoryAudience({
			run: c,
			agentId: l.agentId,
			sessionKey: m,
			sessionId: X,
			admission: r.sessionAdmission,
			assertCallerCurrent: Q
		});
		const $ = E({
			admittedRunContext: G,
			onAbort: () => c.replyOperation?.abortByUser()
		});
		const Ce = captureAgentPluginRuntimeRefresh();
		const assertTargetCurrent = () => {
			if (!$.isAttemptCurrent() || o.sessionId !== X || [
				"agentId",
				"sessionId",
				"sessionKey",
				"storePath",
				"threadId"
			].some((e) => o.sessionTarget?.[e] !== H[e])) throw new Error("Session target preparation outlived its attempt");
		};
		const we = (!ne || c.sessionPersistence === "detached") && U?.agentId && U.sessionId && U.sessionKey && U.storePath ? {
			target: captureSessionTranscriptTargetBinding({
				...U,
				agentId: U.agentId,
				sessionId: U.sessionId,
				sessionKey: U.sessionKey,
				storePath: U.storePath
			}),
			assertCurrent: composeSessionSourceAssertion([Q], (e) => {
				assertTargetCurrent();
				try {
					e();
				} catch (e) {
					throw new Error(`Session target preparation outlived its attempt: ${String(e)}`, { cause: e });
				}
				assertTargetCurrent();
				Q.assertScopeCurrent();
			})
		} : void 0;
		const Te = {
			modelCallSequence: r.modelCallSequence ??= { value: 0 },
			bindWatchdogAttempt: $.bindWatchdogAttempt,
			providerReviewAcknowledgment: c.providerReviewAcknowledgment,
			awaitSessionDiffBaseline: c.awaitSessionDiffBaseline,
			pluginRuntimeRefreshPending: Ce.stopAtStep,
			registerPluginRuntimeRefreshConsumer: (e) => {
				if ($.isCurrent()) Ce.bindConsumer(() => $.isCurrent() && e());
			},
			pluginRuntimeRefreshMessages: c.pluginRuntimeRefreshMessages,
			pluginRuntimeRefreshUserPrompt: c.pluginRuntimeRefreshUserPrompt,
			continuation: o.continuation,
			runCleanupSettlement: c.runCleanupSettlement,
			joinObservation: c.joinObservation,
			permissionChange: e.permissionChange,
			admittedRunContext: c.admittedRunContext,
			startedAtMs: r.startedAtMs,
			contextEngineAgentId: r.contextEngineAgentId,
			...L.pluginHarnessOwnsTransport ? { sandbox: he } : {},
			operation: "attempt",
			sessionId: X,
			sessionKey: m,
			memoryAudience: xe,
			conversationRecall: c.conversationRecall,
			promptCacheKey: c.promptCacheKey,
			sandboxSessionKey: c.sandboxSessionKey,
			sandboxAgentId: c.sandboxAgentId,
			trigger: c.trigger,
			terminalReplyExpectation: resolveReplyExpectation(c),
			memoryFlushWritePath: c.memoryFlushWritePath,
			memoryFlushTools: c.memoryFlushTools,
			messageChannel: c.messageChannel,
			messageProvider: c.messageProvider,
			clientCaps: c.clientCaps,
			bootstrapUserProfileId: c.bootstrapUserProfileId,
			gatewayUiCommandTarget: c.gatewayUiCommandTarget,
			pinnedWidgetAuthoring: c.pinnedWidgetAuthoring,
			toolBindings: c.toolBindings,
			chatType: c.chatType,
			agentAccountId: c.agentAccountId,
			conversationRoutePeerId: c.conversationRoutePeerId,
			messageTo: c.messageTo,
			messageThreadId: c.messageThreadId,
			conversationToolPolicy: c.conversationToolPolicy,
			messageActionTurnCapability: c.messageActionTurnCapability,
			groupId: c.groupId,
			groupChannel: c.groupChannel,
			groupSpace: c.groupSpace,
			memberRoleIds: c.memberRoleIds,
			spawnedBy: c.spawnedBy,
			isCanonicalWorkspace: f,
			...projectEmbeddedMessageContext(c),
			hasRepliedRef: c.hasRepliedRef,
			sessionFile: ee,
			...ne ? { sessionManager: ne } : { sessionTarget: U },
			preparedSessionTarget: we,
			trajectoryRecorder: q ?? void 0,
			...resolveHarnessWorkspace(u, c, de, he),
			bootstrapWorkspaceDir: d,
			permissionMode: c.permissionMode,
			requireWorkspaceOnly: c.requireWorkspaceOnly,
			agentDir: p,
			preparedModelRuntime: r.preparedModelRuntime,
			config: c.config,
			transportConfig: L.transportConfig,
			toolOverrides: c.toolOverrides,
			allowGatewaySubagentBinding: c.allowGatewaySubagentBinding,
			...se ? {
				contextEngine: se,
				contextWindowInfo: L.contextWindowInfo
			} : {},
			...L.contextTokenBudget === void 0 ? {} : { contextTokenBudget: L.contextTokenBudget },
			...L.modelContextWindow === void 0 ? {} : { modelContextWindow: L.modelContextWindow },
			...L.authoredContextTokenCap === void 0 ? {} : { authoredContextTokenCap: L.authoredContextTokenCap },
			skillsSnapshot: ve,
			prompt: remapSkillReferencePaths(me ?? ce.prompt, ye),
			transcriptPrompt: me !== void 0 && c.transcriptPrompt === void 0 ? ce.prompt : ce.transcriptPrompt,
			finalizePromptForResolvedTools: me === void 0 ? c.finalizePromptForResolvedTools : void 0,
			userTurnTranscriptRecorder: c.userTurnTranscriptRecorder,
			onContextEngineTurnCandidate: c.onContextEngineTurnCandidate,
			skipPreparedUserTurnMessage: Z,
			replayCurrentTranscript: o.activePrompt.replayCurrentTranscript,
			currentInboundEventKind: c.currentInboundEventKind,
			currentInboundContext: c.currentInboundContext,
			explicitSkillSelections: c.explicitSkillSelections?.map((e) => copyExplicitSkillSelectionFileHost(e, {
				...e,
				path: remapExplicitSkillSelectionPath(e, ye)
			})),
			images: pe.images,
			imageOrder: pe.imageOrder,
			media: pe.media,
			clientTools: c.clientTools,
			disableTools: c.disableTools,
			provider: D,
			modelId: O,
			requestedModelId: k,
			fallbackActive: oe,
			fallbackReason: J,
			delegationCapability: be,
			isFinalFallbackAttempt: c.isFinalFallbackAttempt,
			agentHarnessId: L.agentHarness.id,
			agentHarnessRuntimeOverride: L.agentHarness.id,
			modelSelectionLocked: c.modelSelectionLocked,
			...re ? { expectedSessionRuntimeOwnership: {
				model: "native",
				auth: re.auth,
				...re.auth === "host" ? { modelRef: re.modelRef } : {}
			} } : {},
			...ae ? { captureRuntimeArtifact: true } : {},
			...A?.artifact ? { expectedRuntimeArtifact: A?.artifact } : {},
			...c.sessionKey ? { agentHarnessCompletionScope: createAgentHarnessCompletionScope({
				requesterSessionKey: c.sessionKey,
				requesterAgentId: l.agentId,
				gatewayContextResolver: getGatewayContextResolver(c.admittedRunContext)
			}) } : {},
			runtimePlan: W,
			observeToolTerminal: createToolTerminalObserver(c.runId),
			model: applyAuthHeaderOverride(applyLocalNoAuthHeaderOverride(R, L.runtimeAuthState ?? L.apiKeyInfo), L.runtimeAuthState !== null ? null : L.apiKeyInfo, L.transportConfig),
			resolvedApiKey: B,
			authProfileId: L.lastProfileId,
			authProfileIdSource: c.authProfileBinding ? c.authProfileIdSource : Y ? "user" : "auto",
			authProfileBinding: c.authProfileBinding,
			initialReplayState: e.replayState,
			authStorage: M,
			authProfileStore: ie,
			toolAuthProfileStore: agentHarnessBuildsOpenClawTools(L.agentHarness.id) ? P : void 0,
			modelRegistry: N,
			agentId: l.agentId,
			thinkLevel: L.thinkLevel,
			thinkingExplicit: c.thinkingExplicit,
			cyberAccessProgram: resolveCyberAccessProgramForProvider(c.cyberAccessProgram, D).program,
			onToolOutcome: e.observeToolOutcome,
			isTurnTainted: e.isTurnTainted,
			allocateToolOutcomeOrdinal: e.allocateToolOutcomeOrdinal,
			onToolStreamBoundary: S,
			onRunProgress: w,
			fastMode: V,
			fastModeAuto: c.fastMode === "auto",
			...c.fastMode === "auto" ? {
				fastModeStartedAtMs: x,
				fastModeAutoOnSeconds: y,
				fastModeAutoProgressState: b
			} : {},
			verboseLevel: c.verboseLevel,
			reasoningLevel: c.reasoningLevel,
			toolResultFormat: h,
			toolProgressDetail: c.toolProgressDetail,
			execSession: c.execSession,
			execOverrides: c.execOverrides,
			bashElevated: c.bashElevated,
			timeoutMs: c.timeoutMs,
			runTimeoutOverrideMs: c.runTimeoutOverrideMs,
			runId: c.runId,
			lifecycleGeneration: v,
			abortSignal: $.abortSignal,
			onAttemptDeadlineChanged: $.onAttemptDeadlineChanged,
			onAttemptTimeout: $.onAttemptTimeout,
			onAttemptAbort: $.onAttemptAbort,
			onSettledTurn: t,
			replyOperation: c.replyOperation,
			shouldEmitToolResult: c.shouldEmitToolResult,
			shouldEmitToolOutput: c.shouldEmitToolOutput,
			onPartialReply: c.onPartialReply,
			onAssistantMessageStart: c.onAssistantMessageStart,
			onBlockReply: c.onBlockReply,
			onBlockReplyFlush: c.onBlockReplyFlush,
			blockReplyBreak: c.blockReplyBreak,
			blockReplyChunking: c.blockReplyChunking,
			onReasoningStream: c.onReasoningStream,
			streamReasoningInNonStreamModes: c.streamReasoningInNonStreamModes,
			onReasoningEnd: c.onReasoningEnd,
			onToolResult: c.onToolResult,
			onAgentToolResult: c.onAgentToolResult,
			onAgentEvent: async (e) => c.onAgentEvent?.(e),
			deferTerminalLifecycle: c.deferTerminalLifecycle ?? c.deferTerminalLifecycleEnd,
			onDeferredLifecycleOwner: c.onDeferredLifecycleOwner,
			onDeferredLifecycleAbort: c.onDeferredLifecycleAbort,
			onExecutionPhase: c.onExecutionPhase,
			extraSystemPrompt: ge,
			extraSystemPromptTurnContext: c.extraSystemPromptTurnContext,
			gitCoauthorPrompt: _e,
			preparedTtsPreferences: c.preparedTtsPreferences,
			sourceReplyDeliveryMode: c.sourceReplyDeliveryMode,
			messageToolFinalByDefault: c.messageToolFinalByDefault,
			silentReplyPromptMode: c.silentReplyPromptMode,
			taskSuggestionDeliveryMode: c.taskSuggestionDeliveryMode,
			inputProvenance: c.inputProvenance,
			trustedInternalHandoff: c.trustedInternalHandoff,
			scheduledToolPolicy: c.scheduledToolPolicy,
			runtimePluginToolGrant: c.runtimePluginToolGrant,
			cronCreatorAuthorityCapability: c.cronCreatorAuthorityCapability,
			cronCreatorAuthorityUnavailableReason: c.cronCreatorAuthorityUnavailableReason,
			streamParams: c.streamParams,
			modelRun: c.modelRun,
			disableTrajectory: c.disableTrajectory,
			skillWorkshopReviewOf: c.skillWorkshopReviewOf,
			skillLibraryAuthoring: c.skillLibraryAuthoring,
			promptMode: c.promptMode,
			ownerNumbers: c.ownerNumbers,
			enforceFinalTag: c.enforceFinalTag,
			silentExpected: c.silentExpected,
			suppressLiveStreamOutput: c.suppressLiveStreamOutput,
			bootstrapContextMode: c.bootstrapContextMode,
			bootstrapContextRunKind: c.bootstrapContextRunKind,
			jobId: c.jobId,
			scheduledRuntimeAuthority: c.scheduledRuntimeAuthority,
			scheduledRuntimeAuthorityRecoveryRequired: c.scheduledRuntimeAuthorityRecoveryRequired,
			toolsAllow: c.toolsAllow,
			toolExecutionAllow: c.toolExecutionAllow,
			toolAuthorityFingerprint: c.toolAuthorityFingerprint,
			sessionPersistence: c.sessionPersistence,
			compactionCountOwner: "caller",
			onContextAccountingEvent: c.onContextAccountingEvent,
			onCompactionRequestBudget: c.onCompactionRequestBudget,
			...c.systemAgentTool ? { systemAgentTool: c.systemAgentTool } : {},
			cleanupBundleMcpOnRunEnd: c.cleanupBundleMcpOnRunEnd,
			oneShotCliRun: c.oneShotCliRun,
			disableMessageTool: c.disableMessageTool,
			swarmCollector: c.swarmCollector,
			swarmOutputSchema: c.swarmOutputSchema,
			codeModeOverride: c.codeModeOverride,
			disableToolSearch: c.disableToolSearch,
			compactionForbidden: c.disableCompactionRecovery,
			sessionReadScopeKey: c.sessionReadScopeKey,
			blindPrompt: c.blindPrompt,
			forceMessageTool: c.forceMessageTool,
			requireExplicitMessageTarget: c.requireExplicitMessageTarget,
			internalEvents: c.internalEvents,
			runtimeContextFragments: c.runtimeContextFragments,
			bootstrapPromptWarningSignaturesSeen: e.bootstrapPromptWarningSignaturesSeen,
			bootstrapPromptWarningSignature: e.bootstrapPromptWarningSignaturesSeen.at(-1),
			suppressNextUserMessagePersistence: te,
			beforeAgentFinalizeRevisionAttempts: s.beforeFinalizeRevisionAttempts,
			completionCheck: s.completionCheck,
			maxBeforeAgentFinalizeRevisions: 3,
			suppressTranscriptOnlyAssistantPersistence: c.suppressTranscriptOnlyAssistantPersistence,
			assistantErrorTranscript: c.assistantErrorTranscript,
			onUserMessagePersisted: o.onUserMessagePersisted,
			onUserMessagePersistenceInvalidated: () => {
				o.activePrompt.persisted = false;
			},
			prepareAssistantTranscriptMessage: c.prepareAssistantTranscriptMessage,
			privateCompletion: c.privateCompletion,
			...fe.capability
		};
		copyChannelSourceTurnContext(Te, c);
		let Ee;
		try {
			Ee = await withPreparedEmbeddedGatewayTools(Te, () => {
				Q();
				ue?.assertCurrent();
				return runEmbeddedAttemptWithBackend(Te, re, c.media);
			});
		} catch (t) {
			throw e.getPostCompactionAbortError() ?? t;
		} finally {
			$.close();
			try {
				if (q) await flushEmbeddedAttemptTrajectoryRecorder({
					runId: c.runId,
					sessionId: X,
					trajectoryRecorder: q,
					log: log$3
				});
			} finally {
				Se();
			}
		}
		const De = e.getPostCompactionAbortError();
		if (De) throw De;
		if (de?.sandboxRuntime) Ee.sandboxRuntime = de.sandboxRuntime;
		fe.applyTo(Ee);
		return {
			dispatchedAttempt: {
				rawAttempt: Ee,
				preparedAttempt: Te
			},
			runtimePlan: W,
			startupStagesEmitted: true
		};
	} catch (e) {
		n.e = e;
	} finally {
		n.d();
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/run-settlement.ts
/** Publishes committed run accounting before retiring its runtime resources. */
async function settleEmbeddedRun(e) {
	const { runInput: t, runtime: n, compaction: r, ownedContextEngineLease: i } = e;
	const a = t.runParams;
	const o = r.session.committedCompactionSuccessor;
	const s = r.session.sessionWriterFence;
	const c = o?.sessionTarget ?? r.originalTarget;
	const l = {
		count: r.state.autoCompactionCount,
		currentContextSnapshot: r.state.currentContextSnapshot ?? (r.state.autoCompactionCount > 0 ? { tokens: void 0 } : void 0)
	};
	const u = r.durable && (o || s) && c.agentId && c.sessionId && c.sessionKey && c.storePath ? {
		kind: "durable",
		...l,
		...o?.previousSessionId !== void 0 ? { previousSessionId: o.previousSessionId } : {},
		...o ? { hostCompactionCommitted: true } : {},
		...r.session.committedCompactionTransitions.length ? { admissionTransitions: r.session.committedCompactionTransitions } : {},
		target: {
			agentId: c.agentId,
			sessionId: o?.entry.sessionId ?? c.sessionId,
			sessionKey: c.sessionKey,
			storePath: c.storePath,
			lifecycleRevision: o ? o.entry.lifecycleRevision : s?.expectedLifecycleRevision,
			activeWriterRunId: o ? o.entry.activeWriterRunId : s?.expectedWriterRunId
		}
	} : l.count > 0 || l.currentContextSnapshot ? {
		kind: "presentation-only",
		...l
	} : void 0;
	if (a.onCompactionAccounting) a.onCompactionAccounting(u);
	else if (u?.kind === "durable" && u.count > 0) try {
		await incrementCompactionCount({
			...u.target,
			expectedSession: u.target,
			amount: u.count,
			tokensAfter: u.currentContextSnapshot?.tokens,
			transcriptByteCompactionLatch: u.hostCompactionCommitted ? null : void 0,
			authorize: () => r.authority !== void 0 && getAdmittedRunDelegatedAuthority(n.admittedRunContext) === r.authority
		});
	} catch (e) {
		log$3.warn(`compaction accounting failed: ${formatErrorMessage(e)}`);
	}
	if (a.isFinalFallbackAttempt !== false) await t.progressController.maybeEmitFastModeAutoResetBestEffort();
	if (i) forgetPromptBuildDrainCacheForRun(a.runId);
	clearProviderPromptState(a.runId);
	clearBoundaryMaintenance(a.runId);
	n.stopRuntimeAuthRefreshTimer();
	await i?.dispose();
	if (a.cleanupBundleMcpOnRunEnd === true) await runAgentCleanupStep({
		runId: a.runId,
		sessionId: a.sessionId,
		step: "bundle-mcp-retire",
		log: log$3,
		cleanup: async () => {
			const onError = (e, t) => {
				recordAgentCleanupFailure();
				log$3.warn(`bundle-mcp cleanup failed after run for ${t}: ${formatErrorMessage(e)}`);
			};
			for (const e of /* @__PURE__ */ new Set([a.sessionId, r.session.sessionId])) if (e) await retireSessionMcpRuntime({
				sessionId: e,
				reason: "embedded-run-end",
				preserveActiveLeases: true,
				onError
			});
		}
	});
}
//#endregion
//#region src/agents/runtime-auth-refresh.ts
/** Clamp an auth refresh deadline to a safe setTimeout delay. */
function clampRuntimeAuthRefreshDelayMs(e) {
	return resolveSafeTimeoutDelayMs(e.refreshAt - e.now, { minMs: e.minDelayMs });
}
/** Bound caller-owned exchanges; native OAuth owners retain durable refresh settlement. */
function createRuntimeAuthDeadline(e) {
	const t = new AbortController();
	const n = e.signal ? AbortSignal.any([e.signal, t.signal]) : t.signal;
	const r = e.timeoutMs;
	const i = r < 2147e6 ? {
		kind: "bounded",
		deadlineAtMs: Date.now() + r
	} : { kind: "unlimited" };
	const withAuthDeadline = (a, o, s) => {
		const c = s ? AbortSignal.any([n, s]) : n;
		const l = e.getDeadline?.() ?? i;
		const u = l.kind === "bounded" ? l.deadlineAtMs - Date.now() : void 0;
		const expire = () => {
			const n = createAbortError(`${e.provider} ${a} timed out at the run deadline (${r}ms). Check the provider's authentication service and retry the run.`);
			t.abort(n);
			return n;
		};
		if (u !== void 0 && u <= 0) return Promise.reject(expire());
		return withTimeout(racePromiseWithAbortSignal(() => o(c), c, () => createAbortError(`${e.provider} ${a} aborted; authentication capability is closed. Retry the run when authentication is available.`)), u ?? 0, { createError: expire });
	};
	return {
		run: withAuthDeadline,
		signal: n,
		cancel: () => t.abort()
	};
}
//#endregion
//#region src/agents/auth-profiles/authorization-settle.ts
const AUTHORIZATION_SETTLE_POLL_MS = 25;
/**
* A peer's credential write (an OAuth refresh claim, then its result) leaves the shared
* authorization observation unavailable until it settles. Wait for that publication within
* the refresh-call bound instead of failing the caller; retirement and closure still throw.
* Returns whether it had to wait, so callers can discard state read before the publication.
*/
async function assertSettledAuthProfileAuthorization(e, t) {
	const n = performance.now() + OAUTH_REFRESH_CALL_TIMEOUT_MS;
	for (let r = false;; r = true) {
		try {
			e();
			return r;
		} catch (e) {
			if (!(e instanceof AuthProfileAuthorizationError) || e.code !== "MCP_AUTHORIZATION_UNAVAILABLE" || performance.now() >= n) throw e;
		}
		await sleepWithAbort(AUTHORIZATION_SETTLE_POLL_MS, t);
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-controller.request-auth.ts
/** The controller retains selection/account lifetime; native OAuth owners retain refresh settlement. */
function createEmbeddedRequestAuth(e) {
	return {
		version: 1,
		async resolve({ signal: t }) {
			const n = e.signal && t ? AbortSignal.any([e.signal, t]) : t ?? e.signal;
			const assertAdmission = () => {
				n?.throwIfAborted();
				e.assertAdmission();
			};
			const assertCurrent = () => {
				assertAdmission();
				e.assertCurrent();
			};
			const r = await e.withDeadline("credential resolution", async (t) => {
				await assertSettledAuthProfileAuthorization(assertCurrent, t);
				while (true) {
					const n = await getApiKeyForModelCore({
						model: e.model,
						cfg: e.config,
						profileId: e.profileId,
						lockedProfile: true,
						allowAuthProfileFallback: false,
						agentDir: e.agentDir,
						workspaceDir: e.workspaceDir,
						signal: t,
						assertRefreshAdmission: assertCurrent,
						validateOAuthCredential: (t) => {
							if (t.provider !== e.selected.provider || t.authFlow !== e.selected.authFlow || !isSafeToCopyOAuthIdentity(e.selected, t) || !hasOAuthIdentity(e.selected) && t.refresh !== e.selected.refresh) throw new Error("Provider request credentials changed account identity.");
						}
					});
					if (!await assertSettledAuthProfileAuthorization(assertCurrent, t)) return n;
				}
			}, n);
			if (r.profileId !== e.profileId || r.mode !== "oauth" || !r.apiKey) throw new Error("Provider request credentials no longer match the selected OAuth profile.");
			const i = await e.prepare(r.apiKey, n);
			const assertRequestCurrent = () => {
				assertCurrent();
				assertProviderAuthAuthority(r);
			};
			assertRequestCurrent();
			const a = i?.apiKey ?? r.apiKey;
			e.install(r, a);
			return {
				apiKey: unwrapSecretSentinelsForProviderEgress(a, "provider request auth"),
				assertCurrent: assertRequestCurrent
			};
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-controller.ts
/** Decides whether one automatic profile may bypass its current cooldown. */
function resolveEmbeddedAuthCooldownProbePolicy(e) {
	const t = e.profileCandidates.filter((t) => typeof t === "string" && t.length > 0 && t !== e.lockedProfileId);
	const n = t.length > 0 && t.every((t) => isProfileInCooldown(e.authStore, t, void 0, e.modelId));
	const r = n ? resolveProfilesUnavailableReason({
		store: e.authStore,
		profileIds: t
	}) ?? "unknown" : null;
	const i = /* @__PURE__ */ new Set();
	if (e.allowTransientCooldownProbe && n && shouldUseTransientCooldownProbeSlot(r)) for (const n of t) {
		const t = resolveProfilesUnavailableReason({
			store: e.authStore,
			profileIds: [n]
		}) ?? "unknown";
		if (shouldUseTransientCooldownProbeSlot(t)) i.add(n);
	}
	return {
		probeProfileIds: i,
		unavailableReason: r
	};
}
/** Shares one transient probe across the selected owner's initial and later candidates. */
function createEmbeddedAuthProfileAdmission(e) {
	const t = resolveEmbeddedAuthCooldownProbePolicy(e);
	let n = false;
	return (r) => {
		if (!r || !isProfileInCooldown(e.authStore, r, void 0, e.modelId)) return true;
		if (n || !t.probeProfileIds.has(r)) return false;
		n = true;
		e.log.warn(`checking cooldowned auth profile for ${e.provider}/${e.modelId} due to ${t.unavailableReason ?? "transient"} unavailability`);
		return true;
	};
}
/**
* Own profile selection, runtime auth refresh and failover for one run's shared snapshots.
*/
function createEmbeddedRunAuthController(e) {
	const { state: t } = e;
	const { run: n, signal: r, cancel: i } = createRuntimeAuthDeadline({
		provider: e.provider,
		timeoutMs: resolveAgentTimeoutMs({
			cfg: e.config,
			overrideMs: e.timeoutMs
		}),
		signal: e.signal,
		getDeadline: e.getDeadline
	});
	let a;
	let o;
	const s = t.models.runtime;
	const c = t.models.effective;
	const applyPreparedRuntimeRequestOverrides = (e, n) => {
		const r = applyPreparedRuntimeAuthToModel(e, n);
		if (r === e) return;
		t.models.runtime = r;
		t.models.effective = applyPreparedRuntimeAuthToModel(t.models.effective, n);
	};
	const prepareRuntimeAuthForModel = (t) => n("runtime auth exchange", async (n) => {
		await e.authProfileBinding?.revalidate();
		n.throwIfAborted();
		e.assertCurrent?.();
		e.authProfileBinding?.assertCurrent();
		const r = await prepareProviderRuntimeAuth({
			assertCurrent: () => {
				n.throwIfAborted();
				e.assertCurrent?.();
			},
			provider: t.runtimeModel.provider,
			config: e.config,
			workspaceDir: e.workspaceDir,
			env: process.env,
			context: {
				config: e.config,
				agentDir: e.agentDir,
				workspaceDir: e.workspaceDir,
				env: process.env,
				provider: t.runtimeModel.provider,
				modelId: e.modelId,
				model: t.runtimeModel,
				apiKey: t.apiKey,
				authMode: t.authMode,
				profileId: t.profileId,
				signal: n
			}
		});
		n.throwIfAborted();
		return protectPreparedProviderRuntimeAuth({
			provider: t.runtimeModel.provider,
			preparedAuth: r
		});
	}, t.signal);
	const clearRuntimeAuthRefreshTimer = () => {
		const e = t.runtimeAuthState;
		if (!e?.refreshTimer) return;
		clearTimeout(e.refreshTimer);
		e.refreshTimer = void 0;
	};
	const stopRuntimeAuthRefreshTimer = () => {
		t.runtimeAuthRefreshCancelled = true;
		o?.dispose();
		o = void 0;
		clearRuntimeAuthRefreshTimer();
	};
	const refreshRuntimeAuth = async (n) => {
		const r = t.runtimeAuthState;
		if (!r) return;
		if (r.refreshInFlight) {
			await r.refreshInFlight;
			return;
		}
		const i = (async () => {
			const i = r.sourceApiKey.trim();
			if (!i) throw new Error(`Runtime auth refresh requires a source credential.`);
			const a = t.models.runtime;
			const o = await prepareRuntimeAuthForModel({
				runtimeModel: a,
				apiKey: i,
				authMode: r.authMode,
				profileId: r.profileId
			});
			if (!o?.apiKey) throw new Error(`Provider "${a.provider}" does not support runtime auth refresh.`);
			if (t.runtimeAuthState !== r) {
				e.log.debug(`Ignoring stale runtime auth refresh for ${a.provider}; auth state advanced before ${n} refresh completed.`);
				return;
			}
			e.authStorage.setRuntimeApiKey(a.provider, o.apiKey);
			applyPreparedRuntimeRequestOverrides(a, o);
			t.runtimeAuthState = {
				...r,
				apiKey: o.apiKey,
				expiresAt: o.expiresAt
			};
		})().catch((n) => {
			const r = t.models.runtime;
			e.log.warn(`Runtime auth refresh failed for ${r.provider}: ${formatErrorMessage(n)}`);
			throw n;
		}).finally(() => {
			const e = t.runtimeAuthState;
			if (e?.refreshInFlight === i) e.refreshInFlight = void 0;
		});
		r.refreshInFlight = i;
		await i;
	};
	const scheduleRuntimeAuthRefresh = () => {
		const n = t.runtimeAuthState;
		if (!n || t.runtimeAuthRefreshCancelled) return;
		const r = t.models.runtime;
		if (!n.sourceApiKey.trim()) {
			e.log.warn(`Skipping runtime auth refresh scheduling for ${r.provider}; source credential missing.`);
			return;
		}
		if (!n.expiresAt) return;
		clearRuntimeAuthRefreshTimer();
		const i = Date.now();
		const a = n.expiresAt - RUNTIME_AUTH_REFRESH_MARGIN_MS;
		const o = clampRuntimeAuthRefreshDelayMs({
			refreshAt: a,
			now: i,
			minDelayMs: RUNTIME_AUTH_REFRESH_MIN_DELAY_MS
		});
		const refresh = (e) => {
			if (t.runtimeAuthRefreshCancelled) return;
			refreshRuntimeAuth(e).then(scheduleRuntimeAuthRefresh).catch(() => {
				if (e === "scheduled-retry" || t.runtimeAuthRefreshCancelled) return;
				const n = setTimeout(() => refresh("scheduled-retry"), RUNTIME_AUTH_REFRESH_RETRY_MS);
				const r = t.runtimeAuthState;
				if (r) r.refreshTimer = n;
			});
		};
		n.refreshTimer = setTimeout(() => refresh("scheduled"), o);
	};
	const resolveAuthProfileFailoverReason = (t) => {
		if (t.allInCooldown) {
			const t = e.profileCandidates.filter((e) => typeof e === "string" && e.length > 0);
			return resolveProfilesUnavailableReason({
				store: e.authStore,
				profileIds: t
			}) ?? "unknown";
		}
		return classifyFailoverReason(t.message, { provider: e.provider }) ?? "auth";
	};
	const recordOAuthRefreshFailure = async (t, n) => {
		if (!(n instanceof OAuthRefreshFailureError)) return;
		const r = n.profileId ?? t;
		const i = n.provider || e.provider;
		const a = formatErrorMessage(n);
		e.log.warn(`auth profile "${r ?? "(unknown)"}" failed for provider "${i}": ${a}`);
		if (!r || e.authProfileStateMode === "read-only") return;
		const o = n.retryable && e.authProfileFailurePolicy !== "local" ? "timeout" : resolveAuthProfileFailureReason({
			failoverReason: resolveAuthProfileFailoverReason({
				allInCooldown: false,
				message: a
			}),
			policy: e.authProfileFailurePolicy
		});
		if (!o) return;
		try {
			await markAuthProfileFailure({
				store: e.authStore,
				profileId: r,
				reason: o,
				cfg: e.config,
				agentDir: e.agentDir,
				runId: e.runId,
				modelId: e.modelId,
				retryAfterMs: resolveRetryAfterMs(a, Date.now(), n)
			});
		} catch (t) {
			e.log.warn(`auth profile "${r}" failure bookkeeping failed for provider "${i}": ${formatErrorMessage(t)}`);
		}
	};
	const throwAuthProfileFailover = (n) => {
		const r = e.provider;
		const i = e.modelId;
		const a = n.error ? formatErrorMessage(n.error).trim() : "";
		const o = n.error ? getFailoverErrorCode(n.error) : void 0;
		const s = resolveAuthProfileFailoverReason({
			allInCooldown: n.allInCooldown,
			message: a
		});
		const c = (o === "selected_auth_profile_unavailable" ? a : void 0) || renderAuthProfileFailoverCopy({
			reason: s,
			provider: r,
			allInCooldown: n.allInCooldown,
			recoveryHint: buildProviderAuthRecoveryHint({
				provider: r,
				config: e.config,
				workspaceDir: e.workspaceDir,
				env: process.env
			})
		});
		if (e.fallbackConfigured) {
			const a = s === "billing" || s === "auth" || s === "auth_permanent" || s === "session_expired" ? resolveSubscriptionAuthModeForProfiles({
				store: e.authStore,
				profileIds: n.allInCooldown ? e.profileCandidates : [e.profileCandidates[t.profileIndex]]
			}) : void 0;
			throw new FailoverError(c, {
				reason: s,
				provider: r,
				model: i,
				authMode: a,
				status: resolveFailoverStatus(s, o),
				code: o,
				authProfileFailure: { allInCooldown: n.allInCooldown },
				cause: n.error
			});
		}
		if (n.error instanceof Error) throw n.error;
		throw new Error(c);
	};
	const applyApiKeyInfo = async (i, l, u = false) => {
		a = void 0;
		o?.dispose();
		o = void 0;
		const d = await e.prepareModelForAuthProfile?.(i, l);
		const f = await n("credential resolution", (n) => getApiKeyForModelCore({
			model: d?.runtimeModel ?? t.models.runtime,
			cfg: e.config,
			profileId: i,
			store: e.authStore,
			agentDir: e.agentDir,
			workspaceDir: e.workspaceDir,
			lockedProfile: u || i != null && i === e.lockedProfileId,
			forceRefresh: u,
			allowAuthProfileFallback: d?.allowAuthProfileFallback,
			secretSentinels: true,
			signal: n
		}));
		if (d?.authRequirement && !providerModelRouteAcceptsAuthMode({
			requirement: d.authRequirement,
			mode: f.mode ?? (f.apiKey ? "api-key" : void 0),
			authRequirement: resolveProviderModelAuthPolicy({
				provider: d.runtimeModel.provider,
				mode: f.mode,
				authFlow: f.authFlow,
				api: d.runtimeModel.api,
				baseUrl: d.runtimeModel.baseUrl
			}).authRequirement
		})) throw new Error(`Resolved ${f.mode ?? "unknown"} credentials are incompatible with the selected ${d.authRequirement} route for ${d.runtimeModel.provider}.`);
		e.authProfileBinding?.assertCurrent();
		if (e.authProfileBinding && f.profileId !== e.authProfileBinding.profileId) throw new Error("Resolved credentials do not belong to the automation inference owner.");
		t.apiKeyInfo = f;
		const p = !f.apiKey && f.mode === "aws-sdk";
		if (!f.apiKey && !p) {
			const e = d?.runtimeModel ?? t.models.runtime;
			throw new MissingProviderAuthError(e.provider, f);
		}
		d?.commit();
		if (!d?.authRequirement) {
			t.models.runtime = s;
			t.models.effective = c;
		}
		const m = getProviderAuthAuthority(f);
		t.models.runtime = attachProviderAuthAuthority(t.models.runtime, m);
		t.models.effective = attachProviderAuthAuthority(t.models.effective, m);
		const h = t.models.runtime;
		const g = f.apiKey || "__aws_sdk_auth__";
		const _ = p ? f.profileId ?? i : f.profileId;
		const v = {};
		a = v;
		const y = _ ? e.authStore.profiles[_] : void 0;
		const assertSelectionCurrent = () => {
			r.throwIfAborted();
			e.assertCurrent?.();
			if (t.runtimeAuthRefreshCancelled || a !== v) throw new Error("Provider request auth capability is closed.");
			e.authProfileBinding?.assertCurrent();
			assertProviderAuthAuthority(h);
		};
		const b = _ && y?.setup?.replacement && isSetupCredentialAccessible({
			profileId: _,
			credential: y,
			agentDir: e.agentDir
		});
		const x = !isEnvOnlyAuthProfileRuntime() && !getScopedSharedAuthStore() && !b && !e.authStore.runtimeExternalProfileIds?.includes(_ ?? "") && f.mode === "oauth" && _ && y?.type === "oauth" ? await captureAuthProfileAuthorization({
			profileId: _,
			agentDir: e.agentDir,
			cfg: e.config,
			assertCurrent: assertSelectionCurrent
		}) : void 0;
		o = x;
		let S = false;
		try {
			const n = await prepareRuntimeAuthForModel({
				runtimeModel: h,
				apiKey: g,
				authMode: f.mode,
				profileId: f.profileId
			});
			if (x) {
				assertSelectionCurrent();
				x.assertCurrent();
			}
			applyPreparedRuntimeRequestOverrides(h, n);
			if (n?.apiKey) {
				clearRuntimeAuthRefreshTimer();
				e.authStorage.setRuntimeApiKey(h.provider, n.apiKey);
				t.runtimeAuthState = {
					apiKey: n.apiKey,
					sourceApiKey: g,
					authMode: f.mode,
					profileId: _,
					expiresAt: n.expiresAt
				};
				if (n.expiresAt) scheduleRuntimeAuthRefresh();
				S = true;
			}
		} catch (t) {
			if (r.aborted || e.authProfileBinding || !p) throw t;
			e.log.warn(`prepareProviderRuntimeAuth failed for ${h.provider}, falling back to sentinel: ${formatErrorMessage(t)}`);
		}
		if (!S) {
			clearRuntimeAuthRefreshTimer();
			e.authStorage.setRuntimeApiKey(h.provider, g);
			t.runtimeAuthState = null;
		}
		t.lastProfileId = _;
		const C = x && f.mode === "oauth" && _ && y?.type === "oauth" ? createEmbeddedRequestAuth({
			model: h,
			selected: y,
			profileId: _,
			config: e.config,
			agentDir: e.agentDir,
			workspaceDir: e.workspaceDir,
			signal: r,
			withDeadline: n,
			assertAdmission: assertSelectionCurrent,
			assertCurrent: () => x?.assertCurrent(),
			prepare: (e, t) => prepareRuntimeAuthForModel({
				runtimeModel: h,
				apiKey: e,
				authMode: "oauth",
				profileId: _,
				signal: t
			}),
			install: (n, r) => {
				e.authStorage.setRuntimeApiKey(h.provider, r);
				t.apiKeyInfo = n;
			}
		}) : void 0;
		t.models.runtime = attachProviderRequestAuth(t.models.runtime, C);
		t.models.effective = attachProviderRequestAuth(t.models.effective, C);
	};
	const advanceAuthProfile = async () => {
		const n = await advanceAuthProfileCandidate({
			candidates: e.profileCandidates,
			state: t,
			isAvailable: (t) => !t || !isProfileInCooldown(e.authStore, t, void 0, e.modelId),
			tryPrepare: async (e, t) => {
				try {
					await applyApiKeyInfo(e, t);
					return true;
				} catch (t) {
					if (r.aborted || t instanceof SecretSurfaceUnavailableError) throw t;
					await recordOAuthRefreshFailure(e, t);
					return false;
				}
			}
		});
		if (n) {
			t.thinkLevel = e.initialThinkLevel;
			e.attemptedThinking.clear();
		}
		return n;
	};
	const initializeAuthProfile = async () => {
		try {
			const n = createEmbeddedAuthProfileAdmission(e);
			while (t.profileIndex < e.profileCandidates.length) {
				if (!n(e.profileCandidates[t.profileIndex])) {
					t.profileIndex += 1;
					continue;
				}
				await applyApiKeyInfo(e.profileCandidates[t.profileIndex], t.profileIndex);
				break;
			}
			if (t.profileIndex >= e.profileCandidates.length) throwAuthProfileFailover({ allInCooldown: true });
		} catch (n) {
			if (r.aborted || n instanceof FailoverError || n instanceof SecretSurfaceUnavailableError) throw n;
			await recordOAuthRefreshFailure(e.profileCandidates[t.profileIndex], n);
			if (!await advanceAuthProfile()) throwAuthProfileFailover({
				allInCooldown: false,
				error: n
			});
		}
	};
	const maybeRefreshRuntimeAuthForAuthError = async (n, i) => {
		if (i || classifyFailoverReason(n, { provider: e.provider }) !== "auth") return false;
		try {
			if (t.runtimeAuthState) {
				await refreshRuntimeAuth("auth-error");
				scheduleRuntimeAuthRefresh();
			} else if (e.provider === "openai" && t.lastProfileId && t.apiKeyInfo?.mode === "oauth" && t.apiKeyInfo.authFlow === "chatgpt-token-sharing" && /\btoken_expired\b|\bauthentication token is expired\b/iu.test(n)) await applyApiKeyInfo(t.lastProfileId, t.profileIndex, true);
			else return false;
			return true;
		} catch (e) {
			if (r.aborted) throw e;
			return false;
		}
	};
	return {
		close: () => {
			stopRuntimeAuthRefreshTimer();
			i();
		},
		applyAuthProfileCandidate: applyApiKeyInfo,
		advanceAuthProfile,
		initializeAuthProfile,
		maybeRefreshRuntimeAuthForAuthError,
		stopRuntimeAuthRefreshTimer
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-plan.ts
async function prepareEmbeddedRunAuthPlan(e) {
	const t = e.runParams;
	t.authProfileBinding?.assertCurrent();
	const n = e.provider === OPENAI_PROVIDER_ID;
	const r = e.getAgentHarness().id !== "openclaw";
	const i = !r && n && e.getEffectiveModel().api === "openai-chatgpt-responses";
	const resolveExternalCliAuthScope = (n) => resolveExternalCliAuthOverlayScopeFromSelection({
		...e,
		cfg: t.config,
		agentId: t.agentId,
		...n ? { store: n } : {},
		userPinnedAuthProfileId: t.authProfileIdSource === "user" ? t.authProfileId : void 0
	});
	let a = r ? { ignoreAutoPreferredProfile: false } : i ? {
		providerIds: [OPENAI_PROVIDER_ID],
		ignoreAutoPreferredProfile: false
	} : resolveExternalCliAuthScope();
	const o = {
		migrationProvider: e.provider,
		config: t.config,
		inheritedAuthDir: e.preparedModelRuntime?.inheritedAuthDir,
		profileId: t.authProfileId,
		allowKeychainPrompt: false
	};
	let s;
	if (!r && !a.providerIds) {
		s = await ensureAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir, o);
		a = resolveExternalCliAuthScope(s);
	}
	const c = n ? [OPENAI_PROVIDER_ID] : r ? void 0 : a.providerIds;
	const l = c ? await ensureAuthProfileStoreAsync(e.agentDir, {
		...o,
		externalCliProviderIds: c
	}) : s ?? await ensureAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir, o);
	const u = t.authProfileId?.trim() || void 0;
	const d = t.authProfileBinding?.profileId ?? (t.authProfileIdSource === "user" ? u : void 0);
	const f = a.ignoreAutoPreferredProfile && !d ? void 0 : u;
	const createAuthPreparation = () => {
		const n = e.getAgentHarness();
		if (e.nativeSessionRuntime?.auth === "native") {
			if (t.authProfileBinding) throw new Error("A native connection cannot replace the automation’s recorded inference account.");
			const r = buildAgentRuntimeAuthPlan({
				provider: e.provider,
				modelId: e.modelId,
				harnessId: n.id,
				allowHarnessAuthProfileForwarding: false,
				metadataSnapshot: e.preparedModelRuntime?.metadataSnapshot,
				config: t.config,
				workspaceDir: e.workspaceDir
			});
			return {
				plan: r,
				attempts: [{
					kind: "implicit",
					plan: r
				}]
			};
		}
		const r = prepareAgentRuntimeAuth({
			provider: e.provider,
			modelId: e.modelId,
			...e.observedRoutes ? { observedRoutes: e.observedRoutes } : {
				modelApi: e.model.api,
				modelBaseUrl: e.model.baseUrl
			},
			requestTransportOverrides: e.requestStreamTransportOverrides,
			config: t.config,
			env: process.env,
			agentId: t.agentId,
			agentDir: e.agentDir,
			workspaceDir: e.workspaceDir,
			metadataSnapshot: e.preparedModelRuntime?.metadataSnapshot,
			authProfileStore: l,
			sessionAuthProfileId: f,
			sessionAuthProfileSource: t.authProfileIdSource,
			requiredAuthProfileId: t.authProfileBinding?.profileId,
			...t.authProfileBinding ? { routeIntent: {
				authRequirement: t.authProfileBinding.authRequirement,
				source: "explicit"
			} } : {},
			allowAuthProfileFallback: t.authProfileBinding ? false : t.allowAuthProfileFallback,
			harnessId: n.id,
			harnessRuntime: n.id,
			harnessAuthBootstrap: n.authBootstrap,
			allowHarnessAuthProfileForwarding: true,
			allowTransientCooldownProbe: t.allowTransientCooldownProbe === true,
			resolveProviderPreferredProfileId: (n) => resolveProviderAuthProfileId({
				provider: e.provider,
				config: t.config,
				workspaceDir: e.workspaceDir,
				env: process.env,
				context: n
			})
		});
		if (e.requireConfiguredTransportAuth && r.attempts.some((n) => {
			if (n.kind === "implicit" && n.plan.credentialSource?.kind === "none" && n.plan.forwardedAuthProfileId === void 0 && hasSyntheticLocalProviderAuthConfig({
				cfg: t.config,
				provider: e.provider
			})) return false;
			return n.kind !== "direct" || n.plan.forwardedAuthProfileId !== void 0 || !isConfiguredKeyAuthSource(n.plan.credentialSource) || n.plan.credentialSource?.kind === "direct" && n.plan.credentialSource.authorization !== "declared";
		})) throw new Error("Connection recovery requires configured direct auth or a local no-auth transport.");
		const i = t.trigger === "cron" && !t.authProfileBinding && !t.scheduledRuntimeAuthority ? r.attempts.find(({ plan: e }) => {
			const t = e.credentialSource;
			return t?.kind === "profile" || t?.kind === "direct" && !isConfiguredKeyAuthSource(t);
		}) : void 0;
		if (i) throw createUnrecordedScheduledAccountRefusal({
			runtime: n.id,
			modelRef: `${e.provider}/${e.modelId}`,
			profileId: i.kind === "profile" ? i.profileId : void 0
		});
		return r;
	};
	const p = providerUsesCredentialScopedModelMetadata({
		...e,
		config: t.config
	});
	const m = providerOwnsDynamicModelPreparation({
		provider: e.provider,
		config: t.config,
		workspaceDir: e.workspaceDir
	});
	const { materialize: h, materializeUncached: g } = createPreparedRuntimeModelMaterializer({
		...e,
		config: t.config,
		metadataSnapshot: e.preparedModelRuntime?.metadataSnapshot,
		getModel: e.getRuntimeModel,
		requestedProfileId: t.authProfileId,
		providerUsesProfileScopedModelMetadata: p,
		providerOwnsDynamicModelRefresh: m,
		generationRouteModelMemo: e.preparedModelRuntime?.routeModelResolutionMemo,
		resolveModel: ({ config: n, authProfileId: r, authProfileMode: i }) => resolveModelAsync(e.provider, e.modelId, e.agentDir, n, {
			abortSignal: t.abortSignal,
			assertCurrent: e.assertCurrent,
			modelIdSource: "selected",
			authStorage: e.authStorage,
			modelRegistry: e.modelRegistry,
			skipAgentDiscovery: true,
			allowBundledStaticCatalogFallback: true,
			preparedModelRuntime: e.preparedModelRuntime,
			workspaceDir: e.workspaceDir,
			authProfileId: r,
			authProfileMode: i
		})
	});
	let _ = createAuthPreparation();
	for (let t = 0;; t += 1) {
		e.applyResolvedRuntimeModel(await h(_.plan));
		const n = e.selectHarnessForPreparedAttempts(e.getEffectiveModel(), _.attempts);
		if (n.id === e.getAgentHarness().id) break;
		if (t > 0) throw new Error(`Prepared auth route did not converge on one agent harness for ${e.provider}/${e.modelId}.`);
		e.setAgentHarness(n);
		_ = createAuthPreparation();
	}
	return {
		attemptAuthProfileStore: l,
		lockedProfileId: d,
		preferredProfileId: f,
		providerUsesProfileScopedModelMetadata: p,
		materializeAuthPlan: h,
		materializeAuthPlanUncached: g,
		preparedAuthAttempts: _.attempts,
		activePreparedAuthPlan: _.plan
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/model-harness.ts
function resolveEmbeddedRunEffectiveModel(e) {
	const { defaultParams: t, modelParams: n, agentModelParams: r, agentParams: i } = resolveModelExtraParamSources({
		config: e.runParams.config,
		provider: e.modelConfigProvider,
		modelId: e.modelId,
		agentId: e.runParams.agentId
	});
	const a = [
		t,
		n,
		r,
		i,
		Object.fromEntries(Object.entries(e.runParams.streamParams ?? {}).filter(([, e]) => e !== void 0)),
		...e.runParams.fastMode === void 0 ? [] : [{ fastMode: e.runParams.fastMode }]
	];
	const o = Object.assign({}, ...a);
	o.serviceTier = resolveAliasedParamValue(a, ["serviceTier", "service_tier"]);
	o.fastMode = resolveAliasedParamValue(a, ["fastMode", "fast_mode"]);
	delete o.service_tier;
	delete o.fast_mode;
	const s = e.nativeModelOwned || e.provider !== "openai" ? void 0 : resolveProviderPolicySurface(e.provider, { config: e.runParams.config })?.resolveServiceTiers?.({
		provider: e.provider,
		modelId: e.runtimeModel.id,
		api: e.runtimeModel.api,
		baseUrl: e.runtimeModel.baseUrl,
		runtimeId: e.agentHarnessId,
		params: o,
		requestCapabilities: getModelProviderRequestRouteFacts(e.runtimeModel)?.capabilities ?? resolveProviderRequestCapabilities({
			provider: e.provider,
			modelId: e.runtimeModel.id,
			api: e.runtimeModel.api,
			baseUrl: e.runtimeModel.baseUrl
		})
	});
	const c = e.pinnedHarnessId || e.agentHarnessId === "openclaw" ? void 0 : resolveAuthoredModelContextTokens({
		cfg: e.runParams.config,
		provider: e.modelConfigProvider,
		model: e.modelId
	});
	return {
		...resolveEmbeddedRuntimeModelPolicy({
			cfg: e.runParams.config,
			provider: e.provider,
			contextConfigProvider: e.modelConfigProvider,
			modelId: e.modelId,
			runtimeModel: e.runtimeModel,
			nativeModelOwned: e.nativeModelOwned,
			authoredContextTokenCap: c,
			requestExtraParams: o,
			requestServiceTiers: s,
			...e.runParams.contextWindow ? { contextWindow: e.runParams.contextWindow } : {},
			...e.runParams.contextTokenBudget === void 0 ? {} : { contextTokenBudget: e.runParams.contextTokenBudget }
		}),
		...c === void 0 ? {} : { authoredContextTokenCap: c }
	};
}
function buildHarnessModelProvider(e) {
	const t = e.plan?.modelRoute;
	const n = resolveAgentHarnessPreparedRouteSupport(e.plan);
	const r = e.requestStreamTransportOverrides ?? n.requestTransportOverrides;
	return {
		api: t?.api ?? e.model.api,
		baseUrl: t?.baseUrl ?? e.model.baseUrl,
		...r ? { requestTransportOverrides: r } : {},
		...n.runtimePolicy ? { runtimePolicy: n.runtimePolicy } : {},
		...e.plan ? { preparedAuth: resolveAgentHarnessPreparedAuthSupport({
			plan: e.plan,
			...e.preparedAuthAttempt?.kind === "profile" || e.preparedAuthAttempt?.kind === "direct" ? { source: e.preparedAuthAttempt.kind } : {}
		}) } : {}
	};
}
function selectEmbeddedRunHarness(e) {
	const t = {
		provider: e.provider,
		modelId: e.modelId,
		config: e.runParams.config,
		agentId: e.runParams.agentId,
		sessionKey: e.runParams.sessionKey,
		agentHarnessId: e.runParams.agentHarnessId,
		agentHarnessRuntimeOverride: e.runParams.agentHarnessRuntimeOverride
	};
	const n = e.attempts !== void 0 ? selectAgentHarnessForPreparedModelProviders({
		...t,
		modelProviders: e.attempts.map((t) => buildHarnessModelProvider({
			...e,
			plan: t.plan,
			preparedAuthAttempt: t
		}))
	}) : selectAgentHarness({
		...t,
		modelProvider: buildHarnessModelProvider(e)
	});
	if (e.pinnedHarnessId && n.id !== e.pinnedHarnessId) {
		const t = e.attempts !== void 0 ? "Prepared auth routes" : "Prepared model route";
		throw new AgentHarnessPreflightError(`${t} changed the session-pinned agent harness from "${e.pinnedHarnessId}" to "${n.id}". Reattach the original native session or use a concrete model chat.`);
	}
	return n;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/model-setup.ts
async function prepareNativeSessionRuntime(e, t, n, r) {
	const i = resolveSessionPinnedHarnessId(n?.entry);
	if (!n || !i || !t.resolveSessionRuntimeOwnershipAsync && !t.resolveSessionRuntimeOwnership) return;
	const { sessionId: a, lifecycleRevision: o } = n.entry;
	const s = "Native model ownership changed during run preparation. Reattach the original native session before retrying.";
	const { sessionAgentId: c } = resolveSessionAgentIdsStrict({
		config: e.config,
		agentId: n.agentId,
		sessionKey: n.sessionKey
	});
	const readOwnership = async (l) => {
		r();
		const u = prepareSessionRowPublicationScope([n.storePath, ...isIncognitoSessionKey(n.sessionKey) ? [resolveIncognitoOpenClawAgentSqlitePath({ agentId: c })] : []]);
		const consume = async (l, d) => {
			let f = false;
			const assertCurrent = () => {
				r();
				e.abortSignal?.throwIfAborted();
				if (e.lifecycleGeneration) assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
				try {
					d();
				} catch (e) {
					throw new AgentHarnessPreflightError(s, { cause: e });
				}
				const n = e.sessionTarget?.expectedWriterRunId;
				if (f || getRegisteredAgentHarness(i)?.harness !== t || l?.sessionId !== a || l?.lifecycleRevision !== o || resolveSessionPinnedHarnessId(l) !== i || n !== void 0 && l?.activeWriterRunId !== n) throw new AgentHarnessPreflightError(s);
			};
			assertCurrent();
			const p = sessionChanges.subscribeFacts((e) => {
				f ||= sessionChangeAffectsStoredRow(e, {
					...u,
					agentId: c,
					sessionKeys: [n.sessionKey]
				});
			});
			try {
				return await readSessionRuntimeOwnershipAsync({
					config: e.config,
					agentId: n.agentId,
					sessionKey: n.sessionKey,
					storePath: n.storePath,
					sessionEntry: l,
					assertCurrent,
					readPreparedPreviousSessionId: () => l?.previousSessionId
				});
			} finally {
				p();
			}
		};
		if (l) return await consume(l, r);
		if (isIncognitoSessionKey(n.sessionKey)) return await withSessionEntryReadOnlyInWorker(n, r, async (e, t) => {
			if (!e.ok) throw e.error;
			return consume(e.value, t.assertCurrent);
		});
		const d = getReplyOperationSessionReader(e.replyOperation);
		if (d) {
			u.prepareSource(d.database, readDatabasePathIdentitySync(d.database.path));
			const e = await d.withRead({
				sessionKeys: [n.sessionKey],
				snapshotFields: []
			}, r, (e) => ({
				entry: e.entries.find((e) => e.sessionKey === n.sessionKey)?.entry,
				assertNativeCurrent: captureSessionEntryNativeMutationWitness([d.database])
			}));
			return await consume(e.entry, () => {
				d.assertCurrent();
				e.assertNativeCurrent();
			});
		}
		return await withSessionEntriesFromStoreInWorker({
			agentId: c,
			sessionKeys: [n.sessionKey],
			storePath: n.storePath,
			includeAuthorization: true,
			snapshotFields: []
		}, (e) => consume(e.result.entries.find((e) => e.sessionKey === n.sessionKey)?.entry, e.assertCurrent), false, (...e) => u.prepareSource(...e));
	};
	const l = e.sessionTarget?.expectedWriterRunId;
	const u = await readOwnership(l === void 0 || n.entry.activeWriterRunId === l ? n.entry : void 0);
	if (!u) throw new AgentHarnessPreflightError("The pinned runtime's native session ownership is unavailable. Reattach the original native session instead of starting a replacement model run.");
	const d = readRunOperatorAuthority(e);
	assertOperatorModelAllowed(d, u.modelRef);
	if (u.auth === "host" && !u.modelRef) throw new AgentHarnessPreflightError("The native session's model and provider are unavailable for host authentication. Reattach the original native session before retrying.");
	let f = u;
	return {
		harness: t,
		...u.auth === "host" ? {
			auth: "host",
			modelRef: u.modelRef
		} : {
			auth: "native",
			get modelRef() {
				return f.modelRef;
			}
		},
		assertCurrent: async () => {
			const e = await readOwnership();
			assertOperatorModelAllowed(d, e?.modelRef);
			if (e?.model !== u.model || e.auth !== u.auth || u.auth === "host" && (e.modelRef?.provider !== u.modelRef?.provider || e.modelRef?.model !== u.modelRef?.model)) throw new AgentHarnessPreflightError("Native model ownership changed before agent harness dispatch. Reattach the original native session before retrying.");
			f = e;
		}
	};
}
async function resolveEmbeddedRunModelSetup(e) {
	const t = e.runParams;
	const n = readRunOperatorAuthority(t);
	const r = t.resolvedModelSelection ?? await resolveHookModelSelection({
		prompt: t.prompt,
		awaitSessionDiffBaseline: t.awaitSessionDiffBaseline,
		attachments: buildBeforeModelResolveAttachments(t.images),
		provider: e.provider,
		modelId: e.modelId,
		modelSelectionLocked: t.modelSelectionLocked,
		hookRunner: e.hookRunner,
		hookContext: e.hookContext
	});
	const i = r.provider !== e.provider || r.modelId !== e.modelId;
	let a = r.provider;
	let o = r.modelId;
	const s = resolveRequestStreamTransportOverrides(t.streamParams);
	e.onHooksResolved();
	await ensureSelectedAgentHarnessPlugin({
		provider: a,
		modelId: o,
		config: t.config,
		agentId: t.agentId,
		sessionKey: t.sessionKey,
		agentHarnessId: t.agentHarnessId,
		agentHarnessRuntimeOverride: t.agentHarnessRuntimeOverride,
		requestTransportOverrides: s,
		workspaceDir: e.workspaceDir,
		pluginRegistry: e.preparedModelRuntime?.pluginRegistry ?? requireActivePluginRegistry()
	});
	const c = resolveSessionPinnedHarnessId(e.sessionAdmission?.entry);
	const l = c ? getRegisteredAgentHarness(c)?.harness : void 0;
	const u = l ? await prepareNativeSessionRuntime(t, l, e.sessionAdmission, e.assertCurrent) : void 0;
	if (u?.auth === "host") {
		a = u.modelRef.provider;
		o = u.modelRef.model;
	}
	if (n?.modelPolicy && !u) {
		const r = resolveModelCandidateChain({
			cfg: t.config,
			agentId: t.agentId,
			provider: a,
			model: o,
			requestedRouteResolution: i ? "raw" : t.requestedRouteResolution,
			fallbacksOverride: [],
			manifestPlugins: e.preparedModelRuntime?.metadataSnapshot
		})[0];
		assertOperatorModelAllowed(n, r);
	}
	const d = o;
	if (u?.auth === "native" && s) throw new AgentHarnessPreflightError("Native session connections cannot apply provider stream parameters. Use a concrete model chat for this request.");
	const f = u?.auth === "native" ? u.harness : selectAgentHarness({
		provider: a,
		modelId: o,
		...s ? { modelProvider: { requestTransportOverrides: s } } : {},
		config: t.config,
		agentId: t.agentId,
		sessionKey: t.sessionKey,
		agentHarnessId: t.agentHarnessId,
		agentHarnessRuntimeOverride: t.agentHarnessRuntimeOverride
	});
	const p = await assertAgentHarnessExecutionEnvironment(f, t);
	if (f.executionEnvironment === "host-only" && !p) assertPluginHarnessConversationToolPolicySupport(f, await prepareAgentHarnessNativeToolPolicyRestricted({
		...t,
		provider: a,
		modelId: o
	}, f));
	const m = f.id !== "openclaw";
	const h = t.expectedAgentHarnessRuntimeArtifact;
	if (h && h.harnessId !== f.id) throw new Error(`Verified inference requires agent harness ${h.harnessId}, but ${f.id} was selected.`);
	if (h && !f.runtimeArtifact) throw new Error(`Agent harness ${f.id} cannot attest the verified inference runtime artifact.`);
	let g = e.preparedModelRuntime?.modelCatalog;
	let _;
	const resolveNativeModel = () => resolveNativeOwnedRuntimeModel({
		catalog: g,
		provider: a,
		modelId: o,
		runtimeId: f.id
	});
	if (!u && m && f.loadModelCatalog && e.preparedModelRuntime?.loadNativeModelCatalog && !resolveNativeModel()) {
		try {
			g = await e.preparedModelRuntime.loadNativeModelCatalog({
				provider: a,
				modelId: o,
				runtime: f.id
			});
		} catch (e) {
			_ = { error: e };
		}
		t.abortSignal?.throwIfAborted();
		e.assertCurrent();
	}
	const v = u !== void 0 ? createNativeModelOwnedRuntimeModel({
		provider: a,
		modelId: o
	}) : resolveNativeModel();
	const y = v !== void 0;
	const b = a;
	let x;
	let S;
	if (v) {
		x = {
			model: v,
			...createEmptyAgentDiscoveryStores()
		};
		const n = getPreparedModelRuntimePluginGeneration();
		const r = n ? getPreparedModelRuntimeBorrowedSnapshot(n) : void 0;
		const i = (r && r.modelCatalog === e.preparedModelRuntime?.modelCatalog ? readAdmittedPublishedModelCatalog(r) : void 0) ?? g;
		const s = i && createModelCatalogSnapshotView(t.config ?? {}, i).variantsOf({
			provider: a,
			id: o
		});
		S = s ? listModelCatalogObservedRoutes(s) : void 0;
	} else {
		const n = await resolveTieredModel({
			abortSignal: t.abortSignal,
			assertCurrent: e.assertCurrent,
			provider: a,
			modelId: o,
			agentDir: e.agentDir,
			requestedRouteResolution: i ? "raw" : t.requestedRouteResolution,
			config: t.config,
			workspaceDir: e.workspaceDir,
			authProfileId: t.authProfileId,
			preparedModelRuntime: e.preparedModelRuntime,
			staticCatalogOwnsTransport: m
		});
		a = n.provider;
		x = n.resolution;
		if (x.model) o = x.logicalRef.model;
	}
	if (!x.model) {
		if (_) throw _.error;
		throw new FailoverError(x.error ?? `Unknown model: ${a}/${o}`, {
			reason: "model_not_found",
			provider: a,
			model: o,
			sessionId: t.sessionId,
			lane: e.globalLane
		});
	}
	const { model: C, authStorage: w, modelRegistry: T } = x;
	if (!u) assertOperatorModelAllowed(n, {
		provider: a,
		model: o
	});
	return {
		provider: a,
		modelId: o,
		requestedModelId: d,
		modelSelectionChangedByHook: i,
		requestStreamTransportOverrides: s,
		expectedHarnessArtifact: h,
		agentHarness: f,
		pluginHarnessOwnsTransport: m,
		pinnedHarnessId: c,
		nativeModelOwned: y,
		observedRoutes: S,
		nativeSessionRuntime: u,
		modelConfigProvider: b,
		model: C,
		authStorage: w,
		modelRegistry: T
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/runtime-preparation.ts
async function prepareEmbeddedRunTransport(e) {
	const t = e.runParams;
	const n = await resolveEmbeddedRunModelSetup({
		assertCurrent: e.assertCurrent,
		runParams: t,
		sessionAdmission: e.sessionAdmission,
		provider: e.provider,
		modelId: e.modelId,
		agentDir: e.agentDir,
		workspaceDir: e.workspaceDir,
		globalLane: e.globalLane,
		hookRunner: e.hookRunner,
		hookContext: e.hookContext,
		onHooksResolved: () => e.markStartupStage("hooks"),
		preparedModelRuntime: e.preparedModelRuntime
	});
	const r = e.preparedModelRuntime?.metadataSnapshot;
	const { provider: i, modelId: a, requestedModelId: o, modelSelectionChangedByHook: s, requestStreamTransportOverrides: c, expectedHarnessArtifact: l, pinnedHarnessId: u, nativeModelOwned: d, observedRoutes: f, nativeSessionRuntime: p, modelConfigProvider: m, model: h, authStorage: g, modelRegistry: _ } = n;
	let v = n.agentHarness;
	let y = false;
	const resolveEffectiveModel = (e) => resolveEmbeddedRunEffectiveModel({
		runParams: t,
		provider: i,
		modelConfigProvider: m,
		modelId: a,
		agentHarnessId: v.id,
		runtimeModel: e,
		nativeModelOwned: d,
		requestStreamTransportOverrides: c,
		pinnedHarnessId: u
	});
	let b = resolveEffectiveModel(h);
	const x = {
		runtime: h,
		effective: b.effectiveModel
	};
	const applyResolvedRuntimeModel = (e, n) => {
		const r = y ? resolvePreparedModelThinkingCompat({
			capability: t.modelThinkingCapability,
			model: e,
			agentRuntime: v.id
		}) : void 0;
		const i = r ? {
			...e,
			compat: {
				...e.compat,
				...r
			}
		} : e;
		b = i === e && n ? n : resolveEffectiveModel(i);
		x.runtime = i;
		x.effective = b.effectiveModel;
	};
	const selectHarness = (e, n) => p?.auth === "native" ? p.harness : selectEmbeddedRunHarness({
		runParams: t,
		provider: i,
		modelId: a,
		model: e,
		attempts: n,
		requestStreamTransportOverrides: c,
		pinnedHarnessId: u
	});
	const assertRefreshTarget = () => {
		const t = e.refreshTransport;
		if (t && (i !== t.provider || a !== t.modelId || x.effective.api !== t.api || v.id !== t.harnessId || d || c)) throw new Error("Connection recovery cannot change the admitted model or harness.");
	};
	assertRefreshTarget();
	e.markStartupStage("model-resolution");
	e.notifyExecutionPhase("model_resolution", {
		provider: i,
		model: a
	});
	v = selectHarness(x.effective);
	let S = v.id !== "openclaw";
	const C = await prepareEmbeddedRunAuthPlan({
		assertCurrent: e.assertCurrent,
		runParams: t,
		provider: i,
		modelId: a,
		model: h,
		agentDir: e.agentDir,
		workspaceDir: e.workspaceDir,
		requestStreamTransportOverrides: c,
		nativeModelOwned: d,
		observedRoutes: f,
		nativeSessionRuntime: p,
		authStorage: g,
		modelRegistry: _,
		preparedModelRuntime: e.preparedModelRuntime,
		requireConfiguredTransportAuth: e.refreshTransport !== void 0,
		getAgentHarness: () => v,
		setAgentHarness: (e) => {
			v = e;
			S = v.id !== "openclaw";
		},
		getRuntimeModel: () => x.runtime,
		getEffectiveModel: () => x.effective,
		applyResolvedRuntimeModel,
		selectHarnessForPreparedAttempts: selectHarness
	});
	assertRefreshTarget();
	const { attemptAuthProfileStore: w, lockedProfileId: T, preferredProfileId: E, providerUsesProfileScopedModelMetadata: D, materializeAuthPlan: O, materializeAuthPlanUncached: k, preparedAuthAttempts: A } = C;
	let { activePreparedAuthPlan: j } = C;
	y = true;
	applyResolvedRuntimeModel(x.runtime);
	const M = !S && !t.disableCompactionRecovery;
	const N = A.map((e) => e.profileId);
	const P = S ? j.forwardedAuthProfileId : void 0;
	const F = resolveInitialThinkLevel({
		requested: t.thinkLevel,
		config: t.config,
		agentId: t.agentId,
		provider: i,
		modelId: a,
		model: x.effective
	});
	const I = s ? resolveCandidateThinkingLevel({
		cfg: t.config,
		provider: i,
		modelId: a,
		level: F,
		catalog: [{
			provider: i,
			id: a,
			api: x.effective.api,
			reasoning: x.effective.reasoning,
			params: x.effective.params,
			compat: x.effective.compat
		}],
		agentId: t.agentId,
		sessionKey: t.sessionKey,
		agentRuntime: v.id
	}) ?? F : F;
	const L = /* @__PURE__ */ new Set();
	const R = {
		models: x,
		thinkLevel: I,
		apiKeyInfo: null,
		lastProfileId: void 0,
		runtimeAuthState: null,
		runtimeAuthRefreshCancelled: false,
		profileIndex: 0
	};
	const z = S && v.authBootstrap === "harness";
	const B = j.modelRoute?.authRequirement === "api-key";
	const V = A.some((e) => e.plan.modelRoute?.authRequirement === "api-key");
	const H = S && (B || !z && A.some((e) => e.kind !== "implicit"));
	const findPreparedAuthAttempt = (e, t) => {
		const n = t === void 0 ? A.find((t) => t.profileId === e) : A[t];
		return n?.profileId === e ? n : void 0;
	};
	let U = false;
	const prepareAuthAttempt = async (e) => {
		if (!canRunPreparedAgentRuntimeAuthAttempt({
			attempt: e,
			priorProfileAttempted: U
		})) throw new Error(`Prepared direct auth fallback cannot bypass unavailable profiles for ${i}/${a}.`);
		const n = resolveCredentialScopedAuthAttemptModelDecision({
			attempt: e,
			priorProfileAttempted: U,
			requestedProfileId: t.authProfileId,
			providerUsesProfileScopedModelMetadata: D
		});
		const r = n.shouldMaterialize ? n.forceResolve ? await k(e.plan, true) : await O(e.plan) : x.runtime;
		const o = resolveEffectiveModel(r);
		if (selectHarness(o.effectiveModel, A).id !== v.id) throw new Error(`Prepared auth retry changed the selected agent harness for ${i}/${a}.`);
		U ||= e.kind === "profile";
		return {
			runtimeModel: r,
			authRequirement: n.authRequirement,
			allowAuthProfileFallback: e.allowAuthProfileFallback,
			commit() {
				applyResolvedRuntimeModel(r, o);
				j = e.plan;
			}
		};
	};
	const W = hasPreparedAuthAttemptModelMetadata({
		attempts: A,
		providerUsesProfileScopedModelMetadata: D
	}) && (!z || V) ? async (e, t) => {
		const n = findPreparedAuthAttempt(e, t);
		if (!n) throw new Error(`Auth profile "${e ?? "(none)"}" is outside the prepared attempts for ${i}/${a}.`);
		const r = await prepareAuthAttempt(n);
		if (n.plan.modelRoute && !r.authRequirement) throw new Error(`Prepared route metadata is missing for ${i}/${a}.`);
		return r;
	} : void 0;
	const G = createEmbeddedRunAuthController({
		config: t.config,
		agentDir: e.agentDir,
		workspaceDir: e.workspaceDir,
		authStore: w,
		authStorage: g,
		profileCandidates: N,
		lockedProfileId: T,
		authProfileBinding: t.authProfileBinding,
		initialThinkLevel: I,
		attemptedThinking: L,
		fallbackConfigured: e.fallbackConfigured,
		allowTransientCooldownProbe: t.allowTransientCooldownProbe === true,
		authProfileFailurePolicy: t.authProfileFailurePolicy,
		authProfileStateMode: t.authProfileStateMode,
		runId: t.runId,
		provider: i,
		modelId: a,
		state: R,
		assertCurrent: e.assertCurrent,
		signal: t.abortSignal,
		timeoutMs: t.timeoutMs,
		getDeadline: e.getAuthDeadline,
		...W ? { prepareModelForAuthProfile: W } : {},
		log: log$3
	});
	try {
		const n = createEmbeddedAuthProfileAdmission({
			authStore: w,
			profileCandidates: N,
			lockedProfileId: T,
			modelId: a,
			provider: i,
			log: log$3,
			allowTransientCooldownProbe: t.allowTransientCooldownProbe === true
		});
		const advancePluginHarnessAuthAttempt = async () => {
			if (!S) return false;
			let e = R.profileIndex + 1;
			while (e < A.length) {
				const t = e++;
				const r = A[t];
				R.profileIndex = t;
				if (!r) continue;
				const i = r.profileId;
				if (!n(i)) continue;
				if (!canRunPreparedAgentRuntimeAuthAttempt({
					attempt: r,
					priorProfileAttempted: U
				})) {
					R.profileIndex = A.length;
					return false;
				}
				if (r.plan.modelRoute?.authRequirement === "api-key") try {
					await G.applyAuthProfileCandidate(i, t);
				} catch {
					continue;
				}
				else {
					if (!i || r.plan.forwardedAuthProfileId !== i) continue;
					const e = await prepareAuthAttempt(r);
					G.stopRuntimeAuthRefreshTimer();
					R.apiKeyInfo = null;
					R.runtimeAuthState = null;
					e.commit();
					R.lastProfileId = i;
				}
				R.thinkLevel = I;
				L.clear();
				return true;
			}
			R.profileIndex = A.length;
			return false;
		};
		const s = z ? advancePluginHarnessAuthAttempt : G.advanceAuthProfile;
		if (!S || H) await G.initializeAuthProfile();
		else if (P) {
			const e = A[R.profileIndex];
			if (!n(e?.kind === "profile" ? e.profileId : void 0)) {
				if (!await advancePluginHarnessAuthAttempt()) throw new Error(`Prepared auth profiles are temporarily unavailable for ${i}/${a}.`);
			} else {
				U = e?.kind === "profile";
				R.lastProfileId = P;
			}
		}
		e.markStartupStage("auth");
		e.notifyExecutionPhase("auth", {
			provider: i,
			model: a
		});
		const c = getModelProviderRequestRouteFacts(x.effective);
		const u = c ? void 0 : resolveProviderEndpoint(x.effective.baseUrl, r?.owners).endpointClass;
		const f = c?.providerOwner ?? (u && ![
			"default",
			"invalid",
			"local",
			"custom"
		].includes(u) ? u : void 0);
		const m = {
			...resolveProviderRuntimePluginHandle({
				provider: i,
				providerOwner: f,
				modelId: a,
				config: t.config,
				workspaceDir: e.workspaceDir,
				env: process.env,
				...r ? { pluginMetadataSnapshot: r } : {}
			}),
			modelId: a,
			prepared: true
		};
		return {
			provider: i,
			modelId: a,
			requestedModelId: o,
			expectedHarnessArtifact: l,
			nativeModelOwned: d,
			nativeSessionRuntime: p,
			model: h,
			authStorage: g,
			modelRegistry: _,
			attemptAuthProfileStore: w,
			lockedProfileId: T,
			preferredProfileId: E,
			profileCandidates: N,
			profileFailureStore: w,
			genericCompactionRecoveryAllowed: M,
			pluginHarnessOwnsAuthBootstrap: z,
			attemptedThinking: L,
			advanceAttemptAuthProfile: s,
			maybeRefreshRuntimeAuthForAuthError: G.maybeRefreshRuntimeAuthForAuthError,
			stopRuntimeAuthRefreshTimer: G.close,
			getApiKeyInfo: () => R.apiKeyInfo,
			setThinkLevel: (e) => {
				R.thinkLevel = e;
			},
			resolveRunAttemptAuthProfileStore: () => {
				if (!S) return w;
				const e = j.modelRoute ? [j.forwardedAuthProfileId, ...j.forwardedAuthProfileCandidateIds ?? []] : [R.lastProfileId];
				return createScopedAuthProfileStore(w, e.filter((e) => Boolean(e)));
			},
			snapshot: () => ({
				agentHarness: v,
				pluginHarnessOwnsTransport: S,
				effectiveModel: x.effective,
				modelContextWindow: x.runtime.contextWindow,
				contextTokenBudget: b.contextTokenBudget,
				authoredContextTokenCap: b.authoredContextTokenCap,
				contextWindowInfo: b.contextWindowInfo,
				outerContextTokenMeta: {
					contextTokens: b.contextTokenBudget,
					contextTokensSource: b.contextTokensSource
				},
				activePreparedAuthPlan: R.apiKeyInfo ? {
					...j,
					selectedAuthMode: R.apiKeyInfo.mode,
					selectedAuthFlow: R.apiKeyInfo.authFlow
				} : j,
				thinkLevel: R.thinkLevel,
				apiKeyInfo: R.apiKeyInfo,
				lastProfileId: R.lastProfileId,
				runtimeAuthState: R.runtimeAuthState,
				pluginMetadataSnapshot: r,
				providerRuntimeHandle: m
			})
		};
	} catch (e) {
		G.close();
		throw e;
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/runtime.ts
/** Admission and request policy survive replacement of a failed configured transport. */
async function prepareEmbeddedRunRuntime(e) {
	const t = e.runParams;
	const n = await prepareEmbeddedRunTransport(e);
	let r = n;
	const i = [];
	const disposeLease = (e) => runAgentCleanupStep({
		runId: t.runId,
		sessionId: t.sessionId,
		step: "transport-lease-dispose",
		log: log$3,
		cleanup: async () => await e[Symbol.asyncDispose]()
	});
	const releaseTransport = async () => {
		r.stopRuntimeAuthRefreshTimer();
		await Promise.all(i.splice(0).map(disposeLease));
	};
	try {
		const a = n.snapshot();
		let o = a.effectiveModel;
		let s = t.config;
		let c = e.preparedModelRuntime;
		const l = await resolvePreparedRunAdmission({
			runId: t.runId,
			runtimeKind: a.pluginHarnessOwnsTransport ? "plugin-harness" : "embedded",
			admittedRunContext: t.admittedRunContext,
			preparedRunAdmission: t.preparedRunAdmission
		});
		const u = resolveAdmittedRunActiveAssertion(l, t.abortSignal);
		const d = readSourceReplyDeliveryRuntime(t);
		if (d?.origin === "runtime_default") {
			const e = (a.agentHarness.deliveryDefaults?.visibleReplies ?? a.agentHarness.deliveryDefaults?.sourceVisibleReplies) === "message_tool" ? "message_tool_only" : "automatic";
			d.applyPreparedMode(t, e);
			t.forceMessageTool = e === "message_tool_only";
		}
		const snapshot = () => {
			const e = r.snapshot();
			const t = r === n ? e : n.snapshot();
			return {
				...e,
				effectiveModel: r === n ? t.effectiveModel : o,
				transportConfig: s,
				thinkLevel: t.thinkLevel,
				modelContextWindow: t.modelContextWindow,
				contextTokenBudget: t.contextTokenBudget,
				authoredContextTokenCap: t.authoredContextTokenCap,
				contextWindowInfo: t.contextWindowInfo,
				outerContextTokenMeta: t.outerContextTokenMeta
			};
		};
		const hasStaticConfiguredTransport = (t) => !providerOwnsDynamicModelPreparation({
			provider: n.provider,
			config: t,
			workspaceDir: e.workspaceDir
		}) && !providerUsesCredentialScopedModelMetadata({
			provider: n.provider,
			modelId: n.modelId,
			config: t,
			agentDir: e.agentDir,
			workspaceDir: e.workspaceDir
		});
		return {
			...n,
			admittedRunContext: l,
			get authStorage() {
				return r.authStorage;
			},
			get modelRegistry() {
				return r.modelRegistry;
			},
			get attemptAuthProfileStore() {
				return r.attemptAuthProfileStore;
			},
			get profileFailureStore() {
				return r.profileFailureStore;
			},
			advanceAttemptAuthProfile: () => r.advanceAttemptAuthProfile(),
			maybeRefreshRuntimeAuthForAuthError: (...e) => r.maybeRefreshRuntimeAuthForAuthError(...e),
			getApiKeyInfo: () => r.getApiKeyInfo(),
			resolveRunAttemptAuthProfileStore: () => r.resolveRunAttemptAuthProfileStore(),
			snapshot,
			refreshTransportForConnectionError: async () => {
				const d = r.snapshot();
				const f = d.activePreparedAuthPlan.credentialSource;
				const p = f?.kind === "none" && r.getApiKeyInfo()?.apiKey === "custom-local" && hasSyntheticLocalProviderAuthConfig({
					cfg: s,
					provider: n.provider
				});
				if (!c || a.pluginHarnessOwnsTransport || n.nativeModelOwned || t.preparedModelRuntimeMode === "isolated-read-only" || t.authProfileBinding || t.authProfileId || resolveRequestStreamTransportOverrides(t.streamParams) || n.profileCandidates.some((e) => e !== void 0) || d.lastProfileId || d.runtimeAuthState || getModelProviderLocalService(a.effectiveModel) || getModelProviderLocalServiceReconciler(a.effectiveModel) || !p && (!isConfiguredKeyAuthSource(f) || f?.kind !== "direct" || f.authorization !== "declared") || !hasStaticConfiguredTransport(s)) return;
				const m = {
					config: c.config,
					agentId: c.agentId ?? t.agentId,
					agentDir: c.agentDir,
					inheritedAuthDir: c.inheritedAuthDir,
					workspaceDir: c.workspaceDir
				};
				const h = getPreparedModelRuntimeSnapshot(m);
				if (!h || h.metadataSnapshot !== c.metadataSnapshot || !resolveMergedModelProviderConfig(h.config, n.provider) || resolveMergedModelProviderConfig(h.config, n.provider)?.localService || isDeepStrictEqual(resolveMergedModelProviderConfig(s, n.provider), resolveMergedModelProviderConfig(h.config, n.provider))) return;
				let g;
				let _;
				try {
					_ = await acquirePreparedModelRuntimeSnapshot(m);
					const d = _.snapshot;
					if (d.config !== h.config || d.metadataSnapshot !== h.metadataSnapshot) return;
					e.assertCurrent();
					u?.();
					g = await withPreparedModelRuntimePluginGenerationScope(_.pluginGeneration, () => withPluginRuntimeGenerationScope(d, async () => {
						if (!hasStaticConfiguredTransport(d.config)) return;
						return await prepareEmbeddedRunTransport({
							...e,
							refreshTransport: {
								provider: n.provider,
								modelId: n.modelId,
								api: a.effectiveModel.api,
								harnessId: a.agentHarness.id
							},
							preparedModelRuntime: d,
							runParams: {
								...t,
								config: d.config,
								admittedRunContext: l,
								preparedRunAdmission: void 0,
								resolvedModelSelection: {
									provider: n.provider,
									modelId: n.modelId
								},
								agentHarnessRuntimeOverride: a.agentHarness.id
							},
							markStartupStage: () => {},
							notifyExecutionPhase: () => {}
						});
					}));
					e.assertCurrent();
					u?.();
					if (!g) return;
					const f = g.snapshot();
					if (getPreparedModelRuntimeSnapshot(m) !== h || f.lastProfileId || f.runtimeAuthState || f.activePreparedAuthPlan.credentialSource?.kind === "none" && g.getApiKeyInfo()?.apiKey !== "custom-local" || getModelProviderLocalService(f.effectiveModel) || getModelProviderLocalServiceReconciler(f.effectiveModel)) return;
					const p = f.effectiveModel;
					o = inheritModelProviderRequestRouteFacts(p, attachModelProviderRequestTransport({
						...a.effectiveModel,
						baseUrl: p.baseUrl,
						headers: p.headers,
						authHeader: p.authHeader,
						requestTimeoutMs: p.requestTimeoutMs
					}, getModelProviderRequestTransport(p) ?? {}));
					r.stopRuntimeAuthRefreshTimer();
					r = g;
					s = d.config;
					c = d;
					i.push(_);
				} catch (t) {
					e.assertCurrent();
					u?.();
					log$3.warn(`connection retry transport refresh failed: ${String(t)}`);
				} finally {
					if (g !== r) {
						g?.stopRuntimeAuthRefreshTimer();
						if (_) await disposeLease(_);
					}
				}
			},
			stopRuntimeAuthRefreshTimer: () => r.stopRuntimeAuthRefreshTimer(),
			releaseTransport
		};
	} catch (e) {
		await releaseTransport();
		throw e;
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/session-prompt-state.ts
const CONTINUATION_PROMPT = "Continue the current task from the existing transcript, preserving completed work and the user's constraints. Use recorded tool results to determine what completed. Before retrying an action with an unknown outcome, inspect its state. If the recorded results already satisfy the remaining request, report them without additional tool calls. Do not restart the task or repeat completed actions.";
async function createEmbeddedRunSessionPromptState(e) {
	const { runParams: t, sessionAgentId: n, resolvedSessionKey: r, lifecycleGeneration: i } = e;
	let a = t.sessionId;
	let o = t.sessionFile;
	let s = await buildContextEngineCompactionSessionTarget({
		agentId: t.agentId ?? n,
		config: t.config,
		sessionFile: o,
		sessionId: a,
		sessionKey: r,
		sessionTarget: t.sessionTarget
	});
	const c = t.sessionTarget?.expectedWriterRunId?.trim();
	const l = c ? {
		expectedLifecycleRevision: t.sessionTarget?.expectedLifecycleRevision,
		expectedWriterRunId: c
	} : void 0;
	const u = await prepareInitialSessionWriter({
		runParams: t,
		target: s,
		onInterrupt: e.onInterrupt
	});
	const d = u?.writer;
	const f = d ? { ...s } : void 0;
	let p = false;
	let m;
	const h = [];
	let g = false;
	let _ = t.suppressNextUserMessagePersistence ?? false;
	let v;
	let y;
	const releaseContinuation = () => {
		if (y) {
			y.messages = [];
			y.prompt = "";
			y = void 0;
		}
	};
	let b;
	const x = {
		get override() {
			const e = b;
			return e && v?.trim() ? `${v}\n\n${e}` : e ?? v;
		},
		persisted: _,
		internal: false
	};
	const notifySessionIdChanged = (e) => {
		registerAgentRunContext(t.runId, {
			sessionId: a,
			lifecycleGeneration: i
		});
		adoptExecRequestSession({
			runId: t.runId,
			previousSessionId: e,
			sessionId: a
		});
		t.replyOperation?.updateSessionId(a);
		t.onSessionIdChanged?.(a);
	};
	const adoptSessionId = (e) => {
		if (!e || e === a) return;
		const t = a;
		a = e;
		notifySessionIdChanged(t);
	};
	const capturePreparedCompactionTarget = (e) => {
		a = e.sessionId;
		o = e.sessionFile;
		s = e.sessionTarget;
		p = true;
	};
	const recordCommittedCompactionSuccessor = (e) => {
		if (e.admissionTransition && m !== e) h.push(e.admissionTransition);
		m = e;
		capturePreparedCompactionTarget(e);
	};
	const notifyCompactionSessionAdopted = (e) => {
		if (e && e !== a) notifySessionIdChanged(e);
	};
	const activateInternalPrompt = (e) => {
		v = e;
		Object.assign(x, {
			persisted: true,
			internal: true,
			replayCurrentTranscript: void 0
		});
		_ = true;
	};
	if (t.pluginRuntimeRefreshContinuation) activateInternalPrompt(t.prompt);
	const activateCompactionContinuation = (e) => {
		b = e;
		activateInternalPrompt(v ?? "");
	};
	const clearCompactionContinuation = () => b = void 0;
	const onUserMessagePersisted = (e) => {
		if (x.internal) clearCompactionContinuation();
		const n = e["__openclaw"]?.beforeAgentRunBlocked;
		const markCurrentUserMessagePersisted = () => {
			x.persisted = true;
			t.onUserMessagePersisted?.(e);
		};
		const r = t.userTurnTranscriptRecorder;
		if (!r) {
			markCurrentUserMessagePersisted();
			return;
		}
		const markWhenPersisted = (e) => {
			if (e?.message || r.hasPersisted()) markCurrentUserMessagePersisted();
		};
		const i = (n !== void 0 ? r.persistBlocked(e) : r.persistApproved()).then(markWhenPersisted).catch((e) => {
			log$3.warn(`failed to persist canonical ${n !== void 0 ? "blocked " : ""}embedded user turn transcript: ${formatErrorMessage(e)}`);
		});
		r.markRuntimePersistencePending(i);
	};
	const canReplayCurrentUserTurn = () => {
		const e = t.userTurnTranscriptRecorder;
		return !x.internal && x.persisted && e?.hasPersisted() === true && Boolean((e.getPersistedMessage?.() ?? e.message)?.idempotencyKey);
	};
	const waitForCurrentUserMessagePersistence = async () => {
		if (t.userTurnTranscriptRecorder?.hasRuntimePersistencePending() === true) await t.userTurnTranscriptRecorder.waitForRuntimePersistence();
	};
	return {
		[Symbol.asyncDispose]: async () => {
			try {
				await u?.close();
			} finally {
				releaseContinuation();
			}
		},
		get sessionId() {
			return a;
		},
		get sessionFile() {
			return o;
		},
		set sessionFile(e) {
			o = e;
		},
		get sessionTarget() {
			return s;
		},
		set sessionTarget(e) {
			s = e;
			p = true;
		},
		get sessionTargetAdopted() {
			return p;
		},
		get committedCompactionTransitions() {
			return Object.freeze([...h]);
		},
		get committedCompactionSuccessor() {
			return m;
		},
		get sessionWriterFence() {
			return l ?? d?.committedFence;
		},
		withSessionWriterContext: (e) => {
			const withContext = () => d && !d.committedFence ? withOwnedSessionTranscriptWrites({
				sessionTarget: f,
				initialWriter: d,
				withTranscriptWrite: d.withTranscriptWrite
			}, e) : runWithoutOwnedSessionTranscriptWrites(e);
			return u && !d?.committedFence ? u.run(withContext) : withContext();
		},
		recordOutputLimitNotice: async (e) => {
			const n = {
				role: "custom",
				customType: "incomplete-tool-call",
				content: (e ? `Runtime notice: The tool call ${JSON.stringify(e.slice(0, 200))} was cut off at the provider's output limit (max_output_tokens) and was not executed. Split the remaining work into smaller tool calls with shorter arguments only if the original request allows continuing that work. ` : "Runtime notice: The model response reached the provider's output limit (max_output_tokens) before producing an answer. Continue with a shorter response and smaller tool calls only if the original request allows continuing that work. ") + "Use recorded tool results to determine what completed, and do not repeat completed actions. Inspect state only for actions whose outcomes are unknown.",
				display: false,
				details: {
					reason: "max_output_tokens",
					...e ? { toolCallId: e } : {}
				},
				timestamp: Date.now()
			};
			if (t.sessionManager) await t.sessionManager.appendMessageAsync(n);
			else {
				const e = s;
				if (!e?.agentId || !e.sessionId || !e.sessionKey || !e.storePath) throw new Error("Missing session transcript target for output-limit recovery");
				await appendSessionTranscriptNote({
					...e,
					agentId: e.agentId,
					sessionId: e.sessionId,
					sessionKey: e.sessionKey,
					storePath: e.storePath,
					...l ?? d?.committedFence
				}, n, { config: t.config });
			}
		},
		get activePrompt() {
			return x;
		},
		get continuation() {
			return y;
		},
		get suppressNextUserMessagePersistence() {
			return _;
		},
		set suppressNextUserMessagePersistence(e) {
			_ = e;
		},
		adoptSessionId,
		capturePreparedCompactionTarget,
		recordCommittedCompactionSuccessor,
		notifyCompactionSessionAdopted,
		activateInternalPrompt,
		activateCompactionContinuation,
		clearCompactionContinuation,
		markOwnedTranscriptRetry: () => {
			g = true;
		},
		settleOwnedTranscriptProjection: async (e, n) => {
			const r = e?.sessionId ?? a;
			if (g && !t.sessionManager && e && r) {
				g = false;
				const { waitForSessionTranscriptProjection: t } = await import("./config/sessions/session-transcript-reconcile.js");
				await t({
					...e,
					sessionId: r
				}, n);
			}
		},
		continueFromCurrentTranscript: (e) => {
			if (t.modelRun === true || t.promptMode === "none") return;
			if (e?.messages) {
				const n = [...y?.messages ?? [], ...e.messages];
				releaseContinuation();
				y = {
					prompt: t.prompt,
					messages: n
				};
			}
			if (e?.replayCurrentUserTurn && canReplayCurrentUserTurn()) {
				x.replayCurrentTranscript = true;
				return;
			}
			const n = e?.includeToolFailureInstruction ? `${CONTINUATION_PROMPT} ${TOOL_FAILURE_INSTRUCTION}` : CONTINUATION_PROMPT;
			activateInternalPrompt(n);
		},
		onUserMessagePersisted,
		waitForCurrentUserMessagePersistence,
		prepareCompactedTranscriptRetry: async (e) => {
			await waitForCurrentUserMessagePersistence();
			e();
			g = true;
			if (x.internal) _ = x.persisted;
			else if (x.persisted) activateInternalPrompt(CONTINUATION_PROMPT);
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/terminal-preparation.ts
function prepareEmbeddedRunTerminal(e) {
	const { runParams: t, attempt: n } = e;
	const r = resolveExplicitFinalSourceReplyDeliveryEvidence(n) === false ? e.replyDeliveryState ?? "missing" : resolveSourceReplyDelivery(n, e.replyDeliveryState);
	const i = resolveSourceReplyDelivery(n, e.sourceReplyDeliveryState ?? r);
	const { timedOutDuringCompaction: a, timedOutDuringToolExecution: o } = projectAgentRunAttemptTerminal(n.terminal);
	const s = isEmbeddedRunTerminalTimeout(e.terminalState.outcome) && !a && !o;
	const c = isEmbeddedRunTimeoutFinal(n);
	const l = e.currentAttemptCompletedAssistant;
	const u = buildUsageAgentMetaFields({
		usageAccumulator: e.usageAccumulator,
		latestUsage: normalizeAssistantUsageForContext(l),
		lastRunPromptUsage: e.lastRunPromptUsage
	});
	const d = l ?? n.currentAttemptAssistant;
	const f = {
		provider: e.provider,
		model: e.model
	};
	const p = resolveReportedModelRef({
		...n.runtimeModelSelection ?? f,
		assistant: d
	});
	const m = d?.responseModel?.trim() || p.model;
	const h = {
		...p,
		responseModel: m
	};
	const g = n.keptAnswer?.assistant ?? l;
	const _ = (g?.stopReason ?? "").trim().toLowerCase();
	const v = _ !== "error" && _ !== "aborted";
	const y = estimateAggregateUsageCost({
		usage: u.usage,
		provider: p.provider,
		model: p.model,
		config: t.config,
		agentDir: t.agentDir
	});
	const b = e.usageAccumulator.assistantTurns;
	const x = n.contextTokens ?? e.outerContextTokenMeta.contextTokens;
	const S = p.provider === e.provider && p.model === e.model ? e.outerContextTokenMeta.contextTokensSource ?? "resolved" : "resolved";
	const C = resolveProviderRefusal(d);
	const w = {
		sessionId: e.sessionIdUsed,
		sessionFile: e.sessionFileUsed,
		provider: p.provider,
		model: p.model,
		contextTokens: x,
		...x !== void 0 ? { contextTokensSource: n.contextTokens !== void 0 ? n.contextTokensSource ?? "resolved" : S } : {},
		agentHarnessId: n.agentHarnessId,
		providerRefusal: C ? {
			...C,
			accessProgram: n.cyberAccessProgram,
			authProfileId: e.authProfileId
		} : void 0,
		...n.runtimeModelSelection ? { runtimeModelSelection: n.runtimeModelSelection } : {},
		credentialSource: n.modelAttempt?.credentialSource,
		usage: u.usage,
		lastCallUsage: u.lastCallUsage,
		promptTokens: u.promptTokens,
		...e.contextRecoveryState.lastContextBudgetStatus ? { contextBudgetStatus: e.contextRecoveryState.lastContextBudgetStatus } : {},
		compactionCount: e.contextRecoveryState.autoCompactionCount > 0 ? e.contextRecoveryState.autoCompactionCount : void 0,
		compactionTokensAfter: e.contextRecoveryState.lastCompactionTokensAfter,
		codeModeEngaged: n.codeModeEngaged === true,
		...b > 0 ? { assistantTurns: b } : {},
		...e.usageAccumulator.bridgeCalls ? { bridgeCalls: { ...e.usageAccumulator.bridgeCalls } } : {},
		...y !== void 0 ? { costUsd: y } : {}
	};
	const T = g ? void 0 : n.assistantTexts.findLast((e) => sanitizeAssistantVisibleStreamText(e).trim().length > 0);
	const E = v ? resolveFinalAssistantRawText(g) ?? T : void 0;
	const D = n.preparedTerminalReply ?? prepareAgentRunTerminalReply({ rawText: E });
	if (!n.preparedTerminalReply && D.terminalReply.disposition !== "silent") {
		const e = D.text;
		D.text = g ? extractAssistantVisibleText(g, (t, n) => n ? e : "") : sanitizeAssistantVisibleStreamText(e);
	}
	const O = parseReplyDirectives(D.text).text;
	if (D.terminalReply.disposition === "visible") D.terminalReply = sanitizeAgentRunTerminalReply(O);
	const k = n.currentAttemptAssistant ?? l;
	const A = k ? resolveFinalMessageRawText(k) ?? "" : void 0;
	const j = n.terminalTurnId;
	Object.assign(w, { terminalReceipt: {
		runId: t.runId,
		sessionId: e.sessionIdUsed,
		turnId: j?.trim() || t.runId,
		requested: f,
		effective: h,
		successfulToolNames: resolveSuccessfulToolNames(n),
		assistantTranscriptIdempotencyKey: n.assistantTranscriptIdempotencyKey,
		sourceReplyDelivered: r === "delivered" ? true : void 0,
		rerouted: isProviderModelRerouted(f, h, t.config)
	} });
	const M = n.yieldDetected && e.terminalState.outcome.status === "ok";
	const N = M ? void 0 : n.yieldDetected ? n.lastAssistant : e.currentAttemptCompletedAssistant;
	const P = buildEmbeddedRunPayloads({
		rateLimitRetriesExhausted: e.rateLimitRetriesExhausted,
		...n,
		preparedTerminalReply: D,
		assistantMessageIndex: n.lastAssistantTextMessageIndex,
		lastAssistant: N,
		currentAssistant: n.yieldDetected ? null : N ?? null,
		lastToolError: M ? void 0 : n.lastToolError,
		config: t.config,
		isCronTrigger: t.trigger === "cron",
		sessionKey: t.sessionKey ?? t.sessionId,
		provider: e.activeErrorContext.provider,
		providerOwner: e.providerOwner,
		model: e.activeErrorContext.model,
		authMode: e.authProfileId ? e.authProfileStore.profiles?.[e.authProfileId]?.type : void 0,
		verboseLevel: t.verboseLevel,
		reasoningLevel: t.reasoningLevel,
		thinkingLevel: t.thinkLevel,
		toolResultFormat: e.resolvedToolResultFormat,
		didDeliverSourceReplyViaMessageTool: i === "delivered",
		sourceReplyDeliveryState: i,
		sourceReplyDeliveryMode: t.sourceReplyDeliveryMode,
		agentId: t.agentId,
		runId: t.runId,
		runAborted: isEmbeddedRunTerminalInterrupted(e.terminalState.outcome) && !(s && c),
		runStopReason: e.terminalState.outcome.stopReason,
		deferAssistantTimeoutError: s && (!hasMessagingToolDeliveryEvidence(n) || c)
	}).map((e) => applyPreparedReplyMedia(e, n.preparedReplyMedia ?? []));
	if (e.sourceReplyDeliveryState === "missing" && e.replyDeliveryState === "delivered") for (const e of P) {
		const t = getReplyPayloadMetadata(e);
		if (!e.isError && !e.isReasoning && !t?.hostNotice && !t?.sourceReplyTranscriptMirror && (t?.assistantTranscriptOwned === true || t?.assistantMessageIndex !== void 0)) setReplyPayloadMetadata(e, { localTranscriptDeliveryConfirmed: true });
	}
	const F = e.mergeToolMedia ?? mergeAttemptToolMediaPayloads;
	const I = i === "pending" ? P : F({
		payloads: P,
		toolMediaUrls: n.toolMediaUrls,
		hostOwnedToolMediaUrls: n.hostOwnedToolMediaUrls,
		toolAutoDeliveryMediaUrls: getCoreTtsAttemptResultMediaUrls(n, n.toolMediaUrls, t.admittedRunContext?.operationalRunInstance),
		toolAudioAsVoice: n.toolAudioAsVoice,
		toolTrustedLocalMedia: n.toolTrustedLocalMedia,
		sourceReplyDeliveryMode: t.sourceReplyDeliveryMode
	}, t.admittedRunContext?.operationalRunInstance);
	const L = s || a && isEmbeddedRunTerminalTimeout(e.terminalState.outcome);
	const R = i === "missing" && L && !c && [
		"completed",
		"end_turn",
		"stop"
	].includes(_) ? (O ?? E)?.trim() : void 0;
	const z = R ? (I ?? []).some((e) => e?.isError !== true && e?.isReasoning !== true && typeof e.text === "string" && e.text.trim() === R) : false;
	const B = R && !z ? replacePartialAssistantPayload({
		payloads: I,
		assistantTexts: n.assistantTexts,
		recoveredText: R
	}) : void 0;
	const V = L && Boolean(z || B?.length);
	const H = s && (n.assistantTexts ?? []).some((e) => e.trim().length > 0) && !n.clientToolCalls && !n.yieldDetected && !n.didSendViaMessagingTool && !n.didSendDeterministicApprovalPrompt && !n.lastToolError && (n.toolMetas?.length ?? 0) === 0;
	const U = filterAgentRunTerminalPayloadsForPresentation({ payloads: B ?? I });
	const W = buildTraceToolSummary(n);
	let G;
	const K = n.lastToolError;
	if (t.trigger === "cron" && K && isExecLikeToolName(K.toolName)) {
		const e = normalizeOptionalString(K.errorCode);
		if (e === "SYSTEM_RUN_DENIED" || e === "INVALID_REQUEST") {
			const t = normalizeOptionalString(K.error) ?? e;
			G = {
				kind: "execution_denied",
				source: "tool",
				toolName: K.toolName,
				code: e,
				message: t,
				fatalForCron: true
			};
		}
	}
	const q = resolveEmbeddedRunTerminalToolFailure({
		trigger: t.trigger,
		codeModeEngaged: n.codeModeEngaged,
		lastToolError: n.lastToolError
	});
	return {
		agentMeta: w,
		replyDeliveryState: r,
		sourceReplyDeliveryState: i,
		reportedModelRef: p,
		preparedTerminalReply: D,
		finalAssistantVisibleText: O,
		finalAssistantRawText: E,
		finalAssistantMessageRawText: A,
		payloads: P,
		payloadsWithToolMedia: I,
		payloadsForVisibleCompletion: U,
		timedOutDuringPrompt: s,
		recoveredFinalAssistantPayloadsAfterPromptTimeout: B,
		hasSuccessfulFinalAssistantAfterPromptTimeout: V,
		hasPartialAssistantTextAfterPromptTimeout: H,
		attemptToolSummary: W,
		failureSignal: G,
		terminalToolFailure: q
	};
}
function replacePartialAssistantPayload(e) {
	const t = e.payloads ? [...e.payloads] : [];
	const n = new Set((e.assistantTexts ?? []).map((e) => e.trim()).filter((e) => e.length > 0));
	const r = t.findLastIndex((e) => e.isError !== true && e.isReasoning !== true && typeof e.text === "string" && n.has(e.text.trim()));
	const i = t[r];
	if (!i) return [...t, { text: e.recoveredText }];
	t[r] = setReplyPayloadMetadata(copyReplyPayloadMetadata(i, {
		...i,
		text: e.recoveredText
	}), { localTranscriptDeliveryConfirmed: void 0 });
	return t;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-profile-success.ts
const POST_RUN_AUTH_PROFILE_SUCCESS_SLOW_MS = 1e3;
function markEmbeddedRunAuthProfileSuccess(e) {
	if (e.authProfileStateMode === "read-only" || !e.profileId) return;
	const t = e.profileId;
	const n = redactIdentifier(t, { len: 12 });
	const r = e.profileStore.profiles[t]?.provider.trim() || e.provider;
	const i = Date.now();
	const a = markAuthProfileSuccess({
		store: e.profileStore,
		provider: r,
		modelId: e.modelId,
		profileId: t,
		agentDir: e.agentDir
	}).then(() => {
		const t = Date.now() - i;
		if (t >= POST_RUN_AUTH_PROFILE_SUCCESS_SLOW_MS) log$3.warn(`post-run auth-profile success bookkeeping completed after ${t}ms: runId=${e.runId} sessionId=${e.sessionId} provider=${sanitizeForLog(r)} profileId=${n}`);
	}).catch((t) => {
		log$3.warn(`post-run auth-profile success bookkeeping failed: runId=${e.runId} sessionId=${e.sessionId} provider=${sanitizeForLog(r)} profileId=${n} error=${formatErrorMessage(t)}`);
	});
	getOpenClawDatabaseMaintenanceScope()?.track(a);
}
function reportEmbeddedRunSuccessfulAuthBinding(e) {
	const t = e.profileId ? e.profileStore.profiles[e.profileId] : void 0;
	const n = resolvePluginHarnessApiKeyInfo(e);
	const r = t && e.profileId && t.type !== "oauth" && e.pluginHarnessOwnsAuthBootstrap ? e.attempt.authBindingFingerprint : t && e.profileId && (t.type === "oauth" || e.pluginHarnessOwnsTransport) ? fingerprintResolvedAuthProfileCredential({
		profileId: e.profileId,
		credential: t,
		resolvedAuth: t.type === "oauth" ? e.apiKeyInfo : n
	}) : fingerprintResolvedProviderAuth(e.apiKeyInfo);
	const i = e.profileId && t !== void 0 ? fingerprintAuthProfileOwnerShape({
		profileId: e.profileId,
		credential: t
	}) : void 0;
	const a = e.pluginHarnessOwnsTransport ? e.attempt.runtimeArtifact : void 0;
	const o = r ? void 0 : e.apiKeyInfo?.mode === "aws-sdk" ? fingerprintAwsSdkRuntimeOwner({
		provider: e.provider,
		backendId: e.agentHarnessId,
		auth: e.apiKeyInfo
	}) : e.pluginHarnessOwnsTransport ? fingerprintOpaqueRuntimeOwner({
		kind: "plugin-harness",
		runner: "embedded",
		provider: e.provider,
		backendId: e.agentHarnessId,
		...a ? { runtimeArtifactFingerprint: a.fingerprint } : {},
		...e.profileId ? { authProfileId: e.profileId } : {},
		...i ? { authProfileOwnerFingerprint: i } : {}
	}) : void 0;
	const s = o && e.apiKeyInfo?.mode === "aws-sdk" ? "aws-sdk" : e.pluginHarnessOwnsTransport ? "plugin-harness" : void 0;
	const c = resolveHarnessAuthMaterialization(e, t);
	if (c) recordRuntimeAuthMaterialization({
		agentDir: e.agentDir,
		provider: e.provider,
		modelId: e.modelId,
		modelApi: c.api,
		modelBaseUrl: c.baseUrl,
		requestTransportOverrides: c.requestTransportOverrides,
		authMode: c.authRequirement === "subscription" ? "oauth" : "api-key",
		runtimeOwnerId: e.agentHarnessId,
		...e.profileId ? { authProfileId: e.profileId } : {}
	});
	e.onSuccessfulAuthBinding?.({
		...e.profileId ? { authProfileId: e.profileId } : {},
		agentHarnessId: e.agentHarnessId,
		modelId: e.modelId,
		modelApi: e.modelApi,
		...r ? { authFingerprint: r } : {},
		...o ? { runtimeOwnerFingerprint: o } : {},
		...s ? { runtimeOwnerKind: s } : {},
		...s ? { runtimeOwnerId: e.agentHarnessId } : {},
		...a ? {
			runtimeArtifactId: a.id,
			runtimeArtifactFingerprint: a.fingerprint
		} : {}
	});
}
function resolveHarnessAuthMaterialization(e, t) {
	const n = e.apiKeyInfo?.profileId;
	const r = t?.type === "api_key" && t.keyRef !== void 0 && e.apiKeyInfo?.mode === "api-key" && n !== void 0 && n === e.profileId && e.apiKeyInfo.source === `profile:${n}`;
	if (!e.pluginHarnessOwnsAuthBootstrap || e.apiKeyInfo && !r || hasInlineCredentialMaterial(t) || !isStringOption(e.modelApi, MODEL_APIS)) return;
	const i = resolveProviderModelRoutes({
		provider: e.provider,
		modelId: e.modelId,
		api: e.modelApi,
		baseUrl: e.modelBaseUrl,
		config: e.config,
		requestTransportOverrides: e.requestTransportOverrides ?? "none"
	});
	if (i?.kind !== "routes") return;
	const a = i.routes.filter((t) => t.api === e.modelApi && t.requestTransportOverrides === (e.requestTransportOverrides ?? "none") && (!e.modelBaseUrl || modelMatchesProviderModelRoute({
		provider: e.provider,
		api: e.modelApi,
		baseUrl: e.modelBaseUrl,
		route: t
	})));
	return a.length === 1 ? a[0] : void 0;
}
function hasInlineCredentialMaterial(e) {
	if (!e) return false;
	if (e.type === "api_key") return Boolean(e.key?.trim());
	if (e.type === "token") return Boolean(e.token?.trim());
	return Boolean(e.access?.trim() && e.refresh?.trim());
}
function resolvePluginHarnessApiKeyInfo(e) {
	const t = e.apiKeyInfo;
	const n = t?.apiKey;
	if (!e.pluginHarnessOwnsTransport || !t || !n || !looksLikeSecretSentinel(n)) return t;
	const r = resolveSecretSentinel(n);
	return r ? {
		...t,
		apiKey: r
	} : null;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/terminal-resolution.ts
const MAX_MISSING_ASSISTANT_RETRIES = 1;
const COMPACTION_CONTINUATION_RETRY_INSTRUCTION = "The previous attempt compacted the conversation context before producing a final user-visible answer. Continue from the compacted transcript and produce the final answer now. Do not restart from scratch, do not repeat completed work, and do not rerun tools unless the transcript clearly lacks required evidence.";
const BEFORE_AGENT_FINALIZE_RETRY_PROMPT_PREFIX = "Before accepting the previous final answer, apply this revision request and produce the revised final answer. Do not repeat completed work or rerun tools unless the request explicitly requires it.";
function createTerminalToolPresentationTracker() {
	let e = -1;
	let t = 0;
	let n;
	return {
		allocateOrdinal: () => t++,
		observe: (t) => {
			const r = t.toolCallOrdinal ?? e + 1;
			if (r >= e) {
				e = r;
				n = t.terminalPresentation;
			}
		},
		read: () => n
	};
}
function resolveSettledTurnFinalizationRequest(e) {
	if (!e.settledTurnFinalizationAvailable || resolveReplyExpectation(e.runParams) === "optional" || isTerminalAssistantError(resolveCurrentAttemptAssistant(e.attempt)) || (e.replyDeliveryState ?? "missing") !== "missing") return null;
	const t = isEmbeddedRunTerminalAbort(e.terminalState.outcome);
	const n = isEmbeddedRunTerminalTimeout(e.terminalState.outcome);
	const r = countSettledTurnDeliveryPayloads({
		payloads: e.payloadsWithToolMedia,
		attempt: e.attempt
	});
	const i = e.recoveredFinalAssistantPayloadsAfterPromptTimeout?.length ?? r;
	if (shouldTreatEmptyAssistantReplyAsSilent({
		terminalReplyExpectation: resolveReplyExpectation(e.runParams),
		payloadCount: i,
		aborted: t,
		timedOut: n,
		attempt: e.attempt
	})) return null;
	const a = resolveSettledToolTerminalContinuation({
		provider: e.activeErrorContext.provider,
		modelId: e.activeErrorContext.model,
		modelApi: e.modelApi,
		executionContract: e.executionContract,
		terminalReplyExpectation: resolveReplyExpectation(e.runParams),
		replyDeliveryState: e.replyDeliveryState ?? "missing",
		allowEmptyStopContinuation: true,
		payloadCount: i,
		hasTerminalToolPresentation: e.hasTerminalToolPresentation,
		aborted: t,
		timedOut: n,
		attempt: e.attempt
	});
	return a?.disableTools ? a.instruction : null;
}
async function resolveEmbeddedRunTerminal(e) {
	const { runParams: t, attempt: n, retryState: r, sessionPromptState: i } = e;
	const a = resolveReplyExpectation(t);
	const o = `runId=${t.runId} sessionId=${t.sessionId}`;
	const s = `${o} provider=${e.activeErrorContext.provider}/${e.activeErrorContext.model}`;
	const { externalAbort: c, promptError: l } = projectAgentRunAttemptTerminal(n.terminal);
	const u = isEmbeddedRunTerminalAbort(e.terminalState.outcome);
	const d = isEmbeddedRunTerminalTimeout(e.terminalState.outcome);
	const f = isEmbeddedRunTerminalInterrupted(e.terminalState.outcome);
	const { signalOwnedInterruption: p } = e.terminalState;
	const m = e.prepared.recoveredFinalAssistantPayloadsAfterPromptTimeout ?? e.prepared.payloadsWithToolMedia;
	const h = {
		payloadCount: e.prepared.payloadsForVisibleCompletion?.length ?? 0,
		rawPayloadCount: m?.length ?? 0,
		aborted: u,
		timedOut: d,
		attempt: n
	};
	const g = !u && !d && resolveSettledToolBatchEvidence(n).intentionalTermination;
	const _ = e.settledTurnFinalizationOutcome !== "not-attempted";
	const v = shouldTreatEmptyAssistantReplyAsSilent({
		terminalReplyExpectation: a,
		...h
	});
	const y = a === "result-required" && classifyAssistantTurn(h).silent;
	const b = !y && (a === "optional" && !isRejectedBeforeDispatch(n) || v || e.prepared.replyDeliveryState !== "missing");
	const x = !b && !_;
	const [S, C] = x ? resolveNonVisibleTurnRetryInstructions({
		provider: e.activeErrorContext.provider,
		modelId: e.activeErrorContext.model,
		modelApi: e.modelApi,
		executionContract: e.executionContract,
		terminalReplyExpectation: a,
		replyDeliveryState: e.prepared.replyDeliveryState,
		...h,
		settledToolPayloadCount: countSettledTurnDeliveryPayloads({
			payloads: e.prepared.payloadsForVisibleCompletion,
			attempt: n
		}),
		hasTerminalToolPresentation: Boolean(e.readTerminalToolPresentation())
	}) : [null, null];
	const w = n.textToolCallAttempt ? "textToolCallAttempts" : "emptyResponseAttempts";
	if (S && r.reasoningOnlyAttempts < 2) {
		r.reasoningOnlyAttempts += 1;
		i.activateInternalPrompt(S);
		log$3.warn(`reasoning-only assistant turn detected: ${s} — retrying ${r.reasoningOnlyAttempts}/${2} with visible-answer continuation`);
		return { action: "retry" };
	}
	const T = S && r.reasoningOnlyAttempts >= 2;
	if (x && shouldRetryMissingAssistantTurn({
		...h,
		promptError: l
	}) && r.missingAssistantAttempts < MAX_MISSING_ASSISTANT_RETRIES) {
		r.missingAssistantAttempts += 1;
		i.suppressNextUserMessagePersistence = i.activePrompt.persisted;
		log$3.warn(`missing assistant terminal message detected: ${s} — retrying ${r.missingAssistantAttempts}/${MAX_MISSING_ASSISTANT_RETRIES} with same prompt`);
		return { action: "retry" };
	}
	const E = e.readTerminalToolPresentation();
	if (!S && C && r[w] < 1) {
		r[w] += 1;
		i.activateInternalPrompt(C);
		log$3.warn(`empty response detected: ${s} stopReason=${e.attemptAssistant?.stopReason ?? "missing"} — retrying ${r[w]}/${1} with visible-answer continuation`);
		return { action: "retry" };
	}
	const D = isTerminalAssistantError(e.attemptAssistant);
	const O = b ? null : resolveIncompleteTurnPayloadText({
		...h,
		externalAbort: c || p,
		hadPotentialSideEffects: e.replayState.hadPotentialSideEffects,
		hasIntentionalTerminalCompletion: g,
		terminalFailure: e
	}) ?? ((y || _) && h.payloadCount === 0 && !f && !n.lastToolError ? "No answer was returned. Ask again if you still need one." : null);
	const k = Boolean(O && !f && !l && !n.lastToolError && !hasAttemptTerminalState(n) && !D && !e.replayState.hadPotentialSideEffects);
	const A = k && (e.attemptAssistant?.stopReason !== "stop" || n.agentHarnessResultClassification !== void 0);
	const j = k ? E : void 0;
	if (x && (e.attemptCompactionCount > 0 || isCompactionReplayCheckpoint(e.attemptAssistant?.providerReplay)) && h.payloadCount === 0 && !f && !l && !n.clientToolCalls && !n.yieldDetected && !n.didSendDeterministicApprovalPrompt && !n.lastToolError && !D && !e.replayState.hadPotentialSideEffects && r.compactionContinuationAttempts < 1) {
		r.compactionContinuationAttempts += 1;
		i.activateCompactionContinuation(COMPACTION_CONTINUATION_RETRY_INSTRUCTION);
		log$3.warn(`compaction interrupted visible final answer: ${o} compactions=${e.attemptCompactionCount} — retrying ${r.compactionContinuationAttempts}/1 with compacted-transcript continuation`);
		e.armPostCompactionGuard();
		return { action: "retry" };
	}
	i.clearCompactionContinuation();
	if (T && !e.prepared.finalAssistantVisibleText) {
		log$3.warn(`reasoning-only retries exhausted: ${s} attempts=${r.reasoningOnlyAttempts}/${2} — surfacing incomplete-turn error`);
		return completeEmbeddedRun({
			...e,
			incompleteTurnText: MISSING_REPLY_NOTICE_TEXT,
			payloadCount: 0,
			incompleteTurnFallbackSafe: A,
			terminalToolPresentation: j
		});
	}
	if (!S && C && r[w] >= 1) log$3.warn(`empty response retries exhausted: ${s} attempts=${r[w]}/${1} — surfacing incomplete-turn error`);
	if (O) {
		const t = e.attemptAssistant?.stopReason;
		log$3.warn(`incomplete turn detected: ${s} stopReason=${t ?? "missing"} hasLastAssistant=${n.lastAssistant ? "yes" : "no"} hasCurrentAttemptAssistant=${n.currentAttemptAssistant ? "yes" : "no"} payloads=${h.payloadCount} tools=${n.toolMetas?.length ?? 0} replaySafe=${n.replayMetadata.replaySafe ? "yes" : "no"} compactions=${e.attemptCompactionCount} reasoningRetries=${r.reasoningOnlyAttempts}/${2} emptyRetries=${r[w]}/${1} missingAssistantRetries=${r.missingAssistantAttempts}/${MAX_MISSING_ASSISTANT_RETRIES} — ` + (j ? "surfacing tool-authored terminal presentation" : "surfacing error to user"));
		return completeEmbeddedRun({
			...e,
			incompleteTurnText: O,
			payloadCount: h.payloadCount,
			incompleteTurnFallbackSafe: A,
			terminalToolPresentation: j
		});
	}
	const M = n.beforeAgentFinalizeRevisionReason;
	if (M && !_ && !f && !l && !n.clientToolCalls && !n.yieldDetected && !v) {
		r.beforeFinalizeRevisionAttempts += 1;
		i.activateInternalPrompt(`${BEFORE_AGENT_FINALIZE_RETRY_PROMPT_PREFIX}\n\n${M}`);
		i.markOwnedTranscriptRetry();
		log$3.warn(`before_agent_finalize requested one more pass: ${o} attempt=${r.beforeFinalizeRevisionAttempts}/${3}`);
		return { action: "retry" };
	}
	return completeEmbeddedRun({
		...e,
		payloadCount: h.payloadCount,
		payloadsForTerminalPath: m,
		emptyAssistantReplyIsSilent: v,
		intentionalTerminalCompletion: g
	});
}
async function completeEmbeddedRun(e) {
	const { outcome: t } = e.terminalState;
	const n = isEmbeddedRunTerminalAbort(t);
	const r = isEmbeddedRunTerminalTimeout(t);
	const i = classifyAgentRunTerminalOutcome(t) === "failure";
	const a = projectAgentRunAttemptTerminal(e.attempt.terminal).promptError ?? t.error ?? e.incompleteTurnText ?? "No answer was returned. Ask again if you still need one.";
	const o = renderStorageFailureSummary(classifyGatewayStorageFailure(a));
	const s = e.incompleteTurnText !== void 0 || i ? {
		kind: "incomplete_turn",
		message: o ?? formatErrorMessage(a),
		code: resolveCurrentAttemptErrorCode(e.attempt, a),
		fallbackSafe: e.incompleteTurnFallbackSafe ?? false,
		terminalPresentation: e.terminalToolPresentation !== void 0
	} : void 0;
	const c = e.incompleteTurnText ?? s?.message ?? null;
	const l = e.resolveReplayInvalid(c);
	const u = !s && e.attempt.yieldDetected ? "paused" : resolveRunLivenessState({
		payloadCount: e.payloadCount,
		aborted: n,
		timedOut: r,
		attempt: e.attempt,
		incompleteTurnText: c
	});
	const d = n || r || i && t.stopReason === "length" ? t.stopReason : s ? "error" : e.attempt.clientToolCalls ? "tool_calls" : e.attempt.yieldDetected ? "end_turn" : e.attemptAssistant?.stopReason;
	e.setTerminalLifecycleMeta({
		replayInvalid: l,
		livenessState: u,
		stopReason: d,
		...!s ? { yielded: e.attempt.yieldDetected === true } : {}
	});
	if (s) {
		if (e.authProfileId) {
			const t = e.attemptAssistant;
			try {
				await e.maybeMarkAuthProfileFailure({
					profileId: e.authProfileId,
					reason: e.assistantProfileFailureReason,
					modelId: e.modelId,
					retryAfterMs: t && buildAssistantFailoverSignal(t).retryAfterMs
				});
			} catch (e) {
				log$3.warn(`terminal auth bookkeeping failed; preserving result: ${String(e)}`);
			}
		}
	} else {
		markEmbeddedRunAuthProfileSuccess({
			authProfileStateMode: e.runParams.authProfileStateMode,
			profileId: e.authProfileId,
			profileStore: e.profileFailureStore,
			provider: e.provider,
			modelId: e.modelId,
			agentDir: e.runParams.agentDir,
			runId: e.runParams.runId,
			sessionId: e.runParams.sessionId
		});
		reportEmbeddedRunSuccessfulAuthBinding({
			profileId: e.authProfileId,
			profileStore: e.attemptAuthProfileStore,
			apiKeyInfo: e.apiKeyInfo,
			attempt: e.attempt,
			provider: e.provider,
			agentDir: e.runParams.agentDir,
			modelId: e.modelTransportId,
			modelApi: e.modelTransportApi,
			...e.modelTransportBaseUrl ? { modelBaseUrl: e.modelTransportBaseUrl } : {},
			requestTransportOverrides: e.requestTransportOverrides ?? "none",
			config: e.runParams.config,
			agentHarnessId: e.agentHarnessId,
			pluginHarnessOwnsTransport: e.pluginHarnessOwnsTransport,
			pluginHarnessOwnsAuthBootstrap: e.pluginHarnessOwnsAuthBootstrap,
			onSuccessfulAuthBinding: e.runParams.onSuccessfulAuthBinding
		});
		e.runParams.onSuccessfulAuthProfile?.(e.authProfileId);
	}
	const f = !s && shouldContinueInteractiveAcceptedSessionSpawns({
		attempt: e.attempt,
		run: e.runParams
	});
	const p = e.attempt.assistantTexts.some((e) => e.trim().length > 0) || resolveFinalAssistantVisibleText(e.attemptAssistant) !== void 0;
	const m = d === "length" && !hasAttemptTerminalState(e.attempt) && p;
	const h = isHostMissingReplyNoticeText(e.incompleteTurnText);
	const g = h && !shouldDeliverMissingReplyNotice(e.runParams);
	const _ = h && (e.incompleteTurnFallbackSafe === true || g);
	const v = e.terminalToolPresentation && e.incompleteTurnText !== void 0 ? e.terminalToolPresentation.concat("\n\n", e.incompleteTurnText) : e.incompleteTurnText ?? (s ? o : void 0);
	const y = _ ? retainSilentFinalPayloads(e.payloadsForTerminalPath ?? []) : v !== void 0 ? [h ? createMissingReplyNotice(v) : {
		text: v,
		isError: true
	}] : s ? e.payloadsForTerminalPath : e.emptyAssistantReplyIsSilent ? retainSilentFinalPayloads(e.payloadsForTerminalPath ?? []) : e.payloadsForTerminalPath?.length ? m ? [...e.payloadsForTerminalPath, setReplyPayloadMetadata({ text: TRUNCATED_REPLY_NOTICE_TEXT }, { hostNotice: true })] : e.payloadsForTerminalPath : e.attempt.yieldDetected && !hasYieldContinuationEvidence(e.attempt) ? [setReplyPayloadMetadata({ text: YIELD_DIAGNOSTIC_TEXT }, { hostNotice: true })] : e.payloadsForTerminalPath;
	const b = e.attempt.messagingToolSourceReplyPayloads?.findLast((e) => e.sourceReplyFinal === true && e.text?.trim());
	const x = b ? sanitizeAgentRunTerminalReply(b.text ?? "") : h ? { disposition: "empty" } : s && e.settledTurnFinalizationOutcome !== "answered" || v !== void 0 ? sanitizeAgentRunTerminalReply(v ?? s?.message ?? "") : e.emptyAssistantReplyIsSilent ? { disposition: "silent" } : e.prepared.preparedTerminalReply.terminalReply;
	return {
		action: "complete",
		result: {
			payloads: y?.length ? y : void 0,
			...!s && e.attempt.diagnosticTrace ? { diagnosticTrace: freezeDiagnosticTraceContext(e.attempt.diagnosticTrace) } : {},
			meta: {
				durationMs: Date.now() - e.startedAtMs,
				agentMeta: e.prepared.agentMeta,
				aborted: n,
				systemPromptReport: e.attempt.systemPromptReport,
				finalPromptText: e.attempt.finalPromptText,
				finalAssistantVisibleText: b?.text ?? (h ? void 0 : e.prepared.finalAssistantVisibleText),
				finalAssistantRawText: h ? void 0 : e.prepared.finalAssistantRawText,
				replayInvalid: l,
				livenessState: u,
				stopReason: d,
				completion: {
					...d ? {
						stopReason: d,
						finishReason: d
					} : {},
					...d?.toLowerCase().includes("refusal") ? { refusal: true } : {}
				},
				agentHarnessResultClassification: e.attempt.agentHarnessResultClassification,
				terminalReply: x,
				terminalReplyExpectation: resolveReplyExpectation(e.runParams),
				...g ? { suppressErrorNotice: g } : {},
				...s ? { error: s } : {
					...e.attempt.yieldDetected ? { yielded: true } : {},
					...e.attempt.yieldAcknowledgment ? { yieldAcknowledgment: e.attempt.yieldAcknowledgment } : {},
					...f ? { continuationPending: true } : {},
					...e.intentionalTerminalCompletion ? { intentionalTerminalCompletion: "tool-batch" } : {},
					pendingToolCalls: e.attempt.clientToolCalls?.map((e) => ({
						id: randomBytes(5).toString("hex").slice(0, 9),
						name: e.name,
						arguments: JSON.stringify(e.params)
					})),
					executionTrace: {
						winnerProvider: e.prepared.reportedModelRef.provider,
						winnerModel: e.prepared.reportedModelRef.model,
						attempts: e.traceAttempts.length > 0 || e.attemptAssistant?.provider || e.attemptAssistant?.model ? [...e.traceAttempts, {
							provider: e.prepared.reportedModelRef.provider,
							model: e.prepared.reportedModelRef.model,
							result: "success",
							stage: "assistant"
						}] : void 0,
						fallbackUsed: e.traceAttempts.some((e) => e.result === "rotate_profile" || e.result === "fallback_model"),
						runner: "embedded"
					},
					requestShaping: {
						...e.authProfileId ? { authMode: "auth-profile" } : {},
						...e.thinkLevel ? { thinking: e.thinkLevel } : {},
						...e.runParams.reasoningLevel ? { reasoning: e.runParams.reasoningLevel } : {},
						...e.runParams.verboseLevel ? { verbose: e.runParams.verboseLevel } : {},
						...e.runParams.blockReplyBreak ? { blockStreaming: e.runParams.blockReplyBreak } : {}
					},
					contextManagement: e.contextRecoveryState.autoCompactionCount > 0 ? { lastTurnCompactions: e.contextRecoveryState.autoCompactionCount } : void 0
				},
				toolSummary: e.prepared.attemptToolSummary,
				...e.prepared.failureSignal ? { failureSignal: e.prepared.failureSignal } : {},
				...e.prepared.terminalToolFailure ? { terminalToolFailure: e.prepared.terminalToolFailure } : {}
			},
			...copyAttemptDeliveryState(e.attempt),
			sourceReplyDeliveryState: e.prepared.sourceReplyDeliveryState
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/settled-turn-finalization.ts
const MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS = 2;
async function prepareSettledTurnFinalization(e, t) {
	const { attempt: n } = e;
	const r = (n.answerSegments?.at(-1)?.messageEnd ?? -1) + 1;
	const observeSourceDelivery = async () => {
		let t;
		const n = e.runParams.resolveReplyDeliveryFacts;
		const i = await observeReplyDelivery(n ? async (e) => {
			const r = await n(e);
			t = r.source;
			return r.terminal;
		} : e.runParams.resolveReplyDelivery, r, (e) => log$3.warn(`reply delivery observation failed; retaining custody: ${formatErrorMessage(e)}`));
		return {
			replyDeliveryState: i,
			sourceReplyDeliveryState: t ?? i
		};
	};
	const i = await observeSourceDelivery();
	const a = prepareEmbeddedRunTerminal({
		...e,
		...i
	});
	return {
		prepared: a,
		prompt: resolveSettledTurnFinalizationRequest({
			runParams: e.runParams,
			attempt: n,
			activeErrorContext: e.activeErrorContext,
			modelApi: t.modelApi,
			executionContract: t.executionContract,
			payloadsWithToolMedia: a.payloadsWithToolMedia,
			recoveredFinalAssistantPayloadsAfterPromptTimeout: a.recoveredFinalAssistantPayloadsAfterPromptTimeout,
			hasTerminalToolPresentation: t.hasTerminalToolPresentation,
			terminalState: e.terminalState,
			replyDeliveryState: a.replyDeliveryState,
			settledTurnFinalizationAvailable: !e.runParams.providerReviewAcknowledgment && typeof t.harness.finalizeSettledTurn === "function"
		}),
		observeSourceDelivery
	};
}
/** Requests projection only after the canonical delivery and finalization decision. */
async function requestSettledTurnFinalizationContext(e, t, n) {
	const { prompt: r } = await prepareSettledTurnFinalization(e, t);
	if (r) e.attempt.settledTurnFinalizationContext = await n();
}
async function prepareTerminalWithSettledTurnFinalization(e) {
	const t = e.initial;
	const { preparedAttempt: n, sessionTarget: r, sessionWriterFence: i } = e.finalization;
	const a = n.sessionTarget || r || i ? {
		...n.sessionTarget,
		...r,
		...i
	} : void 0;
	const o = resolveSessionWriterDeliveryAuthority({
		attempt: n,
		sessionId: a?.sessionId ?? t.sessionIdUsed,
		sessionTarget: a
	});
	let s = t.attempt;
	let c = e.lastRunPromptUsage;
	const l = await prepareSettledTurnFinalization({
		...e.terminalBase,
		...t,
		attempt: s,
		lastRunPromptUsage: c
	}, e.finalization);
	let { prepared: u } = l;
	const { prompt: d, observeSourceDelivery: f } = l;
	const preserveInitial = (e) => ({
		...t,
		prepared: u,
		lastRunPromptUsage: c,
		finalizationOutcome: e
	});
	if (!d) return preserveInitial("not-attempted");
	const p = resolveAdmittedRunActiveAssertion(e.finalization.preparedAttempt.admittedRunContext, e.finalization.abortSignal);
	if (!p) throw new Error("admitted run authority is no longer active");
	const m = e.terminalBase.runParams;
	const h = e.terminalBase.activeErrorContext;
	const describeRun = () => `runId=${m.runId} sessionId=${m.sessionId} provider=${h.provider}/${h.model}`;
	const g = Boolean(t.attempt.lastToolError) || isEmbeddedRunTerminalTimeout(t.terminalState.outcome) || classifyAgentRunTerminalOutcome(t.terminalState.outcome) === "failure";
	log$3.warn(`settled post-tool turn lacked a final answer: ${describeRun()} — running isolated finalization`);
	let _ = "failed";
	let v = false;
	try {
		let n;
		let r = 0;
		for (;;) {
			r += 1;
			p();
			n = await runPreparedSettledTurnFinalization({
				attempt: {
					...e.finalization.preparedAttempt,
					...a ? { sessionTarget: a } : {},
					sessionId: a?.sessionId ?? t.sessionIdUsed,
					sessionFile: t.sessionFileUsed ?? e.finalization.preparedAttempt.sessionFile
				},
				settledAttempt: t.attempt,
				harness: e.finalization.harness,
				prompt: d,
				createAttemptControls: e.finalization.createAttemptControls,
				abortSignal: e.finalization.abortSignal
			});
			p();
			v = n.outcome === "answered";
			s = n.attempt;
			mergeUsageIntoAccumulator(e.terminalBase.usageAccumulator, s.attemptUsage);
			mergeAttemptRunStatsIntoAccumulator(e.terminalBase.usageAccumulator, s);
			c = s.attemptUsage ?? c;
			if (n.outcome === "empty" && shouldTreatEmptyAssistantReplyAsSilent({
				terminalReplyExpectation: resolveReplyExpectation(m),
				payloadCount: 0,
				aborted: e.finalization.abortSignal.aborted,
				timedOut: isEmbeddedRunTerminalTimeout(t.terminalState.outcome),
				attempt: s
			})) {
				if (!g) n.outcome = "answered";
				break;
			}
			if (n.outcome !== "empty" || r >= MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS) break;
			log$3.warn(`settled-turn finalization completed without a visible answer: ${describeRun()} — retrying ${r}/1 with tools disabled`);
		}
		_ = n.outcome;
		if (n.outcome === "empty") log$3.warn(`settled-turn finalization completed without a visible answer: ${describeRun()} attempts=${r}/${MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS} — preserving failed recovery`);
	} catch (t) {
		if (e.finalization.abortSignal.aborted) {
			log$3.warn(`settled-turn finalization was cancelled: ${describeRun()} error=${formatErrorMessage(t)} — preserving cancellation`);
			return preserveInitial("failed");
		}
		p();
		log$3.warn(`settled-turn finalization failed: ${describeRun()} error=${formatErrorMessage(t)} — preserving failed recovery`);
	}
	if (_ !== "answered" && e.finalization.abortSignal.aborted) {
		log$3.warn(`settled-turn finalization was cancelled before terminal delivery: ${describeRun()} — preserving cancellation`);
		return preserveInitial("failed");
	}
	const y = v && _ === "answered" && t.terminalState.outcome.stopReason === "length";
	const b = _ !== "answered" && g ? t : {
		attempt: s,
		attemptAssistant: s.currentAttemptAssistant,
		currentAttemptCompletedAssistant: s.currentAttemptCompletedAssistant,
		terminalState: _ !== "answered" ? t.terminalState : {
			outcome: y ? buildAgentRunTerminalOutcome({
				...t.terminalState.outcome,
				status: "error",
				error: CUT_OFF_SUMMARY_NOTICE_TEXT
			}) : resolveEmbeddedRunAttemptTerminalOutcome({
				attempt: s,
				assistant: s.currentAttemptAssistant
			}),
			signalOwnedInterruption: false
		},
		attemptCompactionCount: 0,
		sessionIdUsed: s.sessionIdUsed,
		sessionFileUsed: s.sessionFileUsed
	};
	const x = prepareEmbeddedRunTerminal({
		...e.terminalBase,
		...b,
		...await f(),
		lastRunPromptUsage: c
	});
	if (_ === "answered" && x.payloadsWithToolMedia?.length && isSettledTurnCutOffByOutputLimit(t.attempt)) x.payloadsWithToolMedia.push(setReplyPayloadMetadata({ text: CUT_OFF_SUMMARY_NOTICE_TEXT }, { hostNotice: true }));
	x.payloadsWithToolMedia?.forEach((e) => {
		if (_ === "answered") markReplyPayloadForSourceSuppressionDelivery(e);
		if (o) setReplyPayloadMetadata(e, { sessionWriterDeliveryAuthority: o });
	});
	u = {
		...x,
		payloadsWithToolMedia: x.sourceReplyDeliveryState === "missing" ? x.payloadsWithToolMedia : x.payloadsWithToolMedia?.filter((e) => !isReplyPayloadTerminalContent(e)),
		..._ !== "answered" && m.sourceReplyDeliveryMode === "message_tool_only" ? {
			finalAssistantVisibleText: "",
			finalAssistantRawText: "",
			finalAssistantMessageRawText: ""
		} : {},
		attemptToolSummary: u.attemptToolSummary,
		failureSignal: u.failureSignal,
		terminalToolFailure: u.terminalToolFailure
	};
	if (v && _ === "answered") {
		p();
		if (!y) m.onAttemptTerminalReplaced?.();
	}
	return {
		...b,
		prepared: u,
		lastRunPromptUsage: c,
		finalizationOutcome: _ === "answered" ? "answered" : "failed"
	};
}
function resolveSessionWriterDeliveryAuthority(e) {
	const t = e.sessionTarget ?? e.attempt.sessionTarget;
	const n = t?.sessionKey ?? e.attempt.sessionKey;
	const r = t?.expectedLifecycleRevision;
	const i = t?.expectedWriterRunId;
	if (!n || r === void 0 && i === void 0) return;
	return {
		...t?.agentId || e.attempt.agentId ? { agentId: t?.agentId ?? e.attempt.agentId } : {},
		expectedSessionId: e.sessionId,
		...r !== void 0 ? { expectedLifecycleRevision: r } : {},
		...i !== void 0 ? { expectedWriterRunId: i } : {},
		sessionKey: n,
		...t?.storePath ? { storePath: t.storePath } : {}
	};
}
async function runPreparedSettledTurnFinalization(e) {
	const t = e.createAttemptControls({
		admittedRunContext: e.attempt.admittedRunContext,
		abortSignal: e.abortSignal,
		initialTimeoutMs: resolveAgentTimeoutMs({
			cfg: e.attempt.config,
			overrideMs: e.attempt.timeoutMs
		})
	});
	try {
		const n = createAdmittedGatewayToolCallerIdentity({
			admittedRunContext: e.attempt.admittedRunContext,
			agentId: e.attempt.agentId,
			sessionKey: e.attempt.sessionKey
		});
		const r = await withGatewayToolCallerIdentity(n, () => runAgentHarnessSettledTurnFinalization({
			...e.attempt,
			abortSignal: t.abortSignal,
			bindWatchdogAttempt: t.bindWatchdogAttempt,
			onAttemptDeadlineChanged: t.onAttemptDeadlineChanged,
			onAttemptTimeout: t.onAttemptTimeout,
			onAttemptAbort: t.onAttemptAbort,
			onAttemptTimeoutArmed: void 0,
			operation: "settled-tool-finalization",
			prompt: e.prompt,
			disableTools: true,
			skipPreparedUserTurnMessage: true,
			suppressNextUserMessagePersistence: true,
			initialReplayState: {
				replayInvalid: false,
				hadPotentialSideEffects: false
			}
		}, e.settledAttempt, e.harness));
		const i = r.outcome;
		const a = r.result;
		const o = e.settledAttempt;
		const s = e.prompt;
		const c = e.attempt.agentHarnessId;
		const l = e.attempt.runtimePlan;
		const { preparedTerminalReply: u } = a;
		const d = u.text;
		return {
			outcome: i,
			attempt: {
				terminal: { kind: "ok" },
				preparedTerminalReply: u,
				sessionIdUsed: o.sessionIdUsed,
				sessionFileUsed: o.sessionFileUsed,
				...c ? { agentHarnessId: c } : {},
				modelAttempt: resolveRuntimeModelAttempt(l),
				...o.runtimeModelSelection ? { runtimeModelSelection: o.runtimeModelSelection } : {},
				contextTokens: o.contextTokens,
				contextTokensSource: o.contextTokensSource,
				authBindingFingerprint: o.authBindingFingerprint,
				runtimeArtifact: o.runtimeArtifact,
				systemPromptReport: o.systemPromptReport,
				finalPromptText: s,
				...copyAttemptDeliveryState(o),
				messagesSnapshot: [...o.messagesSnapshot, a.assistant],
				assistantTexts: d ? [d] : [],
				assistantTranscriptOwned: a.assistantTranscriptOwned,
				assistantTranscriptIdempotencyKey: a.assistantTranscriptIdempotencyKey,
				lastAssistantTextMessageIndex: a.assistantMessageIndex,
				lastAssistant: a.assistant,
				currentAttemptAssistant: a.assistant,
				currentAttemptCompletedAssistant: a.assistant,
				toolMetas: o.toolMetas,
				lastToolError: o.lastToolError,
				successfulNestedToolNames: o.successfulNestedToolNames,
				hasToolMediaBlockReply: false,
				cloudCodeAssistFormatError: false,
				attemptUsage: a.usage,
				codeModeEngaged: o.codeModeEngaged,
				assistantTurns: 1,
				replayMetadata: {
					hadPotentialSideEffects: false,
					replaySafe: true
				},
				currentAttemptReplayMetadata: {
					hadPotentialSideEffects: false,
					replaySafe: true
				},
				itemLifecycle: {
					startedCount: 0,
					completedCount: 0,
					activeCount: 0
				},
				diagnosticTrace: a.diagnosticTrace
			}
		};
	} finally {
		t.close();
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/terminal-timeout.ts
function resolveEmbeddedRunTerminalTimeout(e) {
	const t = isEmbeddedRunTimeoutFinal(e.attempt);
	const n = isEmbeddedRunTerminalTimeout(e.terminalState.outcome);
	const { idleTimedOut: r, timedOutDuringToolExecution: i, timedOutDuringCompaction: a } = projectAgentRunAttemptTerminal(e.attempt.terminal);
	const o = n && (i || a) && !(a && e.terminalPrepared.hasSuccessfulFinalAssistantAfterPromptTimeout) && e.terminalPrepared.replyDeliveryState === "missing" && !e.terminalPrepared.payloads?.some((e) => {
		const t = getReplyPayloadMetadata(e);
		return !isHostNoticePayload(e) && isReplyPayloadTerminalContent(e) && t?.sourceReplyFinal !== false && t?.precedingInputAnswer !== true;
	}) && !hasRunContinuationEvidence(e.attempt);
	if (!e.terminalPrepared.timedOutDuringPrompt && !o || !o && !t && (e.terminalPrepared.hasSuccessfulFinalAssistantAfterPromptTimeout || hasMessagingToolDeliveryEvidence(e.attempt))) return;
	const s = i ? "Tool execution timed out with an unknown outcome. Check the current state before repeating the operation." : a ? "Context compaction timed out before a response was generated. Please try again." : r ? "The model did not produce a response before the model idle timeout. Please try again, or increase `models.providers.<id>.timeoutSeconds` for slow local or self-hosted providers. If `agents.defaults.timeoutSeconds` or a run-specific timeout is lower, raise that ceiling too; provider timeouts cannot extend a model attempt budget." : "Request timed out before a response was generated. Please try again, or increase `agents.defaults.timeoutSeconds` in your config.";
	const c = e.attempt.promptTimeoutOutcome?.message?.trim() || s;
	const l = e.attempt.promptTimeoutOutcome?.replayInvalid ?? e.resolveReplayInvalid(null);
	const u = e.attempt.promptTimeoutOutcome?.livenessState ?? resolveRunLivenessState({
		payloadCount: o || e.terminalPrepared.hasPartialAssistantTextAfterPromptTimeout ? 0 : e.terminalPrepared.payloads?.length ?? 0,
		aborted: false,
		timedOut: n,
		attempt: e.attempt,
		incompleteTurnText: null
	});
	const d = e.attempt.promptTimeoutOutcome?.timeoutPhase ?? e.terminalState.outcome.timeoutPhase;
	const f = e.attempt.promptTimeoutOutcome?.providerStarted ?? e.terminalState.outcome.providerStarted;
	const p = {
		...o && a ? { stopReason: "timeout" } : {},
		...d ? { timeoutPhase: d } : {},
		...typeof f === "boolean" ? { providerStarted: f } : {}
	};
	e.setTerminalLifecycleMeta({
		replayInvalid: l,
		livenessState: u,
		...p
	});
	return {
		payloads: [...e.terminalPrepared.hasPartialAssistantTextAfterPromptTimeout && !t ? [] : e.terminalPrepared.payloadsWithToolMedia || [], {
			text: c,
			isError: true
		}],
		meta: {
			modelFallbackStopReason: "agent_run_terminal_timeout",
			durationMs: Date.now() - e.startedAtMs,
			agentMeta: e.terminalPrepared.agentMeta,
			aborted: false,
			systemPromptReport: e.attempt.systemPromptReport,
			finalPromptText: e.attempt.finalPromptText,
			finalAssistantVisibleText: e.terminalPrepared.finalAssistantVisibleText,
			terminalReply: e.terminalPrepared.preparedTerminalReply.terminalReply,
			finalAssistantRawText: e.terminalPrepared.finalAssistantRawText,
			...e.terminalPrepared.finalAssistantMessageRawText !== void 0 ? { finalAssistantMessageRawText: e.terminalPrepared.finalAssistantMessageRawText } : {},
			replayInvalid: l,
			livenessState: u,
			...p,
			error: {
				kind: "incomplete_turn",
				message: c,
				fallbackSafe: false
			},
			toolSummary: e.terminalPrepared.attemptToolSummary,
			...e.terminalPrepared.failureSignal ? { failureSignal: e.terminalPrepared.failureSignal } : {},
			...e.terminalPrepared.terminalToolFailure ? { terminalToolFailure: e.terminalPrepared.terminalToolFailure } : {},
			agentHarnessResultClassification: e.attempt.agentHarnessResultClassification
		},
		...copyAttemptDeliveryState(e.attempt)
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/turn-taint-state.ts
/** Sticky current-turn taint shared by retries and runtime-specific tool owners. */
function createAgentTurnTaintState(e = false) {
	let t = e;
	return {
		observe(e) {
			if (!e.presentationOnly && e.resultContentSource === "network") t = true;
		},
		isTainted: () => t
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run-loop.ts
async function runPreparedEmbeddedLoop(e, t) {
	try {
		var n = _usingCtx();
		let { runParams: r, provider: i, modelId: a, preReplyGeneration: o } = t;
		const { hookRunner: s, hookContext: c, fallbackConfigured: l, resolvedSessionKey: u, startedAtMs: d, startupStages: f, lifecycleGeneration: p } = t;
		const { notifyExecutionPhase: m } = t.progressController;
		let h = false;
		const g = await measureEmbeddedAgentPreparation("runtime", () => prepareEmbeddedRunRuntime({
			...t,
			assertCurrent: t.laneController.throwIfAborted,
			getAuthDeadline: t.laneController.getExecutionDeadline,
			hookContext: o?.assertCurrent ? withClaimingHookAdmission({ ...c }, { assertCurrent: o?.assertCurrent }) : c,
			markStartupStage: (e) => f.mark(e),
			notifyExecutionPhase: m
		}), { config: r.config });
		n.a({ [Symbol.asyncDispose]: () => g.releaseTransport() });
		const _ = t.laneController.abortSignal;
		r = {
			...r,
			admittedRunContext: g.admittedRunContext,
			abortSignal: _
		};
		const v = getAdmittedRunDelegatedAuthority(g.admittedRunContext);
		const y = resolveAdmittedRunActiveAssertion(g.admittedRunContext, _);
		const b = {
			...t,
			runParams: r,
			modelCallSequence: getAgentRunContext(r.runId)?.modelCallSequence ?? { value: 0 }
		};
		({provider: i, modelId: a} = g);
		const { model: x, profileCandidates: S, pluginHarnessOwnsAuthBootstrap: C, attemptedThinking: w, getApiKeyInfo: T } = g;
		const E = g.snapshot().agentHarness;
		const D = [];
		const resolveRuntimeFallbackReason = () => D.findLast((e) => e.result === "fallback_model" && typeof e.reason === "string")?.reason ?? (r.modelRoutingProvenance?.stage === "fallback" ? r.modelRoutingProvenance.fallbackReason ?? null : null);
		const { sessionKey: O, config: k, agentId: A } = r;
		const { sessionAgentId: j } = resolveSessionAgentIds({
			sessionKey: O,
			config: k,
			agentId: A
		});
		const M = isStrictAgenticExecutionContractActive({
			config: r.config,
			sessionKey: r.sessionKey,
			agentId: r.agentId,
			provider: i,
			modelId: a
		}) ? "strict-agentic" : "default";
		const N = createRunRetryBudget(resolveMaxRunRetryIterations(S.length));
		const P = createEmbeddedRunContextRecoveryState();
		let F = r.bootstrapPromptWarningSignaturesSeen ?? (r.bootstrapPromptWarningSignature ? [r.bootstrapPromptWarningSignature] : []);
		const I = createUsageAccumulator();
		let L;
		let R = 0;
		const z = createEmbeddedRunTerminalRetryState();
		const B = { consecutiveIdleTimeoutsBeforeOutput: 0 };
		const V = resolveToolLoopDetectionConfig({
			cfg: r.config,
			agentId: j
		});
		const H = createPostCompactionLoopGuard({ enabled: V?.enabled !== false });
		let U;
		const W = createTerminalToolPresentationTracker();
		const G = createAgentTurnTaintState(r.initialTurnTainted === true);
		const observeToolOutcome = (e) => {
			W.observe(e);
			G.observe(e);
			if (e.presentationOnly) return;
			const n = H.observe(e);
			if (n.shouldAbort) {
				U ??= Object.assign(new Error(n.message), {
					name: "PostCompactionLoopPersistedError",
					detector: n.detector,
					count: n.count,
					toolName: n.toolName
				});
				t.laneController.laneTaskAbortController.abort(U);
			}
		};
		let K = null;
		let q = 0;
		let J = 0;
		const Y = await createEmbeddedRunSessionPromptState({
			runParams: r,
			sessionAgentId: j,
			resolvedSessionKey: u,
			lifecycleGeneration: p,
			onInterrupt: (e) => t.laneController.laneTaskAbortController.abort(e)
		});
		t.onInitialWriterPrepared(Y);
		const X = createProviderReviewRun({
			run: b,
			runtime: g,
			session: Y,
			assertCurrent: y
		});
		const ee = { ...Y.sessionTarget };
		const te = r.sessionPersistence !== "detached" && !(r.sessionManager && !r.sessionManager.getSessionTarget());
		const Z = createEmbeddedRunFailoverRetryController({
			runInput: b,
			preparedRuntime: g,
			getSessionId: () => Y.sessionId
		});
		const { contextEngine: ne, contextEngineLogicalTurnLease: re, ownsContextEngineLogicalTurnLease: ie } = await admitEmbeddedContextEngine(b, E);
		const ae = createEmbeddedRunPermissionChanges(r);
		try {
			f.mark("context-engine");
			m("context_engine", {
				provider: i,
				model: a
			});
			await X.admit();
			const n = createEmbeddedRunCompactionRuntime({
				runParams: r,
				contextEngine: ne,
				hookRunner: s,
				hookContext: c,
				sessionPromptState: Y
			});
			let u = false;
			let p = createEmbeddedRunReplayState();
			const v = createAttemptCarryover();
			while (true) {
				_?.throwIfAborted();
				if (!y) throw new Error("embedded run requires an active admitted run");
				y();
				X.beginAttempt();
				const s = g.snapshot();
				const { agentHarness: c, pluginHarnessOwnsTransport: f, effectiveModel: m, outerContextTokenMeta: S, lastProfileId: E, thinkLevel: O } = s;
				if (isRunRetryBudgetExhausted(N)) {
					const e = `Exceeded retry limit after ${N.attemptsDispatched} attempts (counted attempts=${N.attemptsCounted}, max=${N.maxAttempts}).`;
					log$3.error(`[run-retry-limit] sessionKey=${r.sessionKey ?? r.sessionId} provider=${i}/${a} attempts=${N.attemptsDispatched} countedAttempts=${N.attemptsCounted} maxAttempts=${N.maxAttempts}`);
					const t = resolveRunFailoverDecision({
						stage: "retry_limit",
						fallbackConfigured: l,
						failoverReason: K
					});
					return X.finish(handleRetryLimitExhaustion({
						message: e,
						decision: t,
						provider: i,
						model: a,
						profileId: E,
						durationMs: Date.now() - d,
						agentMeta: buildErrorAgentMeta({
							sessionId: Y.sessionId,
							sessionFile: Y.sessionFile,
							...v.modelAttempt ?? {
								provider: i,
								model: x.id
							},
							...S,
							usageAccumulator: I,
							lastRunPromptUsage: L
						}),
						replayInvalid: p.replayInvalid ? true : void 0
					}));
				}
				r.assistantErrorTranscript?.clear();
				beginRunAttempt(N);
				o?.assertCurrent();
				o?.release();
				o = void 0;
				r.onAttemptStart?.();
				const k = u;
				u = false;
				w.add(O);
				const A = hasCodexAppServerRecoveryRetryBudget({
					alreadyRetried: q > 0,
					runLoopIterations: N.attemptsCounted,
					maxRunLoopIterations: N.maxAttempts
				});
				const V = P.beginAttempt(_, r.onCompactionRequestBudget);
				const ee = {
					...b,
					runParams: {
						...r,
						onCompactionRequestBudget: V.onCompactionRequestBudget,
						onContextAccountingEvent: V.onContextAccountingEvent
					}
				};
				const terminalBase = (n) => ({
					rateLimitRetriesExhausted: Z.rateLimitRetriesExhausted,
					mergeToolMedia: e.mergeToolMedia,
					runParams: r,
					provider: i,
					providerOwner: g.snapshot().providerRuntimeHandle.plugin,
					model: x.id,
					activeErrorContext: n,
					authProfileStore: g.attemptAuthProfileStore,
					authProfileId: E,
					outerContextTokenMeta: S,
					usageAccumulator: I,
					contextRecoveryState: P,
					resolvedToolResultFormat: t.resolvedToolResultFormat
				});
				let te;
				try {
					const dispatchAttempt = () => prepareAndDispatchEmbeddedRunAttempt({
						permissionChange: ae.forAttempt(),
						runInput: ee,
						preparedRuntime: g,
						contextEngine: ne,
						sessionPromptState: Y,
						terminalRetryState: z,
						replayState: p,
						startupStagesEmitted: h,
						bootstrapPromptWarningSignaturesSeen: F,
						resolveRuntimeFallbackReason,
						observeToolOutcome,
						isTurnTainted: G.isTainted,
						allocateToolOutcomeOrdinal: W.allocateOrdinal,
						getPostCompactionAbortError: () => U
					}, async (n, o) => {
						const s = resolveCurrentAttemptAssistant(n);
						e.applyDeliveryState(n);
						n.sourceReplyDeliveryState = resolveSourceReplyDelivery(n, r.replyOperation?.sourceReplyDelivered ? "delivered" : "missing");
						await requestSettledTurnFinalizationContext({
							...terminalBase(resolveReportedModelRef({
								provider: i,
								model: a,
								assistant: s
							})),
							attempt: n,
							currentAttemptCompletedAssistant: n.currentAttemptCompletedAssistant,
							sessionIdUsed: n.sessionIdUsed,
							sessionFileUsed: n.sessionFileUsed,
							lastRunPromptUsage: L,
							terminalState: resolveEmbeddedRunAttemptTerminalState({
								attempt: n,
								assistant: s,
								abortSignal: t.laneController.abortSignal
							})
						}, {
							harness: c,
							modelApi: m.api,
							executionContract: M,
							hasTerminalToolPresentation: Boolean(W.read())
						}, o);
					});
					te = await withProviderRateLimitRetryDeadline(Z.sharedTpmRetryDeadline, () => Y.withSessionWriterContext(dispatchAttempt));
				} catch (e) {
					V.close();
					X.failure(e);
					const t = await Z.recoverThrownHarnessAuthFailure(e);
					if (!t) throw e;
					D.push(t);
					K = t.reason;
					continue;
				} finally {
					V.close();
				}
				h = te.startupStagesEmitted;
				{
					const { dispatchedAttempt: o, runtimePlan: l } = te;
					const h = await X.settle(o.rawAttempt);
					Z.observeAttempt(o.rawAttempt);
					if (o.rawAttempt.hasSuccessfulModelResponse) recordRunModelProgress(N);
					const _ = e.applyDeliveryState(o.rawAttempt);
					v.apply(_);
					_.sourceReplyDeliveryState = resolveSourceReplyDelivery(_, r.replyOperation?.sourceReplyDelivered ? "delivered" : "missing");
					const S = {
						runInput: b,
						preparedRuntime: g,
						dispatchedAttempt: o,
						recordedCompactionCount: V.recordedCompactionCount,
						sessionPromptState: Y,
						provider: i,
						modelId: a,
						bootstrapPromptWarningSignaturesSeen: F,
						usageAccumulator: I,
						lastRunPromptUsage: L,
						idleTimeoutBreakerState: B,
						contextRecoveryState: P,
						replayState: p,
						lastRetryFailoverReason: K
					};
					const w = await normalizeEmbeddedRunAttempt(S);
					const O = e.continueAfterAttempt(S, y, G.isTainted);
					if (O) return X.finish(O);
					if (w.action === "complete") return X.finish(w.result);
					F = w.bootstrapPromptWarningSignaturesSeen;
					L = w.lastRunPromptUsage;
					p = w.replayState;
					if (w.action === "retry") {
						recordRunRetry(N, w.retryKind);
						continue;
					}
					if (h?.category !== "misalignment" && ae.prepareRestart()) {
						t.laneController.throwIfAborted();
						Y.continueFromCurrentTranscript();
						recordRunRetry(N, "progress_continuation");
						continue;
					}
					const { attempt: U, sessionIdUsed: ee, sessionFileUsed: ie, currentAttemptCompletedAssistant: oe, attemptAssistant: se, terminalState: ce, setTerminalLifecycleMeta: le, attemptCompactionCount: Q, activeErrorContext: ue, resolveReplayInvalidForAttempt: de } = w;
					const fe = await recoverEmbeddedRunAttempt({
						runInput: b,
						preparedRuntime: g,
						normalizedAttempt: w,
						runtimePlan: l,
						sessionPromptState: Y,
						failoverRetryController: Z,
						compactionRuntime: n,
						contextEngine: ne,
						contextRecoveryState: P,
						resolveContextEnginePluginId: () => re.effectiveEnginePluginId ?? resolveContextEngineOwnerPluginId(ne),
						buildRuntimeSettings: (e) => buildContextEngineRuntimeSettings({
							contextEngineHost: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST,
							provider: i,
							requestedModel: g.requestedModelId,
							resolvedModel: a,
							selectedContextEngineId: ne.info.id,
							contextEngineSelectionSource: ne.info.id === "legacy" ? "default" : "configured",
							promptTokenBudget: e.tokenBudget,
							fallbackReason: resolveRuntimeFallbackReason(),
							degradedReason: e.degradedReason
						}),
						armPostCompactionGuard: () => H.armPostCompaction(),
						usageAccumulator: I,
						lastRunPromptUsage: L,
						runtimeAuthRetry: k,
						codexAppServerRecoveryRetryAvailable: A,
						codexAppServerRecoveryRetries: q,
						lastRetryFailoverReason: K,
						traceAttempts: D,
						sessionAgentId: j
					});
					if (fe.action === "complete") return X.finish(fe.result);
					if (fe.action === "retry") {
						u = fe.authRetryPending;
						q = fe.codexAppServerRecoveryRetries;
						K = fe.lastRetryFailoverReason;
						continue;
					}
					const pe = b.preparedModelRuntime;
					const me = await handleEmbeddedAssistantFailure({
						runInput: b,
						providerOutcomes: pe && (readCapturedPreparedModelRuntimeCatalog(pe) ?? pe.modelCatalog).providerOutcomes,
						preparedRuntime: g,
						normalizedAttempt: w,
						runtime: s,
						providerOwner: g.snapshot().providerRuntimeHandle.plugin,
						getThinkLevel: () => g.snapshot().thinkLevel,
						runtimeAuthRetry: k,
						emptyErrorRetries: J,
						overloadProfileRotations: R,
						previousRetryFailoverReason: K,
						failover: Z,
						rateLimitRetriesExhausted: Z.rateLimitRetriesExhausted,
						traceAttempts: D,
						suspensionSessionId: Y.sessionId ?? r.sessionId
					});
					g.setThinkLevel(me.thinkLevel);
					u = me.authRetryPending;
					J = me.emptyErrorRetries;
					R = me.overloadProfileRotations;
					K = me.lastRetryFailoverReason;
					if (me.action === "retry") continue;
					let he = me.assistantProfileFailureReason;
					const ge = W.read();
					const _e = await Y.withSessionWriterContext(() => prepareTerminalWithSettledTurnFinalization({
						initial: {
							attempt: U,
							attemptAssistant: se,
							currentAttemptCompletedAssistant: oe,
							sessionIdUsed: ee,
							sessionFileUsed: ie,
							terminalState: ce,
							attemptCompactionCount: Q
						},
						terminalBase: terminalBase(ue),
						lastRunPromptUsage: L,
						finalization: {
							preparedAttempt: o.preparedAttempt,
							sessionTarget: Y.sessionTarget,
							sessionWriterFence: Y.sessionWriterFence,
							harness: c,
							modelApi: m.api,
							executionContract: M,
							hasTerminalToolPresentation: Boolean(ge),
							createAttemptControls: t.laneController.createAttemptControls,
							abortSignal: t.laneController.abortSignal
						}
					}));
					const { attempt: ve, terminalState: ye, prepared: be, finalizationOutcome: xe } = _e;
					L = _e.lastRunPromptUsage;
					if (xe === "answered") he = null;
					const Se = resolveEmbeddedRunTerminalTimeout({
						terminalPrepared: be,
						attempt: ve,
						terminalState: ye,
						resolveReplayInvalid: de,
						setTerminalLifecycleMeta: le,
						startedAtMs: d
					});
					if (Se) return X.finish(Se);
					const $ = g.snapshot().activePreparedAuthPlan;
					const Ce = $.modelRoute?.requestTransportOverrides ?? $.deferredRouteSupport?.requestTransportOverrides ?? "none";
					const we = await resolveEmbeddedRunTerminal({
						..._e,
						runParams: r,
						retryState: z,
						activeErrorContext: ue,
						modelApi: m.api,
						executionContract: M,
						replayState: p,
						sessionPromptState: Y,
						armPostCompactionGuard: () => H.armPostCompaction(),
						readTerminalToolPresentation: () => ge,
						resolveReplayInvalid: de,
						setTerminalLifecycleMeta: le,
						maybeMarkAuthProfileFailure: Z.maybeMarkAuthProfileFailure,
						assistantProfileFailureReason: he,
						startedAtMs: d,
						provider: i,
						modelId: a,
						modelTransportId: m.id ?? a,
						modelTransportApi: m.api ?? x.api,
						...m.baseUrl ? { modelTransportBaseUrl: m.baseUrl } : {},
						requestTransportOverrides: Ce,
						authProfileId: E,
						profileFailureStore: g.profileFailureStore,
						attemptAuthProfileStore: g.attemptAuthProfileStore,
						apiKeyInfo: T(),
						agentHarnessId: c.id,
						settledTurnFinalizationOutcome: xe,
						pluginHarnessOwnsTransport: f,
						pluginHarnessOwnsAuthBootstrap: C,
						traceAttempts: D,
						thinkLevel: me.thinkLevel,
						contextRecoveryState: P
					});
					if (we.action === "retry") continue;
					const { result: Te } = we;
					return X.finish(be.finalAssistantMessageRawText === void 0 ? Te : {
						...Te,
						meta: {
							...Te.meta,
							finalAssistantMessageRawText: be.finalAssistantMessageRawText
						}
					});
				}
			}
		} finally {
			P.restoreTimeoutRecoveryAbandonment();
			ae.close();
			await settleEmbeddedRun({
				runInput: b,
				runtime: g,
				compaction: {
					state: P,
					session: Y,
					originalTarget: ee,
					durable: te,
					authority: v
				},
				ownedContextEngineLease: ie ? re : void 0
			});
		}
	} catch (e) {
		n.e = e;
	} finally {
		await n.d();
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/execution-phase-diagnostics.ts
/** Tracks session rotation so diagnostics keep the current identity after compaction. */
function withExecutionPhaseDiagnostics(e) {
	const t = e.onExecutionPhase;
	const n = e.onSessionIdChanged;
	let r = e.sessionId;
	const onSessionIdChanged = (e) => {
		r = e;
		n?.(e);
	};
	const onExecutionPhase = (n) => {
		if (areDiagnosticsEnabledForProcess()) emitDiagnosticEvent({
			type: "run.execution_phase",
			runId: e.runId,
			sessionId: r,
			sessionKey: e.sessionKey,
			...n
		});
		t?.(n);
	};
	return {
		...e,
		onExecutionPhase,
		onSessionIdChanged
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/lane-controller.ts
function createEmbeddedRunLaneController(e) {
	const t = e.getParams();
	const n = {
		taskKind: t.trigger === "cron" ? "cron" : t.spawnedBy ? "spawn" : "turn",
		sessionKey: t.sessionKey,
		runId: t.runId,
		requesterSessionKey: t.spawnedBy ?? void 0,
		modelFallbackCandidate: t.isFinalFallbackAttempt !== void 0
	};
	const r = resolveEmbeddedRunSessionLanePolicy(t.trigger, t.inputProvenance);
	const i = resolveEmbeddedRunLaneTimeoutMs(t.timeoutMs);
	const a = new AbortController();
	const o = AbortSignal.any([...t.abortSignal ? [t.abortSignal] : [], a.signal]);
	let s = Date.now();
	let c = s;
	let l;
	let u;
	const createLaneTimeoutError = (t) => new CommandLaneTaskTimeoutError(e.globalLane, {
		elapsedMs: Math.max(0, Date.now() - c),
		taskBudgetMs: i,
		...t === "abort-grace" ? {
			cause: t,
			graceMs: EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS
		} : { cause: t }
	});
	let d;
	const boundedLaneDeadline = () => d?.kind === "bounded" ? d.deadlineAtMs : void 0;
	const setLaneTaskDeadline = (e) => {
		d = e?.kind === "bounded" ? {
			kind: "bounded",
			deadlineAtMs: e.deadlineAtMs + EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS
		} : e;
		p?.setExecutionDeadline(boundedLaneDeadline());
	};
	let f;
	let p;
	let m = 0;
	let h = 0;
	const g = /* @__PURE__ */ new Set();
	const trackGlobalExecution = (e) => {
		const release = () => g.delete(e);
		g.add(e);
		e.then(release, release);
		return e;
	};
	let _;
	let v;
	let y;
	const endCapacityWait = () => {
		y?.();
		y = void 0;
	};
	const noteCapacityWait = () => {
		const t = e.getParams();
		if (!t.abortSignal?.aborted) y = registerAgentRunCapacityWait(t.runId, e.getLifecycleGeneration());
	};
	const releaseQueuedContext = (e) => {
		endCapacityWait();
		v?.removeEventListener("abort", abandonQueuedContext);
		v = void 0;
		_?.(e);
		_ = void 0;
	};
	const abandonQueuedContext = () => releaseQueuedContext("abandoned");
	const noteLaneTaskProgress = () => {
		s = Date.now();
	};
	let b;
	let x;
	let recoverAttemptDeadline;
	const recoverExecutionDeadline = async () => {
		if (await recoverAttemptDeadline?.()) return true;
		if (!o.aborted) u ??= createLaneTimeoutError("owner-deadline");
		return false;
	};
	const createAttemptControls = (t) => {
		b?.();
		const n = {};
		x = n;
		const r = e.getLifecycleGeneration();
		const i = getAdmittedRunDelegatedAuthority(t.admittedRunContext);
		const s = t.abortSignal ? AbortSignal.any([o, t.abortSignal]) : o;
		let c = "active";
		let l = false;
		let d = false;
		const f = e.getParams().replyOperation;
		const isAttemptCurrent = () => c === "active" && x === n && !s.aborted && isAgentEventLifecycleGenerationCurrent(r);
		const isCurrent = () => isAttemptCurrent() && i !== void 0 && getAdmittedRunDelegatedAuthority(t.admittedRunContext) === i && isAttemptCurrent();
		recoverAttemptDeadline = async () => {
			if (!f || !d || !isCurrent()) return false;
			const e = await readSessionControllerOperationState(f)?.retireAdmissionAfterFencing(isCurrent);
			if (!isCurrent()) return true;
			if (e) {
				u ??= createLaneTimeoutError("release-signal");
				a.abort(u);
			}
			return e === true;
		};
		const onAttemptDeadlineChanged = (e) => {
			if (isCurrent()) {
				l = true;
				setLaneTaskDeadline(e);
			}
		};
		if (t.initialTimeoutMs !== void 0) onAttemptDeadlineChanged(t.initialTimeoutMs >= 2147e6 ? { kind: "unlimited" } : {
			kind: "bounded",
			deadlineAtMs: Date.now() + t.initialTimeoutMs
		});
		return {
			bindWatchdogAttempt: (e) => {
				if (!isCurrent()) return;
				p = e;
				e.setExecutionDeadline(boundedLaneDeadline());
			},
			isCurrent,
			isAttemptCurrent,
			abortSignal: s,
			onAttemptDeadlineChanged,
			onAttemptTimeout: (e) => {
				if (!isCurrent() || d) return;
				d = true;
				l = true;
				setLaneTaskDeadline({
					kind: "bounded",
					deadlineAtMs: Date.now()
				});
			},
			onAttemptAbort: () => {
				if (!isCurrent()) return;
				c = "aborted";
				a.abort(createAgentRunDirectAbortError());
				t.onAbort?.();
			},
			close: () => {
				if (c === "closed") return;
				c = "closed";
				if (x === n) {
					x = void 0;
					recoverAttemptDeadline = void 0;
					if (l) setLaneTaskDeadline(void 0);
					p = void 0;
					noteLaneTaskProgress();
				}
			}
		};
	};
	const resolveLaneTimeoutError = () => {
		if (l !== void 0 && Date.now() - l >= 3e4) u ??= createLaneTimeoutError("abort-grace");
		return u;
	};
	const throwIfAborted = () => {
		if (!o.aborted) {
			b?.();
			return;
		}
		const e = resolveLaneTimeoutError() ?? o.reason;
		if (e instanceof Error) throw e;
		throw createAbortError("Operation aborted", e === void 0 ? void 0 : { cause: e });
	};
	const assertCurrent = () => {
		throwIfAborted();
		assertAgentRunLifecycleGenerationCurrent(e.getLifecycleGeneration());
		e.getParams().preparedRunAdmission?.assertSourceCurrent();
	};
	const noteLaneWaitIfBusy = (t) => {
		const n = e.getParams();
		if (!n.onLaneWait) return;
		const r = getCommandLaneSnapshot(t);
		if (shouldNoteLaneWait(r)) n.onLaneWait({
			waitMs: 0,
			queuedAhead: r.queuedCount + r.activeCount,
			waiting: true
		});
	};
	const enqueueGlobal = async (t, l) => {
		let u = false;
		let p = true;
		const g = e.getParams().replyOperation?.watchdog ?? f;
		let _;
		let v = false;
		const beginCapacityWait = () => {
			if (v || !p || o.aborted) return;
			v = true;
			m += 1;
			e.getParams().replyOperation?.markWaitingForGlobalLane();
			_ = g?.beginWait({
				kind: "global_capacity",
				isCurrent: () => p && !o.aborted
			});
		};
		const finishGlobalLaneAdmission = () => {
			if (!p) return;
			p = false;
			_?.close();
			if (v) {
				v = false;
				m -= 1;
			}
		};
		const taskWithCurrentLifecycle = async () => {
			endCapacityWait();
			beginCapacityWait();
			noteLaneTaskProgress();
			let n = e.getParams();
			throwIfAborted();
			let a = e.getLifecycleGeneration();
			const o = getAgentEventLifecycleGeneration();
			const p = getAgentRunContext(n.runId);
			if (a !== o) {
				const t = e.initialQueuedLifecycleGeneration === a;
				const i = p?.lifecycleGeneration === o;
				if (!t || !r.canResumeAcrossRotation || i) assertAgentRunLifecycleGenerationCurrent(a);
				a = o;
				e.setLifecycleGeneration(a);
				n = {
					...n,
					lifecycleGeneration: a
				};
				e.setParams(n);
			}
			const m = await claimAgentSessionWriter(n);
			if (m) {
				n = {
					...n,
					sessionTarget: {
						...n.sessionTarget,
						expectedLifecycleRevision: m.expectedLifecycleRevision,
						expectedWriterRunId: m.expectedWriterRunId
					}
				};
				e.setParams(n);
				e.onSessionWriterClaimed?.(m.entry);
			}
			const h = withAgentRunLifecycleGeneration(a, () => withSessionPlacementTurnAdmission({
				sessionId: n.sessionId,
				...n.agentId ? { agentId: n.agentId } : {},
				...n.sessionKey ? { sessionKey: n.sessionKey } : {},
				runId: n.runId
			}, n, (r) => {
				n = {
					...n,
					abortSignal: r
				};
				e.setParams(n);
				b = resolveSessionPlacementTurnSettlementAssertion();
				const a = e.getParams().replyOperation;
				if (a) {
					assertSessionControllerOperation(a);
					markReplyOperationExecutionStarted(a);
					if (a.phase === "queued") a.setPhase("running");
				}
				const o = resolveSessionPlacementForcedTerminalSettlement();
				const p = o && a?.registerExecutionCleanup(o);
				const m = Date.now();
				c = m;
				const h = (a?.watchdog ?? f)?.beginExecution(() => !u || d?.kind === "unlimited" ? void 0 : d?.deadlineAtMs ?? Math.max(m, s) + (l?.taskTimeoutMs ?? i), recoverExecutionDeadline);
				return t().finally(() => {
					h?.close();
					p?.();
				});
			}, () => {
				throwIfAborted();
				assertAgentRunLifecycleGenerationCurrent(a);
				releaseQueuedContext("admitted");
				claimAgentRunContext(n.runId, {
					...p,
					agentId: n.agentId ?? p?.agentId,
					sessionKey: n.sessionKey ?? p?.sessionKey,
					sessionId: n.sessionId ?? p?.sessionId,
					lifecycleGeneration: a,
					lastActiveAt: Date.now()
				});
				finishGlobalLaneAdmission();
				g?.progress("semantic", "global_capacity:admitted");
				n.replyOperation?.markGlobalLaneWaitEnded();
				n.onLaneWait?.({
					waitMs: 0,
					queuedAhead: 0,
					waiting: false
				});
			}));
			const _ = m && readSessionControllerOperationState(n.replyOperation)?.registerTerminalProducerFence((e, t) => m.revoke(e, t));
			return await h.finally(() => _?.());
		};
		try {
			const { enqueue: t } = e.getParams();
			if (!t) noteLaneWaitIfBusy(e.globalLane);
			const i = {
				taskIdentity: n,
				abortSignal: o,
				maxConcurrent: e.getParams().swarmExecutionLane?.maxConcurrent,
				priority: isBackgroundWorkLane(e.globalLane) ? "background" : r.priority,
				onQueued: () => {
					beginCapacityWait();
					noteCapacityWait();
					l?.onQueued?.();
				},
				onWait: (t, n) => {
					l?.onWait?.(t, n);
					e.getParams().onLaneWait?.({
						waitMs: t,
						queuedAhead: n,
						waiting: true
					});
				},
				warnAfterMs: l?.warnAfterMs
			};
			let s = false;
			const c = withReleasableExecutionCapacity((n) => {
				p = true;
				const runTicket = async () => {
					u = true;
					h += 1;
					noteLaneTaskProgress();
					try {
						if (s) {
							endCapacityWait();
							assertCurrent();
							finishGlobalLaneAdmission();
							e.getParams().replyOperation?.markGlobalLaneWaitEnded();
							e.getParams().onLaneWait?.({
								waitMs: 0,
								queuedAhead: 0,
								waiting: false
							});
						}
						s = true;
						return await n();
					} finally {
						u = false;
						h -= 1;
					}
				};
				return (t ? t(runTicket, i) : enqueueCommandInLane(e.globalLane, runTicket, i)).catch((e) => {
					if (isCommandLaneTaskTimeoutError(e)) a.abort(e);
					throw e;
				});
			}, () => trackGlobalExecution(taskWithCurrentLifecycle()));
			return await trackGlobalExecution(c);
		} catch (e) {
			throw o.aborted && resolveLaneTimeoutError() || e;
		} finally {
			finishGlobalLaneAdmission();
		}
	};
	const enqueueAdmittedSession = async (t, n) => {
		const c = e.getParams().replyOperation;
		c?.markWaitingForDeferredMaintenance();
		let u;
		try {
			u = r.priority === "foreground" ? await beginForegroundSessionMaintenance(e.getParams().sessionKey ?? e.getParams().sessionId) : void 0;
		} finally {
			c?.markDeferredMaintenanceWaitEnded();
		}
		noteLaneTaskProgress();
		try {
			let e = true;
			const r = c?.watchdog ?? createSessionControllerWatchdog({
				startedAtMs: Date.now(),
				isCurrent: () => e,
				readPhase: () => o.aborted ? "terminal" : "active",
				requestStop: () => {
					a.abort(/* @__PURE__ */ new Error("Detached execution stalled"));
					return "blocked";
				},
				expireCleanup: () => "blocked"
			});
			f = r;
			if (!c) r.start();
			const u = c ? void 0 : r.beginWait({
				kind: "runtime_owned",
				isCurrent: () => e && !o.aborted
			});
			const p = r.beginExecution(() => {
				if (g.size > 0 && h === 0 || m > 0 || c?.phase === "waiting_for_deferred_maintenance" || c?.phase === "waiting_for_global_lane" || d?.kind === "unlimited") return;
				return d?.deadlineAtMs ?? s + (n?.taskTimeoutMs ?? i);
			}, recoverExecutionDeadline);
			const abortExecution = () => {
				l ??= Date.now();
				if (!c || c.abortSignal.aborted) r.beginTerminal(Date.now() + EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS);
			};
			o.addEventListener("abort", abortExecution, { once: true });
			if (o.aborted) abortExecution();
			const _ = n?.taskTimeoutSubscribe?.(setLaneTaskDeadline);
			try {
				throwIfAborted();
				endCapacityWait();
				return await t();
			} finally {
				e = false;
				u?.close();
				p.close();
				_?.();
				o.removeEventListener("abort", abortExecution);
				f = void 0;
				if (!c) r.close();
			}
		} finally {
			u?.();
		}
	};
	const enqueueSession = async (t, n) => {
		const r = e.getParams();
		_ = retainQueuedAgentRunContext(r.runId, e.getLifecycleGeneration());
		v = o;
		o.addEventListener("abort", abandonQueuedContext, { once: true });
		if (o.aborted) abandonQueuedContext();
		try {
			return await withSessionTurn({
				...r,
				storePath: r.sessionTarget?.storePath ?? (r.config ? resolveSessionStorePathCore(r.config.session?.store, { agentId: r.agentId }) : void 0),
				detached: r.sessionPersistence === "detached",
				abortSignal: o
			}, async (r, i) => {
				e.setParams({
					...e.getParams(),
					replyOperation: r,
					abortSignal: i
				});
				const abortTurn = () => a.abort(i.reason);
				i.addEventListener("abort", abortTurn, { once: true });
				if (i.aborted) abortTurn();
				try {
					if (r) assertSessionControllerOperation(r);
					try {
						return await enqueueAdmittedSession(t, n);
					} finally {
						while (g.size) await Promise.allSettled(g);
					}
				} finally {
					i.removeEventListener("abort", abortTurn);
				}
			});
		} finally {
			releaseQueuedContext("abandoned");
		}
	};
	return {
		enqueueGlobal,
		enqueueSession,
		abortSignal: o,
		laneTaskAbortController: a,
		noteLaneTaskProgress,
		setLaneTaskDeadline,
		getExecutionDeadline: () => !x ? void 0 : d?.kind === "bounded" ? {
			kind: "bounded",
			deadlineAtMs: d.deadlineAtMs - EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS
		} : d,
		createAttemptControls,
		throwIfAborted,
		assertCurrent
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/model-admission.ts
function resolveEmbeddedRunConfig(e) {
	const t = normalizeOptionalString(e.provider);
	const n = normalizeOptionalString(e.model);
	const r = !e.config && !t && !n;
	return e.config ?? (r ? getRuntimeConfigSnapshot() ?? void 0 : void 0);
}
/** Native sessions attest their own model later; ordinary requests are checked before runtime preparation. */
function assertInitialOperatorModelPolicy(e, t) {
	const n = readRunOperatorAuthority(e);
	if (!n?.modelPolicy || resolveSessionPinnedHarnessId(t)) return;
	const r = resolveInitialEmbeddedRunModel({
		...e,
		config: e.config
	});
	const i = resolveModelCandidateChain({
		cfg: e.config,
		agentId: e.agentId,
		provider: r.provider,
		model: r.modelId,
		requestedRouteResolution: e.requestedRouteResolution,
		fallbacksOverride: [],
		manifestPlugins: e.pluginGeneration?.pluginMetadataSnapshot
	})[0];
	assertOperatorModelAllowed(n, i);
}
//#endregion
//#region src/agents/embedded-agent-runner/run/progress-controller.ts
function createEmbeddedRunProgressController(e) {
	const t = e.attempt.fastModeStartedAtMs ?? e.startedAtMs;
	const n = e.attempt.fastModeAutoOnSeconds ?? resolveFastModeModelAutoOnSeconds({
		cfg: e.attempt.config,
		provider: e.attempt.provider,
		model: e.attempt.model
	});
	const r = e.attempt.fastModeAutoProgressState ?? {
		offAnnounced: false,
		resetAnnounced: false
	};
	const notifyExecutionPhase = (t, n) => {
		e.noteLaneTaskProgress();
		e.attempt.onExecutionPhase?.({
			phase: t,
			...n
		});
	};
	const notifyRunProgress = (t) => {
		e.noteLaneTaskProgress();
		e.attempt.onRunProgress?.(t);
	};
	const emitFastModeAutoProgress = async (t) => {
		const n = formatFastModeAutoProgressText(t);
		const r = {
			kind: "status",
			title: "Fast",
			phase: "update"
		};
		try {
			emitAgentActivityEvent({
				runId: e.attempt.runId,
				...e.attempt.sessionKey ? { sessionKey: e.attempt.sessionKey } : {},
				stream: "item",
				data: {
					itemId: `fast-mode-auto:${t.enabled ? "on" : "off"}`,
					...r,
					status: "running",
					summary: n
				}
			});
		} catch (e) {
			log$3.debug(`embedded run fast mode auto global event failed: ${formatErrorMessage(e)}`);
		}
		try {
			await e.attempt.onAgentEvent?.({
				stream: "item",
				data: {
					...r,
					summary: n
				},
				...e.attempt.sessionKey ? { sessionKey: e.attempt.sessionKey } : {}
			});
		} catch (e) {
			log$3.debug(`embedded run fast mode auto event failed: ${formatErrorMessage(e)}`);
		}
		try {
			await e.attempt.onToolResult?.({
				text: n,
				channelData: { openclawProgressKind: FAST_MODE_AUTO_PROGRESS_KIND }
			});
		} catch (e) {
			log$3.debug(`embedded run fast mode auto progress failed: ${formatErrorMessage(e)}`);
		}
	};
	const resolveCurrentFastMode = () => resolveFastModeForElapsed({
		mode: e.attempt.fastMode,
		startedAtMs: t,
		fastAutoOnSeconds: n
	});
	const maybeAnnounceFastModeAutoOff = async () => {
		if (e.attempt.fastMode !== "auto" || r.offAnnounced) return;
		const t = resolveCurrentFastMode();
		if (t.enabled) return;
		r.offAnnounced = true;
		await emitFastModeAutoProgress(t);
	};
	const resolveAttemptFastMode = () => {
		const e = resolveCurrentFastMode();
		return e.mode === void 0 ? void 0 : e.enabled;
	};
	const resolveAttemptFastModeParam = () => {
		if (e.attempt.fastMode === "auto") return resolveAttemptFastMode;
		return e.attempt.fastMode;
	};
	const maybeEmitFastModeAutoResetBestEffort = async () => {
		try {
			if (e.attempt.fastMode !== "auto" || !r.offAnnounced || r.resetAnnounced) return;
			r.resetAnnounced = true;
			await emitFastModeAutoProgress({
				enabled: true,
				elapsedSeconds: 0,
				fastAutoOnSeconds: n
			});
		} catch (e) {
			log$3.warn(`embedded run fast mode auto reset progress failed: ${formatErrorMessage(e)}`);
		}
	};
	return {
		fastModeAutoOnSeconds: n,
		fastModeAutoProgressState: r,
		fastModeStartedAtMs: t,
		maybeAnnounceFastModeAutoOff,
		maybeEmitFastModeAutoResetBestEffort,
		notifyExecutionPhase,
		notifyRunProgress,
		resolveAttemptFastModeParam
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/recovery-message-action-capability.ts
/** Reconstructs a one-run action capability from host-only restart correlation. */
function createRecoveryMessageActionTurnCapability(e) {
	const t = readChannelSourceTurnId(e);
	const n = normalizeMessageChannel(e.messageProvider ?? e.messageChannel);
	if (e.messageActionTurnCapability || !t || !n || !isTrustedMessageActionTurnIngress(n) || !e.agentId || !e.sessionKey || !e.currentChannelId) return;
	return mintMessageActionTurnCapability({
		agentId: e.agentId,
		runId: e.runId,
		sessionKey: e.sessionKey,
		sourceReplySessionKey: e.sessionKey,
		sessionId: e.sessionId,
		requesterAccountId: e.agentAccountId,
		requesterSenderId: e.senderId ?? void 0,
		requesterSenderName: e.senderName ?? void 0,
		requesterSenderUsername: e.senderUsername ?? void 0,
		requesterSenderE164: e.senderE164 ?? void 0,
		toolContext: {
			currentChannelId: e.currentChannelId,
			currentChatType: e.chatType,
			currentMessagingTarget: e.messageTo,
			currentChannelProvider: n,
			currentThreadTs: e.currentThreadTs,
			currentSourceTurnId: t,
			replyToMode: e.replyToMode,
			hasRepliedRef: e.hasRepliedRef,
			sameChannelThreadRequired: readChannelSourceTurnSameThreadRequired(e)
		},
		...resolveMessageActionTurnCapabilityLifetime(e.timeoutMs)
	});
}
//#endregion
//#region src/agents/embedded-agent-runner/run-orchestrator.ts
const EMPTY_EMBEDDED_AGENT_CONFIG = Object.freeze({});
function runEmbeddedAgent(e) {
	const t = resolveEmbeddedRunConfig(e);
	const n = e.lifecycleGeneration ?? captureAgentRunLifecycleGeneration(e.runId);
	const r = e.pluginGeneration ?? (e.preparedModelRuntimeMode === "isolated-read-only" ? void 0 : getPreparedModelRuntimePluginGeneration());
	return withPluginRetentionOwner({
		agentId: e.agentId,
		sessionKey: e.sessionKey,
		runId: e.runId
	}, () => withAgentRunLifecycleGeneration(n, async () => {
		const i = await prepareEmbeddedRunSession({
			...e,
			config: t,
			lifecycleGeneration: n,
			...r ? { pluginGeneration: r } : {}
		});
		return await withRequiredSessionPlacement(i.runSessionTarget, {
			config: i.params.config,
			assertCurrent: i.params.preparedRunAdmission?.assertSourceCurrent,
			signal: i.params.abortSignal
		}, () => runEmbeddedAgentForSession(i));
	}));
}
async function runEmbeddedAgentForSession(e) {
	const { params: t, runSessionTarget: n, contextEngineAgentId: r, queuedLifecycleGeneration: i } = e;
	const a = t.abortSignal;
	let o = e.sessionAdmission;
	let s = t.lifecycleGeneration;
	let c = withExecutionPhaseDiagnostics({
		...t,
		sessionManager: t.sessionManager ?? (t.sessionPersistence === "detached" ? SessionManager.inMemory(t.cwd ?? t.workspaceDir) : void 0)
	});
	const l = resolveGlobalLane(c.lane, c);
	const u = c.sessionPersistence === "detached" ? void 0 : captureSessionSuspension();
	const suspendForFailure = (e) => u?.({
		...e,
		agentId: e.agentId ?? c.agentId
	});
	const d = createEmbeddedRunLaneController({
		getLifecycleGeneration: () => s,
		getParams: () => c,
		globalLane: l,
		initialQueuedLifecycleGeneration: i,
		setLifecycleGeneration: (e) => {
			s = e;
		},
		setParams: (e) => {
			c = e;
		},
		onSessionWriterClaimed: (e) => {
			if (o) o = {
				...o,
				entry: e
			};
			publishClaimedSessionWriter(c.onCompactionAccounting, n, e);
		}
	});
	const { enqueueGlobal: f, enqueueSession: p, noteLaneTaskProgress: m, throwIfAborted: h } = d;
	const g = c.messageChannel ?? c.messageProvider;
	const _ = c.toolResultFormat ?? (!g || isMarkdownCapableMessageChannel(g) ? "markdown" : "plain");
	const v = c.sessionId?.startsWith("probe-") ?? false;
	h();
	const y = createRecoveryMessageActionTurnCapability(c);
	if (y) c = {
		...c,
		messageActionTurnCapability: y
	};
	const b = captureExecRequestOwners(c);
	const runSession = async () => {
		h();
		if (!c.sessionManager || c.sessionManager.getSessionTarget()) {
			c.replyOperation?.markWaitingForDeferredMaintenance();
			try {
				await waitForSessionMaintenance(c.sessionKey);
				await waitForSessionTranscriptProjection(n, d.abortSignal);
			} finally {
				c.replyOperation?.markDeferredMaintenanceWaitEnded();
			}
		}
		h();
		return f(async () => {
			const e = Date.now();
			const t = serializeAgentEventCallback(c.onAgentEvent);
			c = {
				...c,
				onAgentEvent: t
			};
			const i = createEmbeddedAgentPluginRuntimeRefresh(c);
			const u = createUsageAccumulator();
			const f = createUsageAccumulator();
			let p = false;
			let g = Promise.resolve();
			let y;
			let b;
			const x = c.assistantErrorTranscript === void 0;
			const S = c.onAttemptStart;
			const C = c.onAttemptTerminalReplaced;
			const runGeneration = async () => {
				try {
					var a = _usingCtx();
					h();
					assertInitialOperatorModelPolicy(c, o?.entry);
					const u = await runEmbeddedAgentViaCliBackendIfEligible({
						...c,
						sessionTarget: {
							...c.sessionTarget,
							...n
						}
					});
					if (u) return u;
					const f = {
						...n,
						...c.sessionTarget
					};
					const x = await prepareCronRootSessionGeneration({
						...f,
						sessionId: c.sessionId,
						sessionKey: c.sessionKey ?? f.sessionKey,
						lifecycleRevision: f.expectedLifecycleRevision
					}, (e) => d.laneTaskAbortController.abort(e));
					a.u({ [Symbol.dispose]: () => x?.release() });
					const preReplyAssertCurrent = () => {
						d.assertCurrent();
						x?.assertCurrent();
					};
					const w = createStageTimingTracker(Date.now);
					const { requestedWorkspaceResolution: T, runtimeWorkspaceResolution: E, preserveExecutionWorkspace: D } = resolvePreparedRuntimeWorkspaces(c);
					w.mark("workspace");
					const O = c.config ?? EMPTY_EMBEDDED_AGENT_CONFIG;
					const k = c.agentDir ?? resolveAgentDir(O, T.agentId);
					const A = c.config === void 0;
					const j = resolveInitialEmbeddedRunModel({
						config: O,
						agentId: T.agentId,
						provider: c.provider,
						model: c.model
					});
					const M = c.pluginGeneration?.pluginMetadataSnapshot ?? loadPluginMetadataSnapshot({
						config: O,
						workspaceDir: E.workspaceDir,
						env: process.env
					});
					const N = resolveEmbeddedRuntimePluginSelections({
						run: c,
						config: O,
						agentId: T.agentId,
						manifestPlugins: M,
						requestedModel: j
					});
					const P = {
						config: O,
						agentId: T.agentId,
						agentDir: k,
						inheritedAuthDir: resolveLegacyInheritedAuthDir(O),
						workspaceDir: E.workspaceDir,
						preserveWorkspaceDirOnRefresh: !E.isCanonicalWorkspace,
						...c.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {},
						...resolveEmbeddedRuntimePluginPreparation(c),
						runtimePluginSelections: N
					};
					w.mark("harness-selection");
					const F = createDeferredCore();
					const I = createDeferredCore();
					I.promise.catch(() => {});
					const L = captureAsyncWorkTracker();
					const R = getAsyncWorkSignal();
					const z = new AsyncWorkScope();
					let B = z.run(() => AsyncLocalStorage.snapshot());
					let V;
					let H;
					let U = Promise.resolve();
					const runPreparedCandidate = async () => {
						d.setLaneTaskDeadline({ kind: "unlimited" });
						const a = c.preparedModelRuntimeMode === "isolated-read-only";
						const u = await (a ? acquireReadOnlyPreparedModelRuntime : acquireAgentRunPreparedModelRuntime)(P, {
							abortSignal: d.abortSignal,
							catalogMode: "static",
							...!a ? {
								retainIdleRunOwner: A,
								...p ? { waitForReplacementPublication: true } : {},
								...c.pluginGeneration ? { pluginGeneration: c.pluginGeneration } : {}
							} : {}
						}).catch((e) => {
							if (!p && e instanceof PreparedModelRuntimeOwnerNotPublishedError && e.admissionBlocked) throw new PreparedModelRuntimeInitialRunAdmissionError(e);
							throw e;
						}).finally(() => {
							m();
							d.setLaneTaskDeadline(void 0);
						});
						V = u;
						w.mark("prepared-runtime");
						let f = true;
						try {
							const a = await initializeReadOnlyRunModelCatalog(c, u.snapshot, j, d.abortSignal);
							h();
							if (c.pluginGeneration && a.metadataSnapshot !== c.pluginGeneration.pluginMetadataSnapshot) throw new Error("prepared model runtime replaced the admitted plugin generation");
							const p = bindRunToPreparedModelRuntime({
								runParams: c,
								requestedWorkspaceResolution: T,
								preserveExecutionWorkspace: D,
								preparedModelRuntime: a
							});
							c = p.runParams;
							const g = p.workspaceResolution;
							const E = await prepareAgentPromptProjects({
								config: c.config,
								workspaceDir: g.workspaceDir,
								cwd: c.cwd,
								sessionId: c.sessionId
							});
							const { activeProjectKeys: O } = E;
							const k = copyPreparedModelRuntimeSnapshotBindings(a, Object.freeze({
								...a,
								...E
							}));
							const runPrepared = async () => {
								c = i.withDeliveryCallbacks(c);
								const a = g.agentId;
								const u = g.workspaceDir;
								const f = k.agentDir;
								const p = createEmbeddedRunProgressController({
									attempt: c,
									noteLaneTaskProgress: m,
									startedAtMs: e
								});
								const { notifyExecutionPhase: h } = p;
								const E = createEmbeddedRunStageSummaryEmitter({
									label: "startup stages",
									log: log$3,
									runId: c.runId,
									sessionId: c.sessionId,
									tracker: w
								});
								await c.onExecutionStarted?.({ lifecycleGeneration: s });
								preReplyAssertCurrent();
								h("runner_entered");
								const D = resolveUserPath(resolveAgentWorkspaceDir(k.config, a));
								const A = D === u;
								const j = redactRunIdentifier(c.sessionId);
								const M = redactRunIdentifier(c.sessionKey);
								const N = redactRunIdentifier(u);
								if (T.usedFallback) log$3.warn(`[workspace-fallback] caller=runEmbeddedAgent reason=${T.fallbackReason} run=${c.runId} session=${j} sessionKey=${M} agent=${a} workspace=${N}`);
								w.mark("runtime-context");
								h("workspace");
								w.mark("runtime-plugins");
								h("runtime_plugins");
								const { provider: P, modelId: F } = resolveInitialEmbeddedRunModel({
									config: c.config,
									agentId: g.agentId,
									provider: c.provider,
									model: c.model
								});
								const L = c.sessionKey?.trim();
								const R = (c.resolvedModelSelection?.fallbacksOverride === void 0 ? c.modelFallbackAvailability : void 0) ?? resolveModelFallbackAvailability({
									cfg: c.config ?? EMPTY_EMBEDDED_AGENT_CONFIG,
									agentId: g.agentId,
									sessionKey: L,
									hasSessionModelOverride: false,
									modelFallbacksOverride: c.modelFallbacksOverride
								});
								const z = R.kind === "active";
								if (R.kind === "disabled_by_model_override") log$3.warn(`[model-fallback] configured fallbacks disabled by user model override run=${c.runId} session=${j}`);
								const B = L ?? n.sessionKey;
								const V = getGlobalHookRunner();
								const U = {
									runId: c.runId,
									jobId: c.jobId,
									agentId: g.agentId,
									sessionKey: B,
									sessionId: c.sessionId,
									workspaceDir: u,
									activeProjectKeys: [...O],
									modelProviderId: P,
									modelId: F,
									trigger: c.trigger,
									...buildAgentHookContextChannelFields(c),
									...buildAgentHookContextIdentityFields(c)
								};
								const W = await runBeforeAgentReplyForTurn({
									awaitSessionDiffBaseline: c.awaitSessionDiffBaseline,
									assertCurrent: preReplyAssertCurrent,
									runId: c.runId,
									trigger: c.trigger,
									event: { cleanedBody: c.prompt },
									context: U,
									onDispatch: () => h("before_agent_reply", {
										provider: P,
										model: F
									}),
									onDeclined: () => h("runtime_plugins", {
										provider: P,
										model: F
									})
								});
								if (W?.handled) return {
									payloads: buildHandledBeforeAgentReplyPayloads(W.reply),
									meta: {
										durationMs: Date.now() - e,
										agentMeta: {
											sessionId: c.sessionId,
											provider: P,
											model: F
										},
										terminalReply: W.reply ? sanitizeAgentRunTerminalReply(W.reply.text ?? "") : { disposition: "silent" },
										providerStarted: false
									}
								};
								b ??= c.assistantErrorTranscript ?? createAssistantErrorTranscript();
								y ??= c.deferTerminalLifecycle ?? c.deferTerminalLifecycleEnd ? void 0 : createAgentLifecycleTerminalBackstop({
									runId: c.runId,
									sessionKey: c.sessionKey,
									startedAt: e,
									getLifecycleGeneration: () => s,
									resolveTerminationFields: (e) => resolveAgentRunErrorLifecycleFields(e, c.abortSignal),
									onTerminalEvent: (e) => runBestEffortCallback({
										callback: () => t?.(e),
										label: "lifecycle agent event",
										log: log$3
									})
								});
								const G = y;
								return await runPreparedEmbeddedLoop(i, {
									preReplyGeneration: x,
									onInitialWriterPrepared: (e) => {
										H = e;
									},
									runParams: {
										...c,
										runCleanupSettlement: I.promise,
										assistantErrorTranscript: b,
										deferTerminalLifecycle: true,
										onAttemptStart: () => {
											G?.beginAttempt();
											S?.();
										},
										onAttemptTerminalReplaced: () => {
											G?.replaceAttemptTerminal();
											C?.();
										},
										onAgentEvent: G ? (e) => {
											G.note(e);
											return t?.(e);
										} : t
									},
									sessionAdmission: o,
									contextEngineAgentId: r,
									provider: P,
									modelId: F,
									agentDir: f,
									workspaceResolution: g,
									workspaceDir: u,
									bootstrapWorkspaceDir: D,
									isCanonicalWorkspace: A,
									globalLane: l,
									hookRunner: V,
									hookContext: U,
									fallbackConfigured: z,
									isProbeSession: v,
									resolvedSessionKey: B,
									resolvedToolResultFormat: _,
									startedAtMs: e,
									startupStages: w,
									emitStartupStageSummary: E,
									progressController: p,
									laneController: d,
									lifecycleGeneration: s,
									suspendForFailure,
									preparedModelRuntime: k
								});
							};
							const runWithPreparedRuntime = () => withPluginRuntimeGenerationScope(k, () => {
								B = AsyncLocalStorage.snapshot();
								return runPrepared();
							});
							return c.pluginGeneration ? await withPreparedModelRuntimePluginGenerationScope(u.pluginGeneration, runWithPreparedRuntime, () => f ? a : void 0) : await runWithPreparedRuntime();
						} finally {
							const e = H;
							if (e) {
								U = B(() => z.track(async () => await e[Symbol.asyncDispose]()));
								U.catch(() => {});
							}
							f = false;
						}
					};
					g = L(async () => {
						const closeWork = () => B(() => z.beginClose(R?.reason));
						R?.addEventListener("abort", closeWork, { once: true });
						if (R?.aborted) closeWork();
						try {
							F.resolve(await z.track(runPreparedCandidate));
						} catch (e) {
							F.reject(e);
						} finally {
							try {
								await AsyncWorkScope.runWhenAllIdle(() => [z], () => B(() => z.drain()));
							} finally {
								try {
									try {
										await U;
									} finally {
										await V?.[Symbol.asyncDispose]();
									}
								} finally {
									R?.removeEventListener("abort", closeWork);
								}
							}
						}
					});
					g.then(I.resolve, I.reject);
					g.catch(F.reject);
					return await F.promise;
				} catch (e) {
					a.e = e;
				} finally {
					a.d();
				}
			};
			try {
				let t = true;
				let n;
				try {
					for (;;) {
						const run = () => i.run(runGeneration);
						n = await (p ? runOutsidePreparedModelRuntimePluginGenerationScope(() => runOutsidePluginRuntimeGenerationScope(run)) : run());
						const r = i.takeContinuation();
						if (p || r) mergeCompletedAgentUsage({
							usage: u,
							diagnosticUsage: f,
							agentMeta: n.meta.agentMeta,
							config: c.config ?? EMPTY_EMBEDDED_AGENT_CONFIG,
							agentDir: c.agentDir
						});
						if (!r) {
							if (p && n.meta.agentMeta) n = {
								...n,
								meta: {
									...n.meta,
									durationMs: Date.now() - e,
									agentMeta: {
										...n.meta.agentMeta,
										...buildCompletedAgentUsageMeta(u, f)
									}
								}
							};
							t = Boolean(n.meta.error) || n.meta.stopReason === "error";
							break;
						}
						await g;
						await r.contextEngineLogicalTurnLease?.handOver();
						c = r;
						p = true;
					}
				} finally {
					if (x) b?.settle(t && !a?.aborted);
				}
				i.mergeTerminalReceipt(n);
				if (n.meta.executionTrace?.runner !== "cli" && c.isFinalFallbackAttempt === void 0) await settleRequesterRun(c, n, d.assertCurrent);
				const r = n.meta.error?.message ?? y?.getDeferredError();
				y?.emit(r ? "error" : "end", r ? new Error(r) : n, {
					...resolveAgentLifecycleTerminalMetadata(n.meta),
					...n.meta.agentMeta?.terminalReceipt ? { assistantTranscriptIdempotencyKey: n.meta.agentMeta.terminalReceipt.assistantTranscriptIdempotencyKey } : {}
				});
				return n;
			} catch (e) {
				const t = c.isFinalFallbackAttempt === void 0 ? await settleFailedRequesterRun({
					...c,
					abortSignal: a
				}, e, resolveSessionPlacementTurnSettlementAssertion()) : e;
				y?.emit("error", t);
				throw t;
			} finally {
				i.close();
			}
		});
	};
	return p(() => withExecRequestTurn({
		identity: {
			runId: c.runId,
			sessionKey: c.sessionKey,
			sessionId: c.sessionId,
			agentId: c.agentId
		},
		owners: b,
		abortSignal: c.abortSignal
	}, runSession)).finally(() => {
		revokeMessageActionTurnCapability(y);
	});
}
//#endregion
//#region src/agents/embedded-agent-runner.ts
const compactEmbeddedAgentSession = async (e, t) => {
	const { compactQueuedEmbeddedAgentSession: n } = await import("./compact.queued-B4vSrV79.mjs");
	return n(e, t);
};
//#endregion
export { runEmbeddedAgent as n, compactEmbeddedAgentSession as t };