openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
8,056 lines • 305 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { A as resolveExpiresAtMsFromDurationMs, R as resolveTimerTimeoutMs, S as parseDateStringTimestampMs, _ as finiteSecondsToTimerSafeMilliseconds, d as asPositiveFiniteNumber, g as clampTimerTimeoutMs, n as MAX_TIMER_TIMEOUT_MS, o as asDateTimestampMs, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { n as parseBooleanValue } from "./boolean-2vRuVafy.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as runWithAsyncStore } from "./async-store-C6naia_Y.mjs";
import { p as toErrorObject, r as collectErrorGraphCandidates, u as readErrorCauses } from "./error-coercion-hDrHOSGy.mjs";
import { i as extractBalancedJsonPrefix } from "./src-H3RMXyFL.mjs";
import { n as safeParseJsonRecord, t as safeParseJson } from "./json-coercion-CaJLaav-.mjs";
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs";
import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./utils-C8YECn2Q.mjs";
import { i as createAbortError$1 } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import "./paths-DAcAg5aV.mjs";
import { i as isSecretValueRegisteredForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { a as captureAsyncWorkTracker, o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { n as notifyListeners, t as createChangeListeners } from "./listeners-Cb2-CnP8.mjs";
import { n as appendRegularFile } from "./fs-safe-BbWvmdVn.mjs";
import { n as findNormalizedProviderValue, r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { r as isCloudModelRef } from "./model-catalog-refs-Bk2MNoCv.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { C as isSubagentSessionKey, b as isCronRunSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as freezeJsonSnapshot } from "./immutable-data-Y7xVjZoy.mjs";
import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { s as emitTrustedDiagnosticEvent, t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs";
import { y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { d as normalizeUsage, o as hasNonzeroUsage } from "./usage-CHLnzpJG.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { t as SessionTranscriptReadFenceError } from "./session-transcript-read-fence-error-cGIB8yjw.mjs";
import { t as SessionTranscriptWriterClaimReboundError } from "./session-transcript-writer-claim-error-DhmNAhcx.mjs";
import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import { f as isLoopbackIpAddress } from "./ip-BUyyYvdK.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as AGENT_RUN_RESTART_ABORT_STOP_REASON } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { O as validateAgentRunDelegatedAuthority, l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { r as captureAgentRunLifecycleGeneration } from "./agent-events-BdfWYmot.mjs";
import { f as sessionEntryCommitGuardOptions, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { r as captureAgentRunTerminalPersistence } from "./agent-run-terminal-writes-eqeCFAOx.mjs";
import { t as mapAssistantMessageStream } from "./stream-wrapper-HijZTTa8.mjs";
import { a as mapNestedStrings, i as createStreamIteratorWrapper, r as wrapStreamFnTextTransforms } from "./plugin-text-transforms-CMotGmZ0.mjs";
import { E as projectModelThinkingCompat } from "./model-selection-shared-9Kz63Hhm.mjs";
import { c as mintSecretSentinel, l as resolveSecretSentinel, s as looksLikeSecretSentinel } from "./sentinel-BfPjneyJ.mjs";
import { p as hasRuntimeContextMarker } from "./types-iq-cNLsd.mjs";
import { r as emitSessionTranscriptUpdate } from "./transcript-events-BHwlF03q.mjs";
import { i as sameSessionTranscriptTargetBinding } from "./transcript-target-binding-BvjuRqS9.mjs";
import { n as SILENT_REPLY_TOKEN } from "./tokens-CcE6ESvH.mjs";
import { g as resolveAdmittedRunActiveAssertion, h as readRunOperatorAuthority, i as bindOperatorModelExecution, n as assertOperatorAccessProgramAllowed, p as readAdmittedRunOperatorAuthority, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs";
import { d as setAgentRunAttemptTerminalFailure, r as buildAgentRunTerminalOutcomeFromAttempt, s as mergeAgentRunAttemptTerminal, u as projectAgentRunAttemptTerminal } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { t as AgentRunTerminalOutcomeError } from "./agent-run-terminal-error-CbmFnPGI.mjs";
import { i as FailoverError } from "./error-BCRqSFIY.mjs";
import { n as AGENT_RUN_RESTART_ABORT_ERROR, o as createAgentRunRestartAbortError, r as AGENT_RUN_RESTART_ABORT_ERROR_CODE, s as createAgentRunSupersededAbortError, u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs";
import { a as acceptProviderReviewAcknowledgment, d as readProviderReviewAcknowledgment, o as assertSessionProviderReviewWorkStart } from "./session-work-start-CFJs8WNp.mjs";
import { z as getReplyOperationSessionReader } from "./session-controller.state-BApgK0mV.mjs";
import { d as toolPolicyRestrictsTools, u as replaceWithEffectiveToolAllowlist } from "./tool-policy-BR4v75RA.mjs";
import { F as TOOL_CALL_RAW_TOOL_NAME } from "./tool-catalog-C1ALpCJD.mjs";
import { a as formatToolExecutionGatedMessage, c as normalizeToolPolicyName, n as couldNormalizeToolNamePrefixToAllowedTool, o as isToolExecutionAllowed, r as createToolExecutionMatcher } from "./tool-policy-shared-BHvBopvF.mjs";
import { l as normalizeCodeModeExecBeforeHookParams, n as CODE_MODE_WAIT_TOOL_NAME, s as isCodeModeExecTool, t as CODE_MODE_EXEC_TOOL_NAME } from "./code-mode-control-tools-2pBIuXDg.mjs";
import { n as createRuntimeToolMatcher, r as createToolPolicyMatcher, s as isToolAllowedByPolicyName } from "./tool-policy-match-DzwVnbV4.mjs";
import { _ as normalizeInputProvenance, b as shouldPreserveUserFacingSessionStateForInputProvenance } from "./input-provenance-DupvvURj.mjs";
import { a as resolveSessionPermissionExecMode } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { o as getGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { o as attachInternalToolBatchLifecycle, p as copyInternalToolResultState, t as InternalToolLoopBlocked, v as getInternalToolExecutionPreparer, w as setInternalRepetitionGuard } from "./internal-hooks-Ch3rqxs-.mjs";
import { a as getPluginToolSideEffectOwnerKey, i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as gateAgentToolExecution, r as finalizeAgentToolAvailability } from "./agent-tool-availability-ecKW8hOH.mjs";
import { _ as isAgentToolReplaySafe, h as collectSideEffectToolOwners, m as collectReplaySafeToolNames, u as wrapAgentToolExecutionContext } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { n as getChannelAgentToolMeta } from "./channel-tool-metadata-ZKqhsBg_.mjs";
import { m as isCurrentEmbeddedRunAttachment, p as getEmbeddedRunAttachment, r as ACTIVE_EMBEDDED_RUNS_BY_RUN_ID } from "./run-state-jrY5s7TG.mjs";
import { a as readSessionEntrySummariesInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { i as toDatabaseOptions } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import { o as runWithSessionActorStorage } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { a as resolveSqliteReadScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs";
import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { n as resolveSessionTranscriptReadFence } from "./session-transcript-read-fence-Bl-ZY3_t.mjs";
import { M as filterHeartbeatTranscriptArtifacts } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { n as getOpenClawSystemUpdateKind, r as isOpenClawSystemUpdateMessage } from "./operator-messages-B9HgXnnQ.mjs";
import { d as relocateCurrentRuntimeContextCarrierToTail, f as resolvePendingRuntimeContextReplay } from "./internal-runtime-context-BEUlDNuI.mjs";
import { a as prepareAgentRunTerminalReply } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import "./code-regions-CfNY0afj.mjs";
import { n as findMarkdownCodeRegions } from "./reasoning-tags-DL3sP_9k.mjs";
import { r as isSessionTranscriptProjectionUnavailableError } from "./session-transcript-projection-error-D8lfGKCW.mjs";
import { t as assertSessionEntryCohortScope } from "./session-entry-cohort-scope-BPNP_A27.mjs";
import { i as projectNestedToolActivityForHooks, n as createNestedToolActivity, o as readOwnNestedToolActivity } from "./nested-tool-activity-BiEuCyrz.mjs";
import { a as SKILL_WORKSHOP_CHANGE_NOTICE_KIND, d as MODEL_FALLBACK_NOTICE_KIND, o as isOpenClawDeliveryMirrorAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs";
import { B as prepareForeignLiveSessionPendingInputEntries, K as recoverSessionTranscriptProjection, M as readSessionSubmittedInput } from "./session-accessor-CizTbDQj.mjs";
import { a as isSessionWorkStartInvalidatedError, n as SessionWorkStartChangedError } from "./work-start-error-DaHE71YG.mjs";
import { S as supportsClaudeInHistorySystemMessages } from "./anthropic-D3Mx6AZz.mjs";
import { t as omitNullRequestHeaders } from "./request-headers-Dtgiinuk.mjs";
import "./src-DFw9QOgs.mjs";
import { n as wrapStreamFnWithDiagnosticModelCallEvents } from "./memory-prompt-prepare-Dvvdg4ic.mjs";
import { r as selectBoundedModelRequests } from "./session-model-context-read-_zUjHaE7.mjs";
import { t as readMessageIdempotencyKey } from "./transcript-message-identity-BXVU8GEP.mjs";
import { t as messagesMatchForIdempotentReplay } from "./transcript-message-equality-CGAYRKIx.mjs";
import { n as IncognitoSessionMissingError } from "./incognito-session-error-BxQdjUZa.mjs";
import { s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { r as prepareSessionEntryReplacementDatabase } from "./session-accessor.sqlite-replacement-worker-qf-6oERs.mjs";
import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { c as getOwnedSessionTranscriptInitialWriter, g as withOwnedSessionTranscriptWrites, h as withOwnedSessionTranscriptWriterFence, i as captureOwnedTranscriptWriteAssertion, l as getOwnedSessionTranscriptReader, p as runWithOwnedSessionTranscriptWrite, r as bindOwnedSessionTranscriptWrites, t as assertOwnedTranscriptWriteCommit, y as withSessionTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs";
import "./config-CMA-J084.mjs";
import { t as withSessionTranscriptReadSource } from "./session-transcript-read-source-cqwUFa0e.mjs";
import { i as withSessionManagerMemoryActor, t as captureSessionManagerIncognitoBinding } from "./session-manager-incognito-scope-BRG0nvBK.mjs";
import { n as readSessionTranscriptAnchorsAsync } from "./session-transcript-anchor-read-BUt-Wh3r.mjs";
import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs";
import { t as prepareConversationCapabilityProfile, u as resolveSessionPlacementComputer } from "./conversation-capability-profile-Be5DqCww.mjs";
import { r as projectConversationToolNames } from "./conversation-tool-policy-pipeline-DIjQjgsq.mjs";
import { n as resolveAgentTimeoutMs, t as DEFAULT_AGENT_TIMEOUT_MS } from "./timeout-BEnEcjB4.mjs";
import { o as MessageInjectionWithdrawnError, t as MessageInjectionAcceptedUnconfirmedError } from "./message-injection-authority-B9SdalrV.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { a as recordStructuredReplayTrustForToolCall, p as admitToolCallBatch, s as wrapToolWithBeforeToolCallHook } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { n as clearBatchAdmittedToolCallsForRun } from "./agent-tools.before-tool-call.state-C5F7vnXY.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { s as resolveProviderThinkingLevel } from "./thinking-Da4gHblr.mjs";
import { t as resolveSelectedModelCredential } from "./model-auth-selected-credential-DsmxCC4n.mjs";
import { a as getPreparedModelFullCatalogAuth, l as getPreparedModelRuntimePolicyConfigReader } from "./prepared-model-runtime-auth-DVZroiat.mjs";
import "./http-body-B9w7rzPz.mjs";
import { t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs";
import { t as createPendingPromiseTracker } from "./pending-promises-DNsYFS1E.mjs";
import { t as redactAgentDiagnosticPayload } from "./diagnostic-redaction-DVtKJp3X.mjs";
import { m as readProviderJsonObjectResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { d as resolveProviderRequestHeaders } from "./provider-request-config-CCij-nof.mjs";
import { i as withGuardedFetchRequestAuthority, r as withGuardedFetchBeforeRequest } from "./fetch-request-authority-nK0cxa_-.mjs";
import { s as resolveContextEngineOwnerPluginId } from "./registry-BNPXTWdk.mjs";
import { n as OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST, r as assertContextEngineHostSupport } from "./host-compat-D2mUtPDd.mjs";
import "./tool-fs-policy-dDd9W7xo.mjs";
import { r as getModelProviderRuntimePluginHandle } from "./provider-hook-runtime-CNiG8a3j.mjs";
import { T as resolveProviderTextTransforms } from "./provider-runtime-BddjXkmv.mjs";
import { a as resolveToolCallArgumentsEncoding, n as extractModelCompat } from "./provider-model-compat-DgjEUAN7.mjs";
import { n as normalizeGoogleApiBaseUrl } from "./google-api-base-url-DccJuq-N.mjs";
import { t as captureAgentPluginRuntimeRefresh } from "./plugin-runtime-refresh-DCHb6kdS.mjs";
import "./failover-error-CbIiC30n.mjs";
import { a as findMediaGenerationOperation, d as isTerminalMediaGenerationStatus, f as listMediaGenerationOperations, p as onMediaGenerationOperationChanged } from "./media-generation-activity-C0NELI_p.mjs";
import { r as resolveCompactionTimeoutMs } from "./compaction-safety-timeout-Dm_4UNnX.mjs";
import { n as closeDiagnosticEmbeddedRunOwner, r as createDiagnosticEmbeddedRunOwner, u as markDiagnosticRunProgress } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { c as resolveStagedInputMediaPaths } from "./staged-inputs-p_W1dPfN.mjs";
import { i as runOwnedAgentCleanup, n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
import { t as loadSessionMcpConfig } from "./agent-bundle-mcp-runtime-config-CBo1pSHY.mjs";
import { t as captureAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs";
import { t as prepareCronRootSessionGeneration } from "./session-delivery-generation-CUS9yuZM.mjs";
import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs";
import { t as DEFAULT_UNDICI_STREAM_TIMEOUT_MS } from "./undici-global-dispatcher-CdeU188Q.mjs";
import { t as isEmbeddedMode } from "./embedded-mode-CncGOzNj.mjs";
import { n as hashToolCall, r as observeRepeatedToolError } from "./tool-loop-detection-CR_Hr4G6.mjs";
import "./agent-tools.before-tool-call-CCkSq-k3.mjs";
import { a as resolveUserTimezone } from "./date-time-ChxDjIEM.mjs";
import { o as captureFinalEffectiveCronCreatorToolAllowlist } from "./cron-tool-creator-cap-sxVcNlMi.mjs";
import { a as isOutOfTurnHistoryEntry, o as isSessionContextMetadataEntry } from "./session-manager-codec-DTi9FkQE.mjs";
import { r as resolveLiveToolResultMaxChars } from "./tool-result-limits-BISboI8s.mjs";
import { t as createStageTimingTracker } from "./stage-timing-By2RFvzf.mjs";
import { t as decodeHtmlEntities } from "./html-entities-DQgGLPTJ.mjs";
import { r as SESSION_WATCHDOG_WARNING_MS } from "./session-controller.operation-BXBO7UKT.mjs";
import { n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { a as projectScrubbedPlainTextToolCallMessage, i as normalizePlainTextToolCallStreamEvents, n as createPromotedPlainTextToolCallEvents, r as projectStandalonePlainTextToolCallMessage } from "./src-C9d8oFHe.mjs";
import { f as resolveReplyExpectation } from "./reply-completion-CrT6uEHT.mjs";
import { t as log$2 } from "./logger-DgCpB-Fs.mjs";
import { n as claimPendingAgentQuestionAnswer, t as cancelPendingAgentQuestionForSession } from "./gateway-question-u5Q7erev.mjs";
import { t as hasPromptImageInput } from "./prompt-image-input-BuReFGO-.mjs";
import { n as acquireSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import { r as materializeBundleMcpToolsForRun } from "./agent-bundle-mcp-materialize-DM8C34_b.mjs";
import "./agent-bundle-mcp-tools-CjrVbt71.mjs";
import { i as mergeAcceptedSessionSpawnsForRun, n as hasCompletionMessageSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { t as configuredModelSupportsNativeVideo } from "./model-input-CR8B9uv8.mjs";
import { o as resolveModelAuthModeAsync } from "./model-auth-CEsyk_Yg.mjs";
import { a as toClientToolDefinitions, n as findClientToolNameConflicts, o as toToolDefinitions, t as CLIENT_TOOL_NAME_CONFLICT_PREFIX } from "./agent-tool-definition-adapter-CAIOgFtX.mjs";
import { t as applyFinalEffectiveToolPolicy } from "./effective-tool-policy-DMFsqGJo.mjs";
import { d as setSteeringRuntimeContextRetention, l as prependRuntimeContextForModel, n as applyRuntimeContextCarrierRetention } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { n as wrapToolWithAbortSignal, t as raceWithAbortSignal } from "./agent-tools.abort-BN-GwRlX.mjs";
import { s as agentSessionSetContextReplacementHook, t as DefaultResourceLoader } from "./resource-loader-hGpx6p2H.mjs";
import { t as isThinkingLikeBlock } from "./thinking-block-aWErJJtP.mjs";
import { l as retireQueuedUserMessage, n as agentSessionQueuePromptContext, o as getSteeringMessageIdentity, r as agentSessionSetPromptPreparation, s as subscribeSteeringMessagePersistenceFailure, y as sanitizeCompactionReplayMessages } from "./agent-session-prompting-DwE3NoeR.mjs";
import { n as getAgentToolAssistantTurnId } from "./tool-execution-context-D0eUSg2-.mjs";
import { n as swapSecretSentinelsForEgress, t as buildGuardedModelFetch } from "./ai-transport-host-DfBOurnI.mjs";
import { t as event_stream_exports } from "./event-stream-BvhxOtdO.mjs";
import { _ as withSessionManagerAppend, a as sessionManagerReloadTranscriptCohort, d as sessionManagerReadInitialContext, i as sessionManagerOpenTranscriptCohort, t as SessionManager, u as sessionManagerPrepareCurrentTurnReplay } from "./session-manager-DuaaMI5O.mjs";
import { t as SessionTranscriptMessageCommittedError } from "./session-manager-message-error-bZ375bls.mjs";
import { i as withSessionManagerWrite, t as appendSessionTranscriptNote } from "./session-manager-write-admission-CUQ2naL2.mjs";
import { d as createToolDefinitionFromAgentTool, f as wrapToolDefinition } from "./tools-EkGDfRbZ.mjs";
import { r as createCompactionRequestBudget } from "./request-budget-CDN2iAaH.mjs";
import { t as prepareSessionManagerHydration } from "./session-manager-incognito-BWxlXR5_.mjs";
import { t as agentSessionDeferThresholdCompaction } from "./agent-session-types-CR66-Zb5.mjs";
import "./sessions-G45sHB31.mjs";
import { a as shouldCreateBundleMcpRuntimeForAttempt, i as shouldCreateBundleLspRuntimeForAttempt, n as mergeForcedEmbeddedAttemptToolsAllow, r as resolveEmbeddedAttemptToolConstructionPlan, t as applyEmbeddedAttemptToolsAllow } from "./attempt-tool-construction-plan-Cp8YcsYs.mjs";
import { i as attachActiveEmbeddedRun, o as detachActiveEmbeddedRun } from "./runs-C1RO1Y6L.mjs";
import { i as messageToolOwnsVisibleReply } from "./source-reply-delivery-mode-CYtLiYyC.mjs";
import { n as createOpenClawCodingToolsInternalAsync } from "./agent-tools.async-b-kGzZ4n.mjs";
import { n as assertMemoryFlushPersistenceToolAvailable } from "./agent-tools.memory-flush-t5TUoO5U.mjs";
import { A as resolveLocalModelLeanPreserveToolNames, D as retainToolSearchImplementation, E as createToolSearchSelectionMatcher, O as filterLocalModelLeanTools, g as addClientToolsToToolCatalog, h as resolveToolSearchConfig, k as isLocalModelLeanEnabled, m as resolveToolSearchCatalogTool, v as clearToolSearchCatalog, y as collectUniqueCatalogToolNames } from "./tool-search-DcQ9xra6.mjs";
import { t as resolveNativeWebSearchRoute } from "./native-web-search-BwWfYAuV.mjs";
import { n as filterRuntimeCompatibleTools } from "./tool-schema-projection-D-AbMZEk.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { l as bindCodeModeSessionStore } from "./tool-contract-error-CJHmBmJj.mjs";
import { a as TOOL_SEARCH_RAW_TOOL_NAME, i as TOOL_SEARCH_CONTROL_TOOL_NAMES, n as TOOL_DESCRIBE_RAW_TOOL_NAME } from "./tool-search-types-BgcAJ6c_.mjs";
import { n as normalizeAgentRuntimeTools, t as logAgentRuntimeToolDiagnostics } from "./tools-CX1i5Uw0.mjs";
import { a as resolveEffectiveCompactionMode, i as isSilentOverflowProneModel, n as applyAgentAutoCompactionGuard } from "./agent-settings-Chrl5MIo.mjs";
import { t as createPreparedEmbeddedAgentSettingsManager } from "./agent-project-settings-CndET_5f.mjs";
import { a as declarePromptHistoryRewrite, i as completePromptCacheObservation, o as declarePromptToolPin, r as collectPromptCacheTools, t as beginPromptCacheObservation } from "./prompt-cache-observability-BBkCY6BX.mjs";
import { c as persistToolResultProjections, d as prepareSessionToolSurface, f as recordRuntimeContextProjection, h as retireSessionSystemPrompt, m as retainEmbeddedSessionPromptState, n as buildSystemPromptRouteKey, o as persistSessionSystemPrompt, s as persistSessionToolSurface, t as beginSessionSystemPrompt, u as prepareSessionSystemPrompt } from "./session-prompt-state-H0jXFYE1.mjs";
import { n as buildStreamErrorAssistantMessage } from "./stream-message-shared-CBUzFwdv.mjs";
import { t as safeJsonStringify } from "./safe-json-Y8KShjcX.mjs";
import { t as createTrajectoryRuntimeRecorder } from "./runtime-Bsp-rPbR.mjs";
import { t as runContextEngineMaintenance } from "./context-engine-maintenance-DsWc3w5M.mjs";
import { t as rewriteTranscriptEntriesInSessionManager } from "./transcript-rewrite-CnVCjlmn.mjs";
import { t as isRunnerToolCallBlock } from "./attempt-tool-call-block-type-Die7gJid.mjs";
import { d as resolveFinalMessageRawText, l as resolveFinalAssistantRawText, m as resolveReportedModelRef, u as resolveFinalAssistantVisibleText } from "./helpers-W-meNuDY.mjs";
import { a as joinWithRunLivenessDeadline, i as isOpenClawAbortableWrapper, n as abortable, r as createAbortableError, t as RUN_LIVENESS_JOIN_TIMEOUT_MS } from "./abortable-z1NE23aa.mjs";
import { t as flushEmbeddedAttemptTrajectoryRecorder } from "./attempt-trajectory-flush-ChD2ftw_.mjs";
import { n as createEmbeddedAttemptDeferredLifecycleOwner } from "./deferred-lifecycle-owner-C5yWTb_n.mjs";
import { i as runAgentHarnessBeforeAgentFinalizeHook, s as bindAgentHarnessHookMessages } from "./lifecycle-hook-helpers-XBA2t8zZ.mjs";
import { t as streamWithPayloadPatch } from "./stream-payload-utils-CdDjgfPC.mjs";
import { o as createCodexNativeWebSearchWrapper } from "./proxy-DznATSAw.mjs";
import { a as resolvePreparedExtraParams, c as resolveExplicitCachedContent, n as resolveAgentTransportOverride, o as isGooglePromptCacheEligible, r as resolveExplicitSettingsTransport, s as resolveCacheRetention, t as applyExtraParamsToAgent } from "./extra-params-Dpi54r85.mjs";
import { n as isCodeModeDiagnosticEnabled, r as logCodeModeDiagnostic } from "./code-mode-diagnostic-CA-TPnkt.mjs";
import { r as resolveModelCatalogAccessPrograms } from "./model-catalog-access-programs-D76ru0cU.mjs";
import { t as resolveTranscriptPolicy } from "./transcript-policy-DcIEP7eH.mjs";
import { a as isCoreToolResultMediaTrustedName } from "./embedded-agent-tool-media-Bzv7p-IE.mjs";
import { n as supportsModelTools } from "./model-tool-support-BJrIU874.mjs";
import { r as mergeOrphanedTrailingUserPrompt, t as buildAfterTurnRuntimeContext } from "./attempt-prompt-helpers-bQX_3CMZ.mjs";
import { t as resolveModelCallUrgency } from "./run-trigger-BlSheUsq.mjs";
import { o as resolveEmbeddedCompactionThinkingLevel } from "./compaction-runtime-context-Cqy9zW9t.mjs";
import { r as resolveAttemptSpawnWorkspaceDir, t as appendAttemptCacheTtlIfNeeded } from "./attempt-thread-helpers-BkXHw9TC.mjs";
import { t as buildEmbeddedAttemptToolRunContext } from "./attempt-tool-run-context-DpLguX9-.mjs";
import { a as isToolBatchBoundarySafe, n as decideContextPressure } from "./context-pressure-CRrtrfAa.mjs";
import { C as wrapStreamObjectSettlement, S as wrapStreamObjectEvents, _ as dropThinkingBlocks, b as stripThinkingBlocksFromMessage, g as dropReasoningFromHistory, m as bindToolResultPromptProjectionKeys, o as restoreCacheTtlToolResultProjections, u as truncateOversizedToolResultsInSessionManager, x as wrapAnthropicStreamWithRecovery } from "./tool-result-truncation-CpAX82MP.mjs";
import { c as estimateToolSchemaTokenPressure, d as shouldPreemptivelyCompactBeforePrompt, i as contextPressureSignal, n as buildPrePromptContextBudgetStatus, o as estimateProjectedRequestTokenPressure, t as PREEMPTIVE_OVERFLOW_ERROR_TEXT } from "./preemptive-compaction-DWbzXuZy.mjs";
import { a as prepareHarnessContextEnginePrompt, n as bootstrapHarnessContextEngine } from "./context-engine-lifecycle-VWAug052.mjs";
import { r as projectTrajectorySessionTarget } from "./agent-end-context-CdOi9HMi.mjs";
import { t as resolveSkillWorkshopToolConstructionBlock } from "./tool-availability-BtRss_9J.mjs";
import { n as loadPairedComputerUseAvailabilityForSurface } from "./computer-use-node-capabilities-BLaoxSqZ.mjs";
import { _ as observeAgentRunApprovalWait } from "./code-mode-state-CYIS_OXN.mjs";
import { a as createCodeModePermissionChangeReason } from "./prompt-tool-policy-C3u9Ea5g.mjs";
import { t as createAgentHarnessToolSurfaceRuntimeCore } from "./tool-surface-bridge-BDxYoRUW.mjs";
import { t as runBestEffortCallback } from "./embedded-agent-subscribe.callback-DQMmolWU.mjs";
import { M as hasAsyncActivity, c as countActiveToolExecutions } from "./tool-terminal-outcome-I8TmHIh2.mjs";
import { _ as wrapStreamFnWithProviderPromptState, a as completeEmbeddedAttemptAfterTurn, c as createEmbeddedAttemptRunAbort, d as outsideExecutionCapacity, g as preparePromptCacheHistory, l as createAttemptNestedToolActivityState, m as getProviderPromptState, n as resolveProviderRefusal, o as createEmbeddedAttemptExternalAbortController, r as completeEmbeddedAttemptResult, s as createEmbeddedAttemptIdleInterruption, t as prepareEmbeddedAttemptPromptExecution, u as readAttemptNestedToolActivity } from "./prompt-image-preparation-BxsbSbTi.mjs";
import { n as resolveAgentRunSessionTarget } from "./run-session-target-b0y1C8K8.mjs";
import { t as resolveEmbeddedSessionContextLimits } from "./session-context-limits-Dgvy6_uY.mjs";
import { C as SESSIONS_YIELD_ABORT_REASON, D as isRunnerAbortError, E as queueSessionsYieldInterruptMessage, O as buildEmbeddedAgentHookContext, S as shouldFlagCompactionTimeout, T as isSessionsYieldAbortReason, a as resolveAttemptTrajectorySessionFile, b as resolveRunTimeoutDuringCompaction, d as createPromptBuildToolPolicy, f as observeEmbeddedAttemptPrompt, h as cleanupEmbeddedAttemptResources, m as submitEmbeddedAttemptPrompt, n as normalizeCompactionRecoveryTranscriptTail, o as resolveExistingAttemptTranscriptState, p as handleEmbeddedAttemptPromptError, r as removeTrailingMidTurnPrecheckAssistantError, t as loadAttemptSessionEntryAfterQuotaMaintenance, w as createYieldAbortedResponse, x as selectCompactionTimeoutSnapshot, y as measureEmbeddedAgentPreparation } from "./attempt-transcript-helpers-D399v1wz.mjs";
import { n as buildTrajectoryRunMetadata } from "./metadata-JDXU9_I9.mjs";
import { t as resolveToolCallName } from "./attempt-tool-call-name-resolution-BATV9g0H.mjs";
import { r as remapSkillReferencePaths } from "./sandbox-skills-B_GxuUqP.mjs";
import { t as prepareEmbeddedSkills } from "./skill-runtime-Cm3TP3Aa.mjs";
import { c as shouldAllowProviderOwnedThinkingReplay, l as shouldMergeConsecutiveTurns, p as mapThinkingLevel } from "./replay-history-generic-mEncANYP.mjs";
import { o as normalizeMessagesForLlmBoundary, t as wrapStreamFnWithMessageTransform } from "./message-transform-stream-wrapper-B--6dKUi.mjs";
import { t as guardSessionManager } from "./session-tool-result-guard-wrapper-z-jVIqGv.mjs";
import { a as materializeProviderContext, o as promptImageSessionKey, t as buildPromptImageFailureNotice } from "./images-BfGn0xAm.mjs";
import { t as createBundleLspToolRuntime } from "./agent-bundle-lsp-runtime-BJLVU6_B.mjs";
import { i as wrapStreamFnSanitizeMalformedToolCalls, n as sanitizeReplayToolCallIdsForStream, r as shouldApplyReplayToolCallIdSanitizer, t as replayToolResultPromptProjections } from "./tool-result-projection-replay-BmKdixH0.mjs";
import { n as limitHistoryTurns, t as getHistoryLimitFromSessionKey } from "./history-D_pzOPjp.mjs";
import { i as selectEmbeddedAgentStream, n as resolveEmbeddedAgentBaseStreamFn, t as resolveEmbeddedAgentApiKey } from "./stream-resolution-DTC6X1c4.mjs";
import { t as registerProviderStreamForModel } from "./provider-stream-GeYmJKvk.mjs";
import { n as runBeforeAgentRunGate, t as buildAgentRunBlockedUserMessage } from "./before-agent-run-lMhjm8Ri.mjs";
import { a as collectAllowedToolNames, c as sanitizeSessionHistory, i as AGENT_RESERVED_TOOL_NAMES, l as validateReplayTurns, n as withRuntimeToolSchemaQuarantine, o as collectRegisteredToolNames, r as flushPendingToolResultsAfterIdle, s as toSessionToolAllowlist, u as buildEmbeddedExtensionFactories } from "./tool-schema-quarantine-y3o7ToF3.mjs";
import { n as recordEmbeddedToolReceipt, r as createAgentSession } from "./tool-send-receipts-DPctyfdu.mjs";
import { a as prepareEmbeddedAttemptPromptContext, c as prepareEmbeddedAttemptSetup, d as findCurrentAttemptAssistantMessage, f as findLatestUncompactedAttemptUsageSnapshot, h as readLastCacheTtlTimestamp, i as prepareEmbeddedAttemptPromptAssembly, l as startEmbeddedAttemptDiagnostics, m as isCacheTtlEligibleProvider, n as resolveSessionBoundaryPromptCacheKey, o as prepareEmbeddedAttemptBootstrap, p as resolvePromptCacheTouchTimestamp, r as createOpenAIServiceTierObservationWrapper, s as installEmbeddedAttemptContextGuards, t as prepareEmbeddedAttemptSystemPrompt, u as buildContextEnginePromptCacheInfo } from "./attempt-system-prompt-prepare-6qfGnMHg.mjs";
import { n as isChatGPTV2CompactionEligible, t as createChatGPTV2CompactionBoundary } from "./chatgpt-v2-compaction-EMsvlvyz.mjs";
import { n as installMessageToolTerminalHook, t as subscribeEmbeddedAgentSession } from "./embedded-agent-subscribe-Dd0TB6BC.mjs";
import { n as isSmallModel } from "./model-param-b-BWSuXo4Z.mjs";
import { t as buildExecAutoReviewTranscript } from "./exec-auto-review-transcript-DWwstZmo.mjs";
import { a as isWorkspaceTool, n as gateBoundTool } from "./host-bound-tool-DQpDDt09.mjs";
import path from "node:path";
import crypto$1, { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { AsyncLocalStorage } from "node:async_hooks";
import { performance as performance$1 } from "node:perf_hooks";
import { isDeepStrictEqual } from "node:util";
import { setImmediate } from "node:timers/promises";
import { sanitizeSurrogates, splitSystemPromptCacheBoundary, stripSystemPromptCacheBoundary } from "@openclaw/ai/internal/shared";
import { getEventStreamCompletion, getFirstStreamEventTimeoutMs, onLlmRequestActivity } from "@openclaw/ai/internal/runtime";
import { CompactionReplayRefreshRequiredError, convertGoogleTools, isAnthropicServerToolClearingEnabled, isCompactionReplayCheckpoint, mergeTransportHeaders, preserveCompactionReplayWindow, resolveCompactionReplayEligibility, sanitizeTransportPayloadText, stripCompactionReplayCheckpoint, stripCompactionReplayCheckpointInPlace, withProviderAcceptanceObserver } from "@openclaw/ai/transports";
import { bindResponsesInputMessage, measuredRequestPressure, responsesRequestLifecycle } from "@openclaw/ai/internal/openai";
import { isAnthropicOAuthApiKey, isDirectAnthropicModel } from "@openclaw/ai/internal/anthropic";
import { PROVIDER_MODEL_INPUT } from "@openclaw/ai/provider-types";
//#region src/shared/tool-activity-heartbeat.ts
const { runListeners, runLastActivityMs } = resolveGlobalSingleton(Symbol.for("openclaw.toolActivityHeartbeat"), () => ({
runListeners: /* @__PURE__ */ new Map(),
runLastActivityMs: /* @__PURE__ */ new Map()
}), (e) => {
for (const t of e.runListeners.values()) notifyListeners(t, void 0);
e.runListeners.clear();
e.runLastActivityMs.clear();
});
function notifyToolActivity(e) {
runLastActivityMs.set(e, performance.now());
const t = runListeners.get(e);
if (!t) return;
for (const e of t) e();
}
function onToolActivity(e, t) {
let n = runListeners.get(e);
if (!n) {
n = /* @__PURE__ */ new Set();
runListeners.set(e, n);
}
n.add(t);
return () => {
n.delete(t);
if (n.size === 0 && runListeners.get(e) === n) runListeners.delete(e);
};
}
function getLastToolActivityMs(e) {
return runLastActivityMs.get(e) ?? 0;
}
function clearToolActivityRun(e) {
runListeners.delete(e);
runLastActivityMs.delete(e);
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-bundle-tools.ts
async function prepareEmbeddedAttemptBundleTools(e) {
const { cronCreatorToolAllowlist: t, cronCreatorToolAllowlistCaptureRef: n, effectiveToolsAllow: r, inheritedToolAllowlist: i, additionalInheritedToolNamesRef: a, localModelLeanPreserveToolNames: o, runtimeCapabilityProfile: s, toolsEnabled: c, toolsRaw: l } = e.preparedToolBase;
const normalizeTools = (t, n) => normalizeAgentRuntimeTools({
runtimePlan: e.attempt.runtimePlan,
tools: t,
provider: e.attempt.provider,
config: e.attempt.config,
workspaceDir: e.setup.effectiveWorkspace,
env: process.env,
modelId: e.attempt.modelId,
modelApi: e.attempt.model.api,
model: e.attempt.model,
runtimeHandle: e.setup.getProviderRuntimeHandle(),
onPreNormalizationSchemaDiagnostics: (t, r) => n({
diagnostics: t,
tools: r,
runId: e.attempt.runId,
agentId: e.setup.sessionAgentId,
sessionKey: e.attempt.sessionKey,
sessionId: e.attempt.sessionId
})
});
const u = await withRuntimeToolSchemaQuarantine((e) => normalizeTools(c ? l : [], e));
const d = c && e.attempt.trigger !== "memory" && !e.attempt.disableTools && !e.isRawModelRun && s.policy.globalPolicy?.deny?.some((e) => e.trim() === "*") !== true;
let f = d ? e.attempt.clientTools : void 0;
if (f && r) {
const e = createRuntimeToolMatcher(r);
f = f.filter((t) => e(t.function.name));
}
const p = e.setup.getCurrentAttemptPluginMetadataSnapshot();
const m = p?.pluginIds === void 0 ? p?.manifestRegistry : void 0;
const h = {
workspaceDir: e.setup.effectiveWorkspace,
cfg: e.attempt.config,
manifestRegistry: m,
toolOverrides: e.attempt.toolOverrides,
toolDenylist: s.policy.explicitToolDenylist
};
const g = shouldCreateBundleMcpRuntimeForAttempt({
toolsEnabled: d,
toolsAllow: e.attempt.toolsAllow,
resolveConfiguredMcpNamespaces: () => {
const t = Object.keys(e.attempt.config?.mcp?.servers ?? {});
if (t.length === 0) return [];
const { loaded: n, safeServerNamesByServer: r } = loadSessionMcpConfig({
...h,
logDiagnostics: false
});
return t.flatMap((e) => {
const t = Object.hasOwn(n.mcpServers, e) ? r.get(e) : void 0;
return t ? [`${t}${"__"}`] : [];
});
}
}) ? await acquireSessionMcpRuntime({
...h,
sessionId: e.attempt.sessionId,
sessionKey: e.attempt.sessionKey,
agentId: e.setup.sessionAgentId,
agentDir: e.agentDir,
requesterSenderId: e.attempt.senderId,
agentAccountId: e.attempt.agentAccountId,
messageChannel: e.attempt.messageChannel ?? e.attempt.messageProvider
}) : void 0;
const _ = g ? await materializeBundleMcpToolsForRun({
...g,
agentId: e.setup.sessionAgentId,
reservedToolNames: [...u.map((e) => e.name), ...f?.map((e) => e.function.name) ?? []]
}) : void 0;
let v;
try {
v = shouldCreateBundleLspRuntimeForAttempt({
toolsEnabled: d,
toolsAllow: e.attempt.toolsAllow
}) ? await createBundleLspToolRuntime({
workspaceDir: e.setup.effectiveWorkspace,
cfg: e.attempt.config,
abortSignal: e.attempt.abortSignal,
manifestRegistry: m,
reservedToolNames: [
...u.map((e) => e.name),
...f?.map((e) => e.function.name) ?? [],
..._?.tools.map((e) => e.name) ?? []
]
}) : void 0;
const applyRuntimeAllowlist = (e) => applyEmbeddedAttemptToolsAllow(e, r, { toolMeta: (e) => getPluginToolMeta(e) });
const applyBundlePolicy = (t) => applyFinalEffectiveToolPolicy({
bundledTools: t,
config: e.attempt.config,
workspaceDir: e.setup.effectiveWorkspace,
metadataSnapshot: p,
conversationCapabilityProfile: s,
warn: (e) => log$2.warn(e)
});
const h = applyBundlePolicy([...applyRuntimeAllowlist(_?.tools ?? []), ...applyRuntimeAllowlist(v?.tools ?? [])]);
if (_?.restrictAppTools) _.restrictAppTools(applyBundlePolicy(applyRuntimeAllowlist(_.appTools ?? _.tools)));
const g = (h.length > 0 ? await withRuntimeToolSchemaQuarantine((e) => normalizeTools(h, e)) : h).map((t) => wrapToolWithBeforeToolCallHook(t, e.preparedToolBase.toolHookContext));
const projectTools = (s, l) => {
const u = filterLocalModelLeanTools({
tools: [...s, ...g].map((t) => wrapToolWithAbortSignal(t, e.preparedToolBase.toolAbortSignal)),
config: e.attempt.config,
agentId: e.setup.sessionAgentId,
preserveToolNames: o
});
const d = filterRuntimeCompatibleTools(u);
captureFinalEffectiveCronCreatorToolAllowlist(t, n, d.tools, (e) => getPluginToolMeta(e));
if (i?.length) replaceWithEffectiveToolAllowlist(i, [...d.tools, ...applyEmbeddedAttemptToolsAllow(c ? a.map((e) => ({ name: e })) : [], r)]);
l({
diagnostics: d.diagnostics,
tools: u,
runId: e.attempt.runId,
agentId: e.setup.sessionAgentId,
sessionKey: e.attempt.sessionKey,
sessionId: e.attempt.sessionId
});
return d.tools;
};
const y = await withRuntimeToolSchemaQuarantine((e) => projectTools(u, e));
return {
bundleLspRuntime: v,
bundleMcpRuntime: _,
clientTools: f,
tools: u,
uncompactedEffectiveTools: y,
refreshTools: (e) => {
const t = normalizeTools(c ? l : [], e);
u.splice(0, u.length, ...t);
const n = projectTools(u, e);
y.splice(0, y.length, ...n);
}
};
} catch (e) {
if ((await Promise.allSettled([_, v].map(async (e) => await e?.dispose()))).some((e) => e.status === "rejected")) recordAgentCleanupFailure();
throw e;
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-history-prepare.ts
function boundSettledFinalizationMessages(e) {
const t = e.settledTurnFinalizationMessages.map((e, t) => ({
entry: {
type: "message",
id: String(t),
parentId: t ? String(t - 1) : null,
timestamp: new Date(e.timestamp).toISOString(),
message: e,
seq: t
},
omitCheckpoint: false
}));
const project = (e) => {
const t = e.entry.type === "message" ? e.entry.message : void 0;
return t?.role === "toolResult" && e.toolResultOmission ? {
...t,
content: [{
type: "text",
text: e.toolResultOmission
}]
} : t;
};
return selectBoundedModelRequests(t, (e) => new Map(e.map((e) => [e.entry, Buffer.byteLength(JSON.stringify(project(e)), "utf8") + 1])), resolveEmbeddedSessionContextLimits(e)).map(project);
}
async function prepareEmbeddedAttemptHistory(e, t) {
const { attempt: n, activeContextEngine: r, isRawModelRun: i } = e;
const { agentSession: { activeSession: a, settingsManager: o, setActiveSessionSystemPrompt: s }, boundary: { orphanRepair: c }, cacheTrace: l, isOpenAIResponsesApi: u, sessionManager: d, transcriptPolicy: f, transport: { compactionReplayEnabled: p } } = e.prepared.sessionRuntime;
const { capabilityToolNames: m, replayAllowedToolNames: h } = e.prepared.toolCatalog.toolSearchRunPlan;
const { effectiveWorkspace: g, sessionAgentId: _ } = e.setup;
const v = e.setup.sandbox?.enabled === true;
const y = n.operation === "settled-tool-finalization";
let b = e.prepared.sessionRuntime.state.systemPromptText;
const setSystemPrompt = (e) => {
b = e;
s(e);
};
if (i) {
a.agent.reset();
setSystemPrompt("");
l?.recordStage("session:raw-model-run", {
messages: a.messages,
system: b
});
} else {
const replayContext = () => ({
modelApi: n.model.api,
modelId: n.modelId,
provider: n.provider,
config: n.config,
workspaceDir: g,
env: process.env,
model: n.model,
sessionId: n.sessionId,
policy: f
});
const r = await sanitizeSessionHistory({
...replayContext(),
messages: bindToolResultPromptProjectionKeys(y && n.settledTurnFinalizationMessages ? boundSettledFinalizationMessages(n) : a.messages, e.prepared.sessionRuntime.toolResultPromptProjectionState),
allowedToolNames: h,
sessionManager: d
});
e.setup.prepStages.mark("history-sanitize");
l?.recordStage("session:sanitized", { messages: r });
const i = await validateReplayTurns({
...replayContext(),
messages: r,
preserveUserTurns: true
});
e.setup.prepStages.mark("history-validation");
if (n.sessionKey && n.sessionPersistence !== "detached" && !y) {
const e = resolveSessionStorePathCore(n.config?.session?.store, { agentId: _ });
const r = await loadAttemptSessionEntryAfterQuotaMaintenance({
agentId: _,
storePath: e,
sessionKey: n.sessionKey
}, t);
t();
const a = r?.quotaSuspension;
if (r && a?.state === "resuming") {
const o = await readSessionEntrySummariesInWorker({
agentId: _,
storePath: e
});
t();
const s = o.flatMap(({ entry: e }) => e.spawnedBy === r.sessionId ? [{
sessionId: e.sessionId,
role: e.subagentRole,
lastStatus: e.status
}] : []);
const c = s.length > 0;
i.push({
role: "user",
content: [
"[SYSTEM HANDOFF] The previous model is no longer active and a fallback model is now active.",
...c ? [
"You are the new LEADER (Orchestrator). Do not perform tasks already delegated to subordinates.",
"",
"ACTIVE SUBORDINATE UNITS:",
s.map((e) => `- Subagent ${e.sessionId} (${e.role ?? "leaf"}): ${e.lastStatus ?? "running"}`).join("\n")
] : ["Review the current state below and continue the conversation from where the previous model left off."],
"",
"CURRENT STATE SUMMARY:",
a.summary ?? "No recovery briefing was captured.",
...c ? [
"",
"INSTRUCTIONS:",
"1. Review the state and subordinate reports.",
"2. Provide strategic guidance and commands to subordinates.",
"3. Do not repeat work already performed by subordinates."
] : []
].join("\n"),
timestamp: Date.now()
});
await patchSessionEntryCore({
agentId: _,
storePath: e,
sessionKey: n.sessionKey
}, (e) => {
if (e.sessionId !== r.sessionId || e.quotaSuspension?.state !== "resuming") return null;
return { quotaSuspension: {
...e.quotaSuspension,
state: "active"
} };
}, {
skipMaintenance: true,
takeCacheOwnership: true,
...sessionEntryCommitGuardOptions(t)
});
t();
}
}
let o = i;
if (!y) {
const e = filterHeartbeatTranscriptArtifacts(i);
o = preserveCompactionReplayWindow(e, limitHistoryTurns(e, getHistoryLimitFromSessionKey(n.sessionKey, n.config, {
accountId: n.agentAccountId,
peerId: n.conversationRoutePeerId,
chatType: n.chatType
}), { groupConsecutiveUserTurns: f.validateAnthropicTurns && shouldMergeConsecutiveTurns(f, n.model.api) }), n.model, {
sessionId: n.sessionId,
enabled: p
});
}
e.setup.prepStages.mark("history-window");
l?.recordStage("session:limited", { messages: o });
if (o.length > 0 || r.length > 0 || y) a.agent.state.messages = o;
}
const x = c?.contextEnginePrompt ?? n.prompt ?? "";
const { messages: S, systemPrompt: C, ...w } = await prepareHarnessContextEnginePrompt({
...n,
contextEngine: r,
agentId: _,
appendOnlyRuntimeContext: f.appendOnlyRuntimeContext,
clearsTurnScopedSystemUpdates: f.inHistorySystemUpdates && n.model.api === "anthropic-messages",
messages: a.messages,
availableTools: new Set(m),
citationsMode: n.config?.memory?.citations,
sandboxed: v,
memoryProjectKey: n.preparedModelRuntime?.projectKey ?? void 0,
promptBudget: {
contextTokens: n.contextTokenBudget ?? n.model.contextWindow ?? n.model.maxTokens,
reserveTokens: o.getCompactionReserveTokens(),
systemPrompt: b,
prompt: x
},
contextEngineHostSupport: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST,
providerId: n.provider,
transcriptReadFence: n.userTurnTranscriptRecorder?.getAdmissionReceipt(),
...n.prompt !== void 0 ? { prompt: x } : {},
repairToolUseResultPairing: f.repairToolUseResultPairing,
isOpenAIResponsesApi: u,
warn: (e) => log$2.warn(e)
});
e.setup.prepStages.mark("context-engine");
for (const e of S) if (e.role === "assistant") freezeJsonSnapshot(e);
a.agent.state.messages = S;
if (C !== b) setSystemPrompt(C);
return w;
}
//#endregion
//#region src/agents/embedded-agent-runner/google-prompt-cache.ts
const GOOGLE_PROMPT_CACHE_CUSTOM_TYPE = "openclaw.google-prompt-cache";
const GOOGLE_PROMPT_CACHE_RESPONSE_MAX_BYTES = 1048576;
const GOOGLE_PROMPT_CACHE_RETRY_BACKOFF_MS = 6e5;
const GOOGLE_PROMPT_CACHE_SHORT_REFRESH_WINDOW_MS = 3e4;
const GOOGLE_PROMPT_CACHE_LONG_REFRESH_WINDOW_MS = 3e5;
function stringifyGooglePromptCacheKeyPart(e) {
if (typeof e === "string") return e;
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint") return String(e);
return "";
}
function readLatestGooglePromptCacheEntry(e, t) {
try {
const n = e.getEntries();
for (let e = n.length - 1; e >= 0; e -= 1) {
const r = n[e];
if (r?.type !== "custom" || r?.customType !== GOOGLE_PROMPT_CACHE_CUSTOM_TYPE) continue;
const i = r.data;
if (!i || typeof i !== "object") continue;
const a = i;
if (stableStringify({
provider: stringifyGooglePromptCacheKeyPart(a.provider),
modelId: stringifyGooglePromptCacheKeyPart(a.modelId),
modelApi: typeof a.modelApi === "string" || a.modelApi == null ? a.modelApi : null,
baseUrl: stringifyGooglePromptCacheKeyPart(a.baseUrl),
systemPromptDigest: stringifyGooglePromptCacheKeyPart(a.systemPromptDigest),
cacheConfigDigest: typeof a.cacheConfigDigest === "string" ? a.cacheConfigDigest : void 0
}) === t) return i;
}
} catch {
return null;
}
return null;
}
async function appendGooglePromptCacheEntry(e, t) {
try {
await e.appendCustomEntryAsync(GOOGLE_PROMPT_CACHE_CUSTOM_TYPE, t);
} catch (e) {
if (e instanceof SessionTranscriptWriterClaimReboundError) throw e;
}
}
function readFutureExpireTime(e, t) {
const n = parseDateStringTimestampMs(e);
return typeof e === "string" && isFutureDateTimestampMs(n, { nowMs: t }) ? {
value: e,
timestamp: n
} : null;
}
function readGooglePromptCacheName(e) {
if (typeof e !== "string" || !e.startsWith("cachedContents/")) return null;
const t = e.slice(15);
if (!t || t === "." || t === "..") return null;
try {
return encodeURIComponent(t) === t ? e : null;
} catch {
return null;
}
}
function mapManagedGoogleToolChoice(e) {
if (!e) return;
if (typeof e === "object" && e.type === "function") {
const t = e.function?.name;
return typeof t === "string" ? {
mode: "ANY",
allowedFunctionNames: [t]
} : { mode: "ANY" };
}
switch (e) {
case "none": return { mode: "NONE" };
case "any":
case "required": return { mode: "ANY" };
default: return { mode: "AUTO" };
}
}
async function prepareGooglePromptCacheStreamFn(e) {
if (!e.streamFn || resolveExplicitCachedContent(e.extraParams) || !isGooglePromptCacheEligible({
modelApi: e.model.api,
modelId: e.modelId
})) return;
const t = resolveCacheRetention(e.extraParams, e.provider, e.model.api, e.modelId);
if (t !== "short" && t !== "long") return;
const n = e.apiKey?.trim();
if (!n) return;
const r = e.streamFn;
return async (i, a, o) => {
const s = splitSystemPromptCacheBoundary(a.systemPrompt ?? "");
const c = sanitizeTransportPayloadText(stripSystemPromptCacheBoundary(s?.stablePrefix ?? ""));
if (!s || !c.trim()) return r(i, a, o);
const l = convertGoogleTools(a.tools ?? []);
const u = l ? mapManagedGoogleToolChoice(o?.toolChoice) : void 0;
const d = u ? { functionCallingConfig: u } : void 0;
const f = e.model.provider;
const p = looksLikeSecretSentinel(n);
const m = p ? resolveSecretSentinel(n) : n;
if (m === void 0) throw new Error(`Secret sentinel ${n} is not registered in this process; refusing Google prompt-cache auth`);
const h = m.startsWith("{") ? safeParseJsonRecord(m)?.token : void 0;
const g = {
...typeof h === "string" && h ? { Authorization: `Bearer ${h}` } : { "x-goog-api-key": m },
"Content-Type": "application/json"
};
const _ = !p && !isSecretValueRegisteredForRedaction(n) ? g : Object.fromEntries(Object.entries(g).map(([e, t]) => {
return [e, e.toLowerCase() === "authorization" || e.toLowerCase() === "x-goog-api-key" ? mintSecretSentinel(t, { label: `model-auth:${f}` }) : t];
}));
const v = mergeTransportHeaders(e.model.headers, o?.headers);
const y = omitNullRequestHeaders(resolveProviderRequestHeaders({
provider: e.model.provider,
api: e.model.api,
baseUrl: normalizeGoogleApiBaseUrl(e.model.baseUrl),
capability: "llm",
transport: "http",
defaultHeaders: _,
callerHeaders: v,
precedence: "caller-wins"
}) ?? mergeTransportHeaders(_, v) ?? _) ?? {};
const b = e.model;
const x = e.provider;
const S = e.sessionManager;
const C = e.signal;
const w = await (async () => {
const e = normalizeGoogleApiBaseUrl(b.baseUrl);
const n = asDateTimestampMs(Date.now());
if (n === void 0) return null;
const r = swapSecretSentinelsForEgress({
url: e,
headers: y
}).headers ?? new Headers(y);
const i = {
provider: x,
modelId: b.id,
modelApi: b.api,
baseUrl: e,
systemPromptDigest: sha256Hex(c),
cacheConfigDigest: sha256Hex(stableStringify({
tools: l,
toolConfig: d,
headers: Object.fromEntries(r)
}))
};
const a = readLatestGooglePromptCacheEntry(S, stableStringify(i));
const o = {
timestamp: n,
...i,
cacheRetention: t
};
if (a?.status === "failed" && isFutureDateTimestampMs(a.retryAfter, { nowMs: n })) return null;
const s = buildGuardedModelFetch(b);
const u = t === "long" ? GOOGLE_PROMPT_CACHE_LONG_REFRESH_WINDOW_MS : GOOGLE_PROMPT_CACHE_SHORT_REFRESH_WINDOW_MS;
const f = a?.status === "ready" ? readGooglePromptCacheName(a.cachedContent) : null;
const p = a?.status === "ready" && f ? readFutureExpireTime(a.expireTime, n) : null;
if (p && p.timestamp - n > u) return f;
const m = p ? f : null;
const h = Boolean(m);
const g = t === "long" ? "3600s" : "300s";
let _;
let v;
if (m) {
_ = `${e}/${m}?updateMask=ttl`;
v = JSON.stringify({ ttl: g });
} else {
const t = b.id;
_ = `${e}/cachedContents`;
v = JSON.stringify({
model: t.startsWith("models/") ? t : `models/${t}`,
ttl: g,
systemInstruction: { parts: [{ text: c }] },
...l ? { tools: l } : {},
...d ? { toolConfig: d } : {}
});
}
let w = null;
let T;
try {
T = await s(_, {
method: h ? "PATCH" : "POST",
headers: y,
body: v,
signal: C
});
if (!T.ok) throw new Error(`Google prompt cache request failed (${T.status})`);
const e = await readProviderJsonObjectResponse(T, "Google prompt cache", {
maxBytes: GOOGLE_PROMPT_CACHE_RESPONSE_MAX_BYTES,
onOverflow: ({ size: e, maxBytes: t }) => /* @__PURE__ */ new Error(`Google prompt cache response too large: ${e} bytes (limit: ${t} bytes)`),
requestHeaders: y
});
const t = readFutureExpireTime(e.expireTime, n);
const r = h ? m : readGooglePromptCacheName(e.name);
if (!r || !t) throw new Error("Google prompt cache response is invalid");
w = {
cachedContent: r,
expireTime: t.value
};
} catch {
C?.throwIfAborted();
} finally {
await cancelUnreadResponseBody(T);
}
if (w) await appendGooglePromptCacheEntry(S, {
status: "ready",
...o,
...w
});
else if (!m) await appendGooglePromptCacheEntry(S, {
status: "failed",
...o,
retryAfter: resolveExpiresAtMsFromDurationMs(GOOGLE_PROMPT_CACHE_RETRY_BACKOFF_MS, { nowMs: n }) ?? 0
});
return w?.cachedContent ?? m;
})();
if (!w) {
log$2.debug(`google prompt cache unavailable for ${e.provider}/${e.modelId}; continuing without cachedContent`);
return r(i, a, o);
}
return streamWithPayloadPatch(r, i, {
...a,
systemPrompt: void 0,
messages: prependRuntimeContextForModel(a.messages, sanitizeTransportPayloadText(stripSystemPromptCacheBoundary(s.dynamicSuffix)))
}, {
...o,
headers: y
}, (e) => {
delete e.tools;
delete e.toolConfig;
e.cachedContent = w;
});
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-prompt-preflight.ts
function buildPreflightRecoveryBudgetSnapshot(e) {
return {
estimatedPromptTokens: e.estimatedPromptTokens,
promptBudgetBeforeReserve: e.promptBudgetBeforeReserve,
overflowTokens: e.overflowTokens
};
}
async function handleEmbeddedAttemptMidTurnPrecheck(e) {
const { attempt: t, request: n } = e;
const r = {
route: n.route,
pressure: n.pressure,
source: "mid-turn",
...buildPreflightRecoveryBudgetSnapshot(n)
};
const logMidTurnPrecheck = (r, i) => {
log$2.warn(`[context-overflow-midturn-precheck] sessionKey=${t.sessionKey ?? t.sessionId} provider=${t.provider}/${t.modelId} pressure=${n.pressure} route=${r} estimatedPromptTokens=${n.estimatedPromptTokens} promptBudgetBeforeReserve=${n.promptBudgetBeforeReserve} overflowTokens=${n.overflowTokens} toolResultReducibleChars=${n.toolResultReducibleChars} effectiveReserveTokens=${n.effectiveReserveTokens} prePromptMessageCount=${e.prePromptMessageCount} ` + (i ? `${i} ` : "") + `sessionFile=${t.sessionFile}`);
};
if (n.route === "truncate_tool_results_only") {
const i = t.contextTokenBudget ?? 2e5;
const a = resolveLiveToolResultMaxChars({ contextWindowTokens: i });
const o = await truncateOversizedToolResultsInSessionManager({
sessionManager: e.sessionManager,
projectionState: e.toolResultPromptProjectionState,
contextWindowTokens: i,
maxCharsOverride: a,
preserveSentToolResults: true,
sessionFile: t.sessionFile,
sessionId: t.sessionId,
sessionKey: t.sessionKey,
agentId: e.sessionAgentId
});
if (o.truncated) {
e.replaceSessionMessages(sanitizeCompactionReplayMessages(e.sessionManager.buildSessionContext().messages));
const { truncatedCount: t } = o;
logMidTurnPrecheck(n.route, `handled=true truncatedCount=${t}`);
return { preflightRecovery: {
...r,
handled: true,
truncatedCount: t
} };
}
r.route = "compact_only";
logMidTurnPrecheck(r.route, `truncateFallbackReason=${o.reason ?? "unknown"}`);
} else logMidTurnPrecheck(n.route);
return {
preflightRecovery: r,
promptError: contextPressureSignal(n.pressure)
};
}
async function prepareEmbeddedAttemptPromptPreflight(e) {
const { attempt: t } = e;
const n = {
appendOnlyRuntimeContext: e.appendOnlyRuntimeContext,
...e.timezone ? { timezone: e.timezone } : {},
...e.includeBoundaryTimestamp ? {} : { includeTimestamp: false }
};
const r = e.contextEnginePromptAuthority === "preassembly_may_overflow" ? e.unwindowedContextEngineMessagesForPrecheck : void 0;
const i = r ? normalizeMessagesForLlmBoundary(r, n) : void 0;
if (e.state.skipPromptSubmission) return { ...e.state };
if ((e.pendingInputTokens ?? 0) >= e.contextTokenBudget) {
if (e.providerCompactionAtRequestBoundary) log$2.warn("ChatGPT V2 compaction unavailable; falling back to client compaction: pending input exceeds the context budget");
return {
...e.state,
preflightRecovery: {
route: "compact_only",
pressure: "overflow"
},
promptError: new Error(PREEMPTIVE_OVERFLOW_ERROR_TEXT),
promptErrorSource: "precheck",
skipPromptSubmission: true
};
}
let a;
try {
a = shouldPreemptivelyCompactBeforePrompt({
messages: e.hookMessagesForCurrentPrompt,
unwindowedMessages: i,
systemPrompt: e.systemPrompt,
prompt: e.promptForPrecheck,
contextTokenBudget: e.contextTokenBudget,
reserveTokens: e.reserveTokens,
toolResultMaxChars: e.toolResultMaxChars,
...typeof e.toolSchemaTokens === "number" ? { toolSchemaTokens: e.toolSchemaTokens } : {},
replay: {
model: t.model,
sessionId: t.sessionId,
enabled: e.compactionReplayEnabled
}
});
} catch (t) {
if (!(t instanceof CompactionReplayRefreshRequiredError)) throw t;
return {
...e.state,
promptError: t,
promptErrorSource: "precheck",
skipPromptSubmission: true
};
}
const o = {
result: a,
provider: t.provider,
modelId: t.modelId,
messageCount: e.sessionMessageCount,
contextTokenBudget: e.contextTokenBudget,
reserveTokens: e.reserveTokens,
...t.sessionId ? { sessionId: t.sessionId } : {},
...r ? { unwindowedMessageCount: r.length } : {}
};
const s = buildPrePromptContextBudgetStatus(o);
const c = a.compactionReplay;
const l = c && !e.providerCompactionAtRequestBoundary ? decideContextPressure({
estimatedPromptTokens: c.estimatedPromptTokens,
windowTokens: e.contextTokenBudget,
maintenanceDue: c.route !== "fits",
boundarySafe: true,
runId: t.runId
}) : void 0;
if (c && c.route !== "fits" && l) return {
...e.state,
contextBudgetStatus: s,
preflightRecovery: {
route: c.route,
pressure: l,
...buildPreflightRecoveryBudgetSnapshot(c)
},
promptError: contextPressureSignal(l),
promptErrorSource: "precheck",
skipPromptSubmission: true
};
if (a.route !== "fits") log$2.info(`[context-pressure-diagnostic] admitted provider attempt for ${t.provider}/${t.modelId} route=${a.route} estimatedPromptTokens=${a.estimatedPromptTokens} promptBudgetBeforeReserve=${a.promptBudgetBeforeReserve}`);
return {
...e.state,
contextBudgetStatus: s
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts
function isInterruptedTurnEntry(e, t) {
if (e.type === "custom_message") return e.customType === "openclaw:turn-aborted";
if (e.type !== "message") return false;
const n = e.message;
if (n.role === "custom") return readOwnNestedToolActivity(n)?.details.runId === t;
const r = isOpenClawDeliveryMirrorAssistantMessage(n) ? asOptionalRecord(Reflect.get(n, "openclawDeliveryMirror")) : void 0;
if (r?.kind === "skill-workshop-change" || r?.kind === "model-fallback") return true;
if (Reflect.get(n, "__openclaw")?.runId !== t) return false;
if (n.role !== "assistant") return n.role === "toolResult";
if (isOpenClawDeliveryMirrorAssistantMessage(n)) return r?.kind === "message-tool-source-reply" && r.final === false;
return n.stopReason === "toolUse" || (n.stopReason === "aborted" || n.stopReason === "error") && (n.errorCode === "OPENCLAW_RESTART_ABORT" || n.stopReason === "aborted" && n.errorCode === void 0 && n.errorMessage === "agent run aborted for restart" && n.content.every((e) => e.type === "text" && e.text === ""));
}
function selectCurrentUserTurnFromCohort(e) {
const { sessionManager: t, prepared: n, assertView: r } = e;
r();
const i = n.kind === "bounded" ? n.transcript : void 0;
if (!i || i.replayValidated !== "current" && !(i.replayValidated === "initial" && e.allowInitial && !e.initialWriter?.committedFence)) throw new SessionTranscriptWriterClaimReboundError();
const a = t.resolveCurrentTurnEntryId((t) => isInterruptedTurnEntry(t, e.runId));
const o = a ? t.getEntry(a) : void 0;
if (a && !o) return;
const s = o?.type === "message" && o.message.role === "user" && isDeepStrictEqual(o.message, e.message);
const c = i.anchors.find((e) => e.entryId === a);
if (s && !c) return;
return { current: s && c ? {
entryId: c.entryId,
anchor: c,
version: n.snapshot.version,
assertCurrent: r
} : void 0 };
}
/** The receipt selects a hint; initial replay still consumes freshly hydrated persisted bytes. */
function prepareInitialPersistedUserTurnCohort(e) {
const { message: t, recorder: n } = e;
const r = n?.getAdmissionReceipt()?.entryId;
if (!t?.idempotencyKey || !n || !r) return;
const i = withOwnedSessionTranscriptWriterFence(e.target);
const a = getOwnedSessionTranscriptReader(i);
if (!a) return;
const o = captureOwnedTranscriptWriteAssertion(i);
const s = getOwnedSessionTranscriptInitialWriter({ sessionTarget: i });
const c = Boolean(s) && !s?.committedFence;
const l = {
sessionKey: i.sessionKey,
entryIds: [r],
includeMessagePresence: true,
replayValidation: {
expectedLifecycleRevision: i.expectedLifecycleRevision,
expectedWriterRunId: i.expectedWriterRunId,
allowInitial: c,
admission: resolveSessionTranscriptReadFence(i)
}
};
let u;
return {
selection: l,
consume(r, i, l) {
o();
a.assertCurrent();
const d = selectCurrentUserTurnFromCohort({
sessionManager: r,
message: t,
runId: e.runId,
prepared: i,
assertView: l,
allowInitial: c,
initialWriter: s
});
if (d) {
if (d.current) n.markRuntimePersisted(t, d.current.anchor, { appended: false });
u = { anchor: d.current?.anchor };
}
},
readInitial: () => u
};
}
/** Re-adopt the current turn without reopening arbitrary historical keyed users. */
async function preparePersistedCurrentUserTurn(e) {
const { sessionManager: t, message: n, recorder: r, runId: i } = e;
const a = t.getSessionTarget();
if (!a || !n?.idempotencyKey || !r) return;
const o = withOwnedSessionTranscriptWriterFence(a);
const s = captureOwnedTranscriptWriteAssertion(o);
const c = getOwnedSessionTranscriptInitialWriter({ sessionTarget: o });
const l = prepareSessionManagerHydration(o, {
signal: e.signal,
manager: t
});
const assertCurrent = () => {
s();
l.assertCurrent();
};
const u = l.incognitoBinding;
const withSource = (e, t) => {
assertCurrent();
return u ? withSessionManagerMemoryActor(u, false, async (e) => {
if (!e) throw new Error("Persisted user turn memory session is closed");
return runWithSessionActorStorage({
actor: e.actor,
authority: e.authority,
agentId: e.database.agentId,
path: e.database.path
}, () => t(o, assertCurrent));
}) : withSessionTranscriptReadSource(o, ({ scope: e, assertCurrent: n }) => t({
...o,
agentId: e.agentId,
storePath: e.storePath
}, n), e);
};
const validate = async (e, t, n, r, i) => {
r?.throwIfAborted();
assertCurrent();
const a = !n && Boolean(c) && !c?.committedFence;
let s = false;
await readSessionTranscriptAnchorsAsync(e, {
entryIds: n ? [n.entryId] : [],
replayValidation: {
expectedLifecycleRevision: o.expectedLifecycleRevision,
expectedWriterRunId: o.expectedWriterRunId,
allowInitial: a,
admission: resolveSessionTranscriptReadFence(e)
},
...n ? { contextValidation: { version: n.version } } : {}
}, r, (e) => {
t();
assertCurrent();
n?.assertCurrent();
if (e.replayValidated !== "current" && !(e.replayValidated === "initial" && a && !c?.committedFence)) throw new SessionTranscriptWriterClaimReboundError();
if (n && !e.contextValidated) throw new SessionWorkStartChangedError("Persisted user turn changed before replay admission. Retry the turn.");
const r = e.anchors[0];
i(n && r ? {
...n,
anchor: r
} : void 0);
s = true;
});
assertCurrent();
if (!s) throw new SessionWorkStartChangedError("Persisted user turn changed before replay admission. Retry the turn.");
};
const readCurrentTurn = async (e, r, a) => {
let s = a;
let l = false;
const read = () => withSource(e, async (a, u) => {
const matchesUser = (e) => e?.type === "message" && e.message.role === "user" && isDeepStrictEqual(e.message, n);
const select = () => t[sessionManagerPrepareCurrentTurnReplay]((e) => isInterruptedTurnEntry(e, i), matchesUser, e);
let d;
const accept = (e) => {
if (s && (!e || e.anchor.entryId !== s.entryId || e.anchor.generation !== s.generation)) throw new SessionWorkStartChangedError("Persisted user turn changed before replay admission. Retry the turn.");
d = e;
l = true;
r(e);
};
if (getOwnedSessionTranscriptReader(a)) {
const r = Boolean(c) && !c?.committedFence;
const s = t.resolveCurrentTurnEntryId((e) => isInterruptedTurnEntry(e, i));
await t[sessionManagerReloadTranscriptCohort]({
sessionKey: o.sessionKey,
entryIds: s ? [s] : [],
replayValidation: {
expectedLifecycleRevision: o.expectedLifecycleRevision,
expectedWriterRunId: o.expectedWriterRunId,
allowInitial: r,
admission: resolveSessionTranscriptReadFence(a)
}
}, (e, a) => {
u();
assertCurrent();
const o = selectCurrentUserTurnFromCohort({
sessionManager: t,
message: n,
runId: i,
prepared: e,
assertView: a,
allowInitial: r,
initialWriter: c
});
if (o) accept(o.current);
}, e);
if (l) return d;
}
await t.reloadPersistedTranscriptAsync(e);
u();
assertCurrent();
const f = await select();
if (f) s ??= {
entryId: f.entryId,
generation: f.version.generation
};
await validate(a, u, f, e, accept);
return d;
});
try {
return await read();
} catch (e) {
if (l || !isSessionWorkStartInvalidatedError(e) && !(e instanceof SessionTranscriptReadFenceError)) throw e;
return await read();
}
};
const d = e.initial ? e.initial.anchor : (await readCurrentTurn(e.signal, (e) => {
if (e) r.markRuntimePersisted(n, e.anchor, { appended: false });
}))?.anchor;
if (!d) {
const a = t.resolveCurrentTurnEntryId((e) => isInterruptedTurnEntry(e, i));
const o = a ? t.getEntry(a) : void 0;
if (o?.type === "message" && (o.message.role === "user" && Reflect.get(o.message, "idempotencyKey") === n.idempotencyKey || o.message.role === "assistant" && Reflect.get(o.message, "__openclaw")?.runId === i && (o.message.stopReason === "error" || e.fallbackReason === "timeout" && o.message.stopReason === "aborted" || e.fallbackReason === "format" && o.message.stopReason === "length"))) return;
if (r.getPendingInputMessage?.() && !r.validateCommittedReplay && !r.hasPersisted()) return;
await r.validateCommittedReplay?.();
const s = await withSource(e.signal, async (e, t) => {
const r = await readSessionSubmittedInput(e, n.idempotencyKey, { includeSource: true });
t();
assertCurrent();
return r;
});
e.signal?.throwIfAborted();
return s?.messageSeq !== void 0 && messagesMatchForIdempotentReplay(s.message, n) ? "already-delivered" : void 0;
}
let f = true;
return async (t = e.signal) => {
if (!f) return;
const n = t && e.signal && t !== e.signal ? AbortSignal.any([t, e.signal]) : t;
n?.throwIfAborted();
assertCurrent();
return async (e) => {
await readCurrentTurn(n, () => {
if (!f) throw new Error("Persisted user turn replay was already consumed");
f = false;
e();
}, d);
};
};
}
function sessionMessagesContainIdempotencyKey(e, t) {
return e.some((e) => "idempotencyKey" in e && e.idempotencyKey === t);
}
function reconcilePrePersistedCurrentUserTurn(e) {
const t = e.currentUserTurnMessage?.idempotencyKey;
if (typeof t !== "string" || t.length === 0) return false;
const n = e.durableUserTurnMessage?.idempotencyKey === t;
if (!e.userTurnAlreadyPersisted && !n) return false;
const r = e.activeSession.agent.state.messages;
const i = r.at(-1);
const a = i?.role === "user" && "idempotencyKey" in i && i.idempotencyKey === t;
if (a) e.activeSession.agent.state.messages = r.slice(0, -1);
return a || n || e.currentUserTurnMessage?.excludeFromContext === true;
}
function readUserIdempotencyKey(e) {
return e.role === "user" && "idempotencyKey" in e && typeof e.idempotencyKey === "string" ? e.idempotencyKey : void 0;
}
/** Resolve physical ownership before append admission, then sample live custody at preparation. */
async function prepareForeignPendingUserTurns(e, t) {
const n = e.getSessionTarget();
if (!n) return;
const r = captureOwnedTranscriptWriteAssertion(n);
const assertPrepared = () => {
t?.throwIfAborted();
r();
if (!sameSessionTranscriptTargetBinding(n, e.getSessionTarget())) throw new Error("Session manager target changed during live input preparation");
};
assertPrepared();
const i = await prepareForeignLiveSessionPendingInputEntries(n, t);
assertPrepared();
const a = /* @__PURE__ */ new Map();
const o = /* @__PURE__ */ new Set();
let s = false;
return (e, t) => {
assertPrepared();
for (const [e, t] of i()) a.set(e, t);
if (!a.size) return;
if (!s) {
s = true;
e.subscribe((e) => {
const t = e.type === "message_end" ? readUserIdempotencyKey(e.message) : void 0;
if (t) o.add(t);
});
}
const n = new Set([...a.values()].filter((e) => e !== t));
const omitInput = (e) => e.filter((e) => {
const t = readUserIdempotencyKey(e);
return !t || !n.has(t) || o.has(t);
});
e.agent.state.messages = omitInput(e.agent.state.messages);
return {
ownsEntry: (e) => a.has(e),
omitInput
};
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts
async function runEmbeddedAttemptPromptPhase(e, t) {
const { attempt: n, activeContextEngine: r, isRawModelRun: i, prepared: a, preparedStreamRuntime: o, runAbortController: s } = e;
const { sessionRuntime: c, promptToolPolicy: l } = a;
const { agentSession: { activeSession: u, compactionEnabled: d, hookRunner: f, setActiveSessionSystemPrompt: p, settingsManager: m }, boundary: { boundaryTimezone: h, includeBoundaryTimestamp: g, orphanRepair: _, setCurrentUserTimestampOverride: v }, cacheTrace: y, contextGuards: b, preparedUserTurnMessage: x, sessionManager: S, sessionPromptState: C, state: w, toolResultPromptProjectionState: T, trajectoryRecorder: E, transcriptPolicy: { appendOnlyRuntimeContext: D, inHistorySystemUpdates: O, pinnedSystemPrompt: k }, transport: { effectiveAgentTransport: A, effectiveExtraParams: j, streamStrategy: M, compactionReplayEnabled: N } } = c;
const { effectiveFsWorkspaceOnly: P, effectiveWorkspace: F, sandbox: I, sessionAgentId: L } = e.setup;
const { history: { contextEnginePromptAuthority: R, unwindowedContextEngineMessagesForPrecheck: z }, promptActiveSession: ee, stream: { stopAcceptingSteerMessages: B } } = o;
const { withOwnedTranscriptWrite: V } = e.sessionLock;
const withTranscriptWrite = (e) => V(() => withSessionManagerAppend(S, e));
const observeForegroundRequests = (e) => {
const t = u.agent.streamFn;
u.agent.streamFn = (n, r, i) => {
if (!u.isCompacting) e(n, r);
return t(n, r, i);
};
};
const { diagnosticTrace: H, runTrace: U } = e.diagnostics;
const { systemPromptReport: W, runtimeInfo: G } = a.systemPrompt;
let K = w.systemPromptText;
const te = a.toolCatalog.toolSearch.compacted;
let q = false;
let ne;
const J = isChatGPTV2CompactionEligible({
config: n.config,
model: n.model,
extraParams: j,
compactionEnabled: d,
compactionReplayEnabled: N,
contextEngineOwnsCompaction: r?.info.ownsCompaction,
operation: n.operation
});
const Y = u[agentSessionDeferThresholdCompaction];
if (J) u[agentSessionDeferThresholdCompaction] = true;
const setFailure = (t, n) => {
e.state.terminal = setAgentRunAttemptTerminalFailure(e.state.terminal, t !== null && t !== void 0 ? {
error: t,
source: n ?? "prompt"
} : null);
};
const publishDispatchState = (e) => {
q = e.skipPromptSubmission;
t.contextBudgetStatus = e.contextBudgetStatus;
t.preflightRecovery = e.preflightRecovery;
setFailure(e.promptError, e.promptErrorSource);
};
const handleMidTurnPrecheckRequest = async (e) => {
const r = await handleEmbeddedAttemptMidTurnPrecheck({
attempt: n,
request: e,
sessionAgentId: L,
sessionManager: S,
toolResultPromptProjectionState: T,
prePromptMessageCount: w.prePromptMessageCount,
replaceSessionMessages: (e) => {
u.agent.state.messages = e;
}
});
t.preflightRecovery = r.preflightRecovery;
if (r.promptError) setFailure(r.promptError, "precheck");
};
const X = Date.now();
let Z = null;
try {
if (n.inputAlreadyDelivered) {
s.signal.throwIfAborted();
e.sessionLock.ownedTranscriptWriteContext.assertCommitAllowed?.();
return {
promptStartedAt: X,
transcriptLeafId: Z
};
}
const r = await prepareEmbeddedAttemptPromptAssembly({
attempt: n,
activeSession: u,
sessionManager: S,
hookRunner: f,
hookAgentId: L,
diagnosticTrace: H,
isRawModelRun: i,
..._ ? { orphanRepair: _ } : {},
sessionAgentId: L,
runtimeModel: n.blindPrompt ? void 0 : G.model,
systemPromptText: K,
runAbortSignal: e.runAbortController.signal,
hasBaselineTools: l.hasBaselineTools,
setActiveSessionSystemPrompt: p,
applyPromptBuildToolsAllow: (e, t) => {
return l.apply(e, t).callableToolNames;
},
prepareSystemPrompt: async (e) => {
const t = await a.systemPrompt.prepareToolPrompt?.(l.current.effectiveTools);
return t ? t(e) : e;
}
});
e.setup.prepStages.mark("prompt-build");
K = w.systemPromptText;
if (a.toolCatalog.emptyExplicitToolAllowlistError) {
setFailure(a.toolCatalog.emptyExplicitToolAllowlistError, "precheck");
q = true;
log$2.warn(`[tools] ${a.toolCatalog.emptyExplicitToolAllowlistError.message}`);
}
const { hookCtx: d, promptBuildPrependContext: b, promptBuildAppendContext: B } = r;
Z = r.transcriptLeafId;
const Y = await prepareEmbeddedAttemptPromptContext({
sessionVersion: S.getHeader()?.version,
attempt: n,
systemPromptRuntimeContextFragments: a.systemPrompt.runtimeContextFragments,
capabilityToolNames: a.toolCatalog.toolSearchRunPlan.capabilityToolNames,
messages: u.messages,
prompt: r,
replaceSessionMessages: (e) => {
u.agent.state.messages = e;
},
appendOnlyRuntimeContext: D,
inHistorySystemUpdates: O,
...h ? { boundaryTimezone: h } : {},
includeBoundaryTimestamp: g,
isRawModelRun: i,
...x ? { preparedUserTurnMessage: x } : {},
sessionAgentId: L,
...W ? { systemPromptReport: W } : {},
systemPromptText: K,
toolResultPromptProjectionState: T
});
e.setup.prepStages.mark("prompt-context");
if (s.signal.aborted) throw createAbortableError(s.signal);
r.assertHostActive?.();
const { hookMessagesForCurrentPrompt: re, promptForModel: ie, systemPromptForHook: ae } = Y;
w.prePromptMessageCount = Y.prePromptMessageCount;
v(Y.currentUserTimestampOverride);
const Q = await prepareEmbeddedAttemptPromptExecution({
mediaOwnerAgentId: L,
effectiveFsWorkspaceOnly: P,
effectiveWorkspace: F,
sandbox: I,
attempt: n,
prompt: Y.promptSubmission.prompt,
skipPromptSubmission: q
});
s.signal.throwIfAborted();
r.assertHostActive?.();
if (n.operation !== "settled-tool-finalization") {
const t = await runBeforeAgentRunGate(f, {
prompt: ie,
images: Q.images,
systemPrompt: ae,
messages: re,
channelId: d.channelId,
accountId: n.agentAccountId,
senderId: n.senderId ?? void 0,
senderIsOwner: n.senderIsOwner
}, d);
if (t) {
const r = buildAgentRunBlockedUserMessage(n.runId, t);
if (!sessionMessagesContainIdempotencyKey(u.messages, r.idempotencyKey)) try {
await V(() => withSessionManagerAppend(S, async () => {
await S.appendMessageAsync(r);
S.flushPendingPersistence();
}));
u.agent.state.messages = sanitizeCompactionReplayMessages(S.buildSessionContext().messages);
} catch (e) {
log$2.warn(`before_agent_run block: failed to persist redacted user message: ${e instanceof Error ? e.message : String(e)}`);
}
e.state.beforeAgentRunBlockedBy = t.blockedBy;
setFailure(new Error(t.message), "hook:before_agent_run");
q = true;
}
}
if (!q) {
const { resolvedApiKey: e } = n;
const t = await prepareGooglePromptCacheStreamFn({
apiKey: await resolveEmbeddedAgentApiKey({
provider: n.provider,
resolvedApiKey: e,
authStorage: n.authStorage
}),
extraParams: j,
model: n.model,
modelId: n.modelId,
provider: n.provider,
sessionManager: {
appendCustomEntryAsync: async (e, t) => {
await withTranscriptWrite(async () => {
s.signal.throwIfAborted();
await S.appendCustomEntryAsync(e, t);
});
},
getEntries: () => S.getEntries()
},
signal: s.signal,
streamFn: u.agent.streamFn
});
if (t) u.agent.streamFn = t;
}
const $ = m.getCompactionReserveTokens();
const oe = projectAgentRunAttemptTerminal(e.state.terminal);
let se = {
contextBudgetStatus: t.contextBudgetStatus,
preflightRecovery: t.preflightRecovery,
promptError: oe.promptError,
promptErrorSource: oe.promptErrorSource,
skipPromptSubmission: observeEmbeddedAttemptPrompt({
...Y,
cacheTrace: y,
diagnosticTrace: H,
hookAgentId: L,
hookRunner: f,
isRawModelRun: i,
runTrace: U,
streamStrategy: M,
systemPromptText: K,
toolSearchCompacted: te,
trajectoryRecorder: E,
transport: A,
effectiveTools: l.current.effectiveTools,
tools: l.current.tools,
uncompactedEffectiveTools: l.current.uncompactedEffectiveTools,
attempt: n,
imageCount: Q.images.length,
reserveTokens: $,
sessionMessages: u.messages,
skipPromptSubmission: q,
transcriptLeafId: Z
}).skipPromptSubmission
};
publishDispatchState(se);
let ce;
if (!se.skipPromptSubmission) {
const e = n.userTurnTranscriptRecorder;
const t = n.skipPreparedUserTurnMessage !== true && e?.hasPersisted() === true ? (e.getPersistedMessage?.() ?? e.message)?.idempotencyKey : void 0;
const r = {
contextWindow: Y.contextTokenBudget,
reserveTokens: $
};
const i = Y.runtimeContextMessageForCurrentTurn ? [Y.runtimeContextMessageForCurrentTurn] : [];
ce = createCompactionRequestBudget({
...r,
systemPrompt: Y.systemPromptForHook,
tools: u.agent.state.tools,
pendingPrompt: Y.llmBoundaryPromptForPrecheck,
pendingImageCount: Q.images.length,
...D || Y.runtimeContextMessageForCurrentTurn && isOpenClawSystemUpdateMessage(Y.runtimeContextMessageForCurrentTurn) ? { pendingQueuedContextMessages: resolvePendingRuntimeContextReplay({
messages: u.messages,
pendingContextMessages: i,
persistedUserIdempotencyKey: t
}).pendingContextMessages } : { pendingContextMessages: i },
pendingAdditivePrompt: Y.isDispatchedCanonicalFallback ? void 0 : [b, B].filter(Boolean).join("\n\n"),
pendingUserIdempotencyKey: t
});
n.onCompactionRequestBudget?.(ce);
observeForegroundRequests((e, t) => {
n.onCompactionRequestBudget?.(createCompactionRequestBudget({
...r,
systemPrompt: t.systemPrompt,
tools: t.tools
}));
});
}
se = await prepareEmbeddedAttemptPromptPreflight({
appendOnlyRuntimeContext: D,
compactionReplayEnabled: N,
providerCompactionAtRequestBoundary: J,
contextEnginePromptAuthority: R,
includeBoundaryTimestamp: g,
...h ? { timezone: h } : {},
...z ? { unwindowedContextEngineMessagesForPrecheck: z } : {},
attempt: n,
contextTokenBudget: Y.contextTokenBudget,
hookMessagesForCurrentPrompt: Y.hookMessagesForCurrentPrompt,
promptForPrecheck: Y.llmBoundaryPromptForPrecheck,
pendingInputTokens: ce?.pendingTokens,
reserveTokens: $,
sessionMessageCount: u.messages.length,
state: se,
systemPrompt: Y.systemPromptForHook,
toolResultMaxChars: Y.promptToolResultMaxChars,
toolSchemaTokens: estimateToolSchemaTokenPressure(u.agent.state.tools)
});
e.setup.prepStages.mark("compaction-preflight");
publishDispatchState(se);
if (!se.skipPromptSubmission) await submitEmbeddedAttemptPrompt({
...B ? { appendContext: B } : {},
attempt: n,
registration: o.stream.registration,
activeSession: u,
contextTokenBudget: Y.contextTokenBudget,
compactionRequestBudget: ce,
...J ? { compactBeforeRequest: createChatGPTV2CompactionBoundary({
session: u,
config: n.config,
contextTokenBudget: Y.contextTokenBudget,
reserveTokens: $,
runId: n.runId,
isToolBoundarySafe: () => o.isToolBoundarySafe?.() ?? false,
timeoutMs: e.sessionLock.compactionTimeoutMs,
authProfileId: n.runtimePlan?.auth.forwardedAuthProfileId,
...n.sessionKey ? { hookContext: {
hookRunner: f,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
sessionAgentId: L,
workspaceDir: F,
messageProvider: n.messageProvider,
onHookMessages: async ({ phase: e, messages: t }) => {
const r = t.filter((e) => e.trim());
if (r.length) await n.onAgentEvent?.({
stream: "compaction",
data: {
phase: e === "before" ? "start" : "end",
...e === "after" ? { completed: true } : {},
messages: r
},
sessionKey: n.sessionKey
});
}
} } : {},
postCompaction: {
config: n.config,
sessionKey: n.sessionKey,
sessionId: n.sessionId,
agentId: L,
memoryAudience: n.memoryAudience,
sandboxed: I?.enabled === true,
sessionFile: n.sessionFile
},
assertActive: () => {
s.signal.throwIfAborted();
r.assertHostActive?.();
},
withTranscriptWrite,
onFallback: (e) => {
ne = e;
}
}) } : {},
onModelRequest: o.cache.onModelRequest,
normalizeToolCallIds: o.normalizeToolCallIds,
images: Q.images,
modelPrompt: Y.promptForModel,
onFinalPromptText: (e) => {
t.finalPromptText = e;
},
assertHostActive: r.assertHostActive,
withTranscriptWrite,
getUserTranscriptContexts: c.boundary.getUserTranscriptContexts,
persistToolResultProjections: async () => {
if (!i && (k || C.pendingToolSurface || T.frozen.size > 0)) await withTranscriptWrite(async () => {
s.signal.throwIfAborted();
await persistToolResultProjections(T, (e, t) => S.appendCustomEntryAsync(e, t));
const appendEntry = (e, t) => S.appendCustomEntryAsync(e, t);
await (c.prepareSystemPromptUpdate && k ? persistSessionSystemPrompt(C, appendEntry) : persistSessionToolSurface(C, appendEntry));
});
},
...b ? { prependContext: b } : {},
...Y.runtimeContextMessageForCurrentTurn ? { runtimeContextMessage: Y.runtimeContextMessageForCurrentTurn } : {},
runtimeOnly: Y.promptSubmission.runtimeOnly === true,
setNextUserMessagePersistence: S.setNextUserMessagePersistence,
systemPrompt: Y.systemPromptForHook,
toolResultAggregateMaxChars: Y.promptToolResultAggregateMaxChars,
toolResultMaxChars: Y.promptToolResultMaxChars,
transcriptLeafId: Z,
transcriptPrompt: Y.promptForSession,
appendOnlyRuntimeContext: D,
promptActiveSession: ee,
toolResultPromptProjectionState: T,
trajectoryRecorder: E
});
publishDispatchState(se);
} catch (r) {
const i = await handleEmbeddedAttemptPromptError({
activeSession: u,
attempt: n,
error: r,
handleMidTurnPrecheckRequest,
markYieldAborted: () => {
t.yieldAborted = true;
e.state.terminal = mergeAgentRunAttemptTerminal(e.state.terminal, {
kind: "aborted",
source: "yield_cleanup"
});
},
withOwnedTranscriptWrite: V,
...e.lifecycle.readYieldState()
});
if (i.promptFailure && !(projectAgentRunAttemptTerminal(e.state.terminal).timedOutByRunBudget && isOpenClawAbortableWrapper(i.promptFailure.error) && i.promptFailure.error instanceof Error && i.promptFailure.error.cause === s.signal.reason)) setFailure(i.promptFailure.error, i.promptFailure.source);
} finally {
u[agentSessionDeferThresholdCompaction] = Y;
B();
}
const re = ne ?? b.takePendingMidTurnPrecheckRequest();
if (re) await withTranscriptWrite(async () => {
await removeTrailingMidTurnPrecheckAssistantError({
activeSession: u,
sessionManager: S
});
const n = projectAgentRunAttemptTerminal(e.state.terminal);
if (!t.preflightRecovery && n.promptErrorSource !== "precheck") {
setFailure(null, null);
await handleMidTurnPrecheckRequest(re);
}
});
return {
promptStartedAt: X,
transcriptLeafId: Z
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/access-program.ts
function isSameDiscoveredAccount(e, t, n) {
if (isDeepStrictEqual(e, t)) return true;
if (e?.type !== "oauth" || t.type !== "oauth") return false;
return e.provider === t.provider && e.enterpriseUrl === t.enterpriseUrl && e.issuer === t.issuer && e.clientId === t.clientId && e.authFlow === t.authFlow && n?.auth.some((n) => n.matchesPersonalAccount?.(t, e)) === true;
}
/** Effective Access, including configured defaults, requires current role and account authority. */
async function prepareEmbeddedAccessProgramGuard(e, t) {
const n = e.cyberAccessProgram ?? asOptionalRecord(t?.accessPrograms)?.cyber;
if (n !== void 0 && n !== "standard" && n !== "daybreak_blue" && n !== "daybreak_red") throw new Error("Invalid OpenAI cyber access program.");
const assertRole = () => assertOperatorAccessProgramAllowed(readRunOperatorAuthority(e), n);
assertRole();
if (n === void 0 || n === "standard") return assertRole;
const r = e.preparedModelRuntime;
const i = e.authProfileId;
const a = i ? e.authProfileStore?.profiles[i] : void 0;
const o = resolveSelectedModelCredential({
provider: e.provider,
profileId: i,
mode: a?.type ?? e.runtimePlan?.auth.selectedAuthMode
});
const s = r?.accountCatalog && i && a ? await r.accountCatalog.acquire({
profileId: i,
credential: a,
allowDiscovery: false,
load: async () => []
}) : void 0;
const check = () => {
assertRole();
const t = r?.readFullModelCatalog?.() ?? r?.modelCatalog;
const c = o?.source === "direct" ? t?.providerOutcomes ?? [] : s?.hasPublishedCatalog ? s.outcomes : t && i && a && isSameDiscoveredAccount(getPreparedModelFullCatalogAuth(t)?.authStore.profiles[i], a, r?.pluginRegistry?.providers.find(({ provider: t }) => t.id === e.provider)?.provider) ? t.providerOutcomes : [];
if (!(t && resolveModelCatalogAccessPrograms({
snapshot: {
...t,
providerOutcomes: c
},
entry: {
provider: e.provider,
id: e.modelId
},
evaluation: {
availability: true,
routeResolution: null,
selectedCredential: o,
selectedRoute: e.runtimePlan?.auth.modelRoute
},
runtimeId: "openclaw",
isCurrent: () => r?.isCurrent() === true && s?.isCurrent() !== false
}))?.includes(n)) throw new FailoverError("This Daybreak program is not advertised for the current account, model, and runtime. Select Standard or refresh account capabilities.", {
reason: "format",
provider: e.provider,
model: e.modelId,
code: "OPENAI_ACCESS_PROGRAM_UNAVAILABLE"
});
};
check();
return check;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-async-tasks.ts
const COMPLETION_REQUIRED_TASK_KINDS = /* @__PURE__ */ new Set([
"image_generation",
"music_generation",
"video_generation"
]);
function createAbortError(e) {
return createAbortError$1("aborted", { cause: e.reason });
}
function throwIfAborted(e) {
if (e?.aborted) throw createAbortError(e);
}
function isPendingCompletionTask(e) {
return COMPLETION_REQUIRED_TASK_KINDS.has(e.taskKind) && e.completionDelivery !== "queued" && !isTerminalMediaGenerationStatus(e.status);
}
function* iterateAsyncTaskRunIds(e, t) {
for (const t of e) {
const e = t.asyncStarted === true ? t.asyncTaskRunId?.trim() : void 0;
if (e && findMediaGenerationOperation(e)?.completionDelivery !== "queued") yield e;
}
const n = t?.trim();
if (!n) return;
for (const e of listMediaGenerationOperations(n)) if (isPendingCompletionTask(e)) {
const t = e.runId?.trim();
if (t) yield t;
}
}
function requiresCompletionRequiredAsyncTaskWait(e) {
throwIfAborted(e.abortSignal);
const t = e.sessionKey?.trim();
if (!t || !isCronRunSessionKey(t)) return false;
return iterateAsyncTaskRunIds(e.toolMetas, t).next().done === false;
}
function shouldWaitForCompletionRequiredAsyncTasks(e) {
if (e.yieldDetected === true) return false;
return requiresCompletionRequiredAsyncTaskWait(e);
}
async function waitForCompletionRequiredAsyncTasks(e) {
const t = /* @__PURE__ */ new Set();
const n = /* @__PURE__ */ new Set();
let r = createDeferredCore();
const wake = () => r.resolve();
const i = e.sessionKey?.trim();
const a = onMediaGenerationOperationChanged((e) => {
if (e.requesterSessionKey === i || e.runId && t.has(e.runId)) wake();
});
const o = e.onDeadlineChanged(wake);
e.abortSignal?.addEventListener("abort", wake, { once: true });
let s;
try {
waitForTasks: while (true) {
throwIfAborted(e.abortSignal);
const i = [...new Set(iterateAsyncTaskRunIds(e.getToolMetas(), e.sessionKey))].filter((e) => !t.has(e));
if (i.length === 0) break;
for (const e of i) t.add(e);
let a = i;
while (a.length > 0) {
throwIfAborted(e.abortSignal);
a = a.filter((e) => {
const t = findMediaGenerationOperation(e);
if (t?.completionDelivery === "queued") return false;
return !t || !isTerminalMediaGenerationStatus(t.status);
});
if (a.length === 0) break;
const t = e.getDeadlineAtMs();
const i = t === void 0 ? void 0 : t - Date.now();
if (i !== void 0 && i <= 0) {
for (const e of a) n.add(e);
break waitForTasks;
}
if (i !== void 0) s = setTimeout(wake, i);
await r.promise;
clearTimeout(s);
s = void 0;
r = createDeferredCore();
}
}
return { timedOutRunIds: [...n] };
} finally {
clearTimeout(s);
e.abortSignal?.removeEventListener("abort", wake);
o();
a();
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/compaction-retry-aggregate-timeout.ts
function hasActiveCompactionRetryWork(e) {
return e.isCompactionInFlight || e.isSessionStreaming;
}
/**
* Waits for compaction retry completion with an aggregate timeout so a lost
* retry resolution cannot hold the session lane indefinitely.
*/
async function waitForCompactionRetryWithAggregateTimeout(e) {
const t = resolveTimerTimeoutMs(e.aggregateTimeoutMs, 1);
const n = e.waitForCompactionRetry();
while (true) {
let r;
try {
if (await e.abortable(Promise.race([n, new Promise((e) => {
r = setTimeout(() => e("timeout"), t);
})])) !== "timeout") return { timedOut: false };
if (e.isCompactionRetryStillActive?.()) continue;
return { timedOut: true };
} finally {
if (r !== void 0) clearTimeout(r);
}
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/provider-review-continuation.ts
function countUserInputSlots(e) {
return e.reduce((e, t) => e + (isRecord(t) && t.role === "user" ? 1 : 0), 0);
}
/** Acknowledgment decorates one request; later tool calls retain ordinary transport behavior. */
function wrapStreamFnWithProviderReviewContinuation(e) {
const t = e.acknowledgment;
if (!t) return e.streamFn;
if (readProviderReviewAcknowledgment(t).phase === "accepted") throw new Error("Provider review continuation cannot start another transport attempt");
let n = false;
let r = false;
return async (i, a, o) => {
const s = /* @__PURE__ */ new Set();
const assertCurrent = () => {
o?.signal?.throwIfAborted();
for (const e of s) e.throwIfAborted();
e.assertCurrent();
readProviderReviewAcknowledgment(t);
};
assertCurrent();
const c = readProviderReviewAcknowledgment(t);
const assertWorkStart = () => assertSessionProviderReviewWorkStart({
target: c.target,
acknowledgment: t,
runId: e.runId,
provider: i.provider,
model: i.id,
runtimeId: "openclaw",
api: i.api,
assertCurrent
});
await assertWorkStart();
assertCurrent();
if (c.phase === "accepted") {
if (!r) throw new Error("Provider review continuation belongs to another transport attempt");
return e.streamFn(i, a, o);
}
if (n || i.provider !== "openai" || i.api !== "openai-chatgpt-responses") throw new Error("Provider review continuation cannot be retried or change transport");
const l = c.review.review?.continuation?.message;
const u = a.messages.findLastIndex((e) => !hasRuntimeContextMarker(e));
const d = a.messages[u];
if (!l || d?.role !== "user") throw new Error("Provider review continuation requires its exact next user input");
const f = {
...d,
content: l
};
const p = bindResponsesInputMessage(f);
n = true;
let m = false;
let h = false;
let g;
let _;
const v = {
...o,
onPayload: async (e, t) => {
if (m) throw new Error("Provider review continuation cannot rebuild or retry its request");
if (!isRecord(e) || !Array.isArray(e.input)) throw new Error("Provider continuation payload has no user input");
const n = e.input.findIndex(p);
if (n < 0) throw new Error("Provider continuation payload changed its next user input");
const r = structuredClone(e.input.slice(n + 1));
const i = countUserInputSlots(e.input);
const a = await o?.onPayload?.(e, t);
await assertWorkStart();
assertCurrent();
const s = a === void 0 ? e : a;
if (!isRecord(s) || !Array.isArray(s.input)) throw new Error("Provider continuation payload has no user input");
if (t.provider !== c.review.provider || t.id !== c.review.model || t.api !== c.review.api || s.model !== c.review.model) throw new Error("Provider continuation payload changed the reviewed runtime or model");
const u = s.input.filter(p);
const d = u[0];
const f = s.input.indexOf(d);
const h = s.input.slice(f + 1);
if (u.length !== 1 || !isRecord(d) || d.role !== "user" || !isDeepStrictEqual(h, r)) {
if (countUserInputSlots(s.input) > i && h.length > r.length) throw new Error("Provider continuation payload added user input");
throw new Error("Provider continuation payload changed its next user input");
}
if (countUserInputSlots(s.input) > i) throw new Error("Provider continuation payload added user input");
const g = s.client_metadata;
if (g !== void 0 && !isRecord(g)) throw new Error("Provider continuation metadata is malformed");
const _ = g ?? {};
const v = _["x-codex-turn-metadata"];
let y = {};
if (v !== void 0) {
const e = typeof v === "string" ? safeParseJsonRecord(v) : void 0;
if (!e) throw new Error("Provider continuation turn metadata is malformed");
y = e;
}
m = true;
return {
...s,
input: s.input.with(f, {
...d,
content: [{
type: "input_text",
text: l
}]
}),
client_metadata: {
..._,
"x-codex-turn-metadata": JSON.stringify({
...y,
misalignment_override: JSON.stringify({ timestamp: Date.now() })
})
}
};
}
};
responsesRequestLifecycle.set(v, {
assertCurrent,
beforeDispatch: async (e) => {
if (h || !m) throw new Error("Provider review continuation already dispatched or was not prepared");
if (e) s.add(e);
await assertWorkStart();
assertCurrent();
if (h) throw new Error("Provider review continuation already dispatched");
h = true;
},
accepted: (n, i) => {
if (i) s.add(i);
assertCurrent();
if (!h || g && g !== n) throw new Error("Provider continuation response does not match its request");
if (!_) {
g = n;
_ = acceptProviderReviewAcknowledgment(t, {
runId: e.runId,
assertCurrent
}).then(() => {
assertCurrent();
r = true;
});
}
return _;
},
settle: async () => {
await _;
}
});
return e.streamFn(i, {
...a,
messages: a.messages.with(u, f)
}, v);
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-stream-settle.ts
async function settleEmbeddedAttemptStream(e) {
const { attempt: t, activeSession: n, sessionManager: r, subscription: i, state: a } = e;
try {
if (shouldWaitForCompletionRequiredAsyncTasks({
sessionKey: t.sessionKey,
toolMetas: i.toolMetas,
yieldDetected: a.yieldAborted,
abortSignal: e.runAbortSignal
})) {
const n = await waitForCompletionRequiredAsyncTasks({
getToolMetas: () => i.toolMetas.filter((e) => typeof e.toolName === "string" && e.toolName.trim().length > 0),
sessionKey: t.sessionKey,
getDeadlineAtMs: () => {
const t = e.getRunAbortDeadlineAtMs();
return t === void 0 ? void 0 : Math.max(Date.now(), t - 500);
},
onDeadlineChanged: e.onRunAbortDeadlineChanged,
abortSignal: e.runAbortSignal
});
if (n.timedOutRunIds.length > 0 && !e.readLifecycleState().aborted) {
a.promptError = /* @__PURE__ */ new Error(`Timed out waiting for async task completion: ${n.timedOutRunIds.join(", ")}`);
a.promptErrorSource = "prompt";
}
}
} catch (t) {
const n = e.readLifecycleState();
if (!n.timedOut && !n.aborted || !isRunnerAbortError(t)) throw t;
}
const o = n.isCompacting;
const s = n.messages.slice();
const c = o ? null : s;
const l = n.sessionId;
const u = 6e4;
try {
if (e.onBlockReplyFlush) {
const n = findCurrentAttemptAssistantMessage({
messagesSnapshot: s,
prePromptMessageCount: e.prePromptMessageCount
});
const r = !a.promptError && !e.readLifecycleState().aborted && !e.readLifecycleState().timedOut && !a.yieldAborted && n?.stopReason === "stop";
await joinWithRunLivenessDeadline({
joinWork: () => e.onBlockReplyFlush?.({
reason: "pre_compaction",
attemptAccepted: r
}),
runAbortSignal: e.runAbortSignal,
onTimeout: () => {
log$2.warn(`block-reply flush did not settle within ${RUN_LIVENESS_JOIN_TIMEOUT_MS}ms; proceeding with settlement: runId=${t.runId}`);
}
});
}
if ((a.yieldAborted ? { timedOut: false } : await waitForCompactionRetryWithAggregateTimeout({
waitForCompactionRetry: i.waitForCompactionRetry,
abortable: e.abortable,
aggregateTimeoutMs: u,
isCompactionRetryStillActive: () => hasActiveCompactionRetryWork({
isCompactionInFlight: i.isCompactionInFlight(),
isSessionStreaming: n.isStreaming
})
})).timedOut) {
e.markTimedOutDuringCompaction();
if (!e.isProbeSession) log$2.warn(`compaction retry aggregate timeout (${u}ms): proceeding with pre-compaction state runId=${t.runId} sessionId=${t.sessionId}`);
}
} catch (n) {
if (!isRunnerAbortError(n)) throw n;
if (!a.promptError) {
a.promptError = n;
a.promptErrorSource = "compaction";
}
if (!e.isProbeSession) log$2.debug(`compaction wait aborted: runId=${t.runId} sessionId=${t.sessionId}`);
}
const captureStreamSnapshot = () => {
const { timedOutDuringCompaction: a } = e.readLifecycleState();
const o = i.getCompactionCount() > 0;
const s = selectCompactionTimeoutSnapshot({
timedOutDuringCompaction: a,
preCompactionSnapshot: c,
preCompactionSessionId: l,
currentSnapshot: n.messages.slice(),
currentSessionId: n.sessionId
});
if (a && !e.isProbeSession) log$2.warn(`using ${s.source} snapshot: timed out during compaction runId=${t.runId} sessionId=${t.sessionId}`);
const u = s.messagesSnapshot;
const d = u.findLast((e) => e.role === "assistant");
const f = findCurrentAttemptAssistantMessage({
messagesSnapshot: u,
prePromptMessageCount: e.prePromptMessageCount
});
const p = i.getCurrentAttemptAssistant();
const m = i.getUsageTotals();
const h = findLatestUncompactedAttemptUsageSnapshot({
messagesSnapshot: u,
prePromptMessageCount: e.prePromptMessageCount,
compactionOccurred: o
});
const g = normalizeUsage(p?.usage);
const _ = i.getLastAssistantUsage() ?? (hasNonzeroUsage(g) ? g : h?.usage);
const v = hasNonzeroUsage(g) ? p : h?.assistant;
const y = readLastCacheTtlTimestamp(r, {
provider: t.provider,
modelId: t.modelId
});
const b = buildContextEnginePromptCacheInfo({
retention: e.cache.retention,
lastCallUsage: _,
observation: e.cache.getObservation?.(),
lastCacheTouchAt: resolvePromptCacheTouchTimestamp({
lastCallUsage: _,
assistantTimestamp: v?.timestamp,
fallbackLastCacheTouchAt: y
})
});
return {
compactionOccurredThisAttempt: o,
messagesSnapshot: u,
sessionIdUsed: s.sessionIdUsed,
lastAssistant: d,
currentAttemptAssistant: f,
currentAttemptCompletedAssistant: p,
attemptUsage: m,
lastCallUsage: _,
promptCache: b
};
};
let d;
try {
d = await e.withOwnedTranscriptWrite(() => withSessionManagerAppend(r, async () => {
const { timedOutDuringCompaction: o } = e.readLifecycleState();
const s = i.getCompactionCount() > 0;
const c = t.model.compat;
if (!t.inputAlreadyDelivered) await appendAttemptCacheTtlIfNeeded({
sessionManager: r,
timedOutDuringCompaction: o,
compactionOccurredThisAttempt: s,
config: t.config,
provider: t.provider,
modelId: t.modelId,
modelApi: t.model.api,
modelRoute: {
baseUrl: t.model.baseUrl,
supportsPromptCacheKey: c?.supportsPromptCacheKey
},
isCacheTtlEligibleProvider,
toolResultPromptProjectionState: e.toolResultPromptProjectionState
});
if (o) {
const i = await normalizeCompactionRecoveryTranscriptTail({
activeSession: n,
sessionManager: r
});
if (i > 0 && !e.isProbeSession) log$2.warn(`normalized compaction timeout transcript tail: removedEntries=${i} runId=${t.runId} sessionId=${t.sessionId}`);
}
const l = captureStreamSnapshot();
if (a.promptError && a.promptErrorSource === "prompt" && !l.compactionOccurredThisAttempt && !t.abortSignal?.aborted) try {
await r.appendCustomEntryAsync("openclaw:prompt-error", {
timestamp: Date.now(),
runId: t.runId,
sessionId: t.sessionId,
provider: t.provider,
model: t.modelId,
api: t.model.api,
error: formatErrorMessage(a.promptError)
});
} catch (n) {
t.abortSignal?.throwIfAborted();
e.runAbortSignal.throwIfAborted();
log$2.warn(`failed to persist prompt error entry: ${String(n)}`);
}
if (e.shouldFlushForContextEngine) r.flushPendingPersistence();
return l;
}));
} catch (n) {
const r = t.abortSignal?.aborted && n === t.abortSignal.reason;
const i = e.runAbortSignal.aborted && n === e.runAbortSignal.reason;
if (!r && !i) throw n;
d = captureStreamSnapshot();
}
return {
promptError: a.promptError,
promptErrorSource: a.promptErrorSource,
timedOutDuringCompaction: e.readLifecycleState().timedOutDuringCompaction,
...d,
successfulNestedToolNames: [...e.nestedToolActivityState.successfulToolNames]
};
}
async function prepareEmbeddedAttemptTransport(e) {
const t = e.attempt;
const n = e.session;
const r = resolveAdmittedRunActiveAssertion(t.admittedRunContext, e.abortSignal);
const i = t.preparedModelRuntime;
const a = t.authProfileId;
const o = a ? t.authProfileStore?.profiles[a] : void 0;
const s = i && resolveSelectedModelCredential({
provider: t.model.provider,
profileId: a,
mode: o?.type ?? t.runtimePlan?.auth.selectedAuthMode
});
const c = i?.accountCatalog && s && s.source !== "harness" && s.requirement === "api-key" && t.model.provider === "openai" && t.model.api === "openai-responses" ? i.accountCatalog.prepareServiceTierObserver({
selectedCredential: s,
credential: o
}) : void 0;
const l = resolveEmbeddedAgentBaseStreamFn({ session: n });
const u = resolveExplicitSettingsTransport({
settingsManager: e.settingsManager,
sessionTransport: n.agent.transport
});
if (t.cyberAccessProgram !== void 0 && t.cyberAccessProgram !== "standard" && t.provider !== "openai") throw new Error("Daybreak access is unsupported by this provider. Select Standard or an OpenAI model.");
const d = {
...t.streamParams,
fastMode: t.fastMode,
...t.provider === "openai" && t.cyberAccessProgram !== void 0 ? { accessPrograms: { cyber: t.cyberAccessProgram } } : {},
...t.trigger === "memory" ? {
anthropicServerCompaction: false,
responsesServerCompaction: false
} : {}
};
const f = t.runtimePlan?.auth;
const p = f?.selectedAuthMode ? {
mode: f.selectedAuthMode,
authFlow: f.selectedAuthFlow
} : void 0;
const m = {
extraParamsOverride: d,
thinkingLevel: e.providerThinkingLevel,
agentId: e.sessionAgentId,
workspaceDir: e.workspaceDir,
model: t.model,
resolvedTransport: u
};
const h = t.runtimePlan?.transport.resolveExtraParams(m) ?? resolvePreparedExtraParams({
...m,
cfg: t.config,
transportConfig: t.transportConfig,
provider: t.provider,
modelId: t.modelId,
providerRuntimeHandle: e.getProviderRuntimeHandle(),
agentDir: e.agentDir,
auth: p
});
const g = e.contextEngineInfo?.ownsCompaction === true;
const _ = t.model.api === "openai-responses" && (t.trigger === "memory" || g && h.responsesServerCompaction !== true);
const v = _ ? {
...h,
responsesServerCompaction: false,
responsesCompactEndpoint: false
} : h;
const y = await prepareEmbeddedAccessProgramGuard(t, v);
const assertRunCurrent = () => {
r?.();
e.assertCronRootCurrent?.();
y?.();
};
const b = registerProviderStreamForModel({
model: t.model,
cfg: t.transportConfig ?? t.config,
agentDir: e.agentDir,
workspaceDir: e.workspaceDir,
auth: p
});
const x = await resolveEmbeddedAgentApiKey({
provider: t.model.provider,
resolvedApiKey: t.resolvedApiKey,
authStorage: t.authStorage
});
const { streamFn: S, strategy: C, wrapApiKey: w } = selectEmbeddedAgentStream({
currentStreamFn: l,
providerStreamFn: b,
sessionId: t.sessionId,
promptCacheKey: t.promptCacheKey,
signal: e.abortSignal,
model: t.model,
resolvedApiKey: t.resolvedApiKey,
transportAuthAvailable: Boolean(x?.trim()),
authProfileId: t.runtimePlan?.auth.forwardedAuthProfileId,
authStorage: t.authStorage,
assertCurrent: assertRunCurrent
});
const T = wrapStreamFnWithMessageTransform(S, (e) => e, async ({ context: n, ...r }) => {
assertRunCurrent?.();
const i = await materializeProviderContext({
...r,
context: n,
imageSessionKey: promptImageSessionKey(t),
workspaceDir: e.workspaceDir,
agentWorkspaceDir: t.workspaceDir,
workspaceOnly: e.workspaceOnly,
localRoots: e.workspaceOnly ? void 0 : getAgentScopedMediaLocalRoots(t.config ?? {}, e.sessionAgentId),
onCurrentTurnImageFailure: e.onCurrentTurnImageFailure,
sandbox: e.sandbox?.enabled && e.sandbox.fsBridge ? {
root: e.sandbox.workspaceDir,
bridge: e.sandbox.fsBridge
} : void 0
});
assertRunCurrent?.();
return i;
});
const E = configuredModelSupportsNativeVideo({
cfg: t.config,
provider: t.model.provider,
modelId: t.model.id,
api: t.model.api
}) ? [...t.model.input, "video"] : void 0;
n.agent.streamFn = (e, n, r) => {
const i = {
...r,
openclawThinkingExplicit: t.thinkingExplicit,
...E ? { [PROVIDER_MODEL_INPUT]: E } : {}
};
return withGuardedFetchBeforeRequest(y, () => T(e, n, i));
};
n.agent.streamFn = wrapStreamFnWithProviderPromptState({
streamFn: n.agent.streamFn,
...e.providerPromptState
});
n.agent.streamFn = wrapStreamFnWithProviderReviewContinuation({
streamFn: n.agent.streamFn,
acknowledgment: t.providerReviewAcknowledgment,
runId: t.runId,
assertCurrent: () => {
e.abortSignal.throwIfAborted();
assertRunCurrent?.();
}
});
const D = resolveProviderTextTransforms({
provider: t.provider,
config: t.config,
workspaceDir: e.workspaceDir,
runtimeHandle: e.getProviderRuntimeHandle()
});
if (D?.input?.length) n.agent.streamFn = wrapStreamFnTextTransforms({
streamFn: n.agent.streamFn,
input: D.input,
transformSystemPrompt: false
});
const O = {
webSearchEnabled: t.disableTools !== true && t.toolOverrides?.webSearch !== false && (!t.toolExecutionAllow || isToolExecutionAllowed(t.toolExecutionAllow, "web_search")),
runtimeToolAllowlist: t.toolsAllow,
sessionKey: e.sandboxSessionKey,
sandboxToolPolicy: e.sandbox?.tools,
messageProvider: t.messageProvider ?? t.messageChannel,
agentAccountId: t.agentAccountId,
groupId: t.groupId,
groupChannel: t.groupChannel,
groupSpace: t.groupSpace,
spawnedBy: t.spawnedBy,
senderId: t.senderId,
senderName: t.senderName,
senderUsername: t.senderUsername,
senderE164: t.senderE164
};
const { nativeWebSearchAllowedByToolPolicy: k } = await withPreparedSessionCapabilityRead(() => applyExtraParamsToAgent(n.agent, t.config, t.provider, t.modelId, d, e.providerThinkingLevel, e.sessionAgentId, e.workspaceDir, t.model, e.agentDir, u, {
preparedExtraParams: v,
transportConfig: t.transportConfig,
modelCallUrgency: resolveModelCallUrgency(t),
auth: p,
nativeWebSearchPolicyContext: O
}));
if (e.codeModeControlsEnabled) n.agent.streamFn = createCodexNativeWebSearchWrapper(n.agent.streamFn, {
config: t.config,
agentDir: e.agentDir,
agentId: e.sessionAgentId,
...O,
nativeWebSearchAllowedByToolPolicy: k,
codeModeToolSurfaceEnabled: true
});
const A = resolveCacheRetention(v, t.provider, t.model.api, t.modelId);
const j = resolveAgentTransportOverride({
settingsManager: e.settingsManager,
effectiveExtraParams: v
}) ?? n.agent.transport;
n.agent.transport = j;
const M = t.config?.agents?.defaults?.contextPruning;
const N = M?.mode === "cache-ttl" && isAnthropicServerToolClearingEnabled(t.model, x);
if (N) {
const e = n.agent.streamFn;
n.agent.streamFn = (t, n, r) => {
const i = {
...r,
cacheTtlPruning: { tools: M?.tools }
};
return e(t, n, i);
};
}
n.agent.streamFn = w(n.agent.streamFn);
if (_) n.agent.streamFn = wrapStreamFnWithMessageTransform(n.agent.streamFn, (e) => e.some((e) => e.role === "assistant" && isCompactionReplayCheckpoint(e.providerReplay)) ? e.map((e) => e.role === "assistant" ? stripCompactionReplayCheckpoint(e) : e) : e);
if (c && s && s.source !== "harness") n.agent.streamFn = createOpenAIServiceTierObservationWrapper(n.agent.streamFn, (t, n) => !e.abortSignal.aborted && c({
modelId: t.id,
runtimeId: "openclaw",
api: t.api,
baseUrl: t.baseUrl,
...n
}), {
runId: t.runId,
sessionId: t.sessionId,
accountRoute: s.identityKey
});
return {
serverToolClearingEnabled: N,
compactionReplayEnabled: !_ && resolveCompactionReplayEligibility(t.model, {
extraParams: v,
apiKey: x
}),
effectiveAgentTransport: j,
effectiveExtraParams: v,
effectivePromptCacheRetention: A,
providerTextTransforms: D,
streamStrategy: C
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-settle.ts
const FAILED_PROMPT_MEDIA_NOTE_TYPE = "openclaw.system-note";
const FAILED_PROMPT_MEDIA_NOTE_SOURCE = "prompt-image-hydration";
async function runEmbeddedAttemptSettledPhase(e) {
const { attempt: t, state: n } = e;
const { sessionRuntime: r, toolBase: i } = e.prepared;
const { agentSession: { activeSession: a }, sessionManager: o, state: s, toolResultPromptProjectionState: c, transport: { effectivePromptCacheRetention: l } } = r;
const { nestedToolActivityState: u } = i;
const d = {
contextBudgetStatus: void 0,
preflightRecovery: void 0,
yieldAborted: false
};
const f = e.preparedStreamRuntime;
const { abortable: p, isProbeSession: m, onBlockReplyFlush: h, stream: g, timeout: _ } = f;
const { subscription: v, queueHandle: y, getBeforeAgentFinalizeRevisionReason: b, getBeforeAgentFinalizeRevisionEntryId: x } = g;
const { unsubscribe: S, waitForPendingEvents: C } = v;
const { getRunAbortDeadlineAtMs: w, onRunAbortDeadlineChanged: T, clearTimers: E } = _;
let D;
let O = [];
let k = a.sessionId;
const A = t.sessionFile;
let j;
const readTerminal = () => projectAgentRunAttemptTerminal(n.terminal);
const setFailure = (e, t) => {
n.terminal = setAgentRunAttemptTerminalFailure(n.terminal, e !== null && e !== void 0 ? {
error: e,
source: t ?? "prompt"
} : null);
};
const markTimedOutDuringCompaction = () => {
n.terminal = mergeAgentRunAttemptTerminal(n.terminal, {
kind: "timeout",
phase: "compaction",
source: "observation"
});
};
try {
const { promptStartedAt: n, transcriptLeafId: r } = await runEmbeddedAttemptPromptPhase(e, d);
const isFailureFreeRunBudgetTimeout = () => {
const e = readTerminal();
return e.timedOutByRunBudget && !e.failed;
};
const i = isFailureFreeRunBudgetTimeout();
const drainPendingEventsBounded = (n) => joinWithRunLivenessDeadline({
joinWork: n ? () => C({ includePartialReplies: false }) : C,
...n ? {} : { runAbortSignal: e.runAbortController.signal },
onTimeout: () => {
log$2.warn(`pending subscription events did not settle within ${RUN_LIVENESS_JOIN_TIMEOUT_MS}ms; proceeding to stream settlement: runId=${t.runId}`);
}
});
if (!i) await drainPendingEventsBounded(false);
if (i || isFailureFreeRunBudgetTimeout()) await drainPendingEventsBounded(true);
if (isFailureFreeRunBudgetTimeout()) v.flushPartialAssistantText();
const g = b();
const _ = x();
let y = false;
if (g && _) await e.sessionLock.withOwnedTranscriptWrite(() => withSessionManagerAppend(o, async () => {
const e = o.getEntry(_);
if (e?.type !== "message" || e.message.role !== "assistant") throw new Error(`before_agent_finalize persisted assistant entry is missing or invalid (entry=${_})`);
await o.appendLeafControlAsync({
targetId: e.parentId,
appendParentId: e.parentId
});
y = true;
}));
try {
if (e.getRepairedRejectedProviderReplay() && !y) a.agent.state.messages = sanitizeCompactionReplayMessages(o.buildSessionContext().messages);
const n = readTerminal();
const r = {
promptError: n.promptError,
promptErrorSource: n.promptErrorSource,
yieldAborted: d.yieldAborted
};
try {
D = await settleEmbeddedAttemptStream({
attempt: t,
activeSession: a,
sessionManager: o,
toolResultPromptProjectionState: c,
withOwnedTranscriptWrite: e.sessionLock.withOwnedTranscriptWrite,
state: r,
getRunAbortDeadlineAtMs: w,
onRunAbortDeadlineChanged: T,
shouldFlushForContextEngine: Boolean(e.activeContextEngine && !b()),
subscription: v,
readLifecycleState: readTerminal,
markTimedOutDuringCompaction,
runAbortSignal: e.runAbortController.signal,
isProbeSession: m,
onBlockReplyFlush: h,
abortable: p,
prePromptMessageCount: s.prePromptMessageCount,
nestedToolActivityState: u,
cache: {
getObservation: f.cache.getObservation,
retention: l
}
});
} catch (e) {
setFailure(r.promptError, r.promptErrorSource);
throw e;
}
} finally {
if (y) await e.sessionLock.withOwnedTranscriptWrite(() => {
a.agent.state.messages = sanitizeCompactionReplayMessages(o.buildSessionContext().messages);
});
}
setFailure(D.promptError, D.promptErrorSource);
if (D.timedOutDuringCompaction) markTimedOutDuringCompaction();
O = D.messagesSnapshot;
k = D.sessionIdUsed;
s.promptCache = D.promptCache;
await completeEmbeddedAttemptAfterTurn(e, D, {
yieldAborted: d.yieldAborted,
transcriptLeafId: r,
promptStartedAt: n,
...g ? { beforeAgentFinalizeRevisionReason: g } : {}
});
const S = s.currentTurnImageFailureCount > 0 ? `${FAILED_PROMPT_MEDIA_NOTE_SOURCE}:${sha256Hex(t.runId)}` : void 0;
if (S && !a.messages.some((e) => readMessageIdempotencyKey(e) === S || e.role === "custom" && e.customType === FAILED_PROMPT_MEDIA_NOTE_TYPE && asOptionalRecord(e.details)?.source === FAILED_PROMPT_MEDIA_NOTE_SOURCE && asOptionalRecord(e.details)?.runId === t.runId)) {
const n = {
role: "custom",
customType: FAILED_PROMPT_MEDIA_NOTE_TYPE,
content: buildPromptImageFailureNotice(s.currentTurnImageFailureCount),
display: true,
idempotencyKey: S,
details: {
source: FAILED_PROMPT_MEDIA_NOTE_SOURCE,
runId: t.runId,
failedMediaCount: s.currentTurnImageFailureCount
},
timestamp: Date.now()
};
const r = o.getSessionTarget();
const i = o.getSessionId();
const assertBinding = () => {
if (o.getSessionId() !== i || !sameSessionTranscriptTargetBinding(r, o.getSessionTarget())) throw new SessionTranscriptWriterClaimReboundError();
};
let c;
try {
await e.sessionLock.withOwnedTranscriptWrite(async () => {
assertBinding();
if (r) {
const appendAndPublish = async () => {
assertBinding();
const e = await withSessionTranscriptWriteAssertion(r, assertBinding, () => appendSessionTranscriptNote(r, n, t.config ? { config: t.config } : void 0));
c = e.messageId;
assertBinding();
assertOwnedTranscriptWriteCommit(r);
if (e.appended || e.currentTail) {
a.agent.state.messages = [...a.messages, e.message];
O = [...O, e.message];
}
};
if (isIncognitoSessionKey(r.sessionKey)) await withSessionManagerAppend(o, appendAndPublish);
else await appendAndPublish();
} else await withSessionManagerAppend(o, async () => {
assertBinding();
await o.appendMessageAsync(n);
assertBinding();
a.agent.state.messages = [...a.messages, n];
O = [...O, n];
});
});
} catch (e) {
if (c && r) throw new SessionTranscriptMessageCommittedError(c, e, r);
throw e;
}
}
} finally {
const e = f.stream.registration;
const n = f.stream.deferredLifecycleOwner;
E();
const r = [["unsubscribe", S], ["backend detach", () => t.replyOperation?.detachBackend(y)]];
if (!n) r.push(["active run cleanup", () => detachActiveEmbeddedRun(t.sessionId, y, t.sessionKey, t.sessionFile, void 0, e)]);
for (const [e, n] of r) try {
n();
} catch (n) {
j ??= n instanceof Error ? n : new Error(String(n));
log$2.error(`CRITICAL: ${e} failed, possible resource leak: runId=${t.runId} ${String(n)}`);
}
}
if (j !== void 0) throw j;
const M = b();
const N = completeEmbeddedAttemptResult(e, D, {
...d,
sessionIdUsed: k,
sessionFileUsed: A,
messagesSnapshot: O,
...M ? { beforeAgentFinalizeRevisionReason: M } : {}
});
n.trajectoryEndRecorded = true;
return N;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-queue-message.ts
var EmbeddedSteeringAcceptedUnconfirmedError = class extends Error {
constructor(e, t) {
super(e, t);
this.name = "EmbeddedSteeringAcceptedUnconfirmedError";
}
};
function hasAcceptedSteeringCustody(e) {
return collectErrorGraphCandidates(e, readErrorCauses).some((e) => e instanceof MessageInjectionAcceptedUnconfirmedError);
}
function notifyQueueObserver(e) {
runBestEffortCallback({
callback: () => e?.(),
label: "queued steering",
log: log$2
});
}
/**
* Removes one pending steered user message from both the runtime queue and its
* exact identity-owned display entry.
*/
async function cancelQueuedSteeringMessage(e, t) {
const n = e.agent?.cancelSteeringMessage;
if (!n) return false;
const r = n.call(e.agent, (e) => getSteeringMessageIdentity(e) === t);
if (!r) return false;
try {
if (!retireQueuedUserMessage(r)) log$2.warn("failed to retire queued steering display entry during cancellation");
} catch (e) {
log$2.warn(`failed to retire queued steering display entry: ${String(e)}`);
}
return true;
}
/**
* Tracks one steer until commit or terminal cleanup. Admission-only receipts
* resolve after enqueue, but retain exact-message cleanup until the run ends.
* Only explicit delivery deadlines withdraw input before the receiving run ends.
*/
async function steerWithTranscriptLifecycle(e, t, n, r, i, a, o) {
const { abortSignal: s, onQueueAccepted: c, onQueueSettled: l, waitForTranscriptCommit: u, images: d, userTurnTranscriptRecorder: f, media: p, imageOrder: m, currentInboundContext: h, queueIdentity: g = crypto.randomUUID() } = n;
const _ = n.deliveryTimeoutMs;
await new Promise((n, v) => {
let y = false;
let b = false;
let x = s?.aborted === true;
let S = false;
let C;
let w = true;
const reportAcceptance = (e) => {
if (S) return;
S = true;
notifyQueueObserver(() => c?.(e));
};
const reportRejection = () => {
if (!b) reportAcceptance(false);
};
const finish = (e) => {
if (y) return;
y = true;
clearTimeout(T);
notifyQueueObserver(E);
notifyQueueObserver(D);
s?.removeEventListener("abort", onAbort);
o?.removeEventListener("abort", onClosed);
notifyQueueObserver(l);
if (e !== void 0) {
v(toErrorObject(e, "Non-Error rejection"));
return;
}
n();
};
const rejectAfterCancellation = (t) => {
w = false;
C ??= cancelQueuedSteeringMessage(e, g).then(async (e) => {
if (!e) await O.catch((e) => {
b ||= hasAcceptedSteeringCustody(e);
});
if (!e && b) {
log$2.warn("failed to find queued steering message for cancellation");
throw new EmbeddedSteeringAcceptedUnconfirmedError(t);
}
return e;
});
C.then((e) => {
reportRejection();
finish(e ? new MessageInjectionWithdrawnError(t) : new Error(t));
}, (e) => {
if (!(e instanceof EmbeddedSteeringAcceptedUnconfirmedError)) log$2.warn(`failed to cancel queued steering message: ${String(e)}`);
reportRejection();
finish(e instanceof EmbeddedSteeringAcceptedUnconfirmedError ? e : b ? new EmbeddedSteeringAcceptedUnconfirmedError(t, { cause: e }) : new Error(t, { cause: e }));
});
};
const T = _ === void 0 ? void 0 : setTimeout(() => rejectAfterCancellation("queued steering message was not committed to the transcript before timeout"), Math.max(1, _));
T?.unref();
const E = e.subscribe((e) => {
if (e.type === "message_end" && getSteeringMessageIdentity(e.message) === g) {
b = true;
finish();
return;
}
const t = e.type;
if (t === "agent_settled" || t === "agent_handoff") rejectAfterCancellation(`active session ${t === "agent_handoff" ? "handed off" : "ended"} before queued steering message was committed to the transcript`);
});
const D = subscribeSteeringMessagePersistenceFailure(g, (e) => {
w = false;
O.then(() => {
if (y) return;
b = true;
reportAcceptance(true);
finish(e);
}, (t) => {
if (y) return;
b ||= hasAcceptedSteeringCustody(t) || hasAcceptedSteeringCustody(e);
reportRejection();
finish(new AggregateError([e, t], toErrorObject(e, "Steering persistence failed").message, { cause: e }));
});
});
if (x || o?.aborted) {
w = false;
reportAcceptance(false);
finish(/* @__PURE__ */ new Error(o?.aborted ? "active session is finalizing" : "queued steering message was cancelled before acceptance"));
return;
}
const O = e.steer(t, d, f, p, m, g, () => w && (r?.() ?? true), h, i, a);
O.then(() => {
b = true;
if (!w) return;
reportAcceptance(true);
if (x) rejectAfterCancellation("queued steering message was cancelled before delivery");
else if (u !== true && w) {
clearTimeout(T);
D();
s?.removeEventListener("abort", onAbort);
n();
}
}, (e) => {
b ||= hasAcceptedSteeringCustody(e);
if (!w) return;
reportRejection();
finish(e);
});
function onAbort() {
x = true;
rejectAfterCancellation(`queued steering message was cancelled before ${b ? "delivery" : "acceptance"}`);
}
function onClosed() {
rejectAfterCancellation("active session stopped accepting steering before queued steering message was committed to the transcript");
}
s?.addEventListener("abort", onAbort, { once: true });
o?.addEventListener("abort", onClosed, { once: true });
if (o?.aborted) onClosed();
});
}
function resolveQuestionAuthority(e, t) {
return t ?? (e ? {
kind: "run",
assertCurrent: () => {
if (!e()) throw new Error("active session is finalizing");
}
} : void 0);
}
async function steerActiveSessionWithOptionalDeliveryWait(e, t, n, r, i, a, o, s, c) {
const l = n?.isInboundUserMessage === true;
const u = n?.allowPendingUserInputAnswer !== false;
const d = !hasPromptImageInput(n);
if (l && u && !d) try {
await cancelPendingAgentQuestionForSession({
sessionKey: r,
resolvedBy: "image-reply",
authority: resolveQuestionAuthority(i, a)
});
} catch (e) {
if (i && !i()) throw e;
if (e instanceof Error && e.name === "QuestionDispatchRefusedError") throw e;
log$2.warn(`failed to cancel ask_user before image steering: ${String(e)}`);
}
if (l && u && d && await claimEmbeddedPendingUserInputAnswer(t, n, r, i, a)) {
s?.();
notifyQueueObserver(() => n?.onQueueAccepted?.(true));
notifyQueueObserver(n?.onQueueSettled);
return;
}
if (!n || n.waitForTranscriptCommit === void 0 && !n.onQueueSettled) {
try {
await e.steer(t, n?.images, n?.userTurnTranscriptRecorder, n?.media, n?.imageOrder, n?.queueIdentity, i, n?.currentInboundContext, o, s);
} catch (e) {
if (!hasAcceptedSteeringCustody(e)) notifyQueueObserver(() => n?.onQueueAccepted?.(false));
throw e;
}
notifyQueueObserver(() => n?.onQueueAccepted?.(true));
return;
}
try {
await steerWithTranscriptLifecycle(e, t, n, i, o, s, c);
} catch (e) {
if (e instanceof EmbeddedSteeringAcceptedUnconfirmedError) return {
transcriptCommit: "unconfirmed",
errorMessage: e.message
};
throw e;
}
}
async function claimEmbeddedPendingUserInputAnswer(e, t, n, r, i) {
if (t?.isInboundUserMessage !== true || t.allowPendingUserInputAnswer === false || hasPromptImageInput(t)) return false;
return await claimPendingAgentQuestionAnswer({
sessionKey: n,
text: e,
authority: resolveQuestionAuthority(r, i),
sourceRecorder: t.userTurnTranscriptRecorder
});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-steering-admission.ts
/** Owns steering through preparation rollback, prompt closure, and stream release. */
function withEmbeddedAttemptSteeringAdmission(e, t, n) {
const r = new AbortController();
let i = "accepting";
let a;
let o;
const stop = () => {
if (i === "closed") return;
i = "closed";
r.abort();
t.removeEventListener("abort", stop);
a?.();
};
const unsubscribe = () => {
const e = o;
o = void 0;
try {
stop();
} finally {
e?.();
}
};
try {
a = e.subscribe((e) => {
if (e.type === "agent_settled" || e.type === "agent_handoff") stop();
});
t.addEventListener("abort", stop, { once: true });
if (t.aborted) stop();
return n({
closedSignal: r.signal,
get closed() {
return i === "closed";
},
get accepting() {
return i === "accepting";
},
set accepting(e) {
if (i !== "closed") i = e ? "accepting" : "paused";
},
stop,
bindStreamUnsubscribe: (e) => {
o = e;
return unsubscribe;
}
});
} catch (e) {
try {
unsubscribe();
} catch (e) {
log$2.error(`CRITICAL: embedded stream subscription cleanup failed: ${formatErrorMessage(e)}`);
}
throw e;
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-search-executor.ts
/** One owner for nested execution, acceptance, and durable display activity. */
function createSubscribedToolSearchExecutor(e) {
const { attempt: t, subscription: n } = e;
const { scopeId: r } = e.nestedToolActivityState;
let i = 0;
return async (a) => {
const o = e.runSignal;
const s = AbortSignal.any([a.signal ?? o, o]);
let c = a.input;
let l;
try {
if (a.tool.prepareArguments) c = a.tool.prepareArguments(a.input);
} catch (e) {
l = { error: e };
}
const u = l ? a.input : c;
const d = a.toolName === "sessions_yield" ? o : void 0;
const f = Date.now();
const p = i++;
const m = e.sessionManager;
const h = m.getAppendParentId();
if (a.source === "openclaw" && a.sourceName === "core") recordStructuredReplayTrustForToolCall(a.toolCallId, a.tool, t.runId);
return await raceWithAbortSignal(n.runToolLifecycle({
toolName: a.toolName,
toolCallId: a.toolCallId,
parentToolCallId: a.parentToolCallId,
args: u,
replaySafe: a.replaySafe ?? e.isReplaySafeTool(a.tool),
hideFromChannelProgress: "hideFromChannelProgress" in a.tool && a.tool.hideFromChannelProgress === true,
onTerminal: async (n) => {
const i = {
...createNestedToolActivity({
runId: t.runId,
scopeId: r,
afterEntryId: h,
startOrder: p,
parentToolCallId: a.parentToolCallId,
toolCallId: a.toolCallId,
toolName: a.toolName,
input: n.executedArguments,
result: n.readSanitizedResult(),
isError: n.isError,
startedAt: f,
timestamp: Date.now()
}),
idempotencyKey: `${r}:${a.toolCallId}`
};
if (!await runWithOwnedSessionTranscriptWrite({
sessionTarget: m.getSessionTarget(),
sessionKey: t.sessionKey
}, () => withSessionManagerAppend(m, async () => {
if (!e.isCurrent()) return false;
if (isRecord(n.result)) copyInternalToolResultState(n.result, i);
const t = m.getSessionTarget();
const r = m.getSessionId();
const o = await m.appendMessageAsync(i);
const s = e.nestedToolActivityState;
if (!n.isError) s.successfulToolNames.add(a.toolName);
if (o) {
s.accepted ??= {
firstEntryId: o,
lastEntryId: o,
sessionId: r,
target: t
};
s.accepted.lastEntryId = o;
}
return e.isCurrent();
}))) return false;
notifyToolActivity(t.runId);
},
execute: async (e) => await raceWithAbortSignal(retainToolSearchImplementation((async () => {
if (l) throw l.error;
s.throwIfAborted();
const t = getInternalToolExecutionPreparer(a.tool);
if (!t) {
e();
return await a.tool.execute(a.toolCallId, c, s, a.onUpdate);
}
const n = await t({
toolCallId: a.toolCallId,
args: c,
signal: s,
onUpdate: a.onUpdate
});
try {
if (n.kind === "immediate") {
if (n.outcome.kind === "error") throw n.outcome.error;
return n.outcome.result;
}
return await n.execute(e);
} finally {
n.dispose();
}
})().then((e) => {
s.throwIfAborted();
recordEmbeddedToolReceipt(m, a.toolCallId, e.details, a.source === "openclaw" && a.sourceName === "core" && a.toolName === "message");
return a.acceptResultBeforeProjection(e);
})), s, d)
}), s, d);
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-stream-prepare.ts
function prepareEmbeddedAttemptStream(e) {
return withEmbeddedAttemptSteeringAdmission(e.agentSession.activeSession, e.runAbortController.signal, (t) => prepareStream(e, t));
}
function prepareStream(e, t) {
const { attempt: n, agentSession: r } = e;
const { activeSession: i, hookRunner: a } = r;
const o = e.recoverStalledModelCall;
let s = false;
let c;
let l;
let u = 0;
const isSteeringAdmissionOpen = () => {
const n = e.getRunState();
return t.accepting && !n.aborted && !n.yieldDetected && !e.runAbortController.signal.aborted;
};
const d = n.operation !== "settled-tool-finalization" && a?.hasHooks("before_agent_finalize");
const f = n.operation !== "settled-tool-finalization" && !n.silentExpected && resolveReplyExpectation(n) !== "optional" ? n.completionCheck : void 0;
const p = d || f ? async (o) => {
if (c || o.willRetry || o.isError || o.incompleteTerminalAssistant || !o.hasAssistantVisibleText) return;
const s = o.lastAssistant;
const p = normalizeOptionalString(resolveFinalAssistantVisibleText(s)) ?? normalizeOptionalString(resolveFinalAssistantRawText(s)) ?? normalizeOptionalString(o.assistantTexts.join("\n\n"));
if (!p) return;
const m = e.getRunState();
const h = r.clientToolCallSlots.some((e) => e.completed);
if (m.aborted || e.runAbortController.signal.aborted || m.promptError || m.timedOut || h || m.yieldDetected || resolveReplyExpectation(n) !== "result-required" && prepareAgentRunTerminalReply({ rawText: p }).terminalReply.disposition === "silent") return;
const g = n.maxBeforeAgentFinalizeRevisions ?? 0;
const _ = g > 0 && (n.beforeAgentFinalizeRevisionAttempts ?? 0) >= g;
if (d && _) log$2.warn(`before_agent_finalize revision limit reached; skipping further finalize hooks runId=${n.runId} sessionId=${n.sessionId} attempts=${n.beforeAgentFinalizeRevisionAttempts ?? 0}/${g}`);
t.accepting = false;
if (u > 0 || i.pendingMessageCount > 0 || i.agent.hasQueuedMessages()) {
t.accepting = true;
return;
}
let v = false;
try {
let u = { action: "continue" };
if (d && !_) {
const r = resolveReportedModelRef({
provider: n.provider,
model: n.modelId,
assistant: s
});
u = await runAgentHarnessBeforeAgentFinalizeHook({
event: bindAgentHarnessHookMessages({
runId: n.runId,
sessionId: n.sessionId,
...n.sessionKey ? { sessionKey: n.sessionKey } : {},
provider: r.provider,
model: r.model,
...n.cwd ?? n.workspaceDir ? { cwd: n.cwd ?? n.workspaceDir } : {},
...n.sessionFile ? { transcriptPath: n.sessionFile } : {},
stopHookActive: false,
lastAssistantMessage: p,
messages: i.messages
}, async () => {
const n = await readAttemptNestedToolActivity(i.sessionManager, e.nestedToolActivityState);
if (e.runAbortController.signal.aborted || e.getRunState().aborted || t.closed || !isCurrentRegistration()) throw new Error("Nested tool finalization is no longer current");
return projectNestedToolActivityForHooks(i.messages, n);
}),
ctx: {
...buildEmbeddedAgentHookContext(n, e.hookAgentId, freezeDiagnosticTraceContext(e.diagnosticTrace)),
modelProviderId: r.provider,
modelId: r.model
},
hookRunner: a
});
}
if (u.action === "finalize") return;
if (u.action === "revise") {
if (o.hadDeterministicSideEffect) log$2.warn(`before_agent_finalize requested revision after potential side effects; not rewinding runId=${n.runId} sessionId=${n.sessionId}`);
else if (!o.assistantEntryId) log$2.warn(`before_agent_finalize revision lacks a persisted assistant entry; not rewinding runId=${n.runId} sessionId=${n.sessionId}`);
else {
v = true;
l = o.assistantEntryId;
c = u.reason;
return { suppressTerminalDelivery: true };
}
}
const m = e.getRunState();
if (!f?.unfinishedPlan || f.checked || s?.stopReason !== "stop" || resolveProviderRefusal(s) || o.hasPendingContinuation || r.hasDeliveredSourceReply() || e.runAbortController.signal.aborted || m.aborted || m.timedOut || m.promptError || m.yieldDetected || t.closed || i.pendingMessageCount > 0 || i.agent.hasQueuedMessages() || !hasCurrentRegistration()) return;
f.checked = true;
await i.sendCustomMessage({
customType: "openclaw.plan-completion-check",
display: false,
content: `This run’s latest successfully saved plan still has unfinished steps. Before ending, check whether those steps remain required and authorized under the latest user instructions. Continue feasible work from the current transcript; do not repeat completed actions, and reconcile uncertain effects before retrying. If work is complete, reconcile the plan. If user input, approval, an external dependency, or an explicit pause prevents further work, report that concrete limitation; if your previous reply already reported it, end with only ${SILENT_REPLY_TOKEN}. Do not invent completion or new authority.`
}, { deliverAs: "followUp" });
return { continueCurrentTurn: true };
} finally {
if (!v) t.accepting = true;
}
} : void 0;
const clearActiveRun = () => detachActiveEmbeddedRun(n.sessionId, E, n.sessionKey, n.sessionFile, void 0, D);
let m = [];
let h;
const g = subscribeEmbeddedAgentSession({
runId: n.runId,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
lifecycleGeneration: n.lifecycleGeneration,
initialReplayState: n.initialReplayState,
assistantErrorTranscript: n.assistantErrorTranscript,
verboseLevel: n.verboseLevel,
toolResultFormat: n.toolResultFormat,
toolProgressDetail: n.toolProgressDetail,
shouldEmitToolResult: n.shouldEmitToolResult,
shouldEmitToolOutput: n.shouldEmitToolOutput,
sourceReplyDeliveryMode: n.sourceReplyDeliveryMode,
messageToolFinalByDefault: n.messageToolFinalByDefault,
onToolResult: n.onToolResult,
onAgentToolResult: n.onAgentToolResult,
observeToolTerminal: n.observeToolTerminal,
onReasoningStream: n.onReasoningStream,
streamReasoningInNonStreamModes: n.streamReasoningInNonStreamModes,
onReasoningEnd: n.onReasoningEnd,
blockReplyBreak: n.blockReplyBreak,
blockReplyChunking: n.blockReplyChunking,
onPartialReply: n.onPartialReply,
onAssistantMessageStart: n.onAssistantMessageStart,
onAgentEvent: n.onAgentEvent,
onExecutionPhase: n.onExecutionPhase,
onToolStreamBoundary: n.onToolStreamBoundary,
enforceFinalTag: n.enforceFinalTag,
silentExpected: n.silentExpected,
suppressLiveStreamOutput: n.suppressLiveStreamOutput,
config: n.config,
sessionPersistence: n.sessionPersistence,
currentChannelId: n.currentChannelId,
currentMessagingTarget: n.currentMessagingTarget,
currentMessageId: n.currentMessageId,
replyToMode: n.replyToMode,
hasRepliedRef: n.hasRepliedRef,
internalEvents: n.internalEvents,
compactionCountOwner: n.compactionCountOwner,
onContextAccountingEvent: n.onContextAccountingEvent,
builtinToolNames: r.builtinToolNames,
coreBuiltinToolNames: r.coreBuiltinToolNames,
replaySafeToolNames: r.replaySafeToolNames,
codeModeExecToolNames: r.codeModeExecToolNames,
sourceReplyCapableToolNames: r.sourceReplyCapableToolNames,
sideEffectToolOwners: r.sideEffectToolOwners,
trustedLocalMediaToolNames: r.trustedLocalMediaToolNames,
session: i,
onModelUsage: e.onModelUsage,
messageChannel: e.runtimeChannel,
hookRunner: getGlobalHookRunner() ?? void 0,
reasoningMode: n.reasoningLevel ?? "off",
thinkingLevel: n.thinkLevel,
hasDeliveredMessageToolOnlySourceReply: r.hasDeliveredSourceReply,
onDeliveredMessageToolOnlySourceReply: r.markSourceReplyDelivered,
trajectoryRecorder: e.trajectoryRecorder,
onBlockReply: e.onBlockReply,
onBlockReplyFlush: e.onBlockReplyFlush,
onBeforeTerminalDelivery: p,
deferTerminalDelivery: d === true,
terminalLifecyclePhase: n.deferTerminalLifecycle ? "finishing" : "end",
isTerminalAborted: () => e.getRunState().aborted,
resolveTerminalStopReason: () => isAgentRunRestartAbortReason(e.runAbortController.signal.reason) ? AGENT_RUN_RESTART_ABORT_STOP_REASON : void 0,
onBeforeLifecycleTerminal: async () => {
if (h) return;
let t = false;
try {
t = requiresCompletionRequiredAsyncTaskWait({
sessionKey: n.sessionKey,
toolMetas: m,
abortSignal: e.runAbortController.signal
});
} catch (t) {
if (!e.runAbortController.signal.aborted || !isRunnerAbortError(t)) throw t;
}
if (h || t) return;
clearActiveRun();
},
providerOwner: getModelProviderRuntimePluginHandle(n.model)?.plugin,
currentAccountId: n.agentAccountId,
currentThreadId: n.currentThreadTs,
agentId: e.hookAgentId
});
const _ = t.bindStreamUnsubscribe(g.unsubscribe);
const v = {
...g,
unsubscribe: _
};
m = v.toolMetas;
const y = createSubscribedToolSearchExecutor({
attempt: n,
runSignal: e.runAbortController.signal,
sessionManager: i.sessionManager,
subscription: v,
isCurrent: () => isCurrentRegistration() && !e.getRunState().aborted,
isReplaySafeTool: e.isReplaySafeTool,
nestedToolActivityState: e.nestedToolActivityState
});
let b = false;
const abortActiveRunExternally = (t) => {
if (b) return;
b = true;
e.markExternalAbort();
n.onDeferredLifecycleAbort?.(t);
n.onAttemptAbort?.();
const r = t === "restart" ? createAgentRunRestartAbortError() : t === "superseded" ? createAgentRunSupersededAbortError() : void 0;
e.abortRun(false, r);
};
const isCurrentRegistration = () => D !== void 0 && isCurrentEmbeddedRunAttachment(D) && ACTIVE_EMBEDDED_RUNS_BY_RUN_ID.get(n.runId) === D;
const hasCurrentRegistration = () => {
D?.toolAuthority?.assertActive();
return isCurrentRegistration();
};
const canInject = () => isSteeringAdmissionOpen() && hasCurrentRegistration();
const x = n.admittedRunContext?.operationalRunInstance;
const S = getAgentRunContext(n.runId);
const C = x !== void 0 && S?.delegatedAuthority?.operationalRunInstance === x && !(S.isControlUiVisible === false && S.projectSessionMessages === false);
const recordUserReply = (e) => {
const t = e?.isInboundUserReply ?? e?.isInboundUserMessage;
if (!e || !t || e.terminalReplyExpectation === "optional") return;
if (!C || getAgentRunContext(n.runId) !== S) throw new Error("Accepted user input lost its reply owner");
S.acceptedUserReply = {
operationalRunInstance: x,
expectation: e.terminalReplyExpectation === "result-required" || S.acceptedUserReply?.expectation === "result-required" ? "result-required" : "required"
};
};
const composeInjectionGuard = (e) => () => {
e?.();
return canInject();
};
const questionAuthority = (e, t, n) => ({
kind: t,
toolAuthorityPreparation: n,
assertCurrent: () => {
if (!composeInjectionGuard(e)()) throw new Error("active session is finalizing");
}
});
const queueMessage = async (e, r, a, o = a ? "source-bound" : "run", s, c) => {
const l = composeInjectionGuard(a);
if (!l()) throw new Error("active session is finalizing");
u++;
try {
if (r?.steeringMode) i.agent.steeringMode = r.steeringMode;
return await steerActiveSessionWithOptionalDeliveryWait(i, e, r, n.sessionKey, l, questionAuthority(a, o, c), s, C ? () => recordUserReply(r) : void 0, t.closedSignal);
} finally {
u--;
}
};
const claimPendingUserInputAnswer = (e, t, r, i = r ? "source-bound" : "run", a) => claimEmbeddedPendingUserInputAnswer(e, t, n.sessionKey, composeInjectionGuard(r), questionAuthority(r, i, a)).then((e) => {
if (e && C) recordUserReply(t);
return e;
});
const cancelPendingUserInput = (e, t, r = t ? "source-bound" : "run", i) => cancelPendingAgentQuestionForSession({
sessionKey: n.sessionKey,
resolvedBy: e,
authority: questionAuthority(t, r, i)
});
const w = {
version: 2,
isAvailable: isSteeringAdmissionOpen,
queueMessage,
claimPendingUserInputAnswer,
cancelPendingUserInput,
queueMessageAsync: (e, t, n, r) => queueMessage(e, t, n.assertCurrent, r, n.prepareCurrent, n),
claimPendingUserInputAnswerAsync: (e, t, n, r) => claimPendingUserInputAnswer(e, t, n.assertCurrent, r, n),
cancelPendingUserInputAsync: (e, t, n) => cancelPendingUserInput(e, t.assertCurrent, n, t)
};
const canApplyPermissionMode = () => t.accepting && !e.runAbortController.signal.aborted && isCurrentRegistration();
const T = e.applyPermissionMode;
const E = {
kind: "embedded",
runId: n.runId,
permissionChangeOwner: n.permissionChange?.owner,
diagnosticOwner: e.diagnosticOwner,
closeDiagnostics: () => closeDiagnosticEmbeddedRunOwner(e.diagnosticOwner),
startedAtMs: n.startedAtMs,
get toolAuthorityFingerprint() {
return n.toolAuthorityFingerprint;
},
applyPermissionMode: T ? async (t, r) => {
if (!canApplyPermissionMode()) return false;
if ((n.permissionMode ?? null) === t) return true;
try {
await T(t, r);
return canApplyPermissionMode();
} catch (t) {
e.abortRun(false, t);
throw t;
}
} : void 0,
claimPendingUserInputAnswer,
cancelPendingUserInput,
queueMessage,
messageInjection: w,
messageInjectionV2: w,
isStreaming: () => i.isStreaming,
readSessionForkContext: () => {
if (!isCurrentRegistration()) return;
return {
model: n.model,
systemPrompt: i.systemPrompt,
tools: i.agent.state.tools.map(({ name: e, description: t, parameters: n, async: r }) => ({
name: e,
description: t,
parameters: n,
...r === false ? { async: r } : {}
})),
messages: i.messages,
projectMessages: e.projectSessionForkMessages,
sessionVersion: i.sessionManager.getHeader()?.version,
boundary: e.readSessionForkBoundary?.(),
blockImages: i.settingsManager.getBlockImages()
};
},
isAborted: () => e.getRunState().aborted,
isStopped: () => !isSteeringAdmissionOpen(),
isCompacting: () => v.isCompacting(),
supportsTranscriptCommitWait: true,
supportsQueueMessageImages: true,
sourceReplyDeliveryMode: n.sourceReplyDeliveryMode,
get terminalReplyExpectation() {
return resolveReplyExpectation(n);
},
supportsUserReplyPromotion: C,
taskSuggestionDeliveryMode: n.taskSuggestionDeliveryMode,
recoverStalledModelCall: o ? () => {
if (s) return !b && !n.abortSignal?.aborted && isCurrentRegistration();
s = isSteeringAdmissionOpen() && !v.isCompacting() && countActiveToolExecutions(n.runId) === 0 && hasCurrentRegistration() && o();
return s;
} : void 0,
cancel: abortActiveRunExternally,
abort: abortActiveRunExternally
};
attachActiveEmbeddedRun(n.sessionId, E, n.sessionKey, n.sessionFile, e.hookAgentId, n.replyOperation, n.lifecycleGeneration ?? captureAgentRunLifecycleGeneration(n.runId));
const D = getEmbeddedRunAttachment(E);
if (D) D.runCleanupSettlement = n.runCleanupSettlement;
if (n.deferTerminalLifecycle && n.onDeferredLifecycleOwner) {
h = createEmbeddedAttemptDeferredLifecycleOwner({
runId: n.runId,
sessionId: n.sessionId,
diagnosticOwner: e.diagnosticOwner,
onRetryWaitCompleted: () => n.replyOperation?.recordActivity(),
isCurrent: () => D?.delegatedAuthority !== void 0 && validateAgentRunDelegatedAuthority(D.delegatedAuthority) && isCurrentRegistration(),
trajectoryRecorder: e.trajectoryRecorder ?? null,
clearActiveRun: () => {
try {
_();
} finally {
clearActiveRun();
}
}
});
try {
n.onDeferredLifecycleOwner(h);
} catch (e) {
h.discard();
throw e;
}
}
return {
subscription: v,
queueHandle: E,
registration: D,
deferredLifecycleOwner: h,
toolSearchCatalogExecutor: y,
getBeforeAgentFinalizeRevisionReason: () => c,
getBeforeAgentFinalizeRevisionEntryId: () => l,
stopAcceptingSteerMessages: t.stop
};
}
//#endregion
//#region src/agents/embedded-agent-runner/prompt-cache-request-observer.ts
/** Pairs foreground request inputs with completion usage before billing aggregation. */
function createPromptCacheRequestObserver(e, t, n) {
let r = 0;
let i;
let a;
let o;
return {
onModelRequest: async (t, a, o) => {
await preparePromptCacheHistory(a.messages, o);
if (i) completePromptCacheObservation(e);
r += 1;
i = {
...beginPromptCacheObservation({
...e,
provider: t.provider,
modelId: t.id,
modelApi: t.api,
systemPrompt: a.systemPrompt ?? "",
tools: collectPromptCacheTools(a.tools ?? []),
messages: a.messages
}),
requestIndex: r,
messageCount: a.messages.length,
systemPromptSeries: e.getSystemPromptSeries?.()
};
n?.(i);
return i;
},
onModelUsage: (n, r, s) => {
if (!i) return;
const c = completePromptCacheObservation({
...e,
usage: n,
providerPrompt: r
});
const l = c?.providerPrefix;
const u = !c ? void 0 : c.changes?.length ? "tracked-input-change" : !l || l === "unavailable" ? "unattributed:provider-prompt-unavailable" : l === "prefix-match" ? "provider-cache-reuse-lost:unchanged-prefix" : l.startsWith("continuation:") ? "unattributed:continuation-wire-input" : l.startsWith("unverified-after:") ? "unattributed:bounded-prefix" : `provider-input-change:${l}`;
const d = n?.cacheTelemetry?.state !== "unavailable";
o = n?.contextUsage?.state === "available" ? {
requestIndex: i.requestIndex,
messageCount: i.messageCount,
contextTokens: n.contextUsage.totalTokens,
responseId: s?.responseId?.trim() || void 0,
turnId: s?.turnId?.trim() || void 0
} : void 0;
a = {
requestIndex: i.requestIndex,
messageCount: i.messageCount,
broke: Boolean(c),
previousCacheRead: i.previousCacheRead ?? void 0,
requestGapMs: i.requestGapMs,
providerPrefix: l,
systemPromptSeries: i.systemPromptSeries,
dropCause: u,
requests: c?.requests,
promptTokens: n?.contextUsage?.state === "available" ? n.contextUsage.promptTokens : void 0,
responseId: s?.responseId,
input: n?.input,
cacheRead: d ? n?.cacheRead : void 0,
cacheWrite: d ? n?.cacheWrite : void 0,
changes: c?.changes ?? i.changes
};
const { snapshot: f } = i;
i = void 0;
t(a, f);
},
getObservation: () => a,
getContextUsage: () => o
};
}
//#endregion
//#region src/agents/embedded-agent-runner/thinking-replay-repair.ts
/** Repairs persisted provider replay state after provider-confirmed rejection. */
async function rewriteRejectedReplayInSessionManager(e, t) {
if (t.replacements.length === 0) return {
repaired: false,
reason: t.emptyReason
};
const n = await rewriteTranscriptEntriesInSessionManager({
sessionManager: e.sessionManager,
replacements: t.replacements
});
if (!n.changed) return {
repaired: false,
reason: n.reason
};
const r = e.sessionManager.getSessionTarget();
if (r || e.sessionFile) emitSessionTranscriptUpdate({
...e.sessionFile ? { sessionFile: e.sessionFile } : {},
...r ? { target: r } : {
sessionKey: e.sessionKey,
...e.agentId ? { agentId: e.agentId } : {}
}
});
log$2.warn(`[session-recovery] ${t.logMessage}: repaired=${n.rewrittenEntries} sessionKey=${e.sessionKey ?? e.sessionId ?? "unknown"}`);
return { repaired: true };
}
function repairRejectedThinkingReplayInSessionManager(e) {
return rewriteRejectedReplayInSessionManager(e, {
replacements: e.sessionManager.getBranch().flatMap((e) => {
if (e.type !== "message") return [];
const t = stripThinkingBlocksFromMessage(e.message);
return t === e.message ? [] : [{
entryId: e.id,
message: t
}];
}),
emptyReason: "no thinking blocks on active branch",
logMessage: "stripped thinking blocks after provider rejected replay"
});
}
function repairRejectedCompactionReplayInSessionManager(e) {
const t = e.sessionManager.getBranch().findLast((t) => t.type === "message" && t.message.role === "assistant" && isCompactionReplayCheckpoint(t.message.providerReplay) && t.message.providerReplay.data === e.checkpoint.data && (e.checkpoint.id === void 0 || t.message.providerReplay.id === e.checkpoint.id));
return rewriteRejectedReplayInSessionManager(e, {
replacements: t?.type === "message" && t.message.role === "assistant" ? [{
entryId: t.id,
message: stripCompactionReplayCheckpoint(t.message)
}] : [],
emptyReason: "no matching compaction checkpoint on active branch",
logMessage: "stripped compaction checkpoint after provider rejected replay"
});
}
//#endregion
//#region src/agents/embedded-agent-runner/tool-call-argument-decoding.ts
const decodedToolCallArguments = /* @__PURE__ */ new WeakSet();
function decodeToolCallArgumentsHtmlEntitiesInMessage(e) {
if (!e || typeof e !== "object") return;
const t = e.content;
if (!Array.isArray(t)) return;
for (const e of t) {
if (!e || typeof e !== "object") continue;
const t = e;
if (t.type !== "toolCall" || typeof t.arguments !== "object" || !t.arguments) continue;
if (decodedToolCallArguments.has(t.arguments)) continue;
const n = mapNestedStrings(t.arguments, decodeHtmlEntities);
decodedToolCallArguments.add(n);
t.arguments = n;
}
}
/** Wraps a stream function so tool-call arguments are decoded before consumers inspect them. */
function createHtmlEntityToolCallArgumentDecodingWrapper(e) {
return (t, n, r) => mapAssistantMessageStream(e(t, n, r), (e) => {
const t = e.result.bind(e);
e.result = async () => {
const e = await t();
decodeToolCallArgumentsHtmlEntitiesInMessage(e);
return e;
};
return wrapStreamObjectEvents(e, (e) => {
decodeToolCallArgumentsHtmlEntitiesInMessage(e.partial);
decodeToolCallArgumentsHtmlEntitiesInMessage(e.message);
});
});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-stop-reason-recovery.ts
const UNHANDLED_STOP_REASON_RE = /^Unhandled stop reason:\s*(.+)$/i;
function normalizeUnhandledStopReasonMessage(e) {
if (typeof e !== "string") return;
const t = e.trim().match(UNHANDLED_STOP_REASON_RE)?.[1]?.trim();
return t ? `The model stopped because the provider returned an unhandled stop reason: ${t}. Please rephrase and try again.` : void 0;
}
function normalizeUnhandledStopReasonError(e) {
const t = normalizeUnhandledStopReasonMessage(formatErrorMessage(e));
if (!t) throw e;
return t;
}
function patchUnhandledStopReasonInAssistantMessage(e) {
if (!e || typeof e !== "object") return;
const t = e;
const n = normalizeUnhandledStopReasonMessage(t.errorMessage);
if (!n) return;
t.stopReason = "error";
t.errorMessage = n;
}
function buildUnhandledStopReasonErrorStream(e, t) {
const n = (0, event_stream_exports.createAssistantMessageEventStream)();
queueMicrotask(() => {
n.push({
type: "error",
reason: "error",
error: buildStreamErrorAssistantMessage({
model: e,
errorMessage: t
})
});
n.end();
});
return n;
}
function wrapStreamHandleUnhandledStopReason(e, t) {
const n = t.result.bind(t);
t.result = async () => {
try {
const e = await n();
patchUnhandledStopReasonInAssistantMessage(e);
return e;
} catch (t) {
return buildStreamErrorAssistantMessage({
model: e,
errorMessage: normalizeUnhandledStopReasonError(t)
});
}
};
const r = t[Symbol.asyncIterator].bind(t);
t[Symbol.asyncIterator] = function() {
const t = r();
let n = false;
const observe = (e) => {
try {
if (!e.done && e.value.type === "error") patchUnhandledStopReasonInAssistantMessage(e.value.error);
return e;
} catch (e) {
return recover(e);
}
};
const recover = (t) => {
const r = normalizeUnhandledStopReasonError(t);
n = true;
return {
done: false,
value: {
type: "error",
reason: "error",
error: buildStreamErrorAssistantMessage({
model: e,
errorMessage: r
})
}
};
};
return createStreamIteratorWrapper({
iterator: t,
next: (e) => {
if (n) return Promise.resolve({
done: true,
value: void 0
});
try {
return Promise.resolve(e.next()).then(observe, recover);
} catch (e) {
return new Promise((t) => {
t(recover(e));
});
}
}
});
};
return t;
}
/**
* Wraps provider streams so raw "Unhandled stop reason" failures are rewritten
* into stable error messages. Recovery covers synchronous creation failures,
* async stream creation failures, iterator errors, and `result()` errors.
*/
function wrapStreamFnHandleSensitiveStopReason(e) {
return (t, n, r) => {
try {
const i = e(t, n, r);
if (i && typeof i === "object" && "then" in i) return Promise.resolve(i).then((e) => wrapStreamHandleUnhandledStopReason(t, e), (e) => buildUnhandledStopReasonErrorStream(t, normalizeUnhandledStopReasonError(e)));
return wrapStreamHandleUnhandledStopReason(t, i);
} catch (e) {
return buildUnhandledStopReasonErrorStream(t, normalizeUnhandledStopReasonError(e));
}
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-call-stream-normalization.ts
const BLANK_TOOL_CALL_NAME_DESCRIPTION = "blank tool name";
function rewriteUnknownToolLoopMessage(e, t) {
if (!e || typeof e !== "object") return;
e.content = [{
type: "text",
text: `I can't use the tool "${t}" here because it isn't available. I need to stop retrying it and answer without that tool.`
}];
stripCompactionReplayCheckpointInPlace(e);
}
function wrapStreamFnTrimToolCallNames(e, t, n) {
const r = {
count: 0,
countedMessages: /* @__PURE__ */ new WeakSet()
};
const i = /* @__PURE__ */ new Set();
return (a, o, s) => {
for (const e of o.messages ?? []) {
if (e.role !== "assistant") continue;
for (const t of e.content) if (isRunnerToolCallBlock(t) && typeof t.id === "string" && t.id.trim()) i.add(t.id.trim());
}
const c = new Set(i);
return mapAssistantMessageStream(e(a, o, s), (e) => {
const a = n?.unknownToolThreshold;
const o = r;
const s = [];
let l = false;
const normalize = (e) => {
if (!e || typeof e !== "object") return;
const n = e.content;
if (!Array.isArray(n)) return;
let r;
let a;
let o = false;
let l = false;
let u = false;
const d = t !== void 0;
for (const e of n) {
if (!isRunnerToolCallBlock(e)) continue;
r ??= /* @__PURE__ */ new Set();
const n = typeof e.id === "string" ? e.id : void 0;
const i = resolveToolCallName(typeof e.name === "string" ? e.name : "", t, n);
if (i && i !== e.name) e.name = i;
const s = n?.trim();
if (s) r.add(s);
const c = e.name;
const f = typeof c === "string";
const p = f ? c.trim() : "";
if (!p) {
if (f) u = true;
else l = true;
continue;
}
if (!d) continue;
if (f && t?.has(c)) {
o = true;
continue;
}
const m = normalizeToolPolicyName(p);
if (!a) a = m;
else if (a !== m) l = true;
}
if (!r) return;
const f = /* @__PURE__ */ new Set();
for (const [e, t] of n.entries()) {
if (!isRunnerToolCallBlock(t)) continue;
const n = typeof t.id === "string" ? t.id.trim() : "";
if (n && !c.has(n) && !f.has(n)) {
if (t.id !== n) t.id = n;
f.add(n);
continue;
}
let i = s[e];
while (!i || c.has(i) || r.has(i) || f.has(i)) i = `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
s[e] = i;
t.id = i;
r.add(i);
f.add(i);
}
for (const e of f) i.add(e);
if (!d) return u ? {
kind: "malformed",
toolName: BLANK_TOOL_CALL_NAME_DESCRIPTION
} : void 0;
if (o) return { kind: "allowed" };
if (u && !l && a === void 0) return {
kind: "malformed",
toolName: BLANK_TOOL_CALL_NAME_DESCRIPTION
};
if (l) return { kind: "incomplete" };
return a ? {
kind: "unknown",
toolName: a
} : { kind: "incomplete" };
};
const guard = (e, t, n) => {
const r = n !== "partial" && !l;
if (t?.kind === "allowed") {
if (n !== "partial") {
o.lastUnknownToolName = void 0;
o.count = 0;
}
return false;
}
if (t?.kind === "malformed") {
if (n === "result") {
rewriteUnknownToolLoopMessage(e, t.toolName);
return true;
}
return false;
}
if (a === void 0 || a <= 0) return false;
if (t?.kind !== "unknown") {
if (r && n === "result") {
o.lastUnknownToolName = void 0;
o.count = 0;
}
return false;
}
const i = t.toolName;
const s = e && typeof e === "object" ? e : void 0;
if (r && !(s && o.countedMessages.has(s))) {
if (s) o.countedMessages.add(s);
o.count = o.lastUnknownToolName === i ? o.count + 1 : 1;
o.lastUnknownToolName = i;
}
if (o.lastUnknownToolName === i && o.count > a) rewriteUnknownToolLoopMessage(e, i);
return r;
};
const u = e.result.bind(e);
e.result = async () => {
const e = await u();
guard(e, normalize(e), "result");
return e;
};
wrapStreamObjectEvents(e, (e) => {
const t = normalize(e.partial);
const n = normalize(e.message);
if (e.message && typeof e.message === "object") {
const t = guard(e.message, n, "message");
l ||= t;
}
if (e.partial !== e.message) guard(e.partial, t, "partial");
});
return e;
});
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-call-text-promotion.ts
const STANDALONE_TEXT_TOOL_CALL_PROMOTION_STOP_REASONS = /* @__PURE__ */ new Set(["stop", "toolUse"]);
function wrapStreamPromoteStandaloneTextToolCalls(e, t) {
const n = {
hasExactName: (e) => Boolean(resolveToolCallName(e, t, void 0, true)),
hasNamePrefix: (e) => couldNormalizeToolNamePrefixToAllowedTool(e, t)
};
const r = /* @__PURE__ */ new Map();
const normalizeTerminalMessage = (e) => {
const i = projectScrubbedPlainTextToolCallMessage({
forceIncompleteCandidates: true,
matcher: n,
message: e.message,
preserveEmptyTextBlocks: e.preserveEmptyTextBlocks,
resolveProtectedRanges: findMarkdownCodeRegions,
requireAssistantRole: true
});
if (i) {
stripCompactionReplayCheckpointInPlace(i.message);
return {
kind: "scrubbed",
...i
};
}
if (!e.allowPromotion) return;
let a = 0;
const createStableToolCallBlock = (e, t) => {
const n = `${a}:${e.start}:${e.end}`;
a += 1;
const i = r.get(n) || `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
r.set(n, i);
return {
type: "toolCall",
id: i,
name: t,
arguments: e.arguments
};
};
const o = projectStandalonePlainTextToolCallMessage({
allowedStopReasons: STANDALONE_TEXT_TOOL_CALL_PROMOTION_STOP_REASONS,
allowedToolNames: t,
createToolCallBlock: createStableToolCallBlock,
isRetainableNonTextBlock: isThinkingLikeBlock,
message: e.message,
requireAssistantRole: true,
resolveProtectedRanges: findMarkdownCodeRegions,
resolveToolName: (e) => resolveToolCallName(e, t, void 0, true)
});
if (o) stripCompactionReplayCheckpointInPlace(o.message);
return o ? {
kind: "promoted",
...o
} : void 0;
};
const i = e.result.bind(e);
e.result = async () => {
const e = await i();
return normalizeTerminalMessage({
allowPromotion: STANDALONE_TEXT_TOOL_CALL_PROMOTION_STOP_REASONS.has(e.stopReason),
message: e
})?.message ?? e;
};
const a = e[Symbol.asyncIterator].bind(e);
const wrappedAsyncIterator = function() {
const e = a();
const t = normalizePlainTextToolCallStreamEvents({ [Symbol.asyncIterator]: () => e }, {
createPromotedToolCallEvents: createPromotedPlainTextToolCallEvents,
matcher: n,
normalizeTerminalMessage,
protectedRangesFenceCompatible: true,
resolveProtectedRanges: findMarkdownCodeRegions
})[Symbol.asyncIterator]();
let r = false;
return createStreamIteratorWrapper({
iterator: t,
next: (e) => {
r = true;
return e.next();
},
onReturn: async (t, n) => {
const i = !r;
r = true;
try {
return await t.return?.(n) ?? {
done: true,
value: void 0
};
} finally {
if (i) await e.return?.(n);
}
}
});
};
if (!Reflect.set(e, Symbol.asyncIterator, wrappedAsyncIterator)) throw new TypeError("Cannot replace stream async iterator");
return e;
}
function wrapStreamFnPromoteStandaloneTextToolCalls(e, t) {
if (!t || t.size === 0) return e;
return (n, r, i) => mapAssistantMessageStream(e(n, r, i), (e) => wrapStreamPromoteStandaloneTextToolCalls(e, t));
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt.tool-call-argument-repair.ts
const MAX_TOOLCALL_REPAIR_BUFFER_CHARS = 64e3;
const MAX_TOOLCALL_REPAIR_LEADING_CHARS = 96;
const MAX_TOOLCALL_REPAIR_TRAILING_CHARS = 3;
const TOOLCALL_REPAIR_ALLOWED_LEADING_RE = /^[a-z0-9\s"'`.:/_\\-]+$/i;
const TOOLCALL_REPAIR_ALLOWED_TRAILING_RE = /^[^\s{}[\]":,\\]{1,3}$/;
const TOOLCALL_REPAIR_SMART_QUOTES = /* @__PURE__ */ new Set([
"“",
"”",
"„",
"‟"
]);
const MAX_TOOLCALL_REPAIR_MEMBER_KEY_CHARS = 96;
const TOOLCALL_REPAIR_KNOWN_ARG_KEYS = /* @__PURE__ */ new Set([
"args",
"backupDir",
"cmd",
"command",
"content",
"cwd",
"edits",
"file",
"file_path",
"filePath",
"filepath",
"from",
"line_end",
"line_start",
"lines",
"message",
"new_str",
"new_string",
"newText",
"old_str",
"old_string",
"oldText",
"path",
"paths",
"pattern",
"query",
"replacement",
"text",
"timeoutMs",
"title",
"to",
"url",
"urls",
"workdir"
]);
const TOOLCALL_REPAIR_FREEFORM_VALUE_KEYS = /* @__PURE__ */ new Set([
"content",
"message",
"new_str",
"new_string",
"newText",
"old_str",
"old_string",
"oldText",
"text"
]);
const TOOLCALL_REPAIR_FREEFORM_SUCCESSOR_KEYS = {
old_str: "new_str",
old_string: "new_string",
oldText: "newText"
};
const TOOLCALL_REPAIR_JSON_STRING_ESCAPES = {
"\"": "\"",
"\\": "\\",
"/": "/",
b: "\b",
f: "\f",
n: "\n",
r: "\r",
t: " "
};
function shouldAttemptMalformedToolCallRepair(e, t) {
if (/[}\]]/.test(t)) return true;
const n = t.trim();
return n.length > 0 && n.length <= MAX_TOOLCALL_REPAIR_TRAILING_CHARS && e;
}
function isAllowedToolCallRepairLeadingPrefix(e) {
return !e || e.length <= MAX_TOOLCALL_REPAIR_LEADING_CHARS && TOOLCALL_REPAIR_ALLOWED_LEADING_RE.test(e) && (/^[.:'"`-]/.test(e) || /^(?:functions?|tools?)[._:/-]?/i.test(e));
}
function skipWhitespace(e, t) {
let n = t;
while (n < e.length && e[n]?.trim() === "") n += 1;
return n;
}
function isToolCallRepairSmartQuote(e) {
return e !== void 0 && TOOLCALL_REPAIR_SMART_QUOTES.has(e);
}
function findAsciiQuotedStringEnd(e, t) {
for (let n = t + 1; n < e.length; n += 1) if (e[n] === "\\") n += 1;
else if (e[n] === "\"") return n + 1;
}
function readAsciiQuotedString(e, t) {
const n = findAsciiQuotedStringEnd(e, t);
const r = n === void 0 ? void 0 : safeParseJson(e.slice(t, n));
return typeof r === "string" && n !== void 0 ? {
value: r,
endIndex: n
} : void 0;
}
function readSmartQuotedString(e, t, n, r = Infinity) {
for (let i = t + 1; i < e.length; i += 1) {
if (isToolCallRepairSmartQuote(e[i]) && n(i)) return {
value: e.slice(t + 1, i),
endIndex: i + 1
};
if (i - t > r) return;
}
}
function readObjectKey(e, t) {
const n = e[t];
return n === "\"" ? readAsciiQuotedString(e, t) : isToolCallRepairSmartQuote(n) ? readSmartQuotedString(e, t, (t) => e[skipWhitespace(e, t + 1)] === ":", MAX_TOOLCALL_REPAIR_MEMBER_KEY_CHARS) : void 0;
}
function readObjectMemberKeyAfterComma(e, t) {
const n = readObjectKey(e, skipWhitespace(e, t + 1));
if (!n || e[skipWhitespace(e, n.endIndex)] !== ":") return;
return n.value;
}
function normalizeToolCallRepairToolName(e) {
const t = e.trim();
return /^[a-z0-9_-]{1,128}$/i.test(t) ? t.toLowerCase() : void 0;
}
function extractToolNameFromLeadingPrefix(e) {
const t = /(?:^|[.\s])(?:functions?|tools?)[._:/-]?([a-z0-9_-]+)/i.exec(e);
return t?.[1] ? normalizeToolCallRepairToolName(t[1]) : void 0;
}
function shouldCloseSmartQuotedValueAt(e, t, n, r) {
const i = skipWhitespace(e, t + 1);
const a = e[i];
if (i >= e.length || a === "}") return true;
if (a !== ",") return false;
const o = readObjectMemberKeyAfterComma(e, i);
if (!o) return false;
if (!TOOLCALL_REPAIR_FREEFORM_VALUE_KEYS.has(n)) return TOOLCALL_REPAIR_KNOWN_ARG_KEYS.has(o) || r === "read" && n === "path" && (o === "offset" || o === "limit");
return TOOLCALL_REPAIR_FREEFORM_SUCCESSOR_KEYS[n] === o;
}
function decodeSmartQuotedJsonStringEscapes(e) {
return e.replace(/\\(?:(["\\/bfnrt])|u([0-9a-fA-F]{4}))/g, (e, t, n) => {
if (typeof n === "string") return String.fromCharCode(Number.parseInt(n, 16));
return typeof t === "string" ? TOOLCALL_REPAIR_JSON_STRING_ESCAPES[t] ?? e : e;
});
}
function readJsonValue(e, t) {
let n = 0;
for (let r = t; r < e.length; r += 1) {
const i = e[r];
if (i === "\"") {
const t = findAsciiQuotedStringEnd(e, r);
if (t === void 0) return;
r = t - 1;
} else if (i === "{" || i === "[") n += 1;
else if (i === "}" || i === "]") {
if (n === 0) return parseJsonValuePrefix(e, t, r);
n -= 1;
} else if (i === "," && n === 0) return parseJsonValuePrefix(e, t, r);
}
return parseJsonValuePrefix(e, t, e.length);
}
function parseJsonValuePrefix(e, t, n) {
const r = safeParseJson(e.slice(t, n).trim());
return r === void 0 ? void 0 : {
value: r,
endIndex: n
};
}
function readCommaSeparatedBody(e, t, n, r) {
let i = skipWhitespace(e, t + 1);
if (e[i] === n) return i + 1;
while (i < e.length) {
const t = r(i);
if (t === void 0) return;
i = skipWhitespace(e, t);
if (e[i] === ",") {
i = skipWhitespace(e, i + 1);
continue;
}
return e[i] === n ? i + 1 : void 0;
}
}
function readObjectValue(e, t, n, r) {
const i = e[t];
if (i === "\"") return readAsciiQuotedString(e, t);
if (isToolCallRepairSmartQuote(i)) {
const i = readSmartQuotedString(e, t, (t) => shouldCloseSmartQuotedValueAt(e, t, n, r));
return i && {
...i,
value: decodeSmartQuotedJsonStringEscapes(i.value)
};
}
if (n === "edits" && i === "[") {
const n = [];
const r = readCommaSeparatedBody(e, t, "]", (t) => {
const r = parseSmartQuotedToolCallObject(e, t);
if (!r) return;
n.push(r.value);
return r.endIndex;
});
return r === void 0 ? void 0 : {
value: n,
endIndex: r
};
}
return readJsonValue(e, t);
}
function parseSmartQuotedToolCallObject(e, t, n) {
if (e[t] !== "{") return;
const r = {};
const i = /* @__PURE__ */ new Set();
const a = readCommaSeparatedBody(e, t, "}", (t) => {
const a = readObjectKey(e, t);
if (!a || i.has(a.value)) return;
i.add(a.value);
const o = skipWhitespace(e, a.endIndex);
if (e[o] !== ":") return;
const s = readObjectValue(e, skipWhitespace(e, o + 1), a.value, n);
if (!s) return;
r[a.value] = s.value;
return s.endIndex;
});
return a === void 0 ? void 0 : {
value: r,
endIndex: a
};
}
function tryExtractUsableToolCallArgumentsFromJson(e) {
const t = extractBalancedJsonPrefix(e);
if (!t) return;
const n = e.slice(0, t.startIndex).trim();
if (!isAllowedToolCallRepairLeadingPrefix(n)) return;
const r = e.slice(t.startIndex + t.json.length).trim();
if (n.length === 0 && r.length === 0) return;
return finishToolCallArgumentRepair(safeParseJsonRecord(t.json), n, r);
}
function finishToolCallArgumentRepair(e, t, n) {
if (!e || n.length > MAX_TOOLCALL_REPAIR_TRAILING_CHARS || n.length > 0 && !TOOLCALL_REPAIR_ALLOWED_TRAILING_RE.test(n)) return;
return {
args: e,
kind: "repaired",
leadingPrefix: t,
trailingSuffix: n
};
}
function tryExtractSmartQuotedToolCallArguments(e, t) {
if (!/[\u201c\u201d\u201e\u201f]/.test(e)) return;
const n = e.indexOf("{");
if (n < 0) return;
const r = e.slice(0, n).trim();
if (!isAllowedToolCallRepairLeadingPrefix(r)) return;
const i = parseSmartQuotedToolCallObject(e, n, t ?? extractToolNameFromLeadingPrefix(r));
if (!i) return;
return finishToolCallArgumentRepair(i.value, r, e.slice(i.endIndex).trim());
}
function endsWithRepairableObjectClose(e) {
const t = e.trimEnd();
let n = t.length;
while (n > t.length - MAX_TOOLCALL_REPAIR_TRAILING_CHARS && TOOLCALL_REPAIR_ALLOWED_TRAILING_RE.test(t[n - 1] ?? "")) n -= 1;
return t.slice(0, n).trimEnd().endsWith("}");
}
function tryExtractUsableToolCallArguments(e, t) {
if (!endsWithRepairableObjectClose(e)) return;
const n = safeParseJsonRecord(e);
if (n) return {
args: n,
kind: "preserved",
leadingPrefix: "",
trailingSuffix: ""
};
return tryExtractUsableToolCallArgumentsFromJson(e) ?? tryExtractSmartQuotedToolCallArguments(e, t);
}
function readToolCallBlock(e, t) {
const n = asOptionalObjectRecord(e)?.content;
const r = Array.isArray(n) ? n[t] : void 0;
return isRunnerToolCallBlock(r) ? r : void 0;
}
function wrapStreamRepairMalformedToolCallArguments(e) {
const t = /* @__PURE__ */ new Map();
const n = e.result.bind(e);
e.result = async () => {
const e = await n();
for (const [n, r] of t) {
const t = readToolCallBlock(e, n);
if (t && r.repairedArgs) t.arguments = r.repairedArgs;
}
t.clear();
return e;
};
wrapStreamObjectEvents(e, (e) => {
const n = e.contentIndex;
if (typeof n !== "number" || !Number.isInteger(n)) return;
if (e.type === "toolcall_delta" && typeof e.delta === "string") {
const r = t.get(n) ?? { partialJson: "" };
if (r.disabled) return;
t.set(n, r);
r.partialJson += e.delta;
if (r.partialJson.length > MAX_TOOLCALL_REPAIR_BUFFER_CHARS) {
r.partialJson = "";
r.repairedArgs = void 0;
r.disabled = true;
return;
}
r.sawCloser ||= /[}\]]/.test(e.delta);
const i = r.repairedArgs !== void 0;
if (!shouldAttemptMalformedToolCallRepair(r.sawCloser, e.delta) && !i) return;
const a = [readToolCallBlock(e.partial, n), readToolCallBlock(e.message, n)];
const o = a.map((e) => typeof e?.name === "string" ? normalizeToolCallRepairToolName(e.name) : void 0).find((e) => e !== void 0);
const s = tryExtractUsableToolCallArguments(r.partialJson, o);
const c = r.hadPreexistingArgs || !i && a.some((e) => isRecord(e?.arguments) && Object.keys(e.arguments).length > 0);
r.repairedArgs = s?.args;
if (s) r.hadPreexistingArgs = c;
if (s || !c) {
for (const e of a) if (e) e.arguments = s?.args ?? {};
}
if (s?.kind === "repaired" && !r.loggedRepair) {
r.loggedRepair = true;
log$2.warn(`repairing malformed tool call arguments with ${s.leadingPrefix.length} leading chars and ${s.trailingSuffix.length} trailing chars`);
}
}
if (e.type === "toolcall_end") {
const r = t.get(n)?.repairedArgs;
if (r) {
for (const t of [
asOptionalObjectRecord(e.toolCall),
readToolCallBlock(e.partial, n),
readToolCallBlock(e.message, n)
]) if (t) t.arguments = r;
t.set(n, {
partialJson: "",
repairedArgs: r
});
} else t.delete(n);
}
});
return e;
}
function wrapStreamFnRepairMalformedToolCallArguments(e) {
return (t, n, r) => mapAssistantMessageStream(e(t, n, r), wrapStreamRepairMalformedToolCallArguments);
}
function shouldRepairMalformedToolCallArguments(e) {
const t = e.modelApi ?? "";
return normalizeProviderId(e.provider ?? "") === "kimi" && t === "anthropic-messages" || t === "openai-completions" || t === "azure-openai-responses" || t === "openai-chatgpt-responses";
}
//#endregion
//#region src/agents/embedded-agent-runner/run/llm-idle-timeout.ts
const DEFAULT_LLM_IDLE_TIMEOUT_MS = 12e4;
const SELF_HOSTED_LLM_IDLE_TIMEOUT_MS = 3e5;
const CLOUD_LLM_FIRST_EVENT_TIMEOUT_MS = DEFAULT_LLM_IDLE_TIMEOUT_MS;
const LOCAL_LLM_FIRST_EVENT_TIMEOUT_MS = 3e5;
const CRON_LLM_IDLE_TIMEOUT_MS = 6e4;
const LOCAL_PROVIDER_AUTH_MARKERS = /* @__PURE__ */ new Set(["custom-local", "ollama-local"]);
const SELF_HOSTED_PROVIDER_ID_PREFIXES = [
"ollama",
"lmstudio",
"vllm",
"sglang",
"llama-cpp"
];
const EXPLICIT_LOCAL_HOSTNAMES = /* @__PURE__ */ new Set([
"docker.orb.internal",
"host.docker.internal",
"host.orb.internal"
]);
/**
* Local endpoints can stay silent during prompt evaluation. Classify the URL
* hostname without DNS on this hot path. IPv4-mapped IPv6 deliberately covers
* loopback only, matching the cron model preflight policy.
*/
function isLocalProviderHostname(e) {
let t = e;
if (t.startsWith("[") && t.endsWith("]")) t = t.slice(1, -1);
if (t === "localhost" || t === "0.0.0.0" || isLoopbackIpAddress(t) || t.endsWith(".local")) return true;
if (/^f[cd][0-9a-f]{2}:/.test(t) || /^fe[89ab][0-9a-f]:/.test(t)) return true;
if (!/^\d+\.\d+\.\d+\.\d+$/.test(t)) return false;
const n = t.split(".").map((e) => Number.parseInt(e, 10));
if (n.some((e) => !Number.isInteger(e) || e < 0 || e > 255)) return false;
const [r, i] = n;
return r === 10 || r === 172 && i !== void 0 && i >= 16 && i <= 31 || r === 192 && i === 168 || r === 100 && i !== void 0 && i >= 64 && i <= 127;
}
function isBareProviderHostname(e) {
return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(e);
}
function isSelfHostedProviderId(e) {
const t = e?.trim().toLowerCase();
if (!t || t === "ollama-cloud") return false;
return SELF_HOSTED_PROVIDER_ID_PREFIXES.some((e) => t === e || t.startsWith(`${e}-`));
}
function findConfiguredProviderConfig(e, t) {
const n = t?.trim().toLowerCase();
if (!n) return;
const r = e?.models?.providers;
return r?.[n] || findNormalizedProviderValue(r, n);
}
function hasLocalProviderAuthMarker(e) {
return typeof e === "string" && LOCAL_PROVIDER_AUTH_MARKERS.has(e.trim().toLowerCase());
}
/**
* Classifies the model endpoint locality shared by the idle and first-event
* watchdogs. Explicit remote providers and Ollama `*:cloud` models retain
* hosted timing behind local relays, including those managed by localService.
*/
function resolveRuntimeModelLocality(e) {
const t = findConfiguredProviderConfig(e?.cfg, e?.model?.provider);
if (t?.remote === true) return {
isLocalRuntimeModel: false,
isSelfHostedRuntimeModel: false
};
const n = e?.model?.baseUrl;
const r = typeof n === "string" ? URL.parse(n)?.hostname.toLowerCase() : void 0;
const i = !isCloudModelRef(e?.model?.id);
return {
isLocalRuntimeModel: Boolean(r && isLocalProviderHostname(r) && i),
isSelfHostedRuntimeModel: i && (isSelfHostedProviderId(e?.model?.provider) || Boolean(r && (EXPLICIT_LOCAL_HOSTNAMES.has(r) || isBareProviderHostname(r) && (t?.localService || hasLocalProviderAuthMarker(t?.apiKey)))))
};
}
function resolveLlmTimeoutBounds(e) {
const t = asPositiveFiniteNumber(e?.runTimeoutMs);
const n = finiteSecondsToTimerSafeMilliseconds(e?.cfg?.agents?.defaults?.timeoutSeconds);
const r = t !== void 0;
const i = r && t < 2147e6 ? t : void 0;
return {
boundedRunTimeoutMs: i,
agentTimeoutMs: n,
timeoutBounds: [i, r ? void 0 : n].filter((e) => e !== void 0 && e < 2147e6)
};
}
const clampTimeoutMs = (e) => clampTimerTimeoutMs(e) ?? 1;
function resolveLlmTimeoutMs(e, t) {
const { boundedRunTimeoutMs: n, agentTimeoutMs: r, timeoutBounds: i } = resolveLlmTimeoutBounds(t);
const { isLocalRuntimeModel: a, isSelfHostedRuntimeModel: o } = resolveRuntimeModelLocality(t);
const s = asPositiveFiniteNumber(t?.modelRequestTimeoutMs);
if (s !== void 0) return clampTimeoutMs(Math.min(s, ...i));
if (e === "first-event") return clampTimeoutMs(Math.min(a || o ? LOCAL_LLM_FIRST_EVENT_TIMEOUT_MS : CLOUD_LLM_FIRST_EVENT_TIMEOUT_MS, ...i));
const c = o ? SELF_HOSTED_LLM_IDLE_TIMEOUT_MS : DEFAULT_LLM_IDLE_TIMEOUT_MS;
const l = n ?? r;
if (l === void 0) return a ? 0 : c;
const u = n !== void 0 && t?.trigger === "cron";
if (a || u && o) return clampTimeoutMs(l);
return clampTimeoutMs(Math.min(l, u ? CRON_LLM_IDLE_TIMEOUT_MS : c));
}
function resolveLlmIdleTimeoutMs(e) {
return resolveLlmTimeoutMs("idle", e);
}
function resolveLlmFirstEventTimeoutMs(e) {
return resolveLlmTimeoutMs("first-event", e);
}
/**
* Wraps a stream function with idle timeout detection for both stream creation
* and iterator progress. Each successful `next()` resets the timer; a timeout
* aborts the provider request and surfaces the same Error to the caller.
* Creation ends at provider acceptance or stream activity, not when a producer
* returns its stream object. `scope: "creation-only"` leaves local providers
* free of gap policing after that boundary.
*
* When `runId` is provided, run-scoped tool activity can reset the active wait
* and recent activity before stream creation bridges into the first wait.
*/
function streamWithIdleTimeout(e, t, n, r) {
const i = r?.scope !== "creation-only";
const a = r?.runId;
return (o, s, c) => {
let l = clampTimeoutMs(t * 2);
const u = captureAsyncWorkTracker();
const d = new AbortController();
const f = clampTimeoutMs(getFirstStreamEventTimeoutMs(c) ?? t);
let p = Date.now() + f;
const m = r?.watchdogAttempt?.beginRequest({ get deadlineAtMs() {
return p === void 0 ? void 0 : p + SESSION_WATCHDOG_WARNING_MS;
} });
const startTimer = (e, r, i = t, a = "no response from model", o = "LlmIdleTimeoutError") => {
return setTimeout(() => {
m?.(Date.now() + SESSION_WATCHDOG_WARNING_MS);
if (h?.reject === r) _ = true;
clearRequestDeadline();
const e = Object.assign(/* @__PURE__ */ new Error(`LLM idle timeout (${Math.floor(i / 1e3)}s): ${a}`), { name: o });
d.abort(e);
n?.(e);
r(e);
}, e).unref();
};
let h;
let g = false;
let _ = false;
let v = new Promise((e, t) => {
h = {
timer: startTimer(f, t, f),
reject: t,
accepted: false
};
});
v.catch(() => {});
const clearRequestDeadline = () => {
clearTimeout(h?.timer);
h = void 0;
if (!g) p = void 0;
if (!_) v = void 0;
b();
};
const finishCreation = () => {
if (!h || h.accepted) return;
h.accepted = true;
b();
if (i && !g) {
p = Date.now() + t;
if (f === t) h.timer.refresh();
else {
clearTimeout(h.timer);
h.timer = startTimer(t, h.reject);
}
} else clearRequestDeadline();
};
let y = false;
const recordActivity = (e) => {
y = true;
if (e !== void 0) l = clampTimeoutMs(Math.max(t, e));
};
const b = onLlmRequestActivity(d.signal, (e, t) => {
recordActivity(t);
finishCreation();
});
const x = c?.signal;
const abortFromSourceSignal = () => {
clearRequestDeadline();
d.abort(x?.reason);
};
if (x?.aborted) abortFromSourceSignal();
else x?.addEventListener("abort", abortFromSourceSignal, { once: true });
const cleanupSourceSignal = () => {
m?.(Date.now() + SESSION_WATCHDOG_WARNING_MS);
clearRequestDeadline();
x?.removeEventListener("abort", abortFromSourceSignal);
};
const withSourceAbort = (e) => x ? abortable(x, e) : e;
const withRequestTimeout = (e) => v ? Promise.race([e, v]) : e;
let S;
try {
S = e(o, s, withProviderAcceptanceObserver({
...c,
signal: d.signal
}, finishCreation));
} catch (e) {
cleanupSourceSignal();
throw e;
}
const wrapStream = (e) => {
const n = getEventStreamCompletion(e);
n?.then(cleanupSourceSignal, cleanupSourceSignal);
const r = e[Symbol.asyncIterator].bind(e);
e[Symbol.asyncIterator] = function() {
const e = r();
let o;
const returnIterator = (t) => {
o ??= u(() => Promise.resolve().then(() => e.return?.(t) ?? {
done: true,
value: void 0
}));
o.catch(() => recordAgentCleanupFailure());
return o;
};
let s;
let c = 0;
let f;
let m = 0;
let _ = 0;
let v = performance.now();
let b = Date.now();
let S;
const C = /* @__PURE__ */ new Set();
const abortIteration = () => {
if (x) for (const e of C) e(createAbortableError(x));
};
x?.addEventListener("abort", abortIteration, { once: true });
let w = false;
let T = false;
const clearTimers = () => {
clearTimeout(s);
clearTimeout(f);
s = f = void 0;
p = void 0;
};
const rejectTimeout = (e) => {
clearTimers();
S?.(e);
};
const armTimer = (e = false) => {
if (!i || T || !n && !S) {
clearTimers();
return;
}
const r = performance.now();
let o = t;
if (!w) {
const e = a ? getLastToolActivityMs(a) : 0;
if (e > 0 && r - e < t) o = Math.max(1, t - Math.max(0, r - e));
w = true;
}
if (s && c === o) s.refresh();
else {
clearTimeout(s);
s = startTimer(o, rejectTimeout);
c = o;
}
g = true;
if (h?.accepted) clearRequestDeadline();
if (e) {
v = r;
b = Date.now();
}
p = Math.min(Date.now() + o, b + l);
if (e && f && m === l && _ === l) f.refresh();
else if (e || !f || _ !== l) {
clearTimeout(f);
_ = l;
m = Math.max(1, l - (r - v));
f = startTimer(m, rejectTimeout, l, "no model progress", "LlmNoProgressError");
}
};
const E = onLlmRequestActivity(d.signal, (e, t) => {
recordActivity(t);
armTimer(e);
if (e && a && areDiagnosticsEnabledForProcess()) markDiagnosticRunProgress({
runId: a,
reason: "model_call:stream_progress"
});
});
const D = a ? onToolActivity(a, armTimer) : void 0;
const settle = () => {
if (T) return;
T = true;
S = void 0;
clearTimers();
E();
D?.();
cleanupSourceSignal();
};
n?.then(settle, settle);
let O = false;
const releaseAbortListener = () => {
if (O && C.size === 0) x?.removeEventListener("abort", abortIteration);
};
const finishIterator = () => {
settle();
O = true;
releaseAbortListener();
};
return createStreamIteratorWrapper({
iterator: e,
next: async (e) => {
let t;
let n;
try {
const r = new Promise((r, i) => {
S = i;
n = i;
if (x) C.add(i);
armTimer(false);
t = e.next();
t.then(r, i);
if (x?.aborted) i(createAbortableError(x));
});
const i = await withRequestTimeout(r);
finishCreation();
if (i.done) {
finishIterator();
return i;
}
S = void 0;
armTimer(!y);
return i;
} catch (e) {
finishIterator();
u(() => Promise.allSettled([t, returnIterator()])).catch(() => recordAgentCleanupFailure());
throw x ? toErrorObject(e, "Non-Error rejection") : e;
} finally {
if (n) C.delete(n);
releaseAbortListener();
}
},
onReturn(e, t) {
finishIterator();
return returnIterator(t);
},
onThrow(e, t) {
finishIterator();
return e.throw?.(t) ?? Promise.reject(toErrorObject(t, "Non-Error rejection"));
}
});
};
return e;
};
if (S && typeof S === "object" && "then" in S) {
const e = Promise.resolve(S);
return withSourceAbort(withRequestTimeout(e)).then(wrapStream, (t) => {
cleanupSourceSignal();
u(async () => {
const t = await e.catch(() => void 0);
if (t) await t[Symbol.asyncIterator]().return?.();
}).catch(() => recordAgentCleanupFailure());
throw t;
});
}
return wrapStream(S);
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-stream.ts
function wrapStreamFnWithCompactionReplayRepair(e, t) {
return async (n, r, i) => {
const a = captureAsyncWorkTracker();
const o = [];
const joinRepairs = async () => {
let e = 0;
while (e !== o.length) {
e = o.length;
const t = (await Promise.allSettled(o)).find((e) => e.status === "rejected");
if (t?.status === "rejected") throw t.reason;
}
};
const s = i;
const c = {
...i,
onCompactionRejected: (e) => {
const n = a(() => t(e));
o.push(n);
n.catch(() => {});
s?.onCompactionRejected?.(e);
}
};
let l;
try {
l = await e(n, r, c);
} catch (e) {
await joinRepairs();
throw e;
}
return wrapStreamObjectSettlement(l, joinRepairs, () => o.length > 0);
};
}
function installEmbeddedAttemptStreamGuards(e, t) {
const { attempt: n } = e;
const { agentSession: { activeSession: r }, anthropicPayloadLogger: i, cacheTrace: a, contextGuards: o, isOpenAIResponsesApi: s, sessionManager: c, state: { systemPromptText: l }, transcriptPolicy: u, transport: { compactionReplayEnabled: d, effectiveAgentTransport: f, effectivePromptCacheRetention: p, streamStrategy: m, providerTextTransforms: h } } = e.prepared.sessionRuntime;
setInternalRepetitionGuard(r.agent, isSmallModel);
const { liveAllowedToolNames: g, replayAllowedToolNames: _ } = e.prepared.toolCatalog.toolSearchRunPlan;
const installStreamWrapper = (e, ...t) => {
r.agent.streamFn = e(r.agent.streamFn, ...t);
};
const { sessionAgentId: v } = e.setup;
const { signal: y } = e.runAbortController;
const b = readRunOperatorAuthority(n);
if (b) {
const e = r.agent.streamFn;
r.agent.streamFn = (t, r, i) => {
assertOperatorModelAllowed(b, {
provider: n.provider,
model: n.modelId
});
return e(t, r, i);
};
}
const repairRejectedReplay = async (e, i) => {
try {
const a = {
sessionManager: c,
sessionFile: n.sessionFile,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
agentId: v
};
await withSessionManagerWrite(c, async () => {
y.throwIfAborted();
let n;
if (e === "compaction") {
if (!i) {
log$2.warn(`[session-recovery] unable to repair rejected compaction replay: checkpoint identity unavailable sessionId=${r.sessionId}`);
return;
}
n = await repairRejectedCompactionReplayInSessionManager({
...a,
checkpoint: i
});
} else n = await repairRejectedThinkingReplayInSessionManager(a);
if (n.repaired) {
t.onRejectedProviderReplayRepaired();
return;
}
log$2.warn(`[session-recovery] provider rejected ${e} replay but transcript repair made no changes: sessionId=${r.sessionId} reason=${n.reason ?? "unknown"}`);
});
} catch (t) {
log$2.warn(`[session-recovery] unable to repair rejected ${e} replay: sessionId=${r.sessionId} error=${String(t)}`);
}
};
const x = getProviderPromptState(n.runId);
const S = `trigger=${n.trigger ?? "unknown"} provenance=${n.inputProvenance?.kind ?? "none"}${n.inputProvenance?.sourceTool ? `:${n.inputProvenance.sourceTool}` : ""} replyMode=${n.sourceReplyDeliveryMode ?? "unset"} senderIsOwner=${n.senderIsOwner ?? "unset"}`;
const C = createPromptCacheRequestObserver({
turn: S,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
promptCacheKey: n.promptCacheKey,
cacheRetention: p,
streamStrategy: m,
transport: f,
getSystemPromptSeries: () => e.prepared.sessionRuntime.state.systemPromptSeries
}, (e, t) => {
if (e.broke) {
const r = e.changes?.map((e) => `${e.code}(${e.detail})`).join(", ") ?? e.dropCause;
log$2[e.dropCause?.startsWith("unattributed:") ? "debug" : "warn"](`[prompt-cache] cache read dropped ${e.previousCacheRead} -> ${e.cacheRead} runId=${n.runId} request=${e.requestIndex} for ${t.provider}/${t.modelId} via ${m}; ${r}; requestGapMs=${e.requestGapMs ?? "unknown"} promptTokens=${e.promptTokens ?? "unknown"} responseId=${e.responseId ?? "unknown"} sessionId=${n.sessionId} ${S} ` + (e.systemPromptSeries ? `systemPromptSeries=${e.systemPromptSeries} ` : "") + `providerPrefix=${e.providerPrefix ?? "unavailable"} requests=${JSON.stringify(e.requests)}`);
}
a?.recordStage("cache:result", { options: { ...e } });
}, (e) => {
a?.recordStage("cache:state", { options: {
...e,
previousCacheRead: e.previousCacheRead ?? void 0
} });
});
if (a) {
a.recordStage("session:loaded", {
messages: r.messages,
system: l,
note: "after session create"
});
r.agent.streamFn = a.wrapStreamFn(r.agent.streamFn);
}
if (u.dropThinkingBlocks || u.dropReasoningFromHistory) installStreamWrapper(wrapStreamFnWithMessageTransform, (e) => {
const t = u.dropReasoningFromHistory ? dropReasoningFromHistory(e) : e;
return u.dropThinkingBlocks ? dropThinkingBlocks(t) : t;
});
if (u.preserveSignatures || u.dropThinkingBlocks || u.dropReasoningFromHistory) installStreamWrapper(wrapAnthropicStreamWithRecovery, {
id: r.sessionId,
onRecoveredAnthropicThinking: () => repairRejectedReplay("thinking")
});
const w = {
sanitizeToolCallIds: u.sanitizeToolCallIds,
toolCallIdMode: u.toolCallIdMode,
isOpenAIResponsesApi: s
};
let normalizeToolCallIds;
if (shouldApplyReplayToolCallIdSanitizer(w)) {
const e = w.toolCallIdMode;
normalizeToolCallIds = (t, r) => sanitizeReplayToolCallIdsForStream({
messages: t,
mode: e,
allowedToolNames: _,
preserveNativeAnthropicToolUseIds: u.preserveNativeAnthropicToolUseIds,
duplicateToolCallIdStyle: u.duplicateToolCallIdStyle,
preserveReplaySafeThinkingToolCallIds: shouldAllowProviderOwnedThinkingReplay({
modelApi: r.api,
provider: n.provider,
policy: u
}),
repairToolUseResultPairing: u.repairToolUseResultPairing
});
}
if (s || d) installStreamWrapper(wrapStreamFnWithCompactionReplayRepair, (e) => repairRejectedReplay("compaction", e));
const T = r.agent.streamFn;
r.agent.streamFn = (t, n, r) => {
if (e.lifecycle.readYieldState().yieldDetected && y.aborted && isSessionsYieldAbortReason(y.reason)) return createYieldAbortedResponse(t);
return T(t, n, r);
};
installStreamWrapper(wrapStreamFnSanitizeMalformedToolCalls, _, u, n.provider);
installStreamWrapper(wrapStreamFnPromoteStandaloneTextToolCalls, g);
installStreamWrapper(wrapStreamFnTrimToolCallNames, g, { unknownToolThreshold: 10 });
if (shouldRepairMalformedToolCallArguments({
provider: n.provider,
modelApi: n.model.api
})) installStreamWrapper(wrapStreamFnRepairMalformedToolCallArguments);
if (resolveToolCallArgumentsEncoding(n.model) === "html-entities") installStreamWrapper(createHtmlEntityToolCallArgumentDecodingWrapper);
if (h?.output?.length) r.agent.streamFn = wrapStreamFnTextTransforms({
streamFn: r.agent.streamFn,
output: h.output
});
if (i) r.agent.streamFn = i.wrapStreamFn(r.agent.streamFn);
installStreamWrapper(wrapStreamFnHandleSensitiveStopReason);
const E = resolveAgentTimeoutMs({ cfg: n.config });
const D = n.runTimeoutOverrideMs ?? (n.timeoutMs !== E ? n.timeoutMs : void 0);
const O = {
cfg: n.config,
runTimeoutMs: D,
modelRequestTimeoutMs: n.model.requestTimeoutMs,
model: {
baseUrl: n.model.baseUrl,
id: n.modelId,
provider: n.provider
}
};
const k = resolveLlmIdleTimeoutMs({
...O,
trigger: n.trigger
});
const A = resolveLlmFirstEventTimeoutMs(O);
if (k > 0 || A > 0) installStreamWrapper(streamWithIdleTimeout, k > 0 ? k : A, (e) => t.onIdleTimeout(e), {
runId: n.runId,
watchdogAttempt: t.diagnosticOwner.watchdogAttempt,
scope: k > 0 ? "creation-and-gaps" : "creation-only"
});
if (A > 0) {
const e = r.agent.streamFn;
r.agent.streamFn = (n, r, i) => {
const a = i;
return e(n, r, {
...i,
firstEventTimeoutMs: a?.firstEventTimeoutMs ?? A,
onFirstEventTimeout: a?.onFirstEventTimeout ?? t.onIdleTimeout
});
};
}
const j = n.modelCallSequence ??= { value: 0 };
const M = j.value + 1;
let N = false;
let P;
installStreamWrapper(wrapStreamFnWithDiagnosticModelCallEvents, {
config: n.config,
runId: n.runId,
agentId: v,
priority: resolveModelCallUrgency(n) === "foreground" ? "interactive" : "background",
...n.sessionKey && { sessionKey: n.sessionKey },
...n.sessionId && { sessionId: n.sessionId },
provider: n.provider,
model: n.modelId,
api: n.model.api,
transport: f,
requestTimeoutMs: k || Math.min(n.timeoutMs, 18e5),
...n.contextWindowInfo?.tokens ? { contextTokenBudget: n.contextWindowInfo.tokens } : {},
...n.contextWindowInfo?.source ? { contextWindowSource: n.contextWindowInfo.source } : {},
...n.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: n.contextWindowInfo.referenceTokens } : {},
trace: e.diagnostics.runTrace,
contentCapture: resolveDiagnosticModelContentCapturePolicy(n.config),
nextCallId: () => `${n.runId}:model:${j.value += 1}`,
ownerGeneration: t.diagnosticOwner.generation,
diagnosticOwner: t.diagnosticOwner,
onAgentEvent: n.onAgentEvent,
onSucceeded: o.recordCacheTouch,
onTerminal: () => {
N = true;
},
onFinished: (e) => {
if (P === e) P = void 0;
},
onStarted: (t) => {
P = t;
N = false;
if (j.value === M) {
e.setup.prepStages.mark("model-dispatch");
e.setup.emitPrepStageSummary("model-dispatch");
}
n.onExecutionPhase?.({
phase: "model_call_started",
provider: n.provider,
model: n.modelId,
firstModelCallStarted: true
});
},
suppressPluginHooks: n.operation === "settled-tool-finalization"
});
return {
normalizeToolCallIds,
/** Returns the measured predecessor that may anchor this exact request's pressure. */
onModelRequest: async (...n) => {
const r = C.getContextUsage();
const i = await C.onModelRequest(...n);
const a = r?.requestIndex === i.requestIndex - 1 && i.prefixUnchanged && (i.changes ?? []).every(({ code: e }) => e === "pruning" || e === "aggregateToolResultTruncation") ? r : void 0;
if (e.activeContextEngine?.info.ownsCompaction || i.requestIndex > 1) o.checkMidTurnPrecheck({
context: n[1],
previousRequest: a,
boundarySafe: t.isToolBoundarySafe
});
if (n[0].api === "openai-completions") measuredRequestPressure.set(n[0], n[1], a && a.contextTokens > 0 ? estimateProjectedRequestTokenPressure({
context: n[1],
previousRequest: a
}).estimatedPromptTokens : void 0);
return a;
},
onModelUsage: (e, t) => {
if (N) {
N = false;
C.onModelUsage(e, x.lastAttempt, t);
}
},
getPromptCacheObservation: C.getObservation,
isModelCallActive: () => P !== void 0
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-timeout-prepare.ts
/** Owns the execution deadline, approval pauses, and one compaction grace. */
function prepareEmbeddedAttemptTimeout(e) {
const { activeSession: t, attempt: n, runAbortSignal: r } = e;
let i = { kind: "unlimited" };
let a;
let o;
const s = createChangeListeners();
const c = observeAgentRunApprovalWait(n);
const clearTimers = () => {
i = { kind: "closed" };
c.dispose();
r.removeEventListener("abort", clearTimers);
clearTimeout(a);
clearTimeout(o);
s.publish();
s.clear();
};
const l = {
getRunAbortDeadlineAtMs: () => i.kind === "bounded" ? i.deadlineAtMs : void 0,
onRunAbortDeadlineChanged: s.subscribe,
clearTimers
};
if (r.aborted) {
clearTimers();
return l;
}
r.addEventListener("abort", clearTimers, { once: true });
const scheduleAbortTimer = (r, c) => {
const l = monotonicNow() + Math.max(1, r);
const u = {
kind: "bounded",
deadlineAtMs: Date.now() + Math.max(1, r),
monotonicDeadlineMs: l,
compactionGraceUsed: c
};
i = u;
a = setTimeout(() => {
if (i !== u) return;
const r = {
isCompactionPendingOrRetrying: e.compactionState.isCompacting(),
isCompactionInFlight: t.isCompacting
};
if (resolveRunTimeoutDuringCompaction({
...r,
graceAlreadyUsed: u.compactionGraceUsed
}) === "extend") {
if (!e.isProbeSession) log$2.warn(`embedded run timeout reached during compaction; extending deadline: runId=${n.runId} sessionId=${n.sessionId} extraMs=${e.compactionTimeoutMs}`);
scheduleAbortTimer(e.compactionTimeoutMs, true);
return;
}
clearTimers();
o = setTimeout(() => {
if (t.isStreaming && !e.isProbeSession) log$2.warn(`embedded run abort still streaming: runId=${n.runId} sessionId=${n.sessionId}`);
}, 1e4);
if (!e.isProbeSession) log$2.warn(u.compactionGraceUsed ? `embedded run timeout after compaction grace: runId=${n.runId} sessionId=${n.sessionId} timeoutMs=${n.timeoutMs} compactionGraceMs=${e.compactionTimeoutMs}` : `embedded run timeout: runId=${n.runId} sessionId=${n.sessionId} timeoutMs=${n.timeoutMs}`);
if (shouldFlagCompactionTimeout({
isTimeout: true,
...r
})) e.markTimedOutDuringCompaction();
e.markTimedOutByRunBudget();
e.abortRun(true);
}, Math.max(1, r));
n.onAttemptDeadlineChanged?.({
kind: "bounded",
deadlineAtMs: u.deadlineAtMs
});
s.publish();
};
c.onChange = (e) => {
if (e && i.kind === "bounded") {
i = {
kind: "paused",
remainingMs: Math.max(1, i.monotonicDeadlineMs - monotonicNow()),
compactionGraceUsed: i.compactionGraceUsed
};
clearTimeout(a);
n.onAttemptDeadlineChanged?.({ kind: "unlimited" });
s.publish();
} else if (!e && i.kind === "paused") scheduleAbortTimer(i.remainingMs, i.compactionGraceUsed);
};
if (n.timeoutMs >= 2147e6) n.onAttemptDeadlineChanged?.({ kind: "unlimited" });
else scheduleAbortTimer(n.timeoutMs, false);
if (!r.aborted) n.onAttemptTimeoutArmed?.();
return l;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-execution-phase.ts
async function runEmbeddedAttemptExecutionPhase(e) {
const { attempt: t, state: n } = e;
const { sessionRuntime: r, systemPrompt: i, toolBase: a } = e.prepared;
const { agentSession: { activeSession: o, replaySafeTools: s }, settleTracker: { abortActiveSession: c, trackPromptSettlePromise: l } } = r;
const u = resolveAdmittedRunActiveAssertion(t.admittedRunContext, e.runAbortController.signal);
if (!u) {
e.runAbortController.signal.throwIfAborted();
throw new Error("embedded attempt requires an active admitted run");
}
o[agentSessionSetContextReplacementHook]((e) => {
declarePromptHistoryRewrite({
...t,
reason: "compaction"
});
a.skillInstructionDeliveryCache.clear();
t.onContextAccountingEvent?.({
kind: "compaction",
tokensAfter: e
});
}, u);
let d = false;
const f = createDiagnosticEmbeddedRunOwner({
sessionId: t.sessionId,
sessionKey: t.sessionKey,
runId: t.runId,
watchdogAttempt: getGatewayToolCallerIdentity()?.watchdogAttempt
});
const mergeTerminal = (e) => {
n.terminal = mergeAgentRunAttemptTerminal(n.terminal, e);
};
const p = {};
const m = {};
const { normalizeToolCallIds: h, onModelRequest: g, onModelUsage: _, getPromptCacheObservation: v, isModelCallActive: y } = installEmbeddedAttemptStreamGuards(e, {
onRejectedProviderReplayRepaired: () => {
d = true;
},
onIdleTimeout: (e) => {
if (!o.isCompacting) p.current?.(e);
},
diagnosticOwner: f,
isToolBoundarySafe: () => m.current?.() ?? false
});
e.setup.prepStages.mark("stream-setup");
e.setup.emitPrepStageSummary("stream-ready");
let b;
try {
b = await withOwnedSessionTranscriptWrites(e.sessionLock.ownedTranscriptWriteContext, () => prepareEmbeddedAttemptHistory(e, u));
} catch (e) {
await cleanupEmbeddedAttemptResources({
flushPendingToolResultsAfterIdle,
session: o,
sessionManager: r.sessionManager,
aborted: t.abortSignal?.aborted,
abortSignal: t.abortSignal
});
throw e;
}
const x = t.sessionId?.startsWith("probe-") ?? false;
const S = {};
const C = createEmbeddedAttemptRunAbort({
abortActiveSession: c,
activeSession: o,
attempt: t,
getQueueHandle: () => S.current,
isProbeSession: x,
log: log$2,
runAbortController: e.runAbortController,
state: e.state
});
e.externalAbortController.setRunAbort(C);
const w = createEmbeddedAttemptIdleInterruption({
runAbortController: e.runAbortController,
activeSession: o,
state: n,
abortRun: C
});
p.current = w;
const abortable$1 = (t) => abortable(e.runAbortController.signal, t);
const promptActiveSession = (t, n) => withOwnedSessionTranscriptWrites(e.sessionLock.ownedTranscriptWriteContext, async () => {
if (e.runAbortController.signal.aborted) return abortable$1(Promise.resolve());
const runPrompt = () => o.prompt(t, n);
return abortable$1(l(e.sessionLock.assertCronRootCurrent ? withGuardedFetchRequestAuthority(e.sessionLock.assertCronRootCurrent, runPrompt) : runPrompt()));
});
const bindTranscriptCallback = (t) => t ? bindOwnedSessionTranscriptWrites(e.sessionLock.ownedTranscriptWriteContext, t) : void 0;
const T = bindTranscriptCallback(t.onBlockReply);
const E = bindTranscriptCallback(t.onBlockReplyFlush);
const D = prepareEmbeddedAttemptStream({
attempt: t,
agentSession: r.agentSession,
projectSessionForkMessages: (e) => replayToolResultPromptProjections(e, r.toolResultPromptProjectionState),
readSessionForkBoundary: () => ({
timezone: r.boundary.boundaryTimezone,
includeTimestamp: r.boundary.includeBoundaryTimestamp,
projectPersistedSenderContext: r.boundary.includeBoundaryTimestamp,
userTranscriptContexts: r.boundary.getUserTranscriptContexts?.(),
appendOnlyRuntimeContext: r.transcriptPolicy.appendOnlyRuntimeContext,
inHistorySystemUpdates: r.transcriptPolicy.inHistorySystemUpdates
}),
onModelUsage: _,
applyPermissionMode: e.lifecycle.applyPermissionMode,
runAbortController: e.runAbortController,
abortRun: C,
markExternalAbort: () => mergeTerminal({
kind: "aborted",
source: "external"
}),
recoverStalledModelCall: () => y() && w(Object.assign(/* @__PURE__ */ new Error("LLM idle timeout (diagnostic stuck recovery): no response from model"), { code: "OPENCLAW_SESSION_WATCHDOG" })),
getRunState: () => {
const t = projectAgentRunAttemptTerminal(n.terminal);
return {
aborted: t.aborted,
promptError: t.promptError,
timedOut: t.timedOut,
yieldDetected: e.lifecycle.readYieldState().yieldDetected
};
},
onBlockReply: T,
onBlockReplyFlush: E,
runtimeChannel: i.runtimeChannel,
hookAgentId: e.setup.sessionAgentId,
diagnosticTrace: e.diagnostics.diagnosticTrace,
nestedToolActivityState: a.nestedToolActivityState,
isReplaySafeTool: (e) => s.has(e),
diagnosticOwner: f,
trajectoryRecorder: r.trajectoryRecorder
});
n.deferredLifecycleOwner = D.deferredLifecycleOwner;
m.current = () => isToolBatchBoundarySafe({
pendingToolCalls: o.agent.state.pendingToolCalls.size,
itemLifecycle: D.subscription.getItemLifecycle(),
asyncActivity: hasAsyncActivity(D.subscription.toolMetas),
parkedCodeModeRun: D.subscription.toolMetas.some((e) => e.codeModeSuspended === true),
approvalPromptSent: D.subscription.didSendDeterministicApprovalPrompt()
});
e.lifecycle.setToolSearchCatalogExecutor(D.toolSearchCatalogExecutor);
e.externalAbortController.setCompactionState({
isPendingOrRetrying: D.subscription.isCompacting,
isInFlight: () => o.isCompacting
});
S.current = D.queueHandle;
const O = prepareEmbeddedAttemptTimeout({
attempt: t,
activeSession: o,
runAbortSignal: e.runAbortController.signal,
compactionState: D.subscription,
compactionTimeoutMs: e.sessionLock.compactionTimeoutMs,
isProbeSession: x,
abortRun: C,
markTimedOutDuringCompaction: () => mergeTerminal({
kind: "timeout",
phase: "compaction",
source: "observation"
}),
markTimedOutByRunBudget: () => mergeTerminal({
kind: "timeout",
phase: "prompt",
source: "run_budget"
})
});
a.bindRunAbortDeadline(O.getRunAbortDeadlineAtMs);
const k = {
abortable: abortable$1,
normalizeToolCallIds: h,
cache: {
onModelRequest: g,
getObservation: v
},
history: b,
isProbeSession: x,
isToolBoundarySafe: () => m.current?.() ?? false,
onBlockReplyFlush: E,
promptActiveSession,
stream: D,
timeout: O
};
return await runEmbeddedAttemptSettledPhase({
...e,
preparedStreamRuntime: k,
getRepairedRejectedProviderReplay: () => d
});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-preparation.ts
let nextPreparationStart = Promise.resolve();
const MAX_PREPARATION_STARTS_PER_SLICE = 16;
const PREPARATION_SLICE_MS = 8;
let preparationStarts = MAX_PREPARATION_STARTS_PER_SLICE;
let preparationSyncMs = 0;
/** Dispatches attempt stages without letting concurrent starts monopolize the event loop. */
function createEmbeddedAttemptPreparation(e) {
return async (t, n) => {
nextPreparationStart = nextPreparationStart.then(async () => {
if (preparationStarts >= MAX_PREPARATION_STARTS_PER_SLICE || preparationSyncMs >= PREPARATION_SLICE_MS) {
await setImmediate();
preparationStarts = 0;
preparationSyncMs = 0;
}
preparationStarts++;
});
await nextPreparationStart;
const r = performance$1.now();
try {
e.assertCurrent();
return measureEmbeddedAgentPreparation(t, n, { config: e.config });
} finally {
preparationSyncMs += performance$1.now() - r;
}
};
}
//#endregion
//#region src/agents/queued-file-writer.ts
/** Per-path ordered append writer for diagnostic logs. */
const log$1 = createSubsystemLogger("agents/diagnostic-writer");
/** Returns the cached writer for a path or creates a new ordered append queue. */
function getQueuedFileWriter(e, t) {
const n = e.get(t);
if (n) return n;
const r = path.dirname(t);
let i = false;
const reportFailure = (e) => {
if (!i) {
i = true;
log$1.warn("Diagnostic log write failed; check the configured log path", {
filePath: t,
error: e
});
}
};
let a = fs.mkdir(r, {
recursive: true,
mode: 448
}).catch(reportFailure);
const o = {
filePath: t,
write: (e) => {
a = a.then(() => appendRegularFile({
filePath: t,
content: e,
rejectSymlinkParents: true
})).catch(reportFailure);
return a;
}
};
e.set(t, o);
return o;
}
//#endregion
//#region src/agents/trace-base.ts
/** Build a trace base object while preserving undefined optional fields. */
function buildAgentTraceBase(e) {
return {
runId: e.runId,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
provider: e.provider,
modelId: e.modelId,
modelApi: e.modelApi,
workspaceDir: e.workspaceDir
};
}
//#endregion
//#region src/agents/anthropic-payload-log.ts
/**
* Optional Anthropic request/usage JSONL diagnostics.
* Redacts payload content before writing and stores digests for correlation
* without persisting raw secret-bearing request bodies.
*/
const writers$1 = /* @__PURE__ */ new Map();
const log = createSubsystemLogger("agent/anthropic-payload");
function formatError(e) {
const t = e instanceof Error ? e.message : typeof e === "string" ? e : void 0;
if (t !== void 0) return redactAgentDiagnosticPayload(t);
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint") return String(e);
if (e && typeof e === "object") return safeJsonStringify(redactAgentDiagnosticPayload(e)) ?? "unknown error";
}
function digest$1(e) {
const t = safeJsonStringify(e);
if (!t) return;
return crypto$1.createHash("sha256").update(t).digest("hex");
}
function findLastAssistantUsage(e) {
for (let t = e.length - 1; t >= 0; t -= 1) {
const n = e[t];
if (n?.role === "assistant") return n.usage;
}
return null;
}
function createAnthropicPayloadLogger(e) {
const t = e.env ?? process.env;
const n = parseBooleanValue(t.OPENCLAW_ANTHROPIC_PAYLOAD_LOG) ?? false;
const r = t.OPENCLAW_ANTHROPIC_PAYLOAD_LOG_FILE?.trim();
const i = r ? resolveUserPath(r) : path.join(resolveStateDir(t), "logs", "anthropic-payload.jsonl");
if (!n || isIncognitoSessionKey(e.sessionKey)) return null;
const a = getQueuedFileWriter(writers$1, i);
const o = buildAgentTraceBase(e);
const record = (e) => {
const t = safeJsonStringify(e);
if (!t) return;
a.write(`${t}\n`);
};
const wrapStreamFn = (e) => (t, n, r) => {
if (t?.api !== "anthropic-messages") return e(t, n, r);
const nextOnPayload = (e) => {
const n = redactAgentDiagnosticPayload(e);
record({
...o,
ts: (/* @__PURE__ */ new Date()).toISOString(),
stage: "request",
payload: n,
payloadDigest: digest$1(n)
});
return r?.onPayload?.(e, t);
};
return e(t, n, {
...r,
onPayload: nextOnPayload
});
};
const recordUsage = (t, n) => {
const r = findLastAssistantUsage(t);
const i = formatError(n);
if (!r && !i) return;
record({
...o,
ts: (/* @__PURE__ */ new Date()).toISOString(),
stage: "usage",
...r ? { usage: redactAgentDiagnosticPayload(r) } : {},
error: i
});
if (r) log.info("anthropic usage", {
runId: e.runId,
sessionId: e.sessionId,
usage: r
});
};
log.info("anthropic payload logger enabled", { filePath: a.filePath });
return {
wrapStreamFn,
recordUsage
};
}
//#endregion
//#region src/agents/cache-trace.ts
const writers = /* @__PURE__ */ new Map();
function digest(e) {
const t = stableStringify(e, sanitizeSurrogates);
return crypto$1.createHash("sha256").update(t).digest("hex");
}
function summarizeMessages(e) {
const t = e.map(digest);
return {
messageCount: e.length,
messageRoles: e.map((e) => e.role),
messageFingerprints: t,
messagesDigest: digest(t.join("|"))
};
}
function createCacheTrace(e) {
const t = process.env;
const n = parseBooleanValue(t.OPENCLAW_CACHE_TRACE) ?? e.cfg?.diagnostics?.cacheTrace?.enabled ?? false;
const r = t.OPENCLAW_CACHE_TRACE_FILE?.trim();
const i = r ? resolveUserPath(r) : path.join(resolveStateDir(t), "logs", "cache-trace.jsonl");
const a = parseBooleanValue(t.OPENCLAW_CACHE_TRACE_MESSAGES) ?? true;
const o = parseBooleanValue(t.OPENCLAW_CACHE_TRACE_PROMPT) ?? true;
const s = parseBooleanValue(t.OPENCLAW_CACHE_TRACE_SYSTEM) ?? true;
if (!n || isIncognitoSessionKey(e.sessionKey)) return null;
const c = getQueuedFileWriter(writers, i);
let l = 0;
const u = buildAgentTraceBase(e);
const recordStage = (e, t = {}) => {
const n = {
...u,
ts: (/* @__PURE__ */ new Date()).toISOString(),
seq: l += 1,
stage: e
};
if (t.prompt !== void 0 && o) n.prompt = redactAgentDiagnosticPayload(t.prompt);
if (t.system !== void 0 && s) {
n.system = redactAgentDiagnosticPayload(t.system);
n.systemDigest = digest(t.system);
}
if (t.options) n.options = redactAgentDiagnosticPayload(t.options);
if (t.model) n.model = redactAgentDiagnosticPayload(t.model);
const r = t.messages;
if (r) {
Object.assign(n, summarizeMessages(r));
if (a) n.messages = redactAgentDiagnosticPayload(r);
}
if (t.note) n.note = redactAgentDiagnosticPayload(t.note);
if (t.error) n.error = redactAgentDiagnosticPayload(t.error);
const i = safeJsonStringify(n);
if (!i) return;
c.write(`${i}\n`);
};
const wrapStreamFn = (e) => (t, n, r) => {
const i = n;
recordStage("stream:context", {
model: {
id: t?.id,
provider: t?.provider,
api: t?.api
},
system: i.systemPrompt ?? i.system,
messages: i.messages ?? [],
options: r ?? {}
});
return e(t, n, r);
};
return {
filePath: i,
recordStage,
wrapStreamFn
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-client-tools.ts
function prepareEmbeddedAttemptClientTools(e) {
const t = [];
const n = /* @__PURE__ */ new Map();
const clientToolCallSlotKey = (e) => `${getAgentToolAssistantTurnId() ?? ""}\u0000${e}`;
const reserveClientToolCallSlot = (e, r) => {
const i = clientToolCallSlotKey(e);
let a = n.get(i);
if (!a) {
a = {
toolCallId: e,
name: r,
completed: false
};
n.set(i, a);
t.push(a);
}
return a;
};
const r = resolveToolLoopDetectionConfig({
cfg: e.attempt.config,
agentId: e.sessionAgentId
});
const i = e.clientTools ? toClientToolDefinitions(e.clientTools, {
reserve: reserveClientToolCallSlot,
complete: (e, t, n) => {
const r = reserveClientToolCallSlot(e, t);
r.name = t;
r.params = n;
r.completed = true;
},
discard: (e) => {
const t = n.get(clientToolCallSlotKey(e));
if (t) {
t.completed = false;
t.params = void 0;
}
}
}, {
agentId: e.sessionAgentId,
sessionKey: e.sandboxSessionKey,
config: e.toolSearchRuntimeConfig,
sessionId: e.attempt.sessionId,
runId: e.attempt.runId,
loopDetection: r,
onToolOutcome: e.attempt.onToolOutcome,
allocateToolOutcomeOrdinal: e.attempt.allocateToolOutcomeOrdinal
}) : [];
const buildSurface = () => {
const n = e.pinTools?.(e.effectiveTools) ?? e.effectiveTools;
const r = /* @__PURE__ */ new Set();
const a = /* @__PURE__ */ new Set();
for (const t of e.uncompactedEffectiveTools) {
const e = (t.name ?? "").trim();
if (!e) continue;
r.add(e);
const n = getPluginToolMeta(t);
if (n?.trustedLocalMedia === true || !n && isCoreToolResultMediaTrustedName(e)) a.add(e);
}
const o = collectRegisteredToolNames(e.uncompactedEffectiveTools.filter((e) => !getPluginToolMeta(e)));
const isReplaySafeTool = (t) => isAgentToolReplaySafe(t, e.replaySafetyOptions);
const s = new Set(e.uncompactedEffectiveTools.filter(isReplaySafeTool));
const c = collectReplaySafeToolNames(e.uncompactedEffectiveTools, e.replaySafetyOptions);
const l = new Set(n.filter((e) => isCodeModeExecTool(e)).map((e) => e.name));
const u = new Set(e.uncompactedEffectiveTools.filter((e) => "canDeliverSourceReply" in e && e.canDeliverSourceReply === true).map((e) => normalizeToolPolicyName(e.name ?? "")).filter((e) => e.length > 0));
const d = e.deferredDirectoryToolsCallable ? r : o;
const f = findClientToolNameConflicts({
tools: e.clientTools ?? [],
existingToolNames: [...d, ...AGENT_RESERVED_TOOL_NAMES]
});
if (f.length > 0) throw new Error(`${CLIENT_TOOL_NAME_CONFLICT_PREFIX} ${f.join(", ")}`);
let p = i.map((t) => createToolDefinitionFromAgentTool(wrapToolWithAbortSignal(wrapToolDefinition(t), e.getToolAbortSignal?.())));
const m = collectSideEffectToolOwners([...e.uncompactedEffectiveTools, ...p], { declaredOwner: (e) => getPluginToolSideEffectOwnerKey(e) });
const h = resolveToolSearchConfig(e.toolSearchRuntimeConfig);
const g = addClientToolsToToolCatalog({
tools: p,
enabled: e.codeModeControlsEnabledForRun || h.enabled && h.mode !== "directory",
catalogRef: e.toolSearchCatalogRef,
selection: e.codeModeControlsEnabledForRun ? void 0 : h
});
p = g.tools;
if (g.compacted) emitTrustedDiagnosticEvent({
type: "tool.catalog",
source: "client",
mode: e.codeModeControlsEnabledForRun ? "code-mode" : "tool-search",
toolCount: g.catalogToolCount
});
const _ = [...toToolDefinitions(n, e.catalogToolHookContext, e.getToolAbortSignal?.()), ...p];
const v = toSessionToolAllowlist(collectRegisteredToolNames(_));
return {
allCustomTools: _,
builtinToolNames: r,
coreBuiltinToolNames: o,
clientToolCallSlots: t,
clientToolDefs: p,
replaySafeToolNames: c,
replaySafeTools: s,
codeModeExecToolNames: l,
sourceReplyCapableToolNames: u,
sideEffectToolOwners: m,
sessionToolAllowlist: v,
trustedLocalMediaToolNames: a
};
};
const a = buildSurface();
return {
...a,
refreshTools: () => {
const e = buildSurface();
const replaceItems = (e, t) => e.splice(0, e.length, ...t);
replaceItems(a.allCustomTools, e.allCustomTools);
replaceItems(a.clientToolDefs, e.clientToolDefs);
replaceItems(a.sessionToolAllowlist, e.sessionToolAllowlist);
const replaceSet = (e, t) => {
e.clear();
for (const n of t) e.add(n);
};
for (const t of [
"builtinToolNames",
"coreBuiltinToolNames",
"replaySafeToolNames",
"codeModeExecToolNames",
"sourceReplyCapableToolNames",
"trustedLocalMediaToolNames"
]) replaceSet(a[t], e[t]);
replaceSet(a.replaySafeTools, e.replaySafeTools);
a.sideEffectToolOwners.clear();
for (const [t, n] of e.sideEffectToolOwners) a.sideEffectToolOwners.set(t, n);
}
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-compaction-thinking.ts
/** Keep summary policy bound to the run's config while rechecking the active model and session level. */
function createAttemptCompactionThinkingResolver(e, t) {
return (n, r) => {
const i = projectModelThinkingCompat(n.compat);
const a = [{
provider: n.provider,
id: n.id,
api: n.api,
reasoning: n.reasoning,
...n.thinkingLevelMap ? { thinkingLevelMap: n.thinkingLevelMap } : {},
...n.params ? { params: n.params } : {},
...i ? { compat: i } : {}
}];
const o = {
provider: n.provider,
catalog: a,
agentRuntime: "openclaw"
};
const s = resolveEmbeddedCompactionThinkingLevel({
...o,
config: e.config,
modelId: n.id,
inheritedLevel: r,
compactionThinkingDefault: n.compactionThinkingDefault,
agentId: t,
sessionKey: e.sessionKey ?? e.sandboxSessionKey
});
const c = resolveProviderThinkingLevel({
...o,
model: n.id,
level: s
});
return mapThinkingLevel(c);
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-orphan-repair.ts
function findTrailingMessageEntryForOrphanRepair(e) {
const t = /* @__PURE__ */ new Set();
const n = [];
let r = e.getLeafEntry();
while (r && isSessionContextMetadataEntry(r)) {
if (t.has(r.id)) return;
t.add(r.id);
n.push(r);
r = r.parentId ? e.getEntry(r.parentId) : void 0;
}
return r?.type === "message" ? {
messageEntry: r,
trailingEntries: n.toReversed()
} : void 0;
}
async function replayTrailingEntriesForOrphanRepair(e, t) {
const n = /* @__PURE__ */ new Map();
for (const r of t) {
let t;
switch (r.type) {
case "thinking_level_change":
t = await e.appendThinkingLevelChange(r.thinkingLevel);
break;
case "model_change":
t = await e.appendModelChange(r.provider, r.modelId);
break;
case "custom":
t = await e.appendCustomEntryAsync(r.customType, r.data);
break;
case "session_info":
t = await e.appendSessionInfoAsync(r.name ?? "");
break;
case "label": {
const i = n.get(r.targetId);
if (!i && !e.getEntry(r.targetId)) continue;
t = await e.appendLabelChangeAsync(i ?? r.targetId, r.label);
break;
}
default: continue;
}
n.set(r.id, t);
}
}
function isUserSessionMessageEntry(e) {
return e.message.role === "user";
}
function resolveOrphanRepairPlan(e) {
const t = findTrailingMessageEntryForOrphanRepair(e.sessionManager);
if (!t || !isUserSessionMessageEntry(t.messageEntry) || !e.sessionManager.hasLoadedTranscriptTail(t.messageEntry.id, t.messageEntry.parentId)) return;
const n = t.messageEntry.message.provenance;
if (!e.preserveLeaf && !e.currentTurnPersisted && (!e.currentUserIdempotencyKey || t.messageEntry.message.idempotencyKey !== e.currentUserIdempotencyKey) && t.messageEntry.message.excludeFromContext !== true && (n == null || normalizeInputProvenance(n)?.kind === "external_user")) return;
const r = mergeOrphanedTrailingUserPrompt({
prompt: e.prompt,
leafMessage: t.messageEntry.message
});
return {
contextEnginePrompt: r.prompt,
messageEntry: t.messageEntry,
trailingEntries: t.trailingEntries,
removeLeaf: r.removeLeaf || !e.preserveLeaf
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-permission-prompt.ts
/** Owns permission generations and their initial/continuing prompt admission. */
function installAttemptPermissionPrompt(e) {
const { activeSession: t, attempt: n, prepareSystemPromptUpdate: r, setActiveSessionSystemPrompt: i } = e;
let a;
const refreshPermissionPrompt = async (n, o, s, c = false) => {
const l = o ? AbortSignal.any([o, e.runAbortSignal]) : e.runAbortSignal;
while (true) {
l.throwIfAborted();
const e = a;
try {
const o = e ? AbortSignal.any([l, e.controller.signal]) : l;
const u = e ? await raceWithAbortSignal(e.prepare(), o) : void 0;
l.throwIfAborted();
if (e !== a) continue;
let d;
let f;
if (u || r) {
const o = n ?? t.agent.state.systemPrompt;
const s = u ? u(o) : o;
f = r ? await r(s, u?.freshlyRendered === true) : void 0;
l.throwIfAborted();
if (e !== a) continue;
d = f?.systemPrompt ?? i(s);
}
const p = s ? await raceWithAbortSignal(s(o), o) : void 0;
l.throwIfAborted();
if (e !== a) continue;
const admit = async (n) => {
const commit = () => {
o.throwIfAborted();
if (e !== a) throw new Error("Session prompt preparation is stale after permission replacement.");
if (f) {
f.commit?.();
i(f.systemPrompt);
if (f.update) t[agentSessionQueuePromptContext](f.update);
}
};
if (p) await p(() => n(commit));
else n(commit);
};
if (f && !c) {
await admit((e) => e());
return { systemPrompt: d };
}
return {
systemPrompt: d,
admitReplay: admit
};
} catch (t) {
l.throwIfAborted();
if (e !== a) continue;
throw t;
}
}
};
t[agentSessionSetPromptPreparation](async () => {
const t = await refreshPermissionPrompt(void 0, void 0, e.prepareInitialUserTurnReplay, true);
return async (n) => {
e.runAbortSignal.throwIfAborted();
if (t.admitReplay) await t.admitReplay(n);
else n();
};
});
const o = t.agent.prepareNextTurn;
const prepareNextTurn = async (i) => {
if (n.pluginRuntimeRefreshPending?.()) return { stop: true };
const a = await o?.call(t.agent, i);
if (r) return {
...a,
prepareContinuation: async (r) => {
const o = await a?.prepareContinuation?.(r);
const { systemPrompt: s } = await refreshPermissionPrompt(o?.systemPrompt ?? r.systemPrompt, i);
if (n.model.api === "anthropic-messages") {
let n = false;
for (let a = r.messages.length - 1; a >= 0; a--) {
const o = r.messages[a];
if (o.role === "user") break;
if (o.role === "toolResult") n = true;
else if (o.role === "custom" && !o.excludeFromContext) {
if (!isOpenClawSystemUpdateMessage(o)) {
n = true;
continue;
}
const r = asOptionalRecord(o.details);
if (r?.kind === "runtime-context" && r.turnScoped === true) {
if (n) {
e.runAbortSignal.throwIfAborted();
i?.throwIfAborted();
t[agentSessionQueuePromptContext]({
...o,
timestamp: Date.now()
});
}
break;
}
}
}
}
return {
systemPrompt: s ?? o?.systemPrompt ?? r.systemPrompt,
tools: t.agent.state.tools.slice()
};
}
};
const { systemPrompt: s } = await refreshPermissionPrompt(a?.context?.systemPrompt, i);
return a?.context && s !== void 0 ? {
...a,
context: {
...a.context,
systemPrompt: s,
tools: t.agent.state.tools.slice()
}
} : a;
};
t.agent.prepareNextTurn = prepareNextTurn;
n.registerPluginRuntimeRefreshConsumer?.(() => t.agent.prepareNextTurn === prepareNextTurn && t.agent.state.isStreaming && !e.runAbortSignal.aborted);
return (e) => {
const t = a;
a = e ? {
prepare: e,
controller: new AbortController()
} : void 0;
t?.controller.abort();
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-session-projection-recovery.ts
/** Retry one admitted open after its projection rebuild, outside transcript write custody. */
async function openSessionAfterProjectionRecovery(e) {
e.signal.throwIfAborted();
try {
return await e.open();
} catch (t) {
if (!isSessionTranscriptProjectionUnavailableError(t) || t.reason !== "rebuilding" || t.sessionId !== e.target.sessionId) throw t;
e.assertCurrent();
e.signal.throwIfAborted();
e.replyOperation?.markWaitingForDeferredMaintenance();
try {
await outsideExecutionCapacity(async () => {
const n = new AbortController();
const r = e.timeoutMs >= 2147e6 ? DEFAULT_AGENT_TIMEOUT_MS : Math.max(1, e.timeoutMs);
const i = setTimeout(() => n.abort(t), r);
i.unref();
try {
await recoverSessionTranscriptProjection(e.target, AbortSignal.any([e.signal, n.signal]), e.assertCurrent);
} finally {
clearTimeout(i);
}
});
} catch (n) {
e.assertCurrent();
e.signal.throwIfAborted();
if (n === t || n instanceof Error && n.name === "AbortError" && n.cause === t) throw t;
throw n;
} finally {
e.replyOperation?.markDeferredMaintenanceWaitEnded();
}
e.assertCurrent();
e.signal.throwIfAborted();
return await e.open();
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-transcript-policy.ts
/**
* Resolves the transcript policy for an embedded attempt. RuntimePlan owns the
* policy when present; otherwise the older provider/config/env resolver remains
* the compatibility path for callers that have not produced a runtime plan yet.
*/
function resolveAttemptTranscriptPolicy(e) {
return e.runtimePlan?.transcript.resolvePolicy(e.runtimePlanModelContext) ?? resolveTranscriptPolicy({
modelApi: e.runtimePlanModelContext.modelApi,
directApiKey: e.runtimePlanModelContext.directApiKey,
provider: e.provider,
modelId: e.modelId,
config: e.config,
workspaceDir: e.runtimePlanModelContext.workspaceDir,
env: e.env ?? process.env,
model: e.runtimePlanModelContext.model
});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-user-transcript-context-registry.ts
/** Retains attempt-local runtime-to-transcript pairs across queued user turns. */
function createUserTranscriptContextRegistry() {
const e = [];
const upsert = (t, n) => {
const r = {
runtimeMessage: t,
transcriptMessage: n
};
const i = e.findIndex((e) => e.runtimeMessage === t);
if (i === -1) e.push(r);
else e[i] = r;
};
return {
clear: () => {
e.length = 0;
},
list: (t, n) => {
if (t && n) upsert(t, n);
return e;
},
record: upsert
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/tool-activity-heartbeat.ts
async function withEmbeddedAttemptToolActivity(e, t) {
const n = setInterval(() => notifyToolActivity(e), 6e4);
n.unref();
try {
notifyToolActivity(e);
return await t();
} finally {
clearInterval(n);
notifyToolActivity(e);
}
}
function wrapEmbeddedAttemptToolWithActivity(e, t) {
const n = e.execute;
return wrapAgentToolExecutionContext(e, ((...e) => withEmbeddedAttemptToolActivity(t, () => n(...e))), (e) => withEmbeddedAttemptToolActivity(t, e), (e) => wrapEmbeddedAttemptToolWithActivity(e, t));
}
//#endregion
//#region src/agents/embedded-agent-runner/run/tool-loop-recovery.ts
/** Build the embedded-runner's private bridge into agent-core loop recovery. */
function createToolLoopBatchAdmission(e) {
return async ({ calls: t, toolLoopRecoveryState: n }) => {
const r = t.map((e) => ({
...e,
args: e.tool ? normalizeCodeModeExecBeforeHookParams({
tool: e.tool,
params: e.args
}) : e.args
}));
const blockedCall = (e, t = e.args) => {
const r = n.blockedToolActions;
if (!r?.size) return;
const i = e.tool ? normalizeCodeModeExecBeforeHookParams({
tool: e.tool,
params: t
}) : t;
const a = r.get(hashToolCall(e.toolCall.name, i));
return a ? {
...a,
toolCallId: e.toolCall.id
} : void 0;
};
for (const e of r) {
const t = e.validationFailure ? blockedCall(e) : void 0;
if (t) return { intervention: t };
}
try {
const { commitReadyCalls: t, releaseSkippedCalls: n, ...i } = await admitToolCallBatch(r, e);
return attachInternalToolBatchLifecycle(i, {
commitReadyCalls(e) {
for (const t of e) {
const e = r.find((e) => e.toolCall.id === t.toolCallId);
if (e && !e.validationFailure) {
const n = blockedCall(e, t.args);
if (n) throw new InternalToolLoopBlocked(n);
}
}
t?.(e);
},
releaseSkippedCalls: n,
observeOutcome(e, t) {
const n = r.find((t) => t.toolCall.id === e.toolCall.id)?.tool;
return observeRepeatedToolError({
...e,
args: n ? normalizeCodeModeExecBeforeHookParams({
tool: n,
params: e.args
}) : e.args
}, t);
}
});
} catch (e) {
const t = r[0];
log$2.error(`tool-loop batch admission failed: ${String(e)}`);
return t ? { intervention: {
kind: "critical-tool-loop",
toolCallId: t.toolCall.id,
toolName: t.toolCall.name,
actionKey: hashToolCall(t.toolCall.name, t.args),
detector: "loop_admission_failure",
count: 1,
reason: "Tool execution was blocked because loop safety checks failed."
} } : void 0;
}
};
}
/** Ensure calls blocked by later policies cannot leave run-scoped admission markers behind. */
function installToolLoopRecoveryCleanup(e) {
e.agent.subscribe((t) => {
if (t.type === "agent_end") clearBatchAdmittedToolCallsForRun(e.runId);
});
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-session-prepare.ts
async function prepareEmbeddedAttemptAgentSession(e) {
const { attempt: t, prepareSystemPromptUpdate: n } = e;
const r = createPreparedEmbeddedAgentSettingsManager({
agentId: e.sessionAgentId,
sessionId: t.sessionId,
cwd: e.effectiveCwd,
agentDir: e.agentDir,
cfg: t.config,
pluginMetadataSnapshot: e.getCurrentAttemptPluginMetadataSnapshot(),
contextTokenBudget: t.contextTokenBudget
});
const i = t.compactionForbidden || t.operation === "settled-tool-finalization";
const a = !i && r.getCompactionEnabled();
applyAgentAutoCompactionGuard({
settingsManager: r,
contextEngineInfo: e.activeContextEngineInfo,
compactionMode: resolveEffectiveCompactionMode(t.config),
silentOverflowProneProvider: isSilentOverflowProneModel({
provider: t.provider,
modelId: t.modelId,
baseUrl: t.model.baseUrl
}),
compactionForbidden: i
});
const o = new DefaultResourceLoader({
cwd: e.effectiveCwd,
agentDir: e.agentDir,
extensionFactories: buildEmbeddedExtensionFactories({
cfg: t.config,
sessionManager: e.sessionManager,
workspaceDir: e.effectiveWorkspace,
model: t.model,
agentId: e.sessionAgentId,
sessionId: t.sessionId,
sessionKey: t.sessionKey ?? t.sandboxSessionKey,
runId: t.runId
})
});
await o.reload();
e.markStage("session-resource-loader");
const s = getGlobalHookRunner();
const { allCustomTools: c, sessionToolAllowlist: l, ...u } = prepareEmbeddedAttemptClientTools({
attempt: t,
...e.clientToolPreparation
});
const { session: d } = await createAgentSession({
systemPrompt: e.initialSystemPrompt.trim(),
cwd: e.effectiveCwd,
modelRegistry: t.modelRegistry,
model: t.model,
thinkingLevel: e.agentCoreThinkingLevel,
thinkingExplicit: t.thinkingExplicit,
tools: l,
customTools: c,
sessionManager: e.sessionManager,
settingsManager: r,
resourceLoader: o,
resolveDeferredTool: e.clientToolPreparation.deferredDirectoryToolsCallable ? ({ toolCall: n }) => {
const r = e.clientToolPreparation.getToolAbortSignal?.() ?? e.runAbortSignal;
const i = resolveToolSearchCatalogTool({
config: t.config,
runtimeConfig: t.config,
agentId: e.sessionAgentId,
sessionKey: e.clientToolPreparation.sandboxSessionKey,
sessionId: t.sessionId,
runId: t.runId,
catalogRef: e.clientToolPreparation.toolSearchCatalogRef,
abortSignal: r
}, n.name);
const a = i ? toToolDefinitions([i], e.clientToolPreparation.catalogToolHookContext, r)[0] : void 0;
const o = a ? wrapToolDefinition(a) : void 0;
if (o) {
log$2.info(`tool-search: hydrated deferred directory tool ${n.name}`);
const e = o.execute;
o.execute = (...n) => withEmbeddedAttemptToolActivity(t.runId, () => e(...n));
}
return o;
} : void 0,
withSessionWriteSettlement: (t) => e.transcriptLifecycle.withTranscriptWrite(t),
cleanupProviderSessionResourcesOnDispose: false,
contextOverflowRecoveryOwner: t.contextTokenBudget === void 0 ? "session" : "caller",
resolveCompactionThinkingLevel: createAttemptCompactionThinkingResolver(t, e.sessionAgentId),
beforeToolBatch: e.clientToolPreparation.catalogToolHookContext ? createToolLoopBatchAdmission(e.clientToolPreparation.catalogToolHookContext) : void 0
});
e.onSessionCreated(d);
installToolLoopRecoveryCleanup({
agent: d.agent,
runId: t.runId
});
const setActiveSessionSystemPrompt = (t) => {
e.onSystemPromptChanged(t);
d.setBaseSystemPrompt(t.trim());
return t;
};
const f = installAttemptPermissionPrompt({
activeSession: d,
attempt: t,
runAbortSignal: e.runAbortSignal,
setActiveSessionSystemPrompt,
prepareInitialUserTurnReplay: e.prepareInitialUserTurnReplay,
prepareSystemPromptUpdate: n
});
e.onSystemPromptChanged(e.initialSystemPrompt);
let p = false;
const markSourceReplyDelivered = () => {
p = true;
};
installMessageToolTerminalHook({
agent: d.agent,
sourceReplyDeliveryMode: t.sourceReplyDeliveryMode,
messageToolFinalByDefault: t.messageToolFinalByDefault,
onDeliveredSourceReply: markSourceReplyDelivered,
config: t.config,
currentProvider: t.messageChannel ?? t.messageProvider,
currentAccountId: t.agentAccountId,
currentChannelId: t.currentChannelId,
currentMessagingTarget: t.currentMessagingTarget,
currentThreadId: t.currentThreadTs,
currentMessageId: t.currentMessageId,
replyToMode: t.replyToMode,
hasRepliedRef: t.hasRepliedRef,
sessionKey: t.sessionKey
});
e.markStage("agent-session");
return {
activeSession: d,
compactionEnabled: a,
allCustomTools: c,
...u,
hasDeliveredSourceReply: () => p,
hookRunner: s,
markSourceReplyDelivered,
setActiveSessionSystemPrompt,
settingsManager: r,
refreshTools: () => {
const e = d.agent.state.systemPrompt;
u.refreshTools();
d.replaceCustomTools(c, l);
setActiveSessionSystemPrompt(e);
},
setPermissionPromptPreparation: f
};
}
async function prepareEmbeddedAttemptSessionBoundary(e) {
const { activeSession: t, attempt: n, isRawModelRun: r, sessionManager: i } = e;
const a = r || n.operation === "settled-tool-finalization";
const o = a ? void 0 : await prepareForeignPendingUserTurns(i, e.abortSignal);
setSteeringRuntimeContextRetention(t, e.appendOnlyRuntimeContext === true);
if (r) {
t.agent.reset();
e.setActiveSessionSystemPrompt("");
}
let s;
let c;
const l = a ? void 0 : await withSessionManagerAppend(i, async () => {
e.abortSignal?.throwIfAborted();
const r = i.getSessionTarget();
const a = r && getOwnedSessionTranscriptReader(r);
a?.assertCurrent();
const l = n.skipPreparedUserTurnMessage ? void 0 : n.userTurnTranscriptRecorder?.getPersistedMessage?.() ?? e.preparedUserTurnMessage;
c = o?.(t, l?.idempotencyKey);
if (n.replayCurrentTranscript) return;
if (a && reconcilePrePersistedCurrentUserTurn({
activeSession: t,
currentUserTurnMessage: l,
durableUserTurnMessage: void 0,
userTurnAlreadyPersisted: n.userTurnTranscriptRecorder?.hasPersisted() === true
})) return;
await i.reloadPersistedTranscriptAsync(e.abortSignal);
e.abortSignal?.throwIfAborted();
c = o?.(t, l?.idempotencyKey);
const u = resolveOrphanRepairPlan({
sessionManager: i,
prompt: n.prompt,
preserveLeaf: n.skipPreparedUserTurnMessage === true,
currentTurnPersisted: n.userTurnTranscriptRecorder?.hasPersisted() === true,
currentUserIdempotencyKey: l?.idempotencyKey
});
const d = reconcilePrePersistedCurrentUserTurn({
activeSession: t,
currentUserTurnMessage: l,
durableUserTurnMessage: u?.messageEntry.message,
userTurnAlreadyPersisted: n.userTurnTranscriptRecorder?.hasPersisted() === true
});
const f = normalizeInputProvenance(u?.messageEntry.message.provenance);
if (u && isOutOfTurnHistoryEntry(u.messageEntry)) u.removeLeaf = false;
const p = (n.inputProvenance?.kind === "internal_system" && n.inputProvenance.sourceTool === "restart" || shouldPreserveUserFacingSessionStateForInputProvenance(n.inputProvenance)) && (!f || f.kind === "external_user");
const m = u && c?.ownsEntry(u.messageEntry.id);
if (d || p || m) return;
if (u?.removeLeaf) {
if (u.messageEntry.parentId) await i.branchAsync(u.messageEntry.parentId);
else await i.resetLeafAsync();
s = i.getSessionTarget();
if (s) await i.appendLeafControlAsync({
targetId: i.getLeafId(),
appendParentId: i.getAppendParentId()
});
await replayTrailingEntriesForOrphanRepair(i, u.trailingEntries);
}
return u;
});
if (l?.removeLeaf) {
if (s) {
const { waitForSessionTranscriptProjection: t } = await import("./config/sessions/session-transcript-reconcile.js");
await t(s, e.abortSignal);
e.abortSignal?.throwIfAborted();
}
i.setNextUserMessagePersistence?.("normal");
n.onUserMessagePersistenceInvalidated?.();
}
if (l) {
const e = sanitizeCompactionReplayMessages((await i[sessionManagerReadInitialContext]()).messages);
t.agent.state.messages = l.removeLeaf ? e : e.slice(0, -1);
}
const u = a ? void 0 : resolveUserTimezone(n.config?.agents?.defaults?.userTimezone);
let d;
const buildBoundaryOptions = () => {
if (a) return {
appendOnlyRuntimeContext: e.appendOnlyRuntimeContext,
inHistorySystemUpdates: e.inHistorySystemUpdates,
projectPersistedSenderContext: false
};
const t = e.getUserTranscriptContexts();
return {
sessionVersion: i.getHeader()?.version,
appendOnlyRuntimeContext: e.appendOnlyRuntimeContext,
inHistorySystemUpdates: e.inHistorySystemUpdates,
currentUserIdempotencyKey: e.preparedUserTurnMessage?.idempotencyKey,
...u ? { timezone: u } : {},
...t?.length ? { userTranscriptContexts: t } : {},
...d ? { currentUserTimestampOverride: d } : {}
};
};
const f = t.agent.convertToLlm.bind(t.agent);
t.agent.convertToLlm = async (t) => {
let r;
const i = normalizeMessagesForLlmBoundary(c?.omitInput(t) ?? t, {
...buildBoundaryOptions(),
onRuntimeContextCarrierRemoved: (e) => {
r = e;
}
});
const a = await f(e.appendOnlyRuntimeContext ? i : relocateCurrentRuntimeContextCarrierToTail(i));
applyRuntimeContextCarrierRetention(a, e.appendOnlyRuntimeContext);
if (!e.appendOnlyRuntimeContext && recordRuntimeContextProjection(n.sessionId, r, a)) declarePromptHistoryRewrite({
...n,
reason: "runtimeContextCarrier"
});
return a;
};
return {
getUserTranscriptContexts: e.getUserTranscriptContexts,
boundaryTimezone: u,
includeBoundaryTimestamp: !a,
orphanRepair: l,
setCurrentUserTimestampOverride: (e) => {
d = e;
}
};
}
async function prepareEmbeddedAttemptSessionManager(e) {
const { attempt: t } = e;
const n = {
sessionManager: t.sessionManager,
agentId: e.sessionAgentId,
config: t.config,
sessionFile: t.sessionFile,
sessionId: t.sessionId,
sessionKey: t.sessionKey,
sessionTarget: t.sessionTarget
};
let r = t.sessionManager ? await resolveExistingAttemptTranscriptState(n) : void 0;
const i = t.model.api === "anthropic-messages" && isDirectAnthropicModel(t.model) && supportsClaudeInHistorySystemMessages(t.model) ? await resolveEmbeddedAgentApiKey(t) : void 0;
const a = resolveAttemptTranscriptPolicy({
runtimePlan: t.runtimePlan,
runtimePlanModelContext: {
workspaceDir: e.effectiveWorkspace,
modelApi: t.model.api,
model: t.model,
directApiKey: Boolean(i) && !isAnthropicOAuthApiKey(i)
},
provider: t.provider,
modelId: t.modelId,
config: t.config,
env: process.env
});
const o = t.model.api === "openai-responses" || t.model.api === "azure-openai-responses" || t.model.api === "openai-chatgpt-responses";
const s = t.skipPreparedUserTurnMessage || t.replayCurrentTranscript ? void 0 : await t.userTurnTranscriptRecorder?.resolveMessage();
let c;
let l;
let u = t.userTurnTranscriptRecorder;
const d = createUserTranscriptContextRegistry();
const f = t.abortSignal ? AbortSignal.any([t.abortSignal, e.runAbortSignal]) : e.runAbortSignal;
let p;
let m;
let h;
const openSessionManager = () => e.withOwnedTranscriptWrite(async () => {
const n = e.sessionTarget;
const r = resolveEmbeddedSessionContextLimits(t);
const i = prepareInitialPersistedUserTurnCohort({
target: n,
message: s,
recorder: t.userTurnTranscriptRecorder,
runId: t.runId
});
if (i || getOwnedSessionTranscriptReader(n)) {
const t = await SessionManager[sessionManagerOpenTranscriptCohort](n, {
...r,
cwd: e.effectiveCwd,
signal: f
}, i?.selection ?? {
sessionKey: n.sessionKey,
entryIds: [],
includeMessagePresence: true
}, (t, n, r) => {
try {
i?.consume(t, n, r);
h = n.kind === "bounded" ? n.transcript?.messagePresence : void 0;
} finally {
p = t;
e.onSessionManagerCreated(t);
}
});
m = i?.readInitial();
return t;
}
return SessionManager.openAsync(n, e.effectiveCwd, r, f);
});
const g = !t.sessionManager && t.sessionTarget ? await openSessionAfterProjectionRecovery({
open: openSessionManager,
target: e.sessionTarget,
timeoutMs: t.timeoutMs,
signal: f,
assertCurrent: e.assertCurrent,
replyOperation: t.replyOperation
}) : void 0;
const _ = t.sessionManager ?? g ?? SessionManager.inMemory(e.effectiveCwd);
if (p !== _) e.onSessionManagerCreated(_);
r ??= h === void 0 ? await resolveExistingAttemptTranscriptState(n) : { hasBootstrapTranscriptState: h };
const v = await e.withOwnedTranscriptWrite(() => preparePersistedCurrentUserTurn({
sessionManager: _,
message: s,
recorder: t.userTurnTranscriptRecorder,
runId: t.runId,
fallbackReason: t.fallbackReason,
signal: t.abortSignal,
initial: m
}));
const y = typeof v === "function" ? async (t) => {
const n = await e.withOwnedTranscriptWrite(() => v(t));
return n && ((t) => e.withOwnedTranscriptWrite(() => n(t)));
} : void 0;
t.inputAlreadyDelivered = v === "already-delivered" ? true : void 0;
const b = guardSessionManager(_, {
agentId: e.sessionAgentId,
runId: t.runId,
sessionKey: t.sessionKey,
config: t.config,
contextWindowTokens: t.contextTokenBudget,
inputProvenance: t.inputProvenance,
privateCompletion: t.privateCompletion,
preparedUserTurnMessage: s,
preparedUserTurnTranscriptRecorder: s ? t.userTurnTranscriptRecorder : void 0,
allowSyntheticToolResults: a.allowSyntheticToolResults,
missingToolResultText: o ? "aborted" : void 0,
trigger: t.trigger,
suppressNextUserMessagePersistence: y !== void 0 || t.suppressNextUserMessagePersistence,
suppressTranscriptOnlyAssistantPersistence: t.suppressTranscriptOnlyAssistantPersistence,
assistantErrorTranscript: t.assistantErrorTranscript,
skipBeforeMessageWriteHooks: t.operation === "settled-tool-finalization",
prepareAssistantTranscriptMessage: t.prepareAssistantTranscriptMessage,
onUserMessagePreparingForPersistence: (e, t) => {
c = void 0;
u = t;
},
onUserMessagePersisted: (e, n) => {
c = e;
l = n;
if (n) d.record(n, e);
t.onUserMessagePersisted?.(e);
},
onUserMessagePersistenceSuppressed: (e, n) => {
l = n;
if (y !== void 0 && !t.suppressNextUserMessagePersistence && t.userTurnTranscriptRecorder?.hasPersisted() === true) t.onUserMessagePersisted?.(e);
},
onUserMessageBlocked: () => {
t.userTurnTranscriptRecorder?.markBlocked();
}
});
t.promptCacheKey = resolveSessionBoundaryPromptCacheKey({
api: t.model.api,
boundaryCount: b.getBoundaryCount(),
promptCacheKey: t.promptCacheKey,
sessionId: t.sessionPersistence === "detached" && t.sessionManager && !t.sessionManager.getSessionTarget() ? t.sessionManager.getSessionId() : t.sessionId
});
await e.withOwnedTranscriptWrite(async () => {
await bootstrapHarnessContextEngine({
admittedRunContext: t.admittedRunContext,
hadSessionFile: r.hasBootstrapTranscriptState,
contextEngine: e.activeContextEngine,
sessionId: t.sessionId,
sessionKey: t.sessionKey,
sessionTarget: t.sessionTarget,
sessionFile: t.sessionFile,
sessionManager: b,
tokenBudget: t.contextTokenBudget,
transcriptReadFence: t.userTurnTranscriptRecorder?.getAdmissionReceipt(),
runtimeContext: buildAfterTurnRuntimeContext({
attempt: t,
workspaceDir: e.effectiveWorkspace,
cwd: e.effectiveCwd,
agentDir: e.agentDir,
tokenBudget: t.contextTokenBudget,
activeAgentId: e.sessionAgentId,
contextEnginePluginId: e.resolveActiveContextEnginePluginId()
}),
contextEngineHostSupport: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST,
providerId: t.provider,
requestedModelId: t.requestedModelId,
modelId: t.modelId,
fallbackReason: t.fallbackReason,
degradedReason: t.degradedReason,
runMaintenance: async (n) => await runContextEngineMaintenance({
...n,
sessionManager: n.sessionManager,
config: t.config,
agentId: e.sessionAgentId,
contextEngineAgentId: t.contextEngineAgentId
}),
warn: (e) => log$2.warn(e)
});
});
c = void 0;
l = void 0;
d.clear();
return {
prepareInitialUserTurnReplay: y,
userMessageBoundary: {
getUserTranscriptContexts: () => {
const e = c ?? u?.getPersistedMessage?.();
const n = l ?? (t.suppressNextUserMessagePersistence ? e : void 0);
return d.list(n, e);
},
preparedUserTurnMessage: s
},
isOpenAIResponsesApi: o,
preparedUserTurnMessage: s,
sessionManager: b,
transcriptPolicy: a
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-session-settle.ts
function createEmbeddedAttemptSessionSettleTracker(e) {
const t = /* @__PURE__ */ new Set();
let n = false;
const recordAbortCleanupFailure = () => {
if (n) recordAgentCleanupFailure();
};
const r = createPendingPromiseTracker(t);
return {
abortActiveSession: (t) => r(Promise.resolve(e.abort(t)).catch((e) => {
n = true;
throw e;
})),
buildAbortSettlePromise: () => {
recordAbortCleanupFailure();
return t.size === 0 ? null : Promise.allSettled(t).then(recordAbortCleanupFailure);
},
trackPromptSettlePromise: r
};
}
/** Keep retained review callbacks outside the attempt's tool-execution closure scope. */
function createEmbeddedAttemptSessionResources(e) {
let t = {
trajectoryRecorder: null,
buildAbortSettlePromise: () => null
};
return {
get resources() {
return t;
},
reviewTranscript: () => {
if (!t.session || e.aborted) return;
return buildExecAutoReviewTranscript({
messages: t.session.messages,
userTurnOrigins: new Map(t.getUserTranscriptContexts?.()?.map(({ runtimeMessage: e, transcriptMessage: t }) => [e, t]))
});
},
takeForCleanup: () => {
const e = t;
t = {
trajectoryRecorder: null,
buildAbortSettlePromise: () => null
};
return e;
}
};
}
async function cleanupEmbeddedAttemptSessionPhase(e) {
try {
var t = _usingCtx();
t.u(e.promptStateLease);
const n = e.sessionManager?.clearTranscriptRunCallbacks;
const { attempt: r } = e;
const i = projectAgentRunAttemptTerminal(e.state.terminal);
let a;
try {
try {
if (e.trajectoryRecorder && !e.trajectoryEndRecorded) {
const t = {
status: i.promptError ? "error" : i.aborted || i.timedOut ? "interrupted" : "cleanup",
aborted: i.aborted,
externalAbort: i.externalAbort,
timedOut: i.timedOut,
idleTimedOut: i.idleTimedOut,
timedOutDuringCompaction: i.timedOutDuringCompaction,
timedOutDuringToolExecution: i.timedOutDuringToolExecution,
timedOutByRunBudget: i.timedOutByRunBudget,
promptError: i.promptError ? formatErrorMessage(i.promptError) : void 0
};
if (e.deferredLifecycleOwner) e.deferredLifecycleOwner.recordSessionEnd(t);
else e.trajectoryRecorder.recordEvent("session.ended", t);
}
if (!e.deferredLifecycleOwner || e.state.terminal.kind !== "ok" || e.state.terminal.settlementWarning || r.abortSignal?.aborted || e.state.beforeAgentRunBlockedBy !== void 0) await flushEmbeddedAttemptTrajectoryRecorder({
runId: r.runId,
sessionId: r.sessionId,
log: log$2,
trajectoryRecorder: e.trajectoryRecorder
});
} finally {
clearToolSearchCatalog({ catalogRef: e.toolSearchCatalogRef });
await e.transcriptLifecycle.beginCleanup(n);
}
} catch (e) {
recordAgentCleanupFailure();
a = e;
}
try {
const t = projectAgentRunAttemptTerminal(e.state.terminal);
const n = Boolean(r.abortSignal?.aborted) || t.aborted || t.timedOut || t.idleTimedOut || t.timedOutDuringCompaction;
const a = n || i.cleanupYieldAborted;
await cleanupEmbeddedAttemptResources({
...e,
sessionManager: e.sessionManager,
flushPendingToolResultsAfterIdle,
aborted: a,
abortSignal: r.abortSignal,
abortSettlePromise: n ? e.buildAbortSettlePromise() : null,
runId: r.runId,
sessionId: r.sessionId
});
} catch (e) {
recordAgentCleanupFailure();
a ??= e;
} finally {
try {
await e.transcriptLifecycle.dispose();
} catch (e) {
recordAgentCleanupFailure();
a ??= e;
}
}
const o = projectAgentRunAttemptTerminal(e.state.terminal);
const s = e.state.beforeAgentRunBlockedBy !== void 0;
const c = o.aborted || o.timedOut || o.idleTimedOut;
e.emitDiagnosticRunCompleted?.(a ? "error" : s ? "blocked" : o.promptError ? "error" : c ? "aborted" : "completed", a ?? o.promptError, s ? { blockedBy: e.state.beforeAgentRunBlockedBy } : e.state.diagnosticFinalResponse ? { finalResponse: e.state.diagnosticFinalResponse } : void 0);
if (a) await Promise.reject(toErrorObject(a, "Non-Error rejection"));
} catch (e) {
t.e = e;
} finally {
t.d();
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts
async function prepareEmbeddedAttemptSessionRuntime(e) {
const { attempt: t, resources: n, runAbortSignal: r, sessionLock: i, toolBase: a } = e;
const { agentCoreThinkingLevel: o, effectiveCwd: s, effectiveFsWorkspaceOnly: c, effectiveWorkspace: l, getCurrentAttemptPluginMetadataSnapshot: u, getProviderRuntimeHandle: d, prepStages: f, providerThinkingLevel: p, sandbox: m, sandboxSessionKey: h, sessionAgentId: g } = e.setup;
const { catalogToolHookContext: _, deferredDirectoryToolsCallable: v, effectiveTools: y } = e.toolCatalog;
const { clientTools: b, uncompactedEffectiveTools: x } = e.bundleTools;
const { codeModeControlsEnabledForRun: S, computerContextEpoch: C, localModelLeanEnabled: w, replaySafetyOptions: T, toolSearchCatalogRef: E, toolSearchRuntimeConfig: D } = a;
const { systemPromptReport: O, systemPromptText: k } = e.systemPrompt;
const A = y.length;
const j = {
attempt: t,
assertCurrent: () => {
r.throwIfAborted();
i.ownedTranscriptWriteContext.assertCommitAllowed?.();
i.ownedTranscriptWriteContext.initialWriter?.assertActive();
},
...e.activeContextEngine ? { activeContextEngine: e.activeContextEngine } : {},
agentDir: e.agentDir,
effectiveCwd: s,
effectiveWorkspace: l,
sessionAgentId: g
};
const M = await measureEmbeddedAgentPreparation("attempt.history", () => prepareEmbeddedAttemptSessionManager({
...j,
sessionTarget: i.ownedTranscriptWriteContext.sessionTarget,
runAbortSignal: r,
onSessionManagerCreated: (e) => {
n.sessionManager = e;
},
resolveActiveContextEnginePluginId: e.resolveActiveContextEnginePluginId,
withOwnedTranscriptWrite: i.withOwnedTranscriptWrite
}), { config: t.config });
const { isOpenAIResponsesApi: N, preparedUserTurnMessage: P, sessionManager: F, transcriptPolicy: I } = M;
if (S && E) bindCodeModeSessionStore(E, F, i.withOwnedTranscriptWrite);
const L = retainEmbeddedSessionPromptState(t.sessionId);
n.promptStateLease = L;
const R = L.state;
const z = !e.isRawModelRun && t.operation !== "settled-tool-finalization";
const ee = I.pinnedSystemPrompt === true;
const B = buildSystemPromptRouteKey({
provider: t.provider,
model: t.modelId,
api: t.model.api,
baseUrl: t.model.baseUrl,
inHistorySystemUpdates: I.inHistorySystemUpdates === true,
personalProfile: t.bootstrapUserProfileId
});
const retireSystemPromptUpdates = () => i.withOwnedTranscriptWrite(() => withSessionManagerAppend(F, async () => {
r.throwIfAborted();
await retireSessionSystemPrompt(R, B, (e, t) => F.appendCustomEntryAsync(e, t));
}));
if (z && beginSessionSystemPrompt({
state: R,
routeKey: B,
enabled: ee,
getEntries: () => F.getBranch()
})) await retireSystemPromptUpdates();
let V = k;
let H;
const U = z && ee ? async (e, t = false) => {
if (t || e !== H) V = e;
const r = prepareSessionSystemPrompt({
state: R,
routeKey: B,
systemPrompt: V,
entries: F.getBranch(),
historyBoundaryCount: F.getBoundaryCount()
});
if (r.restart || K.systemPromptSeries === void 0) K.systemPromptSeries = r.seriesStatus;
let i = false;
if (r.restart && n.session) {
await retireSystemPromptUpdates();
i = true;
n.session.agent.state.messages = n.session.messages.filter((e) => getOpenClawSystemUpdateKind(e) !== "prompt-update");
}
H = r.systemPrompt;
return {
...r,
commit: () => r.commit(i)
};
} : void 0;
n.getUserTranscriptContexts = M.userMessageBoundary.getUserTranscriptContexts;
const W = sha256Hex(stableStringify([
t.config?.tools,
t.config?.agents?.entries?.[g]?.tools,
t.config?.plugins,
t.config?.desktop
]));
const G = z ? (e) => {
const n = R.pendingToolSurface;
const r = prepareSessionToolSurface({
state: R,
routeKey: B,
toolPolicy: W,
entries: F.getBranch(),
historyBoundaryCount: F.getBoundaryCount(),
tools: e
});
if (R.pendingToolSurface !== n) declarePromptToolPin(t);
return r;
} : void 0;
const K = {
currentTurnImageFailureCount: 0,
prePromptMessageCount: 0,
promptCache: void 0,
systemPromptText: k
};
const te = await withOwnedSessionTranscriptWrites(i.ownedTranscriptWriteContext, async () => measureEmbeddedAgentPreparation("attempt.actor", () => prepareEmbeddedAttemptAgentSession({
...j,
...e.activeContextEngine ? { activeContextEngineInfo: e.activeContextEngine.info } : {},
agentCoreThinkingLevel: o,
clientToolPreparation: {
catalogToolHookContext: _,
clientTools: b,
codeModeControlsEnabledForRun: S,
deferredDirectoryToolsCallable: v,
effectiveTools: y,
pinTools: G,
replaySafetyOptions: T,
sandboxSessionKey: h,
sessionAgentId: g,
toolSearchCatalogRef: E,
toolSearchRuntimeConfig: D,
uncompactedEffectiveTools: x,
getToolAbortSignal: () => a.toolAbortSignal
},
getCurrentAttemptPluginMetadataSnapshot: u,
initialSystemPrompt: K.systemPromptText,
prepareSystemPromptUpdate: U,
markStage: (e) => f.mark(e),
onSessionCreated: (e) => {
n.session = e;
},
onSystemPromptChanged: (e) => {
K.systemPromptText = e;
},
runAbortSignal: r,
transcriptLifecycle: i.transcriptLifecycle,
sessionManager: F,
prepareInitialUserTurnReplay: M.prepareInitialUserTurnReplay
}), { config: t.config }));
const { activeSession: q, setActiveSessionSystemPrompt: ne, settingsManager: J } = te;
const recordCurrentTurnImageFailure = (e) => {
K.currentTurnImageFailureCount = Math.max(K.currentTurnImageFailureCount, e);
};
await t.userTurnTranscriptRecorder?.waitForRuntimePersistence();
const Y = await measureEmbeddedAgentPreparation("attempt.history-boundary", () => i.withOwnedTranscriptWrite(() => prepareEmbeddedAttemptSessionBoundary({
abortSignal: r,
activeSession: q,
appendOnlyRuntimeContext: I.appendOnlyRuntimeContext,
inHistorySystemUpdates: I.inHistorySystemUpdates,
attempt: t,
...M.userMessageBoundary,
isRawModelRun: e.isRawModelRun,
sessionManager: F,
setActiveSessionSystemPrompt: ne
})), { config: t.config });
K.prePromptMessageCount = q.messages.length;
const X = R.toolResults;
if (!e.isRawModelRun) restoreCacheTtlToolResultProjections(X, F.getToolResultProjectionEntries());
const Z = createEmbeddedAttemptSessionSettleTracker(q);
e.externalAbortController.setActiveSessionAbort(Z.abortActiveSession);
n.buildAbortSettlePromise = Z.buildAbortSettlePromise;
e.onSessionYieldReady({
abortActiveSession: Z.abortActiveSession,
activeSession: q
});
const re = installEmbeddedAttemptContextGuards({
...j,
activeSession: q,
computerContextEpoch: C,
dropThinkingBlocksForEstimate: I.dropThinkingBlocks,
effectiveFsWorkspaceOnly: c,
getPrePromptMessageCount: () => K.prePromptMessageCount,
getPromptCache: () => K.promptCache,
onCurrentTurnImageFailure: recordCurrentTurnImageFailure,
getPromptCacheRetention: () => oe.effectivePromptCacheRetention,
getCompactionReplayEnabled: () => oe.compactionReplayEnabled,
getServerToolClearingEnabled: () => oe.serverToolClearingEnabled,
toolResultPromptProjectionState: X,
getSystemPrompt: () => K.systemPromptText,
isOpenAIResponsesApi: N,
repairToolUseResultPairing: I.repairToolUseResultPairing,
sessionManager: F,
settingsManager: J,
sandbox: m
});
n.removeToolResultContextGuard = re.remove;
const ie = {
env: process.env,
runId: t.runId,
sessionId: q.sessionId,
sessionKey: t.sessionKey,
provider: t.provider,
modelId: t.modelId,
modelApi: t.model.api,
workspaceDir: t.workspaceDir
};
const ae = createCacheTrace({
cfg: t.config,
...ie
});
const Q = createAnthropicPayloadLogger(ie);
let $ = null;
{
const e = te.clientToolDefs.length;
const n = i.ownedTranscriptWriteContext?.sessionTarget;
const r = n?.sessionKey;
const a = i.ownedTranscriptWriteContext?.assertCommitAllowed;
const o = i.ownedTranscriptWriteContext?.initialWriter;
const s = n && r && a && n.agentId === g && n.sessionId === q.sessionId && r === t.sessionKey && n.storePath && n.storePath === t.sessionTarget?.storePath ? {
sessionKey: r,
assertCurrent() {
a();
o?.assertActive();
}
} : void 0;
s?.assertCurrent();
const c = s ? s.sessionKey : await resolveAttemptTrajectorySessionFile({
agentId: g,
config: t.config,
sessionFile: t.sessionFile,
sessionId: q.sessionId,
sessionKey: t.sessionKey,
sessionTarget: t.sessionTarget
});
if (!t.disableTrajectory && t.sessionPersistence !== "detached") {
const n = resolveAdmittedRunActiveAssertion(t.admittedRunContext, t.abortSignal);
if (!n) throw new Error("trajectory preparation requires an active admitted run");
n();
s?.assertCurrent();
const { sessionTarget: r } = projectTrajectorySessionTarget(t.sessionTarget);
const i = await createTrajectoryRuntimeRecorder({
cfg: t.config,
env: process.env,
runId: t.runId,
sessionId: q.sessionId,
sessionKey: t.sessionKey,
sessionFile: c,
sessionTarget: r,
provider: t.provider,
modelId: t.modelId,
modelApi: t.model.api,
workspaceDir: t.workspaceDir
});
n();
s?.assertCurrent();
i?.recordEvent("session.started", {
trigger: t.trigger,
sessionFile: t.sessionFile,
workspaceDir: l,
agentId: g,
messageProvider: t.messageProvider,
messageChannel: t.messageChannel,
localModelLean: w,
toolCount: A,
clientToolCount: e
});
const a = typeof t.fastMode === "boolean" ? t.fastMode : void 0;
i?.recordEvent("trace.metadata", buildTrajectoryRunMetadata({
env: process.env,
config: t.config,
...t.preparedModelRuntime?.metadataSnapshot ? { pluginMetadataSnapshot: t.preparedModelRuntime.metadataSnapshot } : {},
workspaceDir: l,
sessionFile: t.sessionFile,
sessionKey: t.sessionKey,
agentId: g,
trigger: t.trigger,
messageProvider: t.messageProvider,
messageChannel: t.messageChannel,
provider: t.provider,
modelId: t.modelId,
modelApi: t.model.api,
timeoutMs: t.timeoutMs,
fastMode: a,
thinkLevel: t.thinkLevel,
reasoningLevel: t.reasoningLevel,
toolResultFormat: t.toolResultFormat,
disableTools: t.disableTools,
toolsAllow: t.toolsAllow,
skillsSnapshot: t.skillsSnapshot,
systemPromptReport: O
}));
$ = i;
}
}
n.trajectoryRecorder = $;
const oe = await prepareEmbeddedAttemptTransport({
attempt: t,
contextEngineInfo: e.activeContextEngine?.info,
assertCronRootCurrent: i.assertCronRootCurrent,
session: q,
settingsManager: J,
providerThinkingLevel: p,
sessionAgentId: g,
workspaceDir: l,
workspaceOnly: c,
agentDir: e.agentDir,
abortSignal: r,
getProviderRuntimeHandle: d,
onCurrentTurnImageFailure: recordCurrentTurnImageFailure,
sandboxSessionKey: h,
...m !== void 0 ? { sandbox: m } : {},
codeModeControlsEnabled: S,
providerPromptState: {
state: getProviderPromptState(t.runId),
effectiveContextTokenBudget: Math.max(1, Math.floor(t.contextTokenBudget ?? t.model.contextWindow ?? 2e5)),
...$ ? { recordEvent: $.recordEvent } : {}
}
});
return {
agentSession: te,
anthropicPayloadLogger: Q,
boundary: Y,
cacheTrace: ae,
contextGuards: re,
isOpenAIResponsesApi: N,
preparedUserTurnMessage: P,
prepareSystemPromptUpdate: U,
sessionManager: F,
sessionPromptState: R,
settleTracker: Z,
state: K,
toolResultPromptProjectionState: X,
trajectoryRecorder: $,
transcriptPolicy: I,
transport: oe
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-catalog.ts
function hasExplicitlyAllowedClientTool(e) {
const t = (e.clientTools ?? []).map((e) => e.function?.name).filter((e) => Boolean(e?.trim()));
if (t.length === 0) return false;
const n = e.explicitAllowlistSources.map((e) => createToolPolicyMatcher({ allow: e.entries }));
return t.some((e) => n.some((t) => t(e)));
}
async function prepareEmbeddedAttemptToolCatalog(e) {
const buildCatalog = (t) => {
const { attempt: n, preparedToolBase: r } = e;
const { codeModeControlsEnabledForRun: i, codeModeSkills: a, localModelLeanPreserveToolNames: o, runtimeCapabilityProfile: s, toolSearchConfig: c, toolSearchControlsEnabledForRun: l, toolsEnabled: u } = r;
const { clientTools: d, uncompactedEffectiveTools: f } = e.bundleTools;
const p = r.toolAbortSignal ?? e.abortSignal;
let m = n.toolExecutionAllow ? gateToolExecution(f, n.toolExecutionAllow) : f;
const h = r.toolHookContext;
const g = r.toolSurfaceRuntime.compactTools(m, {
hookContext: h,
prepared: {
abortSignal: p,
toolExecutionAllow: n.toolExecutionAllow,
executeTool: e.executeCodeModeTool,
codeModeSkills: a,
preserveToolNames: o
}
});
const _ = g.catalog;
t({
diagnostics: g.diagnostics,
tools: g.projectedTools,
runId: n.runId,
agentId: e.setup.sessionAgentId,
sessionKey: n.sessionKey,
sessionId: n.sessionId
});
m = normalizeAgentRuntimeTools({
runtimePlan: n.runtimePlan,
tools: g.tools,
provider: n.provider,
config: n.config,
workspaceDir: e.setup.effectiveWorkspace,
env: process.env,
modelId: n.modelId,
modelApi: n.model.api,
model: n.model,
runtimeHandle: e.setup.getProviderRuntimeHandle()
}).map((e) => wrapEmbeddedAttemptToolWithActivity(wrapToolWithAbortSignal(e, p), n.runId));
if (i && isCodeModeDiagnosticEnabled()) logCodeModeDiagnostic(log$2, "final-surface", {
runId: n.runId,
fallbackActive: n.fallbackActive === true,
catalogToolCount: _.catalogToolCount,
visibleToolNames: m.map((e) => e.name)
});
if (_.compacted && !_.catalogReused) emitTrustedDiagnosticEvent({
type: "tool.catalog",
source: "builtin",
mode: i ? "code-mode" : "tool-search",
toolCount: _.catalogToolCount
});
const v = l && c.mode === "directory" && _.catalogRegistered;
const { agentId: y, globalPolicy: b, globalProviderPolicy: x, agentPolicy: S, agentProviderPolicy: C, groupPolicy: w, sandboxPolicy: T, subagentPolicy: E, inheritedToolPolicy: D } = s.policy;
const O = y ? `agents.${y}.tools` : "agent tools";
const k = [
{
label: "tools.allow",
allow: b?.allow
},
{
label: "tools.byProvider.allow",
allow: x?.allow
},
{
label: `${O}.allow`,
allow: S?.allow
},
{
label: `${O}.byProvider.allow`,
allow: C?.allow
},
{
label: "group tools.allow",
allow: w?.allow
},
{
label: "sandbox tools.allow",
allow: T?.allow
},
{
label: "subagent tools.allow",
allow: E?.allow
},
{
label: "inherited tools.allow",
allow: D?.allow
},
{
label: "runtime toolsAllow",
allow: n.toolsAllow,
enforceWhenToolsDisabled: true
}
].flatMap(({ label: e, allow: t, enforceWhenToolsDisabled: n }) => {
const r = normalizeStringEntries(t);
return r.length === 0 ? [] : [{
label: e,
entries: r,
enforceWhenToolsDisabled: n
}];
});
const A = createToolSearchSelectionMatcher(i ? void 0 : c);
const j = new Set(_.catalogRegistered && (i || c.enabled && c.mode !== "directory") ? (d ?? []).map((e) => e.function.name).filter((e) => A({
source: "client",
name: e
})) : []);
const M = l || i;
const N = i ? [CODE_MODE_EXEC_TOOL_NAME, CODE_MODE_WAIT_TOOL_NAME] : c.mode === "directory" ? [
TOOL_SEARCH_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_CALL_RAW_TOOL_NAME
] : [...TOOL_SEARCH_CONTROL_TOOL_NAMES];
const P = collectAllowedToolNames({
tools: m,
clientTools: d?.filter((e) => !j.has(e.function.name))
});
const F = collectAllowedToolNames({
tools: f,
clientTools: d
});
const I = collectAllowedToolNames({ tools: [...v ? f : m].filter((e) => {
const t = getPluginToolMeta(e);
return !t?.mcp && t?.pluginId !== "bundle-mcp";
}) });
for (const e of r.toolSurfaceRuntime.toolSearchCatalogRef?.current?.entries ?? []) if (e.source === "openclaw") I.add(normalizeToolPolicyName(e.name));
if (M) {
for (const e of N) if (P.has(e)) F.add(e);
}
const L = v ? collectUniqueCatalogToolNames(f) : P;
if (v) {
for (const e of TOOL_SEARCH_CONTROL_TOOL_NAMES) if (!P.has(e)) {
L.delete(e);
I.delete(e);
}
for (const e of P) L.add(e);
}
const R = new Set(k.flatMap((e) => e.entries.map((e) => normalizeToolPolicyName(e))));
const z = new Set((M ? N : []).filter((e) => !R.has(normalizeToolPolicyName(e))));
const ee = hasExplicitlyAllowedClientTool({
clientTools: d,
explicitAllowlistSources: k
});
const B = v ? collectAllowedToolNames({ tools: m }) : P;
const V = _.catalogToolCount > 0 || (j.size > 0 || v) && ee || [...B].some((e) => !z.has(e));
const H = {
visibleAllowedToolNames: P,
replayAllowedToolNames: F,
liveAllowedToolNames: L,
capabilityToolNames: I,
hasCallableTools: V
};
const U = (() => {
const t = n.disableTools === true || r.effectiveToolsAllow?.length === 0 || s.policy.explicitToolDenylist.includes("*");
const i = t ? k.filter((e) => e.enforceWhenToolsDisabled === true) : k;
if (i.length === 0 || V) return null;
const a = i.map((e) => `${e.label}: ${e.entries.map(normalizeToolPolicyName).join(", ")}`).join("; ");
const o = i.every((e) => isToolAllowedByPolicyName("skill_workshop", { allow: e.entries })) ? resolveSkillWorkshopToolConstructionBlock({
sandboxed: e.setup.sandbox?.enabled,
libraryAuthoring: n.skillLibraryAuthoring
}) : void 0;
if (u && !t && o) return /* @__PURE__ */ new Error(`No callable tools remain after resolving explicit tool allowlist (${a}); ${o.detail} ${o.fix}`);
const c = n.disableTools === true ? "tools are disabled for this run" : u ? "no registered tools matched" : "the selected model does not support tools";
return /* @__PURE__ */ new Error(`No callable tools remain after resolving explicit tool allowlist (${a}); ${c}. Fix the allowlist or enable the plugin that registers the requested tool.`);
})();
logAgentRuntimeToolDiagnostics({
runtimePlan: n.runtimePlan,
tools: m,
provider: n.provider,
config: n.config,
workspaceDir: e.setup.effectiveWorkspace,
env: process.env,
modelId: n.modelId,
modelApi: n.model.api,
model: n.model,
runtimeHandle: e.setup.getProviderRuntimeHandle()
});
return {
catalogToolHookContext: h,
deferredDirectoryToolsCallable: v,
effectiveTools: m,
emptyExplicitToolAllowlistError: U,
toolSearch: _,
toolSearchRunPlan: H
};
};
const t = await withRuntimeToolSchemaQuarantine(buildCatalog);
const n = [
"visibleAllowedToolNames",
"liveAllowedToolNames",
"capabilityToolNames"
];
const r = {
visibleAllowedToolNames: new Set(t.toolSearchRunPlan.visibleAllowedToolNames),
liveAllowedToolNames: new Set(t.toolSearchRunPlan.liveAllowedToolNames),
capabilityToolNames: new Set(t.toolSearchRunPlan.capabilityToolNames)
};
return Object.assign(t, {
applyPromptToolPolicy: (e) => {
if (!t.toolSearch.catalogRegistered) finalizeAgentToolAvailability(t.effectiveTools, { toolExecutionAllow: [...e] });
for (const i of n) {
const n = t.toolSearchRunPlan[i];
n.clear();
for (const t of r[i]) if (e.has(t)) n.add(t);
}
},
refreshTools: (e) => {
const i = buildCatalog(e);
t.effectiveTools.splice(0, t.effectiveTools.length, ...i.effectiveTools);
for (const e of [...n, "replayAllowedToolNames"]) {
const n = t.toolSearchRunPlan[e];
if (e !== "replayAllowedToolNames") n.clear();
for (const t of i.toolSearchRunPlan[e]) n.add(t);
}
Object.assign(t.toolSearch, i.toolSearch);
for (const e of n) r[e] = new Set(i.toolSearchRunPlan[e]);
t.emptyExplicitToolAllowlistError = i.emptyExplicitToolAllowlistError;
t.toolSearchRunPlan.hasCallableTools = i.toolSearchRunPlan.hasCallableTools;
}
});
}
function gateToolExecution(e, t) {
const n = createToolExecutionMatcher(t);
return e.map((e) => n(e.name) || TOOL_SEARCH_CONTROL_TOOL_NAMES.has(e.name) ? e : gateAgentToolExecution(e, formatToolExecutionGatedMessage(e.name, t)));
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-prepare.ts
async function prepareEmbeddedAttemptToolBase(e) {
const { attempt: t } = e;
let n;
const r = readAdmittedRunOperatorAuthority(t.admittedRunContext);
const i = t.skillsSnapshot;
const a = captureAgentWorkspaceReadiness(t.sessionKey);
const o = t.awaitSessionDiffBaseline;
const s = o ? resolveAdmittedRunActiveAssertion(t.admittedRunContext, e.runAbortController.signal) : void 0;
const c = o ? async () => {
try {
if (!s) throw new Error("session attribution requires active admitted run authority");
s();
await o();
s();
} catch (t) {
e.runAbortController.abort(t);
throw t;
}
} : void 0;
const l = t.completionCheck;
const u = t.requireExplicitMessageTarget ?? isSubagentSessionKey(t.sessionKey);
const d = messageToolOwnsVisibleReply(t);
const f = buildEmbeddedAttemptToolRunContext(t, {
forceMessageTool: d,
trace: e.runTrace
});
const p = f.runtimeToolAllowlist;
const m = supportsModelTools(t.model);
const h = t.modelRun === true || t.promptMode === "none";
const g = resolveEmbeddedAttemptToolConstructionPlan({
disableTools: t.disableTools,
isRawModelRun: h,
toolsEnabled: m,
toolsAllow: p
});
const _ = createAgentHarnessToolSurfaceRuntimeCore({
config: t.config,
trigger: t.trigger,
agentId: e.setup.sessionAgentId,
sessionKey: e.setup.sandboxSessionKey,
forceMessageTool: d,
model: t.model,
modelProvider: t.provider,
modelId: t.modelId,
codeModeOverride: t.codeModeOverride,
disableToolSearch: t.disableToolSearch,
modelToolsEnabled: m,
disableTools: t.disableTools,
isRawModelRun: h,
toolsAllow: t.toolsAllow,
runtimeToolAllowlist: p,
sessionId: t.sessionId,
runId: t.runId,
contextTokenBudget: t.contextTokenBudget,
executeTool: e.toolSearchCatalogExecutor
});
const { codeModeControlsEnabled: v, toolSearchConfig: y, toolSearchControlsEnabled: b, toolSearchRuntimeConfig: x } = _.plan;
if (isCodeModeDiagnosticEnabled()) logCodeModeDiagnostic(log$2, "activation", {
runId: t.runId,
modelProvider: t.provider,
modelId: t.modelId,
modelCodeMode: extractModelCompat(t.model)?.codeMode ?? "unflagged",
active: v,
toolsEnabled: m,
rawRun: h,
toolsDisabled: t.disableTools === true,
fallbackActive: t.fallbackActive === true,
allowlist: t.toolsAllow === void 0 ? "unset" : t.toolsAllow.length === 0 ? "empty" : "nonempty"
});
const S = mergeForcedEmbeddedAttemptToolsAllow(p, { forceToolNames: b ? [...TOOL_SEARCH_CONTROL_TOOL_NAMES] : [] });
const C = g.constructTools || b || v;
const w = { value: 0 };
const T = /* @__PURE__ */ new Map();
const E = _.toolSearchCatalogRef;
const D = createAttemptNestedToolActivityState();
const O = toolPolicyRestrictsTools({ allow: t.toolsAllow }) ? [] : e.codeModeSkills;
const k = [];
const A = {};
const j = [];
const M = [];
const N = [];
const P = /* @__PURE__ */ new Set();
let F = false;
const retireToolGeneration = (e) => {
const t = N.splice(0);
const n = Promise.allSettled(t.map(async (t) => await t(e))).then((e) => {
F ||= e.some((e) => e.status === "rejected");
});
P.add(n);
n.then(() => P.delete(n));
};
const I = e.setup.effectiveCwd !== e.setup.effectiveWorkspace ? e.setup.resolvedWorkspace : resolveAttemptSpawnWorkspaceDir({
sandbox: e.setup.sandbox,
resolvedWorkspace: e.setup.resolvedWorkspace
});
const buildConversationContext = () => ({
...f,
requireExplicitMessageTarget: u,
config: x,
sessionKey: e.setup.sandboxSessionKey,
runSessionKey: t.sessionKey?.trim() || t.sessionId,
sessionId: t.sessionId,
runId: t.runId,
agentDir: e.agentDir,
messageProvider: t.messageProvider ?? t.messageChannel,
messageChannel: t.messageChannel,
modelProvider: t.provider,
modelId: t.modelId,
modelApi: t.model.api,
modelBaseUrl: t.model.baseUrl,
modelParams: t.model.params,
modelContextWindowTokens: t.contextTokenBudget ?? t.model.contextWindow,
modelHasVision: t.model.input?.includes("image") ?? false,
workspaceDir: e.setup.effectiveWorkspace,
cwd: e.setup.effectiveCwd,
spawnWorkspaceDir: I,
skillsSnapshot: e.skillsSnapshot,
runtimeToolAllowlist: S
});
const L = await prepareConversationCapabilityProfile({
...buildConversationContext(),
agentId: t.sandboxAgentId ?? e.setup.sessionAgentId,
conversationToolPolicy: t.conversationToolPolicy,
sandboxToolPolicy: e.setup.sandbox?.tools,
inheritRuntimeToolAllowlist: true,
runtimePluginToolGrant: t.runtimePluginToolGrant,
inputProvenance: t.inputProvenance,
trustedInternalHandoff: t.trustedInternalHandoff,
pluginMetadataSnapshot: t.preparedModelRuntime?.metadataSnapshot
});
const R = resolveSessionPlacementComputer(t.admittedRunContext.operationalRunInstance);
const allowsConversationTool = (e) => projectConversationToolNames({
capabilityProfile: L,
toolNames: [e],
warn: () => void 0
}).length === 1;
const z = C && allowsConversationTool("computer");
const ee = (await loadPairedComputerUseAvailabilityForSurface({
computerAllowed: z,
modelHasVision: t.model.input?.includes("image") ?? true,
computerTransport: R,
embeddedMode: isEmbeddedMode(),
signal: e.runAbortController.signal
}))?.prepared;
const B = isLocalModelLeanEnabled({
config: t.config,
agentId: e.setup.sessionAgentId,
sessionKey: t.sessionKey
});
const V = resolveLocalModelLeanPreserveToolNames({
toolNames: L.policy.explicitToolOverrideAllowlist,
forceMessageTool: t.forceMessageTool,
sourceReplyDeliveryMode: t.sourceReplyDeliveryMode
});
const H = { declaredReplaySafe: (e) => {
const t = getPluginToolMeta(e);
if (t) return t.replaySafe === true;
return getChannelAgentToolMeta(e) ? false : void 0;
} };
let U = false;
const constructTools = async (o, s) => {
U = false;
M.length = 0;
let u = [];
if (C) {
const d = resolveAdmittedRunActiveAssertion(t.admittedRunContext, s);
const f = {
awaitSessionDiffBaseline: c,
getRunAbortDeadlineAtMs: () => n?.(),
pluginExecutionAuthority: r,
pluginExecutionSkillsSnapshot: i,
assertInvocationCurrent: d,
agentId: e.setup.sessionAgentId,
...buildConversationContext(),
exec: {
...t.execOverrides,
...o ? { mode: resolveSessionPermissionExecMode(o) } : {},
config: t.config,
elevated: t.bashElevated,
reviewTranscript: e.reviewTranscript
},
sandbox: e.setup.sandbox,
stagedMediaPaths: resolveStagedInputMediaPaths(t.media),
sessionPermissionPolicy: o,
channelContext: t.channelContext,
allowGatewaySubagentBinding: t.allowGatewaySubagentBinding,
operationalRunInstance: t.admittedRunContext.operationalRunInstance,
computerTransport: R,
pairedNodeComputerUse: ee,
conversationRecall: t.conversationRecall,
memoryAudience: t.memoryAudience,
oneShotCliRun: t.oneShotCliRun,
toolSearchCatalogRef: E,
codeModeSkills: O,
installedSkills: e.installedSkills,
preparedModelRuntime: t.preparedModelRuntime,
readDelegationConfig: getPreparedModelRuntimePolicyConfigReader(t.preparedModelRuntime),
requireWorkspaceOnly: t.requireWorkspaceOnly,
sessionReadScopeKey: t.sessionReadScopeKey,
sessionConfigSource: t.oneShotCliRun ? "pinned" : "runtime",
webSearchEnabled: t.toolOverrides?.webSearch !== false,
onWebSearchConfiguration: (n) => {
U = !n && allowsConversationTool("web_search") && resolveNativeWebSearchRoute({
...buildConversationContext(),
agentId: e.setup.sessionAgentId,
webSearchEnabled: t.toolOverrides?.webSearch !== false,
sandboxToolPolicy: e.setup.sandbox?.tools,
authStore: t.authProfileStore,
preparedRequesterPolicy: L.policy,
pluginMetadataSnapshot: t.preparedModelRuntime?.metadataSnapshot
}).kind === "managed";
},
githubPublicationAvailable: t.githubPublicationAvailable,
abortSignal: s,
skillWorkshop: {
...t.skillWorkshopReviewOf ? { reviewOf: t.skillWorkshopReviewOf } : {},
libraryAuthoring: t.skillLibraryAuthoring
},
modelCompat: extractModelCompat(t.model),
delegationCapability: t.delegationCapability,
modelAuthMode: await resolveModelAuthModeAsync(t.model.provider, t.config, t.authProfileStore, { workspaceDir: e.setup.effectiveWorkspace }),
includeCoreTools: g.includeCoreTools,
includeToolSearchControls: b,
toolSearchCatalogExecutor: e.toolSearchCatalogExecutor,
toolConstructionPlan: g.codingToolConstructionPlan,
computerContextEpoch: w,
skillInstructionDeliveryCache: T,
registerRunCleanup: (e) => N.push(e),
inboundEventKind: t.currentInboundEventKind,
inputProvenance: t.inputProvenance,
disableMessageTool: t.disableMessageTool,
forceMessageTool: t.forceMessageTool,
inheritedToolAllowlistRef: j,
additionalInheritedToolNamesRef: M,
cronCreatorToolAllowlistRef: k,
cronCreatorToolAllowlistCaptureRef: A,
authProfileStore: t.authProfileStore,
recordToolPrepStage: e.markCoreToolStage,
onToolOutcome: t.onToolOutcome,
isTurnTainted: t.isTurnTainted,
allocateToolOutcomeOrdinal: t.allocateToolOutcomeOrdinal,
skillUsagePaths: e.skillUsagePaths,
conversationCapabilityProfile: L,
onProgressCardPlanSaved: l ? (e) => {
l.unfinishedPlan = e;
} : void 0,
onYield: e.onYield
};
const p = await createOpenClawCodingToolsInternalAsync(f, e.skillReadResources, void 0, void 0, {
reader: getReplyOperationSessionReader(t.replyOperation),
assertCurrent: d
});
let m = p;
if (t.hostCapabilities) m = t.hostCapabilities.bindToolSurface(p);
else if (a) {
if (!d) throw new Error("Workspace tools require active run authority");
m = p.map((e) => isWorkspaceTool(e) ? gateBoundTool(e, d, () => {}, a) : e);
}
e.markCoreToolStage("attempt:create-openclaw-coding-tools");
u = applyEmbeddedAttemptToolsAllow(m, S, { toolMeta: (e) => getPluginToolMeta(e) });
e.markCoreToolStage("attempt:tools-allow");
}
const d = u;
assertMemoryFlushPersistenceToolAvailable(d, t.memoryFlushTools);
return d;
};
let W = new AbortController();
let G = AbortSignal.any([e.runAbortController.signal, W.signal]);
const K = { ...t.permissionChange?.baseExecOverrides ?? t.execOverrides };
const releaseTools = async (e) => {
W.abort();
materializeErrorStack(W.signal.reason);
retireToolGeneration(e);
await Promise.all(P);
if (F) recordAgentCleanupFailure();
};
try {
const r = await constructTools(e.setup.sessionPermissionPolicy, G);
return {
bindRunAbortDeadline: (e) => {
n = e;
},
toolHookContext: {
getRunAbortDeadlineAtMs: () => n?.(),
awaitSessionDiffBaseline: c,
watchdogAttempt: getGatewayToolCallerIdentity()?.watchdogAttempt,
agentId: e.setup.sessionAgentId,
config: t.config,
cwd: e.setup.effectiveCwd,
sessionKey: e.setup.sandboxSessionKey,
sessionId: t.sessionId,
runId: t.runId,
approvalReviewerDeviceId: t.approvalReviewerDeviceId,
channelId: t.currentChannelId,
trace: e.runTrace,
loopDetection: resolveToolLoopDetectionConfig({
cfg: t.config,
agentId: e.setup.sessionAgentId
}),
onToolOutcome: t.onToolOutcome,
allocateToolOutcomeOrdinal: t.allocateToolOutcomeOrdinal
},
get toolAbortSignal() {
return G;
},
refreshPermissionMode: async (n, i) => {
W.abort(createCodeModePermissionChangeReason());
materializeErrorStack(W.signal.reason);
i();
retireToolGeneration("cancel");
e.runAbortController.signal.throwIfAborted();
W = new AbortController();
G = AbortSignal.any([e.runAbortController.signal, W.signal]);
t.permissionMode = n ?? void 0;
t.execOverrides = { ...K };
const a = n ? {
root: e.setup.sessionPermissionRoot,
mode: n
} : void 0;
const o = await constructTools(a, G);
r.splice(0, r.length, ...o);
},
get webSearchUnconfigured() {
return U;
},
codeModeControlsEnabledForRun: v,
codeModeSkills: O,
computerContextEpoch: w,
skillInstructionDeliveryCache: T,
cronCreatorToolAllowlist: k,
cronCreatorToolAllowlistCaptureRef: A,
effectiveToolsAllow: S,
forceDirectMessageTool: d,
requireExplicitMessageTarget: u,
inheritedToolAllowlist: j,
additionalInheritedToolNamesRef: M,
localModelLeanEnabled: B,
localModelLeanPreserveToolNames: V,
replaySafetyOptions: H,
runtimeCapabilityProfile: L,
releaseTools,
toolSearchCatalogRef: E,
toolSurfaceRuntime: _,
toolSearchConfig: y,
toolSearchControlsEnabledForRun: b,
toolSearchRuntimeConfig: x,
nestedToolActivityState: D,
toolsEnabled: m,
toolsRaw: r
};
} catch (e) {
try {
await runOwnedAgentCleanup({
runId: t.runId,
sessionId: t.sessionId,
oneShotCliRun: t.oneShotCliRun,
step: "embedded-tool-preparation",
cleanup: () => releaseTools("error"),
log: log$2
});
} catch {
recordAgentCleanupFailure();
}
throw e;
}
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle.ts
/** Serializes run-owned transcript callbacks and bounds teardown settlement. */
const TRANSCRIPT_TEARDOWN_BUDGET_MS = 3e4;
const lifecycleOwners = new AsyncLocalStorage();
function createEmbeddedAttemptTranscriptLifecycle(e) {
let t = false;
let n = Promise.resolve();
let r;
let i;
let a = 0;
const o = Symbol("transcript-attempt");
const currentOwner = () => {
for (let e = lifecycleOwners.getStore(); e; e = e.parent) if (e.attempt === o) return e;
};
const createLifecycleOwner = () => ({
attempt: o,
parent: lifecycleOwners.getStore(),
active: true,
nestedTail: Promise.resolve(),
pendingOperations: /* @__PURE__ */ new Set()
});
const drainLifecycleOwner = async (e) => {
let t;
while (e.pendingOperations.size > 0) {
const n = [...e.pendingOperations];
e.pendingOperations.clear();
const r = (await Promise.allSettled(n)).find((e) => e.status === "rejected");
if (t === void 0 && r?.status === "rejected") t = toErrorObject(r.reason, "nested transcript write failed");
}
if (t !== void 0) throw t;
};
const runLifecycleOwner = async (e, t) => {
let n;
let r;
try {
n = await runWithAsyncStore(lifecycleOwners, e, async () => await t());
} catch (e) {
r = toErrorObject(e, "transcript write failed");
}
let i;
try {
await drainLifecycleOwner(e);
} catch (e) {
i = toErrorObject(e, "nested transcript drain failed");
} finally {
e.active = false;
}
if (r !== void 0 && i !== void 0 && i !== r && r.cause === void 0) try {
r.cause = i;
} catch {}
const a = r ?? i;
if (a !== void 0) throw a;
return n;
};
const serializeLifecycle = async (e) => {
const t = currentOwner();
if (t?.active) {
const n = t.nestedTail.then(async () => await runLifecycleOwner(createLifecycleOwner(), e));
t.nestedTail = n.then(() => void 0, () => void 0);
const r = n.then(() => void 0);
r.catch(() => {});
t.pendingOperations.add(r);
return await n;
}
const r = n;
const { promise: i, resolve: a } = createDeferredCore();
n = i;
await r;
const o = createLifecycleOwner();
try {
return await runLifecycleOwner(o, e);
} finally {
a();
}
};
const settleWithinTeardownBudget = async (t) => {
if (!await settlesWithin(t, TRANSCRIPT_TEARDOWN_BUDGET_MS)) log$2.error(`transcript teardown budget expired: runId=${e.runId ?? "unknown"} sessionId=${e.sessionId ?? "unknown"} pendingWrites=${a} timeoutMs=${TRANSCRIPT_TEARDOWN_BUDGET_MS}`);
};
const beginCleanup = async (t) => {
if (currentOwner()?.active) throw new Error("cannot start attempt cleanup inside a transcript write callback");
r ??= settleWithinTeardownBudget(serializeLifecycle(async () => {
currentOwner().active = false;
try {
await e.onDrained?.();
} finally {
t?.();
}
}));
await r;
};
return {
withTranscriptWrite: (e) => {
const n = currentOwner()?.active === true;
if ((r || t) && !n) {
const e = Promise.reject(/* @__PURE__ */ new Error(t ? "attempt disposed before transcript write" : "attempt cleanup started before transcript write"));
e.catch(() => {});
return e;
}
a += 1;
const i = serializeLifecycle(e);
i.finally(() => {
a -= 1;
}).catch(() => {});
return i;
},
beginCleanup,
dispose: async () => {
if (currentOwner()?.active) throw new Error("cannot dispose an attempt from inside a transcript write callback");
i ??= (async () => {
await beginCleanup();
t = true;
})();
await i;
}
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-transcript-lifecycle-prepare.ts
/** Prepares the admitted writer context and teardown tracker for one attempt. */
async function prepareEmbeddedAttemptTranscriptLifecycle({ runAbortController: e, attempt: { abortSignal: t, admittedRunContext: n, config: r, runId: i, replyOperation: a, sessionFile: o, sessionId: s, sessionKey: c, sessionManager: l, sessionPersistence: u, sessionTarget: d, preparedSessionTarget: f }, externalAbortController: p }) {
f?.assertCurrent();
const m = getOwnedSessionTranscriptInitialWriter({
sessionFile: o,
sessionKey: c,
sessionTarget: l?.getSessionTarget() ?? d
});
const h = f?.target ?? await resolveAgentRunSessionTarget({
agentId: d?.agentId,
config: r,
missingSessionKey: "resolve-existing",
sessionFile: o,
sessionId: s,
sessionKey: c,
sessionPersistence: u,
sessionTarget: d
});
await p.throwIfFiredAfterPrepCleanup();
f?.assertCurrent();
m?.assertActive();
const g = {
...h,
expectedLifecycleRevision: d?.expectedLifecycleRevision,
expectedWriterRunId: d?.expectedWriterRunId
};
const _ = await prepareCronRootSessionGeneration({
...h,
sessionKey: c ?? h.sessionKey,
lifecycleRevision: g.expectedLifecycleRevision
}, e ? (t) => e.abort(t) : void 0);
const v = createEmbeddedAttemptTranscriptLifecycle({
runId: i,
sessionId: s,
onDrained: async () => {
try {
await S.sessionActor?.actor.release();
} finally {
_?.release();
}
}
});
const y = f?.assertCurrent ?? (n ? resolveAdmittedRunActiveAssertion(n, t) : void 0);
const { writeContext: b } = captureAgentRunTerminalPersistence(i);
const x = composeSessionSourceAssertion([b?.assertCurrent, _?.assertCurrent]);
const withTranscriptWrite = (e) => m ? m.withTranscriptWrite(() => v.withTranscriptWrite(e)) : v.withTranscriptWrite(e);
const S = {
sessionFile: o,
sessionKey: c,
sessionTarget: g,
sessionReader: getReplyOperationSessionReader(a),
...m ? { initialWriter: m } : {},
assertCommitAllowed: composeSessionSourceAssertion([y, _?.assertCurrent], (e) => {
t?.throwIfAborted();
e();
}),
withTranscriptWrite,
withRestartAbortWrite: b ? async (n) => {
if (!isAgentRunRestartAbortReason(t?.reason) && !isAgentRunRestartAbortReason(e?.signal.reason)) throw new Error("Interrupted transcript write requires a restart abort");
const r = m?.committedFence ?? g;
if (!r.expectedWriterRunId || m && !m.committedFence) throw new SessionTranscriptWriterClaimReboundError();
return await v.withTranscriptWrite(() => b.run(() => withOwnedSessionTranscriptWrites({
...S,
sessionTarget: {
...g,
...r
},
initialWriter: void 0,
settledInitialWriter: m,
sessionReader: void 0,
assertCommitAllowed: x,
withTranscriptWrite: (e) => v.withTranscriptWrite(e),
withRestartAbortWrite: void 0
}, n)));
} : void 0
};
try {
const assertCurrent = () => {
m?.assertActive();
S.assertCommitAllowed?.();
};
assertCurrent();
if (u !== "detached") {
const e = S.sessionReader;
if (e) assertSessionEntryCohortScope(e, g);
const t = b ? x : assertCurrent;
const n = {
assertCurrent: t,
assertReadable: t
};
const r = captureSessionManagerIncognitoBinding(g, l);
if (r) {
const e = await r.acquire(false, n);
if (!e) throw new IncognitoSessionMissingError();
S.sessionActor = {
actor: e,
database: r.database
};
} else {
const t = e?.database ?? toDatabaseOptions(resolveSqliteReadScope(g));
const r = {
...t,
env: Object.freeze({ ...t.env ?? process.env }),
path: resolveOpenClawAgentSqlitePath(t)
};
const { createSessionActorFactory: i } = await import("./session-actor-durable-CzuTz_1a.mjs");
assertCurrent();
let a = readDatabasePathIdentitySync(r.path);
if (a.key.startsWith("path:")) {
await prepareSessionEntryReplacementDatabase(r, assertCurrent);
assertCurrent();
a = readDatabasePathIdentitySync(r.path);
}
const o = await i(r).acquire({
database: {
kind: "file",
physicalIdentity: a.key.slice(5),
birthtime: a.birthtime,
nativeLocation: a.canonicalPath
},
sessionKey: h.sessionKey
}, n);
if ("kind" in o) throw new Error("Durable session actor acquisition was declined");
S.sessionActor = {
actor: o,
database: r
};
}
}
p.arm();
await p.throwIfFiredAfterPrepCleanup();
f?.assertCurrent();
} catch (e) {
await v.dispose();
throw e;
}
return {
compactionTimeoutMs: resolveCompactionTimeoutMs(r),
assertCronRootCurrent: _ ? S.assertCommitAllowed : void 0,
ownedTranscriptWriteContext: S,
transcriptLifecycle: v,
withOwnedTranscriptWrite: (e) => withOwnedSessionTranscriptWrites(S, async () => withTranscriptWrite(e))
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt.ts
async function runEmbeddedAttempt(e) {
const t = bindOperatorModelExecution(readRunOperatorAuthority(e), {
provider: e.provider,
model: e.modelId,
cyberAccessProgram: e.cyberAccessProgram
});
try {
const n = t ? {
...e,
abortSignal: e.abortSignal ? AbortSignal.any([e.abortSignal, t.signal]) : t.signal
} : e;
const r = getAsyncWorkSignal();
const i = r ? n.abortSignal ? AbortSignal.any([n.abortSignal, r]) : r : n.abortSignal;
const a = await runWithAsyncWorkResources((e) => runEmbeddedAttemptOwned(n, (t) => e({
release: t,
releaseBeforeResultWhenIdle: true
}), i));
t?.assertCurrent();
return a;
} finally {
e.continuation = void 0;
t?.release();
}
}
async function runEmbeddedAttemptOwned(e, t, n) {
let r = e;
const i = new AbortController();
const a = await measureEmbeddedAgentPreparation("attempt.setup", () => prepareEmbeddedAttemptSetup(r), { config: r.config });
const { effectiveWorkspace: o, emitCorePluginToolStageSummary: s, prepStages: c, sandbox: l, sessionAgentId: u } = a;
let d;
const f = {
beforeAgentRunBlockedBy: void 0,
terminal: r.abortSignal?.aborted ? {
kind: "aborted",
source: "external"
} : { kind: "ok" },
trajectoryEndRecorded: false
};
let p;
const m = {
bundleMcpRuntime: void 0,
bundleLspRuntime: void 0
};
let h;
let g = false;
let _;
let v;
let y;
const b = createEmbeddedAttemptSessionResources(i.signal);
const cleanupStep = (e, t) => runOwnedAgentCleanup({
runId: r.runId,
sessionId: r.sessionId,
oneShotCliRun: r.oneShotCliRun,
step: e,
cleanup: t,
log: log$2
});
const cleanupEmbeddedPrepResourcesAfterEarlyExit = async () => {
if (g) {
clearToolSearchCatalog({ catalogRef: h });
g = false;
}
for (const e of ["bundleMcpRuntime", "bundleLspRuntime"]) try {
await m[e]?.dispose();
} catch {
recordAgentCleanupFailure();
} finally {
m[e] = void 0;
}
};
const x = createEmbeddedAttemptExternalAbortController({
abortSignal: n,
cleanupAfterEarlyAbort: cleanupEmbeddedPrepResourcesAfterEarlyExit,
runAbortController: i,
runId: r.runId,
state: f
});
const S = createEmbeddedAttemptPreparation({
config: r.config,
assertCurrent: x.throwIfFired
});
const C = resolveAdmittedRunActiveAssertion(r.admittedRunContext, r.abortSignal);
try {
const e = await S("attempt.skills", () => prepareEmbeddedSkills({
assertCurrent: () => {
x.throwIfFired();
C?.();
},
includeCodeModeSkills: true,
attempt: r,
effectiveWorkspace: o,
sandbox: l,
sessionAgentId: u
}));
d = e.restoreSkillEnv;
const { codeModeSkills: t, installedSkills: n, skillReadResources: w, skillUsagePaths: T, skillsPrompt: E, skillsSnapshotForRun: D } = e;
if (r.skillsSnapshot?.librarySelections?.length && l?.enabled) {
const e = remapSkillReferencePaths(r.prompt, T);
if (e !== r.prompt) r = {
...r,
prompt: e,
transcriptPrompt: r.transcriptPrompt ?? r.prompt
};
}
c.mark("skills");
const O = r.modelRun === true || r.promptMode === "none";
const k = O ? void 0 : r.contextEngine;
if (k && k.info.id !== "legacy") assertContextEngineHostSupport({
contextEngine: k,
operation: "agent-run",
host: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST
});
const resolveActiveContextEnginePluginId = () => resolveContextEngineOwnerPluginId(k);
const A = r.agentDir ?? resolveAgentDir(r.config ?? {}, u);
const { diagnosticTrace: j, runTrace: M, emitCompleted: N } = startEmbeddedAttemptDiagnostics(r);
p = N;
const P = createStageTimingTracker(Date.now);
const executeCatalogTool = (e, t) => {
if (!v) throw new Error(`${t} catalog executor is unavailable for this run.`);
return v(e);
};
const F = await S("attempt.tool-base", () => prepareEmbeddedAttemptToolBase({
agentDir: A,
attempt: r,
setup: a,
markCoreToolStage: (e) => P.mark(e),
onYield: (e, t, n, r) => {
H = V ? H && r?.conditional === true : r?.conditional === true;
V = true;
W = e;
G = t;
K = n;
},
runAbortController: i,
runTrace: M,
skillUsagePaths: T,
skillReadResources: w,
skillsSnapshot: D,
codeModeSkills: t,
installedSkills: n,
reviewTranscript: b.reviewTranscript,
toolSearchCatalogExecutor: (e) => executeCatalogTool(e, "Tool Search")
}));
h = F.toolSearchCatalogRef;
const { codeModeControlsEnabledForRun: I, toolSearchControlsEnabledForRun: L, toolSearchRuntimeConfig: R, toolsEnabled: z, toolsRaw: ee } = F;
_ = F.releaseTools;
c.mark("core-plugin-tools");
s("core-plugin-tools", P.snapshot());
const B = await S("attempt.bootstrap", () => prepareEmbeddedAttemptBootstrap({
attempt: r,
setup: a,
hasReadTool: z && ee.some((e) => e.name === "read"),
isRawModelRun: O
}));
let V = false;
let H = false;
const U = captureAgentPluginRuntimeRefresh();
let W = null;
let G;
let K;
let te = null;
const q = await S("attempt.bundle-tools", () => c.measure("bundle-tools", () => prepareEmbeddedAttemptBundleTools({
agentDir: A,
attempt: r,
setup: a,
isRawModelRun: O,
preparedToolBase: F
})));
m.bundleMcpRuntime = q.bundleMcpRuntime;
m.bundleLspRuntime = q.bundleLspRuntime;
const { clientTools: ne, uncompactedEffectiveTools: J } = q;
g = h !== void 0;
const Y = await S("attempt.tool-catalog", () => c.measure("tool-catalog", () => prepareEmbeddedAttemptToolCatalog({
attempt: r,
setup: a,
preparedToolBase: F,
bundleTools: {
clientTools: ne,
uncompactedEffectiveTools: J
},
abortSignal: i.signal,
executeCodeModeTool: (e) => executeCatalogTool(e, "Code Mode")
})));
c.mark("tool-preparation");
const { effectiveTools: X, toolSearch: Z, toolSearchRunPlan: re, deferredDirectoryToolsCallable: ie } = Y;
g = Z.catalogRegistered;
const ae = await S("attempt.system-prompt", () => prepareEmbeddedAttemptSystemPrompt({
activeContextEngine: k,
attempt: r,
setup: a,
bootstrap: B,
capabilityToolNames: re.capabilityToolNames,
effectiveTools: X,
isRawModelRun: O,
modelToolsEnabled: z,
skillsPrompt: E,
codeModeActive: I,
webSearchUnconfigured: () => F.webSearchUnconfigured,
toolSearchCatalogRef: h,
toolSearchDirectoryEnabled: L && Z.catalogRegistered,
deferredToolsDirectlyCallable: ie,
toolSearchRuntimeConfig: R
}));
const Q = await S("attempt.transcript-lifecycle", () => prepareEmbeddedAttemptTranscriptLifecycle({
attempt: r,
runAbortController: i,
externalAbortController: x
}));
try {
const e = await S("attempt.session-runtime", () => prepareEmbeddedAttemptSessionRuntime({
attempt: r,
...k ? { activeContextEngine: k } : {},
agentDir: A,
isRawModelRun: O,
resolveActiveContextEnginePluginId,
setup: a,
toolBase: F,
toolCatalog: Y,
bundleTools: q,
systemPrompt: ae,
sessionLock: Q,
runAbortSignal: i.signal,
externalAbortController: x,
resources: b.resources,
onSessionYieldReady: ({ abortActiveSession: t, activeSession: n }) => {
y = n.agent.subscribe((a) => {
if (a.type !== "turn_end" || !V || i.signal.aborted) return;
if (H && (a.message.role === "assistant" && a.message.content.some((e) => e.type === "toolCall" && e.async === true) || U.requestSource() === "tool" || r.admittedRunContext && hasCompletionMessageSessionSpawn(mergeAcceptedSessionSpawnsForRun(r.admittedRunContext.operationalRunInstance)) || a.toolResults.some((t) => e.agentSession.codeModeExecToolNames?.has(t.toolName) && isRecord(t.details) && t.details.status === "waiting"))) {
V = false;
H = false;
W = null;
G = void 0;
K = void 0;
return;
}
r.replyOperation?.yield();
queueSessionsYieldInterruptMessage(n);
i.abort(SESSIONS_YIELD_ABORT_REASON);
te = t(SESSIONS_YIELD_ABORT_REASON);
});
}
}));
const t = createPromptBuildToolPolicy({
session: e.agentSession.activeSession,
effectiveTools: X,
uncompactedEffectiveTools: J,
tools: q.tools,
catalogRef: F.toolSearchCatalogRef,
codeModeControlsEnabled: F.codeModeControlsEnabledForRun,
onApplied: (e) => {
const t = /* @__PURE__ */ new Set([...e.callableToolNames, ...e.uncompactedEffectiveTools.map((e) => e.name)]);
Y.applyPromptToolPolicy(t);
},
forceToolNames: [...F.forceDirectMessageTool ? ["message"] : [], ...r.swarmCollector && r.swarmOutputSchema ? ["structured_output"] : []]
});
const n = await runEmbeddedAttemptExecutionPhase({
attempt: r,
...k ? { activeContextEngine: k } : {},
agentDir: A,
isRawModelRun: O,
resolveActiveContextEnginePluginId,
runAbortController: i,
externalAbortController: x,
prepared: {
bootstrap: B,
bundleTools: q,
sessionRuntime: e,
systemPrompt: ae,
toolBase: F,
toolCatalog: Y,
promptToolPolicy: t
},
sessionLock: Q,
setup: a,
diagnostics: {
diagnosticTrace: j,
runTrace: M
},
state: f,
lifecycle: {
applyPermissionMode: (n, i) => withRuntimeToolSchemaQuarantine(async (a) => {
r.permissionChange?.recordApplied(n);
await F.refreshPermissionMode(n, i);
q.refreshTools(a);
Y.refreshTools(a);
e.agentSession.refreshTools();
t.refresh();
const o = ae.prepareToolPrompt;
e.agentSession.setPermissionPromptPreparation(o ? () => o(t.current.effectiveTools, { permissionChanged: true }) : void 0);
}),
readYieldState: () => ({
yieldAbortSettled: te,
yieldDetected: V,
yieldMessage: W,
yieldAcknowledgment: G,
yieldMessageWaitRegistered: K
}),
setToolSearchCatalogExecutor: (e) => {
v = e;
}
}
});
f.diagnosticFinalResponse = resolveDiagnosticModelContentCapturePolicy(getRuntimeConfigSnapshot()).outputMessages ? resolveFinalMessageRawText(n.currentAttemptAssistant ?? n.currentAttemptCompletedAssistant) : void 0;
const o = h?.current;
const s = e.agentSession.settingsManager.getProviderRetrySettings();
return {
...n,
codeModeEngaged: I,
providerRetryMaxRetries: s.maxRetries,
providerRequestTimeoutExplicit: s.timeoutMs !== void 0 || r.model.requestTimeoutMs !== void 0,
providerRetryMaxDelayMs: s.maxRetryDelayMs,
...o ? { bridgeCalls: {
search: o.searchCount,
describe: o.describeCount,
call: o.callCount
} } : {}
};
} finally {
y?.();
y = void 0;
const e = b.takeForCleanup();
const t = { ...m };
m.bundleMcpRuntime = void 0;
m.bundleLspRuntime = void 0;
g = false;
await cleanupStep("embedded-session", () => cleanupEmbeddedAttemptSessionPhase({
attempt: r,
...e,
transcriptLifecycle: Q.transcriptLifecycle,
...t,
toolSearchCatalogRef: h,
trajectoryEndRecorded: f.trajectoryEndRecorded,
deferredLifecycleOwner: f.deferredLifecycleOwner,
emitDiagnosticRunCompleted: p,
state: f
}));
}
} catch (e) {
let t = e;
try {
x.throwIfFired();
} catch (e) {
t = e;
}
if (f.terminal.kind === "ok") f.terminal = {
kind: "failed",
source: "precheck",
error: t
};
const n = buildAgentRunTerminalOutcomeFromAttempt({
terminal: f.terminal,
abortSignal: r.abortSignal
});
if (n.status === "timeout") throw new AgentRunTerminalOutcomeError(t, n);
throw t;
} finally {
r.continuation = void 0;
e.continuation = void 0;
const resolveCleanupReason = () => {
const e = projectAgentRunAttemptTerminal(f.terminal);
return e.timedOut || e.timedOutDuringCompaction || e.timedOutDuringToolExecution ? "timeout" : e.aborted ? "cancel" : e.failed ? "error" : "completion";
};
const releaseTools = async () => {
const e = resolveCleanupReason();
try {
await cleanupStep("embedded-registered-resources", async () => {
try {
await _?.(e);
_ = void 0;
v = void 0;
} catch {
recordAgentCleanupFailure();
}
});
} finally {
a[Symbol.dispose]();
x.dispose();
}
};
if (resolveCleanupReason() === "completion") t(releaseTools);
else await releaseTools();
clearToolActivityRun(r.runId);
try {
await cleanupStep("embedded-preparation", cleanupEmbeddedPrepResourcesAfterEarlyExit);
} catch (e) {
recordAgentCleanupFailure();
log$2.warn(`failed to clean up embedded prep resources after early attempt exit: runId=${r.runId} ${String(e)}`);
}
const n = projectAgentRunAttemptTerminal(f.terminal);
p?.(n.aborted ? "aborted" : "error", n.promptError ?? /* @__PURE__ */ new Error("run exited before diagnostic completion"));
d?.();
}
}
//#endregion
export { runEmbeddedAttempt };