UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,726 lines • 101 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { v as floorPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { a as captureAsyncWorkTracker, o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { C as resolveSessionAgentIds, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { b as getActiveDiagnosticTraceContext, g as createDiagnosticTraceContext, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { d as normalizeUsage } from "./usage-CHLnzpJG.mjs";
import { i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { o as resolveAgentModelFallbackValues } from "./model-input-DrM4DWHG.mjs";
import { i as DEFAULT_PROVIDER, n as DEFAULT_MODEL } from "./defaults-BWyoTPqn.mjs";
import { c as loadPluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { d as resolveRunModelFallbacksOverride } from "./agent-scope-BwB8YH6y.mjs";
import { n as withPluginRuntimeGenerationScope, t as runOutsidePluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { r as wrapStreamFnTextTransforms } from "./plugin-text-transforms-CMotGmZ0.mjs";
import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs";
import { a as normalizeOptionalAgentRuntimeId, r as isDefaultAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs";
import { E as projectModelThinkingCompat } from "./model-selection-shared-9Kz63Hhm.mjs";
import { r as isOpenAIProvider } from "./openai-routing-Dakz1nVk.mjs";
import { i as generateSecureToken } from "./secure-random-CW5OZnK1.mjs";
import { h as hasPersistedMedia } from "./chat-message-content-DNUdbbJ8.mjs";
import { f as prepareSystemAgentRunAdmission } from "./admitted-run-context-D3Jvk_f_.mjs";
import { M as resolveSessionControllerOperationForSignal, gt as assertSessionControllerOperation } from "./session-controller.state-BApgK0mV.mjs";
import { d as toolPolicyRestrictsTools } from "./tool-policy-BR4v75RA.mjs";
import { a as resolveSessionPermissionExecMode, t as SESSION_PERMISSION_BY_EXEC_MODE } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { t as formatSqliteSessionFileMarker } from "./legacy-sqlite-marker-D_RUp-nb.mjs";
import { n as wrapStreamFnWithDiagnosticModelCallEvents, t as prepareAgentMemoryPrompt } from "./memory-prompt-prepare-Dvvdg4ic.mjs";
import { n as estimateTokens } from "./compaction-cut-point-CEj7MSFJ.mjs";
import { i as projectExecutionSessionEntry } from "./session-entry-projection-ncqx2CJQ.mjs";
import { i as rethrowIncognitoSessionError } from "./incognito-session-error-BxQdjUZa.mjs";
import { _ as sanitizeTranscriptMessage } from "./session-accessor.sqlite-transcript-store-DRtj0wNT.mjs";
import { R as getCurrentSessionControllerOwner } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { h as resolveSessionPinnedHarnessId } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { c as getOwnedSessionTranscriptInitialWriter, i as captureOwnedTranscriptWriteAssertion, y as withSessionTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs";
import { t as captureSessionActorTranscriptRead } from "./session-actor-transcript-read-CHpAgP2z.mjs";
import { t as prepareSessionTranscriptHydration } from "./session-transcript-hydration-B_Y3bole.mjs";
import { i as resolveRuntimeOsLabel } from "./os-summary-CMRUbVgk.mjs";
import { s as withSandboxRuntimeStatusInWorker } from "./runtime-status-C5ZOG7YR.mjs";
import { t as prepareConversationCapabilityProfile } from "./conversation-capability-profile-Be5DqCww.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import { r as projectPreparedModelProvider } from "./support-LWqLDjUq.mjs";
import { c as getPreparedModelRuntimeAuthStore } from "./prepared-model-runtime-auth-DVZroiat.mjs";
import { o as applyLocalNoAuthHeaderOverride } from "./model-auth-markers-4YSUG71a.mjs";
import { g as attachProviderAuthAuthority, t as applyPreparedRuntimeAuthToModel, v as getProviderAuthAuthority } from "./provider-request-config-CCij-nof.mjs";
import { i as listRegisteredPluginAgentPromptGuidance } from "./command-registry-state-D8aXLQW8.mjs";
import { w as MissingProviderAuthError } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs";
import { t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { r as getModelProviderRuntimePluginHandle, t as attachModelProviderRuntimePluginHandle, u as resolveProviderRuntimePlugin } from "./provider-hook-runtime-CNiG8a3j.mjs";
import { L as prepareProviderRuntimeAuth, M as transformProviderSystemPrompt, T as resolveProviderTextTransforms } from "./provider-runtime-BddjXkmv.mjs";
import { i as unwrapSecretSentinelsForProviderEgress } from "./provider-secret-egress-DZ6iOD2F.mjs";
import { n as getModelRegistryRuntime } from "./model-registry.core-DcVMaqxb.mjs";
import { n as extractModelCompat } from "./provider-model-compat-DgjEUAN7.mjs";
import { r as resolveModelCandidateChain } from "./model-fallback-candidates-CFJLuJlL.mjs";
import { r as coerceToFailoverError, s as hasModelFallbackStop } from "./failover-error-CbIiC30n.mjs";
import { n as enqueueCommandInLane } from "./command-queue-BenRlAaO.mjs";
import { n as compactWithSafetyTimeout, r as resolveCompactionTimeoutMs } from "./compaction-safety-timeout-Dm_4UNnX.mjs";
import { c as markDiagnosticEmbeddedRunStarted, n as closeDiagnosticEmbeddedRunOwner, r as createDiagnosticEmbeddedRunOwner } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { t as getRemoteSkillEligibility } from "./remote-BFNOi3gh.mjs";
import { t as isAcpRuntimeSpawnAvailable } from "./availability-CBszSK60.mjs";
import { r as resolveImageSanitizationLimits } from "./image-sanitization-CSJ5feF-.mjs";
import { n as cliBackendAcceptsAuthProfileForwarding, r as resolveCliExecutionAuthProfileId, t as CliExecutionAuthProfileError } from "./cli-execution-auth-iYQVEZdU.mjs";
import { m as generateSessionEntryId } from "./session-manager-codec-DTi9FkQE.mjs";
import { t as withSessionTurn } from "./session-controller.admission-DDiE4tNx.mjs";
import { n as CompactionError, r as InvalidSummaryOutputError } from "./types-CD5C4AET.mjs";
import { c as resolveCompactionFailure, i as describeCompactionFailure, n as buildCompactionFailureResult, r as classifyCompactionReason, s as isSummaryTimeoutFailure } from "./compact-reasons-DCGXQXOD.mjs";
import { t as buildProviderAuthRecoveryHint } from "./provider-auth-recovery-hint-SMK7UCzs.mjs";
import { t as log } from "./logger-DgCpB-Fs.mjs";
import { n as createBundleMcpToolRuntime } from "./agent-bundle-mcp-materialize-DM8C34_b.mjs";
import { a as wrapUntrustedPromptDataBlock } from "./sanitize-for-prompt-CAahLekM.mjs";
import "./agent-bundle-mcp-tools-CjrVbt71.mjs";
import { o as resolveModelAuthModeAsync, t as applyAuthHeaderOverride } from "./model-auth-CEsyk_Yg.mjs";
import { o as toToolDefinitions } from "./agent-tool-definition-adapter-CAIOgFtX.mjs";
import { t as applyFinalEffectiveToolPolicy } from "./effective-tool-policy-DMFsqGJo.mjs";
import { r as resolveOpenClawReferencePaths } from "./docs-path-B3SUA8k7.mjs";
import { t as ensureSelectedAgentHarnessPlugin } from "./runtime-plugin-Cug3vi2h.mjs";
import { h as runSummarizationCompletionFromSource, i as capCompactionSummary, m as prepareCompactionSummaryRequest, o as compactFromSource } from "./compaction-z9gtIF8y.mjs";
import { c as createCompactionRuntime, l as resolveCompactionInstructions, o as agentSessionAutomaticCompaction, s as agentSessionSetContextReplacementHook, t as DefaultResourceLoader } from "./resource-loader-hGpx6p2H.mjs";
import { m as createSessionCompactionEntry, o as createSessionHeader, p as appendSessionMetadataInWorker, s as prepareSessionInitialMetadata, t as SessionManager } from "./session-manager-DuaaMI5O.mjs";
import { i as withSessionManagerWrite } from "./session-manager-write-admission-CUQ2naL2.mjs";
import { i as createStandaloneCompactionRequestBudget } from "./request-budget-CDN2iAaH.mjs";
import { n as setSessionModelUsageSink, t as recordSessionModelUsage } from "./session-model-usage-uTeV8br8.mjs";
import "./sessions-G45sHB31.mjs";
import { r as detectRuntimeShell } from "./shell-utils-rrqUwXNm.mjs";
import { c as resolveContextInjectionMode, i as resolveBootstrapContextForRun, r as makeBootstrapWarn } from "./bootstrap-files-CdJt18lf.mjs";
import { t as applyEmbeddedAttemptToolsAllow } from "./attempt-tool-construction-plan-Cp8YcsYs.mjs";
import { r as resolveEmbeddedSandboxInfoExecPolicy, t as buildEmbeddedSandboxInfo } from "./sandbox-info-CWgYLZq4.mjs";
import { n as createOpenClawCodingToolsInternalAsync } from "./agent-tools.async-b-kGzZ4n.mjs";
import { n as resolveProcessToolScopeKey } from "./bash-process-scope-B7TaQfLU.mjs";
import { n as filterRuntimeCompatibleTools, t as filterProviderNormalizableTools } from "./tool-schema-projection-D-AbMZEk.mjs";
import { n as resolveModelAsync } from "./model-BmrpLWB9.mjs";
import { t as isReasoningTagProvider } from "./provider-utils-D545sPXZ.mjs";
import { i as buildBootstrapPromptWarningNotice, n as buildBootstrapBudgetState, r as buildBootstrapInjectionStats } from "./bootstrap-budget-BcnE4Zqz.mjs";
import { r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs";
import { t as protectPreparedProviderRuntimeAuth } from "./provider-runtime-auth-protection-CMR822Jv.mjs";
import { t as materializePreparedRuntimeModel } from "./materialize-model-DK894Ocx.mjs";
import { a as resolveReusableRuntimeModelAuth, r as providerUsesCredentialScopedModelMetadata } from "./credential-scoped-model-zYnbfp2r.mjs";
import { n as resolvePreparedRuntimeModelAuth, t as resolvePreparedRuntimeAuthAttempts } from "./resolve-auth-Cds1OOn0.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 } from "./prompt-cache-observability-BBkCY6BX.mjs";
import { n as resolveSkillSnapshotExecutionFileHost } from "./skill-snapshot-provenance-BVqVnPW0.mjs";
import { t as resolveReusableWorkspaceSkillSnapshot } from "./session-snapshot-D1VlwnxO.mjs";
import { t as rewriteTranscriptEntriesInSessionManager } from "./transcript-rewrite-CnVCjlmn.mjs";
import { i as selectAgentHarnessForPreparedModelProviders, r as selectAgentHarness } from "./selection-Dmb46Mcc.mjs";
import { r as isFallbackSummaryError } from "./model-fallback-attempt-DPZU4qST.mjs";
import { t as runWithModelFallback } from "./model-fallback-runner-DRFeYUEn.mjs";
import { t as prepareAgentPromptProjects } from "./prompt-projects-DPH7_MHZ.mjs";
import { n as resolveRuntimeAgentName } from "./system-prompt-params-B0WSdtCC.mjs";
import { p as prepareWatchedSessionsPromptAsync } from "./system-prompt-context-files-BTDEQYK6.mjs";
import { t as applyExtraParamsToAgent } from "./extra-params-Dpi54r85.mjs";
import { a as sanitizeToolUseResultPairingForModel } from "./session-transcript-repair-DDBSgN6b.mjs";
import { n as buildAgentRuntimePlan, r as resolvePreparedProviderRuntimeHandle } from "./build-1KVS3lgO.mjs";
import { n as supportsModelTools } from "./model-tool-support-BJrIU874.mjs";
import { t as listActiveProcessSessionReferences } from "./bash-process-references-BBxu9q4V.mjs";
import { o as resolvePromptModeForSession } from "./attempt-prompt-helpers-bQX_3CMZ.mjs";
import { a as resolveEmbeddedCompactionTarget, i as resolveCompactionTargetRuntime, n as resolveCompactionContextTokenBudget, o as resolveEmbeddedCompactionThinkingLevel, r as resolveCompactionHarnessRuntime } from "./compaction-runtime-context-Cqy9zW9t.mjs";
import { r as resolveAttemptSpawnWorkspaceDir } from "./attempt-thread-helpers-BkXHw9TC.mjs";
import { r as resolveSandboxContext } from "./context-DNnE7m_d.mjs";
import { a as estimateLlmBoundaryTokenPressure, s as estimateRenderedLlmBoundaryTokenPressure } from "./preemptive-compaction-DWbzXuZy.mjs";
import { a as resolveTieredModel, i as resolveSharedPluginRuntimeWorkspace, o as pickFallbackThinkingLevel, s as resolveGlobalLane } from "./prepared-runtime-context-G3hnwl7-.mjs";
import { n as resolveAgentRunSessionTarget, t as applyAgentRunSessionTargetIdentity } from "./run-session-target-b0y1C8K8.mjs";
import { r as readCompactionAccountingRecorder } from "./compaction-accounting-bridge-BYYhZqhH.mjs";
import { i as buildBeforeCompactionHookMetrics, n as runCompactionHooks, r as runPostCompactionSideEffects, t as estimateTokensAfterCompaction } from "./compaction-hooks-CIs7VqLG.mjs";
import { t as prepareEmbeddedSkills } from "./skill-runtime-Cm3TP3Aa.mjs";
import { a as isSameModelSnapshot, i as MODEL_SNAPSHOT_CUSTOM_TYPE, m as mapThinkingLevelForProvider, p as mapThinkingLevel } from "./replay-history-generic-mEncANYP.mjs";
import { t as guardSessionManager } from "./session-tool-result-guard-wrapper-z-jVIqGv.mjs";
import { t as createBundleLspToolRuntime } from "./agent-bundle-lsp-runtime-BJLVU6_B.mjs";
import { a as resolveAgentPromptSurfaceForSessionKey } from "./system-prompt-l--vCJFZ.mjs";
import { t as buildConfiguredAgentSystemPrompt } from "./system-prompt-config-Cs2owSg-.mjs";
import { t as resolveRuntimeChannelPromptContext } from "./runtime-capabilities-hnv8ZePB.mjs";
import { n as limitHistoryTurns, t as getHistoryLimitFromSessionKey } from "./history-D_pzOPjp.mjs";
import { n as resolveEmbeddedAgentBaseStreamFn, r as resolveEmbeddedAgentStream, t as resolveEmbeddedAgentApiKey } from "./stream-resolution-DTC6X1c4.mjs";
import { t as registerProviderStreamForModel } from "./provider-stream-GeYmJKvk.mjs";
import { _ as setCompactionSafeguardRuntime, a as collectAllowedToolNames, c as sanitizeSessionHistory, d as resolveEmbeddedCompactionSafeguard, f as executeCompactionSafeguard, g as setCompactionSafeguardCancellation, h as getCompactionSafeguardRuntime, l as validateReplayTurns, m as consumeCompactionSafeguardCancellation, o as collectRegisteredToolNames, p as getCompactionProvider, r as flushPendingToolResultsAfterIdle, s as toSessionToolAllowlist, t as logRuntimeToolSchemaQuarantine, u as buildEmbeddedExtensionFactories } from "./tool-schema-quarantine-y3o7ToF3.mjs";
import { n as isRealConversationMessage } from "./compaction-real-conversation-BUniUPG5.mjs";
import { r as createAgentSession } from "./tool-send-receipts-DPctyfdu.mjs";
import { a as summarizePreparedCompactionHistory } from "./post-compaction-context-BSROIzvn.mjs";
import { t as getMachineDisplayName } from "./machine-name-Dw9TPjxw.mjs";
import fs from "node:fs/promises";
import os from "node:os";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { supportsNativeOpenAIResponsesEndpoint } from "@openclaw/ai/internal/openai-responses-payload-policy";
import { clampThinkingLevel } from "@openclaw/ai/internal/runtime";
import { captureOpenAIResponsesCompaction, preserveCompactionReplayWindow, requestPreparedOpenAIResponsesCompaction, requiresCompactionReplayRefresh, resolveCompactionReplayEligibility, resolveOpenAIResponsesCompactEndpointPlan } from "@openclaw/ai/transports";
//#region src/agents/embedded-agent-runner/compact.foreground-work.ts
/** Both compaction runtimes cancel pending queue admission before releasing their writer. */
function enqueueCompactionInLanes(e, t) {
	const n = resolveGlobalLane(e.lane, e);
	const r = e.enqueue ?? ((e, t) => enqueueCommandInLane(n, e, t));
	const i = getCurrentSessionControllerOwner();
	let a = true;
	let o;
	const beginWait = () => {
		if (o || !a) return;
		o = i?.watchdog.beginWait({
			kind: "global_capacity",
			isCurrent: () => {
				if (!a || !i) return false;
				assertSessionControllerOperation(i);
				return true;
			}
		});
	};
	const finishWait = () => {
		a = false;
		o?.close();
	};
	try {
		return r(async () => {
			finishWait();
			e.abortSignal?.throwIfAborted();
			if (i) assertSessionControllerOperation(i);
			i?.watchdog.progress("semantic", "compaction:capacity_admitted");
			return await t();
		}, {
			abortSignal: e.abortSignal,
			onQueued: beginWait
		}).finally(finishWait);
	} catch (e) {
		finishWait();
		throw e;
	}
}
/** A timeout can return a result while the exact turn still owns raw work and disposal. */
async function withQueuedCompactionTurn(e, t) {
	const n = createDeferredCore();
	captureAsyncWorkTracker()(() => withSessionTurn(e, async (r, i) => {
		const a = new AsyncWorkScope();
		const o = [];
		try {
			const s = await a.track(() => t(r, i, (e) => o.push(e)));
			if (a.hasPendingWork && !e.replyOperation) n.resolve(s);
			return s;
		} catch (t) {
			if (a.hasPendingWork && !e.replyOperation) n.reject(t);
			throw t;
		} finally {
			await AsyncWorkScope.runWhenAllIdle(() => [a], () => a.drain());
			await Promise.all(o.toReversed().map(async (e) => e()));
		}
	})).then(n.resolve, n.reject);
	return await n.promise;
}
/** Keeps physical cleanup separate from the compaction result and transcript fences. */
async function runForegroundCompactionWork(e, t) {
	const n = createDeferredCore();
	const r = captureAsyncWorkTracker();
	const i = getAsyncWorkSignal();
	const a = t && i ? AbortSignal.any([t, i]) : t ?? i;
	r(async () => {
		const t = new AsyncWorkScope();
		const r = new AsyncWorkScope();
		let i = t.run(() => AsyncLocalStorage.snapshot());
		let o = r.run(() => AsyncLocalStorage.snapshot());
		let s;
		const closeForegroundWork = () => s ??= AsyncWorkScope.runWhenAllIdle(() => [t], () => i(() => t.drain()));
		let c;
		const closeFactoryWork = () => c ??= o(() => r.drain());
		let l;
		let u;
		let d = false;
		const closeFromParent = () => {
			i(() => t.beginClose(a?.reason));
			if (!d) o(() => r.beginClose(a?.reason));
		};
		a?.addEventListener("abort", closeFromParent, { once: true });
		if (a?.aborted) closeFromParent();
		try {
			n.resolve(await t.track(() => e({
				adoptLease: (e) => {
					l = e;
					return {
						closeFactoryWork,
						release: async () => {
							await closeForegroundWork();
							await e[Symbol.asyncDispose]();
						}
					};
				},
				resolveEngine: (e) => r.track(async () => {
					o = AsyncLocalStorage.snapshot();
					u = await e();
					return u;
				}),
				captureContext: () => {
					i = AsyncLocalStorage.snapshot();
				},
				transferEngine: () => {
					u = void 0;
					d = true;
				}
			})));
		} catch (e) {
			n.reject(e);
		} finally {
			try {
				await closeForegroundWork();
				if (!d) {
					const e = o(() => r.track(async () => {
						try {
							await u?.dispose?.();
						} catch (e) {
							log.warn("context engine dispose failed", { errorMessage: formatErrorMessage(e) });
						}
					}));
					await Promise.all([e, closeFactoryWork()]);
				}
			} finally {
				a?.removeEventListener("abort", closeFromParent);
				if (!d) await l?.[Symbol.asyncDispose]();
			}
		}
	}).catch(n.reject);
	return await n.promise;
}
//#endregion
//#region src/agents/embedded-agent-runner/compaction-runtime-preparation.ts
/** Resolves the shared policy, target, and harness ownership for either compaction entry point. */
function resolveCompactionRuntimeSelection(e) {
	const t = e.sandboxSessionKey ?? e.sessionKey ?? void 0;
	const n = e.sandboxAgentId ?? (e.sandboxSessionKey && parseAgentSessionKey(e.sandboxSessionKey) ? void 0 : e.agentId);
	const r = resolveEmbeddedCompactionTarget({
		...e,
		defaultProvider: DEFAULT_PROVIDER,
		defaultModel: DEFAULT_MODEL
	});
	const i = r.provider ?? "openai";
	const a = r.model ?? "gpt-6-astra";
	const o = resolveAgentHarnessPolicy({
		provider: i,
		modelId: a,
		config: e.config,
		agentId: n,
		sessionKey: t
	});
	const s = o.runtimeSource && o.runtimeSource !== "implicit" && !isDefaultAgentRuntimeId(o.runtime) ? o.runtime : void 0;
	const c = normalizeOptionalAgentRuntimeId(e.boundHarnessRuntime);
	const l = e.selectedHarnessRuntime ?? resolveCompactionHarnessRuntime({
		boundHarnessRuntime: c,
		preparedRuntimePlan: e.preparedRuntimePlan,
		configuredHarnessRuntime: s,
		provider: i,
		modelId: a
	});
	const u = {
		...r,
		...resolveCompactionTargetRuntime(r.provider, l)
	};
	const d = u.provider ?? "openai";
	const f = u.model ?? "gpt-6-astra";
	const p = normalizeOptionalAgentRuntimeId(l);
	return {
		attemptNativeHarnessCompaction: Boolean(p && p !== "auto" && p !== "openclaw" && (!isOpenAIProvider(d) || u.nativeHarnessCompaction === true)),
		runtimePolicySessionKey: t,
		runtimePolicyAgentId: n,
		boundHarnessRuntime: c,
		selectedHarnessRuntime: l,
		selectedHarnessRuntimeOverride: c ? void 0 : l,
		target: u,
		runtimeModelAuth: resolveReusableRuntimeModelAuth({
			plan: e.runtimeAuthPlan ?? e.preparedRuntimePlan?.auth,
			provider: d,
			modelId: f,
			authProfileId: u.authProfileId
		}),
		provider: d,
		runtimeProvider: d,
		contextConfigProvider: d,
		modelId: f
	};
}
/** Prepares one ordered auth-attempt set and converges it on a single compaction harness. */
async function prepareCompactionHarnessAuth(e) {
	const t = isOpenAIProvider(e.provider);
	const n = await (t ? ensureAuthProfileStoreAsync : ensureAuthProfileStoreWithoutExternalProfilesAsync)(e.agentDir, {
		profileId: e.authProfileId ?? e.reusableRuntimeAuthPlan?.forwardedAuthProfileId,
		...t ? { externalCliProviderIds: ["openai"] } : {},
		allowKeychainPrompt: false
	});
	const r = {
		provider: e.provider,
		modelId: e.modelId,
		config: e.config,
		agentId: e.runtimePolicyAgentId,
		sessionKey: e.runtimePolicySessionKey ?? void 0,
		agentHarnessId: e.agentHarnessId,
		agentHarnessRuntimeOverride: e.agentHarnessRuntimeOverride
	};
	const selectPreparedHarness = (t) => selectAgentHarnessForPreparedModelProviders({
		...r,
		modelProviders: t.map((t) => projectPreparedModelProvider({
			model: e.model,
			plan: t.plan,
			attemptKind: t.kind
		}))
	});
	const i = e.reusableRuntimeAuthPlan ? void 0 : selectAgentHarness({
		...r,
		modelProvider: projectPreparedModelProvider({ model: e.model })
	});
	const prepare = (t) => {
		try {
			return {
				ok: true,
				auth: prepareAgentRuntimeAuth({
					provider: e.provider,
					modelId: e.modelId,
					modelApi: e.model?.api,
					modelBaseUrl: e.model?.baseUrl,
					config: e.config,
					agentId: e.runtimePolicyAgentId,
					env: process.env,
					agentDir: e.agentDir,
					workspaceDir: e.workspaceDir,
					authProfileStore: n,
					sessionAuthProfileId: e.authProfileId,
					sessionAuthProfileSource: e.authProfileIdSource,
					harnessId: t.id,
					harnessRuntime: t.id,
					harnessAuthBootstrap: t.authBootstrap
				})
			};
		} catch (e) {
			if (isAbortError(e)) throw e;
			return {
				ok: false,
				error: e
			};
		}
	};
	const a = e.reusableRuntimeAuthPlan ? {
		ok: true,
		auth: {
			plan: e.reusableRuntimeAuthPlan,
			attempts: [{
				kind: "implicit",
				plan: e.reusableRuntimeAuthPlan
			}]
		}
	} : prepare(i);
	if (!a.ok) return a;
	let o = a.auth;
	let s = selectPreparedHarness(o.attempts);
	if (!e.reusableRuntimeAuthPlan && s.id !== i?.id) {
		const t = prepare(s);
		if (!t.ok) return t;
		o = t.auth;
		const n = selectPreparedHarness(o.attempts);
		if (n.id !== s.id) throw new Error(`${e.convergenceErrorPrefix ?? "Prepared compaction"} auth routes did not converge on one agent harness for ${e.provider}/${e.modelId}.`);
		s = n;
	}
	return {
		ok: true,
		runtimeAuthProfileStore: n,
		runtimeAuthPreparation: o,
		selectedPreparedHarness: s,
		providerUsesProfileScopedModelMetadata: providerUsesCredentialScopedModelMetadata({
			...e,
			provider: e.metadataProvider ?? e.provider
		})
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/compaction-session-agent.ts
async function prepareCompactionSessionAgent(e) {
	const t = e.authStorage ? await resolveEmbeddedAgentApiKey({
		...e,
		provider: e.effectiveModel.provider
	}) : e.resolvedApiKey;
	e.session.agent.streamFn = resolveEmbeddedAgentStream({
		...e,
		currentStreamFn: resolveEmbeddedAgentBaseStreamFn({ session: e.session }),
		model: e.effectiveModel,
		transportAuthAvailable: Boolean(t?.trim()),
		authProfileId: e.runtimePlan?.auth.forwardedAuthProfileId
	}).streamFn;
	const n = resolveProviderTextTransforms({
		provider: e.provider,
		config: e.config,
		workspaceDir: e.effectiveWorkspace,
		runtimeHandle: getModelProviderRuntimePluginHandle(e.effectiveModel)
	});
	if (n) e.session.agent.streamFn = wrapStreamFnTextTransforms({
		streamFn: e.session.agent.streamFn,
		input: n.input,
		output: n.output,
		transformSystemPrompt: false
	});
	const r = mapThinkingLevelForProvider(e.thinkLevel, e.effectiveModel);
	const i = e.runtimePlan?.transport.resolveExtraParams({
		thinkingLevel: r,
		agentId: e.sessionAgentId,
		workspaceDir: e.effectiveWorkspace,
		model: e.effectiveModel
	});
	return {
		...applyExtraParamsToAgent(e.session.agent, e.config, e.provider, e.modelId, void 0, r, e.sessionAgentId, e.effectiveWorkspace, e.effectiveModel, e.agentDir, void 0, {
			modelCallUrgency: e.modelCallUrgency,
			...i ? { preparedExtraParams: i } : {},
			auth: e.runtimePlan?.auth.selectedAuthMode ? {
				mode: e.runtimePlan.auth.selectedAuthMode,
				authFlow: e.runtimePlan.auth.selectedAuthFlow
			} : void 0,
			nativeWebSearchPolicyContext: {
				webSearchEnabled: false,
				runtimeToolAllowlist: []
			}
		}),
		transportApiKey: t
	};
}
//#endregion
//#region src/config/sessions/session-compaction-prepared.ts
/** Capture source custody for each short worker read; never retain a reader across inference. */
async function readPreparedSessionCompactionInWorker(e, t, n) {
	const r = prepareSessionTranscriptHydration(e, { compaction: true }, n);
	if (!r.readCompaction) throw new Error("In-memory compaction uses its session actor");
	return r.readCompaction(t);
}
//#endregion
//#region src/agents/embedded-agent-runner/prepared-compaction-metadata.ts
/** Initialize before planning; true means the captured source must be refreshed. */
async function initializePreparedCompactionMetadata(e, t, n, r, i) {
	r();
	let a = t.leafEntryId;
	const o = prepareSessionInitialMetadata(t, n);
	if (o) {
		const t = o.initialModelChange ? {
			...o.initialModelChange,
			id: generateSessionEntryId(),
			parentId: a,
			timestamp: (/* @__PURE__ */ new Date()).toISOString()
		} : void 0;
		const n = {
			...o.change,
			id: generateSessionEntryId(),
			parentId: t?.id ?? a,
			timestamp: (/* @__PURE__ */ new Date()).toISOString()
		};
		await withSessionTranscriptWriteAssertion(e, r, () => appendSessionMetadataInWorker({
			scope: e,
			event: n,
			initialModel: t,
			header: i,
			appendIntent: "active-branch"
		}, r));
		a = n.id;
		r();
	}
	const s = {
		timestamp: Date.now(),
		provider: n.provider,
		modelApi: n.modelApi,
		modelId: n.modelId
	};
	if (t.lastModelSnapshot && isSameModelSnapshot(t.lastModelSnapshot, s)) return o !== void 0;
	r();
	try {
		await withSessionTranscriptWriteAssertion(e, r, () => appendSessionMetadataInWorker({
			scope: e,
			appendIntent: "active-branch",
			event: {
				type: "custom",
				id: generateSessionEntryId(),
				parentId: a,
				timestamp: (/* @__PURE__ */ new Date()).toISOString(),
				customType: MODEL_SNAPSHOT_CUSTOM_TYPE,
				data: s
			}
		}, r));
	} catch (e) {
		rethrowIncognitoSessionError(e);
	}
	r();
	return true;
}
//#endregion
//#region src/agents/embedded-agent-runner/prepared-compaction-session.ts
/** Actor history, full-array callbacks, and server endpoints retain their session adapter. */
function needsCompactionSessionAdapter(e, t, n) {
	const { params: r, provider: i, effectiveWorkspace: a, effectiveModel: o } = e;
	const s = readCompactionAccountingRecorder(r.contextEngineRuntimeContext);
	const c = resolveProviderRuntimePlugin({
		provider: i,
		config: r.config,
		workspaceDir: a,
		env: process.env
	});
	return Boolean(s?.memoryTranscript || s?.preparedSession?.sessionManager || captureSessionActorTranscriptRead(n, r.abortSignal) || r.config?.agents?.defaults?.compaction?.provider && getCompactionProvider(r.config.agents.defaults.compaction.provider) || c?.sanitizeReplayHistoryAsync || c?.sanitizeReplayHistory || c?.validateReplayTurns || resolveOpenAIResponsesCompactEndpointPlan(o, t).enabled);
}
/** Host effects stay here; the worker owns history, projection, cuts, and lazy source reads. */
async function prepareEmbeddedCompactionSession(e, t, n, r, i, a, o) {
	const { params: s, effectiveModel: c } = e;
	const l = readCompactionAccountingRecorder(s.contextEngineRuntimeContext);
	const u = n.getCompactionSettings();
	const d = resolveEmbeddedCompactionSafeguard({
		cfg: s.config,
		workspaceDir: e.effectiveWorkspace,
		model: c
	});
	const f = {};
	setCompactionSafeguardRuntime(f, d?.runtime ?? null);
	const p = {
		replay: {
			model: c,
			policy: e.runtimePlan.transcript.resolvePolicy(e.runtimePlanModelContext),
			sessionId: s.sessionId,
			allowedToolNames: Array.from(e.allowedToolNames),
			imageLimits: resolveImageSanitizationLimits(s.config),
			historyLimit: getHistoryLimitFromSessionKey(s.sessionKey, s.config, {
				accountId: s.agentAccountId,
				peerId: s.conversationRoutePeerId,
				chatType: s.chatType
			}),
			replayEnabled: a,
			observedTokenCount: floorPositiveFiniteNumber(s.currentTokenCount)
		},
		mode: "manual",
		requestState: l?.pendingRequestState ?? (e.trigger === "overflow" ? "unresolved" : void 0),
		requestBudget: (e.trigger === "manual" ? void 0 : l?.requestBudget) ?? createStandaloneCompactionRequestBudget({
			maxSummaryChars: u.maxSummaryChars,
			contextWindow: (e.trigger === "manual" ? e.contextTokenBudget : c.contextWindow) ?? 0,
			reserveTokens: u.reserveTokens,
			systemPrompt: i.trim(),
			tools: e.effectiveTools
		}),
		requestFromEntryId: l?.requestFromEntryId,
		pendingUserEntryId: l?.pendingUserEntryId,
		safeguard: d ? {
			recentTurnsPreserve: d.runtime.recentTurnsPreserve,
			qualityGuardEnabled: d.runtime.qualityGuardEnabled
		} : void 0
	};
	let m = l?.preparedSession?.source;
	if (!m) {
		const e = await readPreparedSessionCompactionInWorker(t, { kind: "preflight" }, s.abortSignal);
		r();
		if (e.status !== "preflight") throw new Error("Compaction transcript view could not prepare metadata");
		m = e.source;
	}
	if (await initializePreparedCompactionMetadata(t, m.metadata, {
		provider: c.provider,
		modelId: c.id,
		modelApi: c.api,
		thinkingLevel: clampThinkingLevel(c, o)
	}, r, m.header ? void 0 : createSessionHeader(s.sessionId, e.effectiveWorkspace))) m = void 0;
	if (l?.preparedSession) l.preparedSession.source = void 0;
	const h = await readPreparedSessionCompactionInWorker(t, {
		kind: "plan",
		source: m,
		settings: u,
		requestState: p.requestState,
		work: p
	}, s.abortSignal);
	r();
	if (h.status !== "prepared" && h.status !== "skipped") throw new Error("Compaction transcript view could not prepare its source");
	return {
		effects: f,
		value: h,
		async execute(n) {
			if (h.status === "skipped") return {
				status: "skipped",
				reason: "Nothing to compact (session too small)"
			};
			const i = n.signal ?? new AbortController().signal;
			const { plan: a, source: o } = h;
			const p = a.preparation;
			const assertCurrent = () => {
				n.signal?.throwIfAborted();
				s.abortSignal?.throwIfAborted();
				r();
			};
			const render = async (e, r) => {
				assertCurrent();
				const i = await readPreparedSessionCompactionInWorker(t, {
					kind: "render",
					entries: a.selections[e],
					version: o.version,
					maxChars: r
				}, n.signal);
				assertCurrent();
				if (i.status !== "rendered") throw new Error("Compaction source did not render its captured rows");
				return i.conversation;
			};
			assertCurrent();
			let m;
			let g = false;
			if (n.summaryOutputPolicy === "deterministic") {
				if (!a.deterministic) throw new CompactionError(a.deterministicError.code, a.deterministicError.message);
				m = a.deterministic;
			} else if (d && a.safeguard) {
				const t = await executeCompactionSafeguard({
					type: "session_before_compact",
					preparation: p,
					customInstructions: s.customInstructions,
					signal: i,
					thinkingLevel: n.thinkingLevel,
					streamFn: n.streamFn
				}, {
					model: c,
					modelRegistry: e.modelRegistry,
					identity: f
				}, {
					facts: a.safeguard,
					summarize: (e, t) => summarizePreparedCompactionHistory({
						...t,
						messageCount: e === "history" ? a.safeguard.reconciliationCount : a.safeguard.turnPrefixCount
					}, (t) => render(e, t))
				});
				if (t.cancel) throw new Error("Compaction cancelled");
				m = t.compaction;
				g = true;
			} else {
				const t = await e.modelRegistry.getApiKeyAndHeaders(c);
				if (!t.ok) throw new Error(t.error);
				const r = normalizeOptionalString(s.customInstructions);
				const o = r ? resolveCompactionInstructions(r, void 0) : void 0;
				const l = [o ? wrapUntrustedPromptDataBlock({
					label: "Compaction focus",
					text: o
				}) : "", p.latestUnresolvedUserRequest ? ["The run owner will resume this request after compaction. Preserve it as current work.", wrapUntrustedPromptDataBlock({
					label: "Latest unresolved user request",
					text: p.latestUnresolvedUserRequest
				})].join("\n") : ""].filter(Boolean).join("\n\n");
				const generate = () => compactFromSource(p, {
					history: a.selections.history.length,
					turnPrefix: a.selections.turnPrefix.length
				}, (e, r, a) => runSummarizationCompletionFromSource({
					...prepareCompactionSummaryRequest({
						model: c,
						reserveTokens: u.reserveTokens,
						previousSummary: r,
						summaryPrompt: a
					}),
					model: c,
					apiKey: t.apiKey,
					headers: t.headers,
					previousSummary: r,
					customInstructions: l || void 0,
					signal: i,
					thinkingLevel: n.thinkingLevel,
					streamFn: n.streamFn,
					runtime: createCompactionRuntime((e) => recordSessionModelUsage(f, e))
				}, (t) => render(e, t)));
				let d = await generate();
				assertCurrent();
				if (n.summaryOutputPolicy === "retry-invalid-once" && !d.ok && d.error instanceof InvalidSummaryOutputError) d = await generate();
				if (!d.ok) throw d.error;
				m = d.value;
			}
			n.onSummaryReady();
			assertCurrent();
			const _ = {
				...m,
				summary: capCompactionSummary(m.summary, u.maxSummaryChars)
			};
			const v = await readPreparedSessionCompactionInWorker(t, {
				kind: "finalize",
				version: o.version,
				retainedSequences: a.retainedSequences,
				summary: _,
				work: {
					itemId: e.diagId,
					requestBudget: a.requestBudget,
					requestTokenLimit: a.requestTokenLimit,
					pendingEntryId: a.pendingEntryId
				},
				reportingBudget: l?.requestBudget
			}, n.signal);
			assertCurrent();
			if (v.status !== "finalized") throw new Error("Compaction transcript view could not finalize its replacement");
			const y = getOwnedSessionTranscriptInitialWriter({ sessionTarget: t });
			const b = {
				scope: t,
				event: createSessionCompactionEntry(o.leafEntryId, _.summary, _.firstKeptEntryId, _.tokensBefore, _.details, g, { itemId: e.diagId }, v.tokensAfter),
				appendIntent: "active-branch",
				expectedMutationAt: v.transcriptMutationAt,
				...y && !y.committedFence ? { initializeEntry: true } : {}
			};
			const x = s.seedCompaction ?? l?.withCompactionPersistenceAsync;
			await withSessionTranscriptWriteAssertion(t, assertCurrent, () => x ? x(b) : appendSessionMetadataInWorker(b, assertCurrent));
			n.onCommitted({
				tokensBefore: _.tokensBefore,
				tokensAfter: v.tokensAfter,
				compactionKind: "context-engine",
				details: _.details
			});
			return {
				status: "completed",
				result: _,
				tokensAfter: v.tokensAfter,
				reportingTokensAfter: v.reportingTokensAfter,
				messageCountAfter: v.messageCountAfter
			};
		}
	};
}
//#endregion
//#region src/agents/embedded-agent-runner/bounded-compaction-execution.ts
/** Same host lifecycle, without constructing a session/agent history graph. */
async function executeBoundedCompactionSession(e, t, n, r, i, a, o) {
	const { params: s, provider: c, modelId: l, modelRegistry: u, effectiveModel: d, trigger: f } = e;
	const p = readCompactionAccountingRecorder(s.contextEngineRuntimeContext);
	const m = resolveCompactionTimeoutMs(s.config);
	let h = e.thinkLevel;
	let g = true;
	while (true) {
		e.attemptedThinking.add(h);
		let _;
		let v;
		let y;
		const refresh = () => {
			_?.watchdogAttempt?.setExecutionDeadline(Date.now() + m);
			y?.();
			s.compactionTimeoutReset?.();
		};
		try {
			let b = o.replayEnabled;
			const x = g ? o : { agent: { streamFn: void 0 } };
			if (!g) {
				const t = registerProviderStreamForModel({
					model: d,
					cfg: s.config,
					agentDir: e.agentDir,
					workspaceDir: e.effectiveWorkspace,
					apiRegistry: getModelRegistryRuntime(u).apiRegistry
				});
				x.agent.streamFn = t ?? getModelRegistryRuntime(u).llmRuntime.streamSimple;
				const n = await prepareCompactionSessionAgent({
					...e,
					session: x,
					llmRuntime: getModelRegistryRuntime(u).llmRuntime,
					providerStreamFn: t,
					sessionId: s.sessionId,
					resolvedApiKey: e.hasRuntimeAuthExchange ? void 0 : e.apiKeyInfo?.apiKey,
					config: s.config,
					thinkLevel: h,
					modelCallUrgency: f === "manual" ? "foreground" : s.modelCallUrgency ?? "background"
				});
				b = resolveCompactionReplayEligibility(d, {
					extraParams: n.effectiveExtraParams,
					apiKey: n.transportApiKey
				});
			}
			g = false;
			const S = getCurrentSessionControllerOwner();
			_ = createDiagnosticEmbeddedRunOwner({
				watchdogAttempt: S ? S.watchdog.attachAttempt({
					nested: true,
					assertCurrent: () => {
						s.abortSignal?.throwIfAborted();
						assertSessionControllerOperation(S);
					}
				}) : void 0,
				sessionId: s.sessionId,
				...s.sessionKey ? { sessionKey: s.sessionKey } : {},
				runId: e.diagnosticCompactionRunId,
				workKey: e.diagnosticCompactionRunId
			});
			refresh();
			markDiagnosticEmbeddedRunStarted({
				..._,
				owner: _
			});
			if (!x.agent.streamFn) throw new Error("Compaction transport did not provide a stream function");
			x.agent.streamFn = wrapStreamFnWithDiagnosticModelCallEvents(x.agent.streamFn, {
				config: s.config,
				runId: e.diagnosticCompactionRunId,
				...s.sessionKey ? { sessionKey: s.sessionKey } : {},
				sessionId: s.sessionId,
				provider: c,
				model: l,
				api: d.api,
				requestTimeoutMs: m,
				contextTokenBudget: e.contextTokenBudget,
				trace: e.compactionModelCallTrace,
				contentCapture: resolveDiagnosticModelContentCapturePolicy(s.config),
				nextCallId: e.nextDiagnosticModelCallId,
				ownerGeneration: _.generation,
				onStarted: refresh,
				onOutputDelta: refresh
			});
			const C = await prepareEmbeddedCompactionSession(e, t, n, r, e.buildSystemPromptText(), b, mapThinkingLevel(mapThinkingLevelForProvider(h, d)));
			v = C.effects;
			setSessionModelUsageSink(v, a ?? null);
			const w = C.value.beforeHookMetrics;
			const T = {
				hookRunner: p?.hostOwnsCompactionLifecycle ? null : getGlobalHookRunner(),
				sessionId: s.sessionId,
				sessionKey: t.sessionKey,
				sessionAgentId: e.sessionAgentId,
				workspaceDir: e.effectiveWorkspace,
				messageProvider: e.resolvedMessageProvider,
				assertActive: r,
				onHookMessages: s.onCompactionHookMessages
			};
			const E = formatSqliteSessionFileMarker({
				...t,
				sessionId: s.sessionId
			});
			const skipped = async (e) => {
				await runCompactionHooks({
					...T,
					phase: "after",
					messageCountAfter: w.messageCountBefore,
					tokensAfter: w.tokenCountBefore,
					compactedCount: 0,
					compactionOutcome: "skipped",
					sessionFile: E
				});
				return {
					ok: true,
					compacted: false,
					reason: e
				};
			};
			await runCompactionHooks({
				...T,
				phase: "before",
				metrics: w
			});
			if (!C.value.hasRealConversation) return await skipped("no real conversation messages");
			let D = false;
			let O;
			const compactClient = (e) => compactWithSafetyTimeout(async (t, n) => {
				O = t;
				y = n;
				setCompactionSafeguardCancellation(v, void 0);
				return C.execute({
					signal: t,
					summaryOutputPolicy: e,
					thinkingLevel: mapThinkingLevel(mapThinkingLevelForProvider(h, d)),
					streamFn: x.agent.streamFn,
					onSummaryReady: () => {
						D = true;
					},
					onCommitted: i
				});
			}, m, {
				abortSignal: s.abortSignal,
				...s.compactionDeadlineAt !== void 0 && e !== "deterministic" ? { deadlineAt: s.compactionDeadlineAt - m } : {}
			});
			refresh();
			const k = await compactClient(f === "manual" || resolveEffectiveCompactionMode(s.config) !== "default" ? "none" : "retry-invalid-once").catch(async (e) => {
				if (f === "manual" || s.abortSignal?.aborted || D || !isSummaryTimeoutFailure({
					error: e,
					summarySignal: O,
					abortSignal: s.abortSignal,
					safeguardCancellation: getCompactionSafeguardRuntime(v)?.cancellation
				})) throw e;
				refresh();
				return compactClient("deterministic");
			});
			y = void 0;
			if (k.status === "skipped") return await skipped(k.reason);
			refresh();
			if (!p?.hostOwnsCompactionLifecycle) await runPostCompactionSideEffects({
				config: s.config,
				sessionKey: s.sessionKey,
				sessionId: s.sessionId,
				agentId: e.sessionAgentId,
				memoryAudience: s.memoryAudience,
				sandboxed: e.sandbox?.enabled === true,
				sessionFile: E,
				assertActive: r
			});
			await runCompactionHooks({
				...T,
				phase: "after",
				messageCountAfter: k.messageCountAfter,
				tokensAfter: k.reportingTokensAfter,
				compactedCount: Math.max(0, w.messageCountOriginal - k.messageCountAfter),
				sessionFile: E,
				summaryLength: k.result.summary.length,
				tokensBefore: k.result.tokensBefore,
				firstKeptEntryId: k.result.firstKeptEntryId
			});
			return {
				ok: true,
				compacted: true,
				result: {
					sessionTarget: {
						agentId: t.agentId,
						sessionId: t.sessionId,
						sessionKey: t.sessionKey,
						storePath: t.storePath,
						...s.sessionTarget?.threadId !== void 0 ? { threadId: s.sessionTarget.threadId } : {}
					},
					summary: k.result.summary,
					firstKeptEntryId: k.result.firstKeptEntryId,
					tokensBefore: floorPositiveFiniteNumber(s.currentTokenCount) ?? k.result.tokensBefore,
					tokensAfter: k.reportingTokensAfter,
					details: k.result.details
				}
			};
		} catch (t) {
			const n = resolveCompactionFailure({
				error: t,
				safeguardCancellation: consumeCompactionSafeguardCancellation(v),
				abortSignal: s.abortSignal
			});
			r();
			const i = pickFallbackThinkingLevel({
				message: formatErrorMessage(n.error),
				attempted: e.attemptedThinking
			});
			if (i) {
				h = i;
				refresh();
				continue;
			}
			return e.fail(n.reason, n.error);
		} finally {
			if (_) closeDiagnosticEmbeddedRunOwner(_);
			setSessionModelUsageSink(v, null);
		}
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/compaction-duplicate-user-messages.ts
const DUPLICATE_USER_MESSAGE_WINDOW_MS = 6e4;
const MIN_DUPLICATE_USER_MESSAGE_CHARS = 24;
function normalizeUserMessageContent(e) {
	let t = e;
	if (Array.isArray(t)) {
		const e = [];
		for (const n of t) {
			if (!isRecord(n) || n.type === "image") return;
			if (n.type === "text" && typeof n.text === "string") e.push(n.text);
		}
		t = e.join("\n");
	}
	return typeof t === "string" ? t.replace(/\s+/g, " ").trim() : void 0;
}
function duplicateSignature(e) {
	if (!isRecord(e) || e.role !== "user" || typeof e.timestamp !== "number") return;
	const t = normalizeUserMessageContent(e.content);
	if (!t || t.length < MIN_DUPLICATE_USER_MESSAGE_CHARS || hasPersistedMedia(e)) return;
	const n = e["__openclaw"];
	const r = isRecord(n) && typeof n.senderId === "string" ? n.senderId : "";
	return {
		key: JSON.stringify([r, t.normalize("NFC")]),
		timestamp: e.timestamp
	};
}
/** Drop later duplicate user messages while preserving the first prompt. */
function dedupeDuplicateUserMessagesForCompaction(e) {
	const t = /* @__PURE__ */ new Map();
	const n = [];
	for (let r = 0; r < e.length; r++) {
		const i = e[r];
		if (i.role === "user" && t.size === 0 && (r + 1 === e.length || e[r + 1]?.role === "assistant")) {
			n.push(i);
			continue;
		}
		const a = duplicateSignature(i);
		if (!a) {
			if (i.role === "assistant") t.clear();
			n.push(i);
			continue;
		}
		const o = t.get(a.key);
		const s = Math.max(o ?? a.timestamp, a.timestamp);
		t.set(a.key, s);
		if (typeof o === "number" && a.timestamp >= o && a.timestamp - o <= DUPLICATE_USER_MESSAGE_WINDOW_MS) continue;
		n.push(i);
	}
	return n;
}
//#endregion
//#region src/agents/embedded-agent-runner/server-endpoint-compaction.ts
/** Try provider-owned compaction and persist its replay checkpoint on the session owner. */
async function attemptServerEndpointCompaction(e) {
	if (e.trigger === "overflow" || e.customInstructions?.trim() || !resolveOpenAIResponsesCompactEndpointPlan(e.model, e.extraParams).enabled) return;
	e.assertActive?.();
	let t = false;
	try {
		const n = e.context.messages.filter((e) => e.role === "user" || e.role === "assistant" || e.role === "toolResult");
		if (n.at(-1)?.role !== "assistant") {
			log.warn("Responses compact endpoint skipped: history does not end with an assistant message; using client compaction");
			return;
		}
		if (requiresCompactionReplayRefresh(n, e.model, e.requestOptions)) {
			log.warn("Responses compact endpoint skipped: the stored checkpoint needs a full-history rebuild; using client compaction");
			return;
		}
		const r = findEndpointWindowNormalizationSource(e);
		if (r) {
			log.warn(`Responses compact endpoint skipped: its ${r} would require image normalization in the stored window; using client compaction`);
			return;
		}
		const i = e.sessionManager.getBranch().findLast((e) => e.type === "message" && e.message.role === "assistant");
		if (!i || i.type !== "message" || i.message.role !== "assistant") throw new Error("Responses compact endpoint requires a persisted assistant owner");
		const a = await compactWithSafetyTimeout((t) => requestPreparedOpenAIResponsesCompaction(e.streamFn, e.model, {
			systemPrompt: e.context.systemPrompt,
			messages: n
		}, {
			...e.requestOptions,
			signal: t
		}), e.requestOptions.timeoutMs, e.requestOptions.signal ? { abortSignal: e.requestOptions.signal } : void 0);
		e.onUsage?.(a.modelUsage ?? a.usage);
		e.assertActive?.();
		const o = structuredClone(i.message);
		captureOpenAIResponsesCompaction(o, a.item, a.historyMode === "retained-users" ? "retained-users" : o.content.length, a.model, a.replayMetadata, a.output);
		if (e.trigger === "budget" && e.requestBudget) {
			const t = e.requestBudget;
			const n = estimateLlmBoundaryTokenPressure({
				messages: [o],
				prompt: "",
				replay: {
					model: e.model,
					sessionId: e.requestOptions.sessionId
				}
			}) - estimateRenderedLlmBoundaryTokenPressure({ prompt: "" });
			if (n + t.fixedTokens + t.pendingTokens > t.contextWindow - t.reserveTokens) {
				log.warn(`Responses compact endpoint result discarded: returned window does not fit the request budget (windowTokens=${n}); using client compaction`);
				return;
			}
		}
		const s = sanitizeTranscriptMessage(o);
		if (s.role !== "assistant" || !isDeepStrictEqual(s.providerReplay, o.providerReplay)) throw new Error("Responses compact endpoint window requires image normalization");
		await withSessionManagerWrite(e.sessionManager, async () => {
			e.requestOptions.signal?.throwIfAborted();
			e.assertActive?.();
			const n = await rewriteTranscriptEntriesInSessionManager({
				sessionManager: e.sessionManager,
				replacements: [{
					entryId: i.id,
					message: s
				}],
				preserveReplacementCompactionReplay: true
			});
			if (o.providerReplay?.data !== a.item.encrypted_content || !n.changed) throw new Error(`Responses compact endpoint checkpoint was not persisted: ${n.reason}`);
			t = true;
			e.onCompactionCommitted?.(a.usage.input_tokens);
		});
		return a;
	} catch (n) {
		if (t) throw n;
		e.assertActive?.();
		log.warn(`Responses compact endpoint failed; falling back to client compaction: ${formatErrorMessage(n)}`);
		return;
	}
}
/** Name the first request source the endpoint may retain that image normalization would rewrite. */
function findEndpointWindowNormalizationSource(e) {
	if (e.context.systemPrompt && !supportsNativeOpenAIResponsesEndpoint(e.model)) {
		const t = {
			role: "user",
			content: e.context.systemPrompt,
			timestamp: 0
		};
		if (sanitizeTranscriptMessage(t) !== t) return "system prompt";
	}
	return e.context.messages.some((e) => e.role === "user" && sanitizeTranscriptMessage(e) !== e) ? "user message" : void 0;
}
//#endregion
//#region src/agents/embedded-agent-runner/compaction-session-execution.ts
async function executePreparedCompactionSession(e) {
	const { params: t, diagId: n, trigger: r, runId: i, compactionModelCallTrace: a, diagnosticCompactionRunId: o, nextDiagnosticModelCallId: s, agentDir: c, provider: l, modelId: u, attemptedThinking: d, fail: f, modelRegistry: p, apiKeyInfo: m, hasRuntimeAuthExchange: h, sandboxSessionKey: g, sandbox: _, effectiveWorkspace: v, effectiveCwd: y, contextTokenBudget: b, effectiveModel: x, runtimePlan: S, runtimePlanModelContext: C, effectiveTools: w, allowedToolNames: T, buildSystemPromptText: E, resolvedMessageProvider: D, sessionAgentId: O } = e;
	let k = e.thinkLevel;
	let A = null;
	try {
		const f = resolveCompactionTimeoutMs(t.config);
		const j = readCompactionAccountingRecorder(t.contextEngineRuntimeContext);
		const M = j?.memoryTranscript;
		const ee = j?.preparedSession;
		const N = M?.sessionTarget ?? ee?.sessionTarget ?? await resolveAgentRunSessionTarget({
			agentId: O,
			config: t.config,
			missingSessionKey: "resolve-existing",
			sessionFile: t.sessionFile,
			sessionId: t.sessionId,
			sessionKey: t.sessionKey,
			sessionTarget: t.sessionTarget
		});
		const P = j?.recordCompaction ?? (() => declarePromptHistoryRewrite({
			...N,
			reason: "compaction"
		}));
		const F = M?.assertActive ?? captureOwnedTranscriptWriteAssertion(N);
		F();
		const I = S.transcript.resolvePolicy(C);
		const L = createPreparedEmbeddedAgentSettingsManager({
			agentId: O,
			sessionId: t.sessionId,
			cwd: y,
			agentDir: c,
			cfg: t.config,
			pluginMetadataSnapshot: getCurrentPluginMetadataSnapshot({
				config: t.config,
				env: process.env,
				workspaceDir: v
			}),
			contextTokenBudget: b
		});
		const { llmRuntime: R } = getModelRegistryRuntime(p);
		const z = registerProviderStreamForModel({
			model: x,
			cfg: t.config,
			agentDir: c,
			workspaceDir: v,
			apiRegistry: getModelRegistryRuntime(p).apiRegistry
		});
		const B = j?.recordUsage ? (e) => {
			const t = normalizeUsage(e);
			if (t) j.recordUsage?.(t);
		} : void 0;
		const V = { agent: { streamFn: z ?? R.streamSimple } };
		const H = {
			...e,
			llmRuntime: R,
			providerStreamFn: z,
			sessionId: t.sessionId,
			resolvedApiKey: h ? void 0 : m?.apiKey,
			config: t.config,
			modelCallUrgency: t.trigger === "manual" ? "foreground" : t.modelCallUrgency ?? "background"
		};
		const U = await prepareCompactionSessionAgent({
			...H,
			session: V,
			thinkLevel: k
		});
		if (!needsCompactionSessionAdapter(e, U.effectiveExtraParams, N)) return await executeBoundedCompactionSession(e, N, L, F, P, B, {
			...V,
			replayEnabled: resolveCompactionReplayEligibility(x, {
				extraParams: U.effectiveExtraParams,
				apiKey: U.transportApiKey
			})
		});
		const te = M?.sessionManager ?? ee?.sessionManager ?? await SessionManager.openAsync(N, void 0, { compaction: true }, t.abortSignal);
		F();
		const W = x.api === "openai-responses" || x.api === "azure-openai-responses" || x.api === "openai-chatgpt-responses";
		const G = guardSessionManager(te, {
			agentId: O,
			runId: t.runId,
			sessionKey: t.sessionKey,
			config: t.config,
			contextWindowTokens: b,
			allowSyntheticToolResults: I.allowSyntheticToolResults,
			missingToolResultText: W ? "aborted" : void 0,
			withCompactionPersistenceAsync: t.seedCompaction ?? j?.withCompactionPersistenceAsync
		});
		A = G;
		if (B) setSessionModelUsageSink(G, B);
		const K = buildEmbeddedExtensionFactories({
			cfg: t.config,
			sessionManager: G,
			workspaceDir: v,
			model: x,
			agentId: O,
			sessionId: t.sessionId,
			sessionKey: t.sessionKey ?? g,
			runId: i
		});
		const q = new DefaultResourceLoader({
			cwd: y,
			agentDir: c,
			extensionFactories: K
		});
		await q.reload();
		applyAgentAutoCompactionGuard({
			settingsManager: L,
			silentOverflowProneProvider: isSilentOverflowProneModel({
				provider: l,
				modelId: u,
				baseUrl: x.baseUrl ?? void 0
			})
		});
		const ne = toToolDefinitions(w, {
			agentId: O,
			config: t.config,
			cwd: y,
			sessionKey: g,
			sessionId: t.sessionId,
			runId: t.runId,
			channelId: t.currentChannelId
		});
		const re = toSessionToolAllowlist(collectRegisteredToolNames(ne));
		while (true) {
			setCompactionSafeguardCancellation(G, void 0);
			d.add(k);
			const e = E();
			let c;
			let m;
			let h;
			const refreshCompactionWatchdogs = () => {
				m?.watchdogAttempt?.setExecutionDeadline(Date.now() + f);
				h?.();
				t.compactionTimeoutReset?.();
			};
			try {
				c = (await createAgentSession({
					cleanupProviderSessionResourcesOnDispose: false,
					systemPrompt: e,
					cwd: y,
					modelRegistry: p,
					model: x,
					thinkingLevel: mapThinkingLevel(mapThinkingLevelForProvider(k, x)),
					tools: re,
					customTools: ne,
					sessionManager: G,
					settingsManager: L,
					resourceLoader: q
				})).session;
				c[agentSessionSetContextReplacementHook]((e, t, n) => P({
					tokensBefore: t,
					tokensAfter: e,
					compactionKind: "context-engine",
					details: n
				}), F);
				c.setBaseSystemPrompt(e.trim());
				const { effectiveExtraParams: d, transportApiKey: g } = await prepareCompactionSessionAgent({
					...H,
					session: c,
					thinkLevel: k
				});
				const C = resolveCompactionReplayEligibility(x, {
					extraParams: d,
					apiKey: g
				});
				const w = getCurrentSessionControllerOwner();
				m = createDiagnosticEmbeddedRunOwner({
					watchdogAttempt: w ? w.watchdog.attachAttempt({
						nested: true,
						assertCurrent: () => {
							t.abortSignal?.throwIfAborted();
							assertSessionControllerOperation(w);
						}
					}) : void 0,
					sessionId: t.sessionId,
					...t.sessionKey ? { sessionKey: t.sessionKey } : {},
					runId: o,
					workKey: o
				});
				m.watchdogAttempt?.setExecutionDeadline(Date.now() + f);
				markDiagnosticEmbeddedRunStarted({
					...m,
					owner: m
				});
				c.agent.streamFn = wrapStreamFnWithDiagnosticModelCallEvents(c.agent.streamFn, {
					config: t.config,
					runId: o,
					...t.sessionKey && { sessionKey: t.sessionKey },
					sessionId: t.sessionId,
					provider: l,
					model: u,
					api: x.api,
					transport: c.agent.transport,
					requestTimeoutMs: f,
					contextTokenBudget: b,
					trace: a,
					contentCapture: resolveDiagnosticModelContentCapturePolicy(t.config),
					nextCallId: s,
					ownerGeneration: m.generation,
					onStarted: refreshCompactionWatchdogs,
					onOutputDelta: refreshCompactionWatchdogs
				});
				const replayContext = () => ({
					modelApi: x.api,
					modelId: u,
					provider: l,
					config: t.config,
					workspaceDir: v,
					env: process.env,
					model: x,
					sessionId: t.sessionId,
					policy: I
				});
				const E = await sanitizeSessionHistory({
					...replayContext(),
					messages: c.messages,
					allowedToolNames: T,
					sessionManager: G,
					preserveLatestAssistantThinking: false
				});
				const ee = await validateReplayTurns({
					...replayContext(),
					messages: E
				});
				const R = dedupeDuplicateUserMessagesForCompaction(ee);
				c.agent.state.messages = R;
				const z = c.messages;
				const V = preserveCompactionReplayWindow(z, limitHistoryTurns(c.messages, getHistoryLimitFromSessionKey(t.sessionKey, t.config, {
					accountId: t.agentAccountId,
					peerId: t.conversationRoutePeerId,
					chatType: t.chatType
				})), x, {
					sessionId: t.sessionId,
					enabled: C
				});
				const U = I.repairToolUseResultPairing ? sanitizeToolUseResultPairingForModel(V, W) : V;
				if (U.length > 0) c.agent.state.messages = U;
				const te = j?.hostOwnsCompactionLifecycle ? null : getGlobalHookRunner();
				const K = floorPositiveFiniteNumber(t.currentTokenCount);
				const J = buildBeforeCompactionHookMetrics({
					originalMessages: z,
					currentMessages: c.messages,
					observedTokenCount: K,
					estimateTokensFn: estimateTokens
				});
				const hookContext = () => ({
					hookRunner: te,
					sessionId: t.sessionId,
					sessionKey: N.sessionKey,
					sessionAgentId: O,
					workspaceDir: v,
					messageProvider: D,
					assertActive: F,
					onHookMessages: t.onCompactionHookMessages
				});
				const ie = M ? t.sessionFile : formatSqliteSessionFileMarker({
					...N,
					sessionId: t.sessionId
				});
				const completeSkippedCompaction = async (e) => {
					await runCompactionHooks({
						...hookContext(),
						phase: "after",
						messageCountAfter: J.messageCountBefore,
						tokensAfter: J.tokenCountBefore,
						compactedCount: 0,
						compactionOutcome: "skipped",
						sessionFile: ie
					});
					return {
						ok: true,
						compacted: false,
						reason: e
					};
				};
				await runCompactionHooks({
					...hookContext(),
					phase: "before",
					metrics: J
				});
				const { messageCountOriginal: ae, tokenCountBefore: oe } = J;
				if (!c.messages.some((e, t, n) => isRealConversationMessage(e, n, t))) {
					log.info(`[compaction] skipping — no real conversation messages (sessionKey=${t.sessionKey ?? t.sessionId})`);
					return await completeSkippedCompaction("no real conversation messages");
				}
				refreshCompactionWatchdogs();
				let Y;
				const recordServerCompaction = (n) => {
					Y = estimateLlmBoundaryTokenPressure({
						messages: G.buildSessionContext().messages,
						systemPrompt: j?.requestBudget ? void 0 : e,
						prompt: "",
						replay: {
							model: x,
							sessionId: t.sessionId,
							enabled: C
						}
					});
					Y += j?.requestBudget ? j.requestBudget.fixedTokens - estimateLlmBoundaryTokenPressure({
						messages: [],
						prompt: ""
					}) : 0;
					P({
						tokensBefore: n,
						tokensAfter: Y,
						compactionKind: "server-endpoint"
					});
				};
				const X = t.seedCompaction ? void 0 : await attemptServerEndpointCompaction({
					trigger: r,
					streamFn: c.agent.streamFn,
					model: x,
					context: {
						systemPrompt: e,
						messages: c.messages
					},
					sessionManager: G,
					extraParams: d,
					requestBudget: j?.requestBudget,
					customInstructions: t.customInstructions,
					onUsage: B,
					onCompactionCommitted: recordServerCompaction,
					assertActive: F,
					requestOptions: {
						apiKey: g,
						sessionId: t.sessionId,
						authProfileId: S.auth.forwardedAuthProfileId,
						timeoutMs: f,
						signal: t.abortSignal
					}
				});
				const Z = c;
				const se = r === "manual" ? createStandaloneCompactionRequestBudget({
					maxSummaryChars: L.getCompactionSettings().maxSummaryChars,
					contextWindow: b,
					reserveTokens: L.getCompactionReserveTokens(),
					systemPrompt: c.agent.state.systemPrompt,
					tools: c.agent.state.tools
				}) : void 0;
				let Q;
				let $ = false;
				if (!X) {
					let e;
					const compactClient = (n) => compactWithSafetyTimeout(async (i, a) => {
						e = i;
						h = a;
						setCompactionSafeguardCancellation(A, void 0);
						const o = j?.pendingRequestState ?? (r === "overflow" ? "unresolved" : void 0);
						if (r === "manual" && !se) return {
							status: "completed",
							result: await Z.compact(t.customInstructions)
						};
						return Z[agentSessionAutomaticCompaction](t.customInstructions, o, r === "manual" ? "none" : n, {
							requestBudget: se ?? j?.requestBudget,
							requestFromEntryId: j?.requestFromEntryId,
							pendingUserEntryId: j?.pendingUserEntryId,
							onSummaryReady: () => {
								$ = true;
							}
						});
					}, f, {
						abortSignal: t.abortSignal,
						onCancel: () => Z.abortCompaction(),
						...t.compactionDeadlineAt !== void 0 && n !== "deterministic" ? { deadlineAt: t.compactionDeadlineAt - f } : {}
					});
					try {
						refreshCompactionWatchdogs();
						const a = await compactClient(resolveEffectiveCompactionMode(t.config) === "default" ? void 0 : "none").catch(async (a) => {
							if (r === "manual" || t.abortSignal?.aborted || $ || !isSummaryTimeoutFailure({
								error: a,
								summarySignal: e,
								abortSignal: t.abortSignal,
								safeguardCancellation: getCompactionSafeguardRuntime(G)?.cancellation
							})) throw a;
							refreshCompactionWatchdogs();
							log.warn(`[compaction-diag] fallback runId=${i} sessionKey=${t.sessionKey ?? t.sessionId} diagId=${n} trigger=${r} provider=${l}/${u} reason=timeout summary=deterministic`);
							return await compactClient("deterministic");
						});
						if (a.status === "skipped") {
							F();
							return await completeSkippedCompaction(a.reason);
						}
						Q = a.result;
					} finally {
						h = void 0;
					}
				}
				refreshCompactionWatchdogs();
				const ce = X?.usage.input_tokens ?? Q.tokensBefore;
				const le = X ? Y : estimateTokensAfterCompaction({
					messagesAfter: c.messages,
					observedTokenCount: K,
					fullSessionTokensBefore: oe ?? 0,
					estimateTokensFn: estimateTokens,
					requestBudget: j?.requestBudget
				});
				const ue = c.messages.length;
				const de = Math.max(0, ae - ue);
				if (!M && !j?.hostOwnsCompactionLifecycle) await runPostCompactionSideEffects({
					config: t.config,
					sessionKey: t.sessionKey,
					sessionId: t.sessionId,
					agentId: O,
					memoryAudience: t.memoryAudience,
					sandboxed: _?.enabled === true,
					sessionFile: ie,
					assertActive: F
				});
				await runCompactionHooks({
					...hookContext(),
					phase: "after",
					messageCountAfter: ue,
					tokensAfter: le,
					compactedCount: de,
					sessionFile: ie,
					summaryLength: Q?.summary.length,
					tokensBefore: ce,
					firstKeptEntryId: Q?.firstKeptEntryId
				});
				const fe = {
					agentId: N.agentId,
					sessionId: N.sessionId,
					sessionKey: N.sessionKey,
					storePath: N.storePath
				};
				if (t.sessionTarget?.threadId !== void 0) fe.threadId = t.sessionTarget.threadId;
				return {
					ok: true,
					compacted: true,
					...X ? { compactionKind: "server-endpoint" } : {},
					result: {
						sessionTarget: fe,
						...Q ? {
							summary: Q.summary,
							firstKeptEntryId: Q.firstKeptEntryId
						} : { kind: "server-endpoint" },
						tokensBefore: X ? ce : K ?? Q.tokensBefore,
						tokensAfter: le,
						details: X ? {
							compactionKind: "server-endpoint",
							droppedMessageCount: X.usage.dropped_message_count
						} : Q.details
					}
				};
			} catch (e) {
				const n = resolveCompactionFailure({
					error: e,
					safeguardCancellation: getCompactionSafeguardRuntime(G)?.cancellation,
					abortSignal: t.abortSignal
				});
				F();
				const r = pickFallbackThinkingLevel({
					message: formatErrorMessage(n.error),
					attempted: d
				});
				if (r) {
					log.warn(`[compaction] request rejected for ${l}/${u}; retrying with ${r}`);
					k = r;
					refreshCompactionWatchdogs();
					continue;
				}
				throw e;
			} finally {
				if (m) closeDiagnosticEmbeddedRunOwner(m);
				try {
					await flushPendingToolResultsAfterIdle({
						agent: c?.agent,
						sessionManager: G,
						abortSignal: t.abortSignal
					});
				} catch {}
				try {
					c?.dispose();
				} catch {}
			}
		}
	} catch (e) {
		const n = resolveCompactionFailure({
			error: e,
			safeguardCancellation: consumeCompactionSafeguardCancellation(A),
			abortSignal: t.abortSignal
		});
		return f(n.reason, n.error);
	} finally {
		setSessionModelUsageSink(A, null);
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/direct-compaction-preparation.ts
async function prepareDirectCompactionAttempt(e) {
	const t = Date.now();
	const n = e.diagId?.trim() || `cmp-${Date.now().toString(36)}-${generateSecureToken(4)}`;
	const r = e.trigger ?? "manual";
	const i = e.attempt ?? 1;
	const a = e.maxAttempts ?? 1;
	const o = e.runId ?? e.sessionId;
	const s = freezeDiagnosticTraceContext(getActiveDiagnosticTraceContext() ?? createDiagnosticTraceContext());
	const c = `${o}:compaction:${n}`;
	let l = 0;
	const u = resolveUserPath(e.workspaceDir);
	const { sessionAgentId: d } = resolveSessionAgentIds({
		sessionKey: e.sessionKey,
		config: e.config,
		agentId: e.agentId
	});
	const f = e.agentDir ?? resolveAgentDir(e.config ?? {}, d);
	const { runtimePolicySessionKey: p, runtimePolicyAgentId: m, boundHarnessRuntime: h, selectedHarnessRuntimeOverride: g, runtimeModelAuth: { plan: _, authProfileId: v, modelAuth: y }, provider: b, runtimeProvider: x, contextConfigProvider: S, modelId: C } = resolveCompactionRuntimeSelection({
		...e,
		modelId: e.model,
		boundHarnessRuntime: e.agentHarnessId,
		preparedRuntimePlan: e.runtimePlan
	});
	await ensureSelectedAgentHarnessPlugin({
		config: e.config,
		provider: b,
		modelId: C,
		agentId: m,
		sessionKey: p,
		agentHarnessId: h,
		agentHarnessRuntimeOverride: g,
		workspaceDir: u,
		pluginRegistry: e.preparedModelRuntime.pluginRegistry
	});
	const fail = (s, c, l) => {
		const u = l ?? classifyCompactionReason(s);
		const d = c ? describeCompactionFailure(c) : void 0;
		log.warn(`[compaction-diag] end runId=${o} sessionKey=${e.sessionKey ?? e.sessionId} diagId=${n} trigger=${r} provider=${b}/${C} attempt=${i} maxAttempts=${a} outcome=failed reason=${u} durationMs=${Date.now() - t}`);
		return {
			ok: false,
			compacted: false,
			reason: s,
			failure: d ? {
				reason: d.reason,
				status: d.status,
				code: d.code,
				rawError: d.rawError ?? d.message
			} : void 0
		};
	};
	const w = e.preparedModelRuntime;
	const { resolution: T } = await resolveTieredModel({
		abortSignal: e.abortSignal,
		provider: x,
		modelId: C,
		requestedRouteResolution: e.requestedRouteResolution,
		agentDir: f,
		config: e.config,
		workspaceDir: u,
		...y,
		preparedModelRuntime: w
	});
	const { model: E, error: D, authStorage: O, modelRegistry: k } = T;
	if (!E) return {
		ok: false,
		result: fail(D ?? `Unknown model: ${x}/${C}`, void 0, "compaction_model_unresolved")
	};
	const A = await prepareCompactionHarnessAuth({
		...e,
		provider: b,
		metadataProvider: x,
		modelId: C,
		model: E,
		reusableRuntimeAuthPlan: _,
		agentDir: f,
		workspaceDir: u,
		authProfileId: v,
		runtimePolicyAgentId: m,
		runtimePolicySessionKey: p,
		agentHarnessId: h,
		agentHarnessRuntimeOverride: g
	});
	if (!A.ok) {
		e.abortSignal?.throwIfAborted();
		return {
			ok: false,
			result: fail(formatErrorMessage(A.error), A.error)
		};
	}
	const { runtimeAuthProfileStore: j, runtimeAuthPreparation: M, selectedPreparedHarness: ee, providerUsesProfileScopedModelMetadata: N } = A;
	const P = ee.id;
	let F;
	try {
		F = await resolvePreparedRuntimeAuthAttempts({
			attempts: M.attempts,
			store: j,
			modelId: C,
			model: E,
			materializeModel: async (t) => await materializePreparedRuntimeModel({
				...t,
				provider: b,
				modelId: C,
				config: e.config,
				workspaceDir: u,
				metadataSnapshot: w.metadataSnapshot,
				resolveModel: ({ config: t, authProfileId: n, authProfileMode: r }) => resolveModelAsync(x, C, f, t, {
					abortSignal: e.abortSignal,
					authStorage: O,
					modelRegistry: k,
					preparedModelRuntime: w,
					workspaceDir: u,
					modelIdSource: e.requestedRouteResolution === "resolved" ? "selected" : "input",
					skipAgentDiscovery: true,
					allowBundledStaticCatalogFallback: true,
					authProfileId: n,
					authProfileMode: r
				})
			}) ?? t.model,
			forceCredentialScopedDirectModelResolve: N,
			resolveAuth: async ({ attempt: t, model: n }) => await resolvePreparedRuntimeModelAuth({
				plan: t.plan,
				model: n,
				cfg: e.config,
				store: j,
				agentDir: f,
				workspaceDir: u,
				...t.allowAuthProfileFallback !== void 0 ? { allowAuthProfileFallback: t.allowAuthProfileFallback } : {},
				secretSentinels: true
			}),
			errorMessage: `Prepared compaction auth attempts could not be resolved for ${b}/${C}.`
		});
		e.abortSignal?.throwIfAborted();
	} catch (e) {
		return {
			ok: false,
			result: fail(formatErrorMessage(e), e)
		};
	}
	const I = F.auth;
	let L = attachProviderAuthAuthority(F.model, getProviderAuthAuthority(I));
	let R = I.apiKey;
	const z = F.plan;
	let B = false;
	try {
		if (I.apiKey) {
			const t = await prepareProviderRuntimeAuth({
				provider: L.provider,
				config: e.config,
				workspaceDir: u,
				env: process.env,
				context: {
					config: e.config,
					agentDir: f,
					workspaceDir: u,
					env: process.env,
					provider: L.provider,
					modelId: C,
					model: L,
					apiKey: unwrapSecretSentinelsForProviderEgress(I.apiKey, "provider runtime auth exchange"),
					authMode: I.mode,
					profileId: I.profileId
				}
			});
			e.abortSignal?.throwIfAborted();
			const n = protectPreparedProviderRuntimeAuth({
				provider: L.provider,
				preparedAuth: t
			});
			L = applyPreparedRuntimeAuthToModel(L, n);
			R = n?.apiKey ?? I.apiKey;
			B = Boolean(n?.apiKey);
			if (!R) throw new Error(`Provider "${L.provider}" runtime auth returned no apiKey.`);
			O.setRuntimeApiKey(L.provider, R);
		} else if (I.mode !== "aws-sdk") throw new MissingProviderAuthError(L.provider, I);
	} catch (e) {
		return {
			ok: false,
			result: fail(formatErrorMessage(e), e)
		};
	}
	const V = projectModelThinkingCompat(L.compat);
	const H = {
		provider: L.provider,
		id: L.id,
		api: L.api,
		reasoning: L.reasoning,
		...L.thinkingLevelMap ? { thinkingLevelMap: L.thinkingLevelMap } : {},
		params: L.params,
		...V ? { compat: V } : {}
	};
	const U = resolveEmbeddedCompactionThinkingLevel({
		config: e.config,
		provider: L.provider,
		modelId: L.id,
		inheritedLevel: e.thinkLevel,
		compactionThinkingDefault: L.compactionThinkingDefault,
		catalog: [H],
		agentId: m,
		sessionKey: p,
		agentRuntime: P
	});
	await fs.mkdir(u, { recursive: true });
	const te = e.sessionKey?.trim() || e.sessionId;
	const W = e.sandboxSessionKey?.trim() || te;
	const G = e.sandboxAgentId ?? (W === te ? d : void 0);
	const assertCurrent = () => e.abortSignal?.throwIfAborted();
	let K = e.skillsSnapshot;
	if (K && K.resolvedSkills === void 0 && (K.prompt.trim() || K.discoverySkills?.length || K.librarySelections?.length)) {
		const t = K;
		const n = t.skillRoots;
		const { snapshot: r } = await resolveReusableWorkspaceSkillSnapshot({
			workspaceDir: n?.agentWorkspaceDir ?? (e.config && hasAgentRosterProperty(e.config) ? resolveAgentWorkspaceDir(e.config, d) : e.bootstrapWorkspaceDir ?? u),
			executionWorkspaceDir: n?.executionWorkspaceDir,
			executionWorkspaceFileHost: resolveSkillSnapshotExecutionFileHost(K),
			config: e.config ?? {},
			agentId: d,
			existingSnapshot: K,
			skillFilter: K.skillFilter,
			skillOverrides: K.skillOverrides,
			resolveEligibility: () => ({
				nodeSkills: t.nodeSkillsEligibility,
				remote: getRemoteSkillEligibility({ advertiseExecNode: t.nodeSkillsEligibility?.canExec === true })
			}),
			watch: false,
			assertCurrent
		});
		K = r;
	}
	assertCurrent();
	const q = e.sandbox === void 0 ? await withSandboxRuntimeStatusInWorker({
		cfg: e.config,
		agentId: G,
		sessionKey: W
	}, {
		env: process.env,
		cwd: process.cwd(),
		assertCurrent
	}, async (t) => resolveSandboxContext({
		config: e.config,
		agentId: G,
		execOverrides: e.execOverrides,
		sessionKey: W,
		workspaceDir: u,
		skillsSnapshot: K,
		assertCurrent,
		preparedRuntimeStatus: t
	})) : e.sandbox;
	const releaseSandbox = () => {
		if (e.sandbox === void 0) q?.[Symbol.dispose]?.();
	};
	try {
		const t = q?.enabled && q.workspaceAccess !== "rw" ? q.workspaceDir : u;
		const p = e.cwd ? resolveUserPath(e.cwd) : void 0;
		if (q?.enabled && p && p !== u) throw new Error("cwd override is not supported for sandboxed embedded compaction runs; omit cwd or use the agent workspace as cwd");
		const m = q?.enabled ? t : p ?? t;
		await fs.mkdir(t, { recursive: true });
		return {
			ok: true,
			value: {
				params: {
					...e,
					skillsSnapshot: K
				},
				diagId: n,
				trigger: r,
				attempt: i,
				maxAttempts: a,
				runId: o,
				compactionModelCallTrace: s,
				diagnosticCompactionRunId: c,
				nextDiagnosticModelCallId: () => `${c}:model:${l += 1}`,
				agentDir: f,
				provider: b,
				contextConfigProvider: S,
				modelId: C,
				preparedHarnessRuntime: P,
				thinkLevel: U,
				attemptedThinking: /* @__PURE__ */ new Set(),
				fail,
				authStorage: O,
				modelRegistry: k,
				runtimeModel: L,
				apiKeyInfo: I,
				runtimeApiKey: R,
				resolvedRuntimeAuthPlan: z,
				hasRuntimeAuthExchange: B,
				resolvedWorkspace: u,
				sandboxSessionKey: W,
				sandboxAgentId: G,
				sandbox: q,
				effectiveWorkspace: t,
				effectiveCwd: m,
				sessionAgentId: d,
				releaseSandbox
			}
		};
	} catch (e) {
		releaseSandbox();
		throw e;
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/prepared-compaction-runtime.ts
async function buildPreparedCompactionRuntime(e, t) {
	const { params: n, runId: r, agentDir: i, provider: a, contextConfigProvider: o, modelId: s, preparedHarnessRuntime: c, thinkLevel: l, runtimeModel: u, apiKeyInfo: d, runtimeApiKey: f, resolvedRuntimeAuthPlan: p, hasRuntimeAuthExchange: m, resolvedWorkspace: h, sandboxSessionKey: g, sandboxAgentId: _, sandbox: v, effectiveWorkspace: y, effectiveCwd: b, sessionAgentId: x } = e;
	const S = n.execOverrides?.mode ? SESSION_PERMISSION_BY_EXEC_MODE[n.execOverrides.mode] : n.permissionMode ?? n.sessionEntry?.permissionMode;
	const C = n.sessionRoot ?? n.sessionEntry?.sessionRoot;
	const w = S ? {
		mode: S,
		root: C ?? await fs.realpath(h)
	} : void 0;
	const T = w ? {
		...n.execOverrides,
		mode: resolveSessionPermissionExecMode(w)
	} : n.execOverrides;
	let E;
	let D;
	let O;
	const disposeToolRuntimes = async () => {
		const e = [D, O];
		D = void 0;
		O = void 0;
		for (const t of e) try {
			await t?.dispose();
		} catch {}
	};
	const restoreSkillEnvironment = () => {
		const e = E;
		E = void 0;
		e?.();
	};
	t({
		disposeToolRuntimes,
		restoreSkillEnvironment
	});
	try {
		const t = await prepareEmbeddedSkills({
			assertCurrent: () => n.abortSignal?.throwIfAborted(),
			attempt: {
				config: n.config,
				bootstrapWorkspaceDir: n.bootstrapWorkspaceDir,
				skillsSnapshot: n.skillsSnapshot
			},
			effectiveWorkspace: y,
			sandbox: v,
			sessionAgentId: x,
			includeCodeModeSkills: false
		});
		E = t.restoreSkillEnv;
		const { skillsSnapshotForRun: S, skillReadResources: C, skillUsagePaths: k, skillsPrompt: A } = t;
		const j = n.sessionKey ?? n.sessionId;
		const M = n.messageChannel ?? n.messageProvider;
		const { bootstrapFiles: ee, contextFiles: N } = resolveContextInjectionMode(n.config, x) === "never" ? {
			bootstrapFiles: [],
			contextFiles: []
		} : await resolveBootstrapContextForRun({
			workspaceDir: y,
			config: n.config,
			sessionKey: n.sessionKey,
			sessionId: n.sessionId,
			chatType: n.chatType,
			agentId: x,
			warn: makeBootstrapWarn({
				sessionLabel: j,
				warn: (e) => log.warn(e)
			})
		});
		const P = buildBootstrapInjectionStats({
			bootstrapFiles: ee,
			injectedFiles: N
		});
		const F = buildBootstrapBudgetState({
			config: n.config,
			agentId: x,
			files: P
		});
		const I = buildBootstrapPromptWarningNotice(F.bootstrapPromptWarning.lines);
		const L = resolveCompactionContextTokenBudget({
			config: n.config,
			provider: o,
			modelId: s,
			model: u,
			requestedTokenBudget: n.contextTokenBudget,
			fallbackTokenBudget: n.tokenBudget
		});
		const R = applyAuthHeaderOverride(applyLocalNoAuthHeaderOverride(u, { apiKey: f }), m ? null : d, n.config);
		const z = resolvePreparedProviderRuntimeHandle({
			provider: a,
			modelId: s,
			config: n.config,
			workspaceDir: y,
			providerRuntimeHandle: n.runtimePlan?.providerRuntimeHandle,
			metadataSnapshot: n.preparedModelRuntime.metadataSnapshot
		});
		const B = attachModelProviderRuntimePluginHandle(R, z);
		const V = n.runtimePlan?.auth === p;
		const H = (V ? n.runtimePlan : void 0) ?? buildAgentRuntimePlan({
			provider: a,
			modelId: s,
			model: B,
			modelApi: B.api,
			providerRuntimeHandle: z,
			harnessId: c,
			harnessRuntime: c,
			authProfileMode: p.selectedAuthMode,
			sessionAuthProfileId: p.forwardedAuthProfileId,
			sessionAuthProfileSource: p.forwardedAuthProfileSource,
			sessionAuthProfileCandidateIds: p.forwardedAuthProfileCandidateIds,
			modelRoute: p.modelRoute,
			config: n.config,
			workspaceDir: y,
			agentDir: i,
			agentId: x,
			thinkingLevel: mapThinkingLevelForProvider(l, B)
		});
		const U = V ? H : {
			...H,
			auth: p
		};
		const te = b !== y ? h : resolveAttemptSpawnWorkspaceDir({
			sandbox: v,
			resolvedWorkspace: h
		});
		const W = {
			config: n.config,
			sessionKey: g,
			runSessionKey: n.sessionKey?.trim() || n.sessionId,
			sessionId: n.sessionId,
			runId: n.runId,
			agentDir: i,
			agentAccountId: n.agentAccountId,
			messageProvider: M,
			chatType: n.chatType,
			requesterOrigin: n.requesterOrigin,
			operatorProfileId: n.operatorProfileId,
			conversationId: n.conversationId,
			messageThreadId: n.messageThreadId,
			memberRoleIds: n.memberRoleIds,
			groupId: n.groupId,
			groupChannel: n.groupChannel,
			groupSpace: n.groupSpace,
			spawnedBy: n.spawnedBy,
			senderId: n.senderId,
			senderName: n.senderName,
			senderUsername: n.senderUsername,
			senderE164: n.senderE164,
			modelProvider: B.provider,
			modelId: s,
			modelApi: B.api,
			modelContextWindowTokens: L,
			workspaceDir: y,
			cwd: b,
			spawnWorkspaceDir: te,
			skillsSnapshot: S
		};
		const G = await prepareConversationCapabilityProfile({
			...W,
			agentId: _,
			conversationToolPolicy: n.conversationToolPolicy,
			senderIsOwner: n.senderIsOwner,
			sandboxToolPolicy: v?.tools,
			inputProvenance: n.inputProvenance,
			trustedInternalHandoff: n.trustedInternalHandoff,
			pluginMetadataSnapshot: n.preparedModelRuntime.metadataSnapshot
		});
		const K = supportsModelTools(B);
		const q = K ? getPreparedModelRuntimeAuthStore(n.preparedModelRuntime) ?? await ensureAuthProfileStoreWithoutExternalProfilesAsync(i) : void 0;
		n.abortSignal?.throwIfAborted();
		const ne = /* @__PURE__ */ new Map();
		const re = K ? await createOpenClawCodingToolsInternalAsync({
			...W,
			authProfileStore: q,
			agentId: x,
			exec: {
				...T,
				config: n.config,
				elevated: n.bashElevated
			},
			sandbox: v,
			sessionPermissionPolicy: w,
			requireWorkspaceOnly: n.requireWorkspaceOnly,
			clientCaps: n.clientCaps,
			pinnedWidgetAuthoring: n.pinnedWidgetAuthoring,
			oneShotCliRun: n.oneShotCliRun,
			allowGatewaySubagentBinding: n.allowGatewaySubagentBinding,
			webSearchEnabled: n.toolOverrides?.webSearch !== false,
			sourceReplyDeliveryMode: n.sourceReplyDeliveryMode,
			modelHasVision: B.input?.includes("image") ?? false,
			modelCompat: extractModelCompat(B),
			skillUsagePaths: k,
			skillInstructionDeliveryCache: ne,
			conversationCapabilityProfile: G,
			preparedModelRuntime: n.preparedModelRuntime,
			modelAuthMode: await resolveModelAuthModeAsync(B.provider, n.config, q, { workspaceDir: y })
		}, C) : [];
		const J = {
			workspaceDir: y,
			modelApi: B.api,
			model: B
		};
		const ie = {
			runId: r,
			agentId: x,
			sessionKey: n.sessionKey,
			sessionId: n.sessionId
		};
		const normalizeToolSchemas = async (e, t) => {
			const n = filterProviderNormalizableTools(e);
			if (t === "core" || n.diagnostics.length > 0) await logRuntimeToolSchemaQuarantine({
				...ie,
				diagnostics: n.diagnostics,
				tools: e
			});
			return t === "core" || e.length > 0 ? U.tools.normalize([...n.tools], J) : e;
		};
		const ae = await normalizeToolSchemas(re, "core");
		D = K ? await createBundleMcpToolRuntime({
			workspaceDir: y,
			cfg: n.config,
			reservedToolNames: ae.map((e) => e.name)
		}) : void 0;
		O = K ? await createBundleLspToolRuntime({
			workspaceDir: y,
			cfg: n.config,
			abortSignal: n.abortSignal,
			reservedToolNames: [...ae.map((e) => e.name), ...D?.tools.map((e) => e.name) ?? []]
		}) : void 0;
		const oe = await normalizeToolSchemas(applyFinalEffectiveToolPolicy({
			bundledTools: [...D?.tools ?? [], ...O?.tools ?? []],
			config: n.config,
			conversationCapabilityProfile: G,
			warn: (e) => log.warn(e)
		}), "bundle");
		const Y = [...ae, ...oe];
		const X = filterRuntimeCompatibleTools(Y);
		await logRuntimeToolSchemaQuarantine({
			...ie,
			diagnostics: X.diagnostics,
			tools: Y
		});
		const Z = [...X.tools];
		const se = collectAllowedToolNames({ tools: Z });
		const Q = toolPolicyRestrictsTools({ allow: n.toolsAllow });
		const $ = applyEmbeddedAttemptToolsAllow(Z, n.toolsAllow, { toolMeta: (e) => getPluginToolMeta(e) });
		const ce = collectAllowedToolNames({ tools: $ });
		U.tools.logDiagnostics(Z, J);
		const le = await getMachineDisplayName();
		const { runtimeChannel: ue, runtimeCapabilities: de, reactionGuidance: fe, messageToolHints: pe, customInlineButtonHint: me } = resolveRuntimeChannelPromptContext({
			cfg: n.config,
			channel: n.messageChannel ?? n.messageProvider,
			accountId: n.agentAccountId,
			requester: n
		});
		const he = {
			agentId: x,
			agentName: n.config ? resolveRuntimeAgentName(n.config, x) : void 0,
			sessionKey: n.sessionKey,
			host: le,
			os: resolveRuntimeOsLabel(),
			arch: os.arch(),
			node: process.version,
			model: `${a}/${s}`,
			shell: detectRuntimeShell(),
			channel: ue,
			chatType: n.chatType,
			capabilities: de,
			customInlineButtonHint: me,
			blind: n.sessionEntry?.blindPrompt,
			activeProcessSessions: listActiveProcessSessionReferences({ scopeKey: resolveProcessToolScopeKey({
				sessionKey: n.sessionKey,
				sessionId: n.sessionId,
				agentId: x
			}) })
		};
		if (v?.enabled) n.abortSignal?.throwIfAborted();
		const ge = v?.enabled && n.bashElevated?.enabled === true ? await resolveEmbeddedSandboxInfoExecPolicy({
			config: n.config,
			agentId: x,
			sessionKey: n.sessionKey,
			permissionMode: w?.mode,
			sandboxAvailable: v.enabled,
			execOverrides: T
		}, { signal: n.abortSignal }) : void 0;
		const _e = buildEmbeddedSandboxInfo(v, n.bashElevated, ge);
		const ve = isReasoningTagProvider(a, {
			config: n.config,
			workspaceDir: y,
			env: process.env,
			modelId: s,
			modelApi: B.api,
			model: B
		});
		const ye = resolveAgentPromptSurfaceForSessionKey(n.sessionKey);
		const be = Q ? "minimal" : resolvePromptModeForSession(n.sessionKey);
		const xe = listRegisteredPluginAgentPromptGuidance({ surface: ye });
		const Se = await resolveOpenClawReferencePaths({
			sandbox: v,
			workspaceDir: y,
			argv1: process.argv[1],
			cwd: b,
			moduleUrl: import.meta.url
		});
		const buildPromptContributionContext = () => ({
			config: n.config,
			agentDir: i,
			workspaceDir: y,
			provider: a,
			modelId: s,
			promptMode: be,
			runtimeChannel: ue,
			runtimeCapabilities: de,
			agentId: x
		});
		const Ce = U.prompt.resolveSystemPromptContribution(buildPromptContributionContext());
		const we = await prepareAgentMemoryPrompt({
			enabled: be === "full",
			toolNames: $.map((e) => e.name),
			citationsMode: n.config?.memory?.citations,
			agentId: he.agentId,
			agentSessionKey: he.sessionKey,
			sandboxed: _e?.enabled === true
		});
		const Te = await prepareWatchedSessionsPromptAsync({
			enabled: be === "full",
			config: n.config,
			sessionKey: n.sessionKey,
			sandboxed: _e?.enabled === true,
			toolNames: $.map((e) => e.name),
			capabilityToolNames: ce,
			assertCurrent: () => n.abortSignal?.throwIfAborted()
		});
		const Ee = n.preparedModelRuntime?.activeProjectKeys ?? [];
		const { prepareTtsPreferences: De } = await import("./tts-preferences-Dex9XQ35.mjs");
		const Oe = be === "full" ? await De() : void 0;
		const buildSystemPromptText = () => {
			const e = buildConfiguredAgentSystemPrompt({
				preparedTtsPreferences: Oe,
				config: n.config,
				preparedModelRuntime: n.preparedModelRuntime,
				agentId: x,
				workspaceDir: y,
				runtimeCwd: b,
				reasoningLevel: n.reasoningLevel ?? "off",
				extraSystemPrompt: n.extraSystemPrompt,
				ownerNumbers: n.ownerNumbers,
				reasoningTagHint: ve,
				skillsPrompt: Q ? void 0 : A,
				docsPath: Se.docsPath ?? void 0,
				sourcePath: Se.sourcePath ?? void 0,
				promptMode: be,
				promptSurface: ye,
				sourceReplyDeliveryMode: n.sourceReplyDeliveryMode,
				acpEnabled: isAcpRuntimeSpawnAvailable({
					config: n.config,
					sandboxed: _e?.enabled === true
				}),
				runtimeInfo: he,
				reactionGuidance: fe,
				messageToolHints: pe,
				sandboxInfo: _e,
				tools: $,
				contextFiles: N,
				bootstrapTruncationNotice: I,
				activeProjectKeys: Ee,
				preparedMemoryPrompt: we,
				preparedWatchedSessions: Te,
				promptContribution: Ce,
				nativeCommandGuidanceLines: xe
			});
			return transformProviderSystemPrompt({
				provider: a,
				config: n.config,
				workspaceDir: y,
				context: {
					...buildPromptContributionContext(),
					systemPrompt: e
				}
			});
		};
		return {
			...e,
			contextTokenBudget: L,
			effectiveModel: B,
			runtimePlan: U,
			runtimePlanModelContext: J,
			effectiveTools: Z,
			allowedToolNames: se,
			buildSystemPromptText,
			resolvedMessageProvider: M
		};
	} catch (e) {
		restoreSkillEnvironment();
		throw e;
	}
}
//#endregion
//#region src/agents/embedded-agent-runner/direct-compaction.ts
async function compactEmbeddedAgentSessionDirectOnce(e) {
	const t = createDeferredCore();
	const n = captureAsyncWorkTracker();
	const r = getAsyncWorkSignal();
	const i = e.abortSignal && r ? AbortSignal.any([e.abortSignal, r]) : e.abortSignal ?? r;
	const a = new AsyncWorkScope();
	const o = a.run(() => AsyncLocalStorage.snapshot());
	const s = new AsyncWorkScope();
	const c = s.run(() => AsyncLocalStorage.snapshot());
	let l;
	let releaseSandbox = () => {};
	const runAttempt = async () => {
		const t = await prepareDirectCompactionAttempt({
			...e,
			abortSignal: a.signal
		});
		if (!t.ok) return t.result;
		releaseSandbox = t.value.releaseSandbox;
		try {
			const e = await buildPreparedCompactionRuntime(t.value, (e) => {
				l = e;
			});
			return await executePreparedCompactionSession(e);
		} catch (e) {
			if (hasModelFallbackStop(e)) throw e;
			return t.value.fail(formatErrorMessage(e), e);
		} finally {
			l?.restoreSkillEnvironment();
		}
	};
	n(async () => {
		const closeWork = () => {
			o(() => a.beginClose(i?.reason));
			c(() => s.beginClose(i?.reason));
		};
		i?.addEventListener("abort", closeWork, { once: true });
		if (i?.aborted) closeWork();
		try {
			t.resolve(await a.track(runAttempt));
		} catch (e) {
			t.reject(e);
		} finally {
			try {
				await AsyncWorkScope.runWhenAllIdle(() => [a], () => o(() => a.beginClose()));
				await AsyncWorkScope.runWhenAllIdle(() => [a], () => s.track(() => c(() => l?.disposeToolRuntimes())));
			} finally {
				try {
					await AsyncWorkScope.runWhenAllIdle(() => [a, s], () => c(() => s.beginClose()));
					await AsyncWorkScope.runWhenAllIdle(() => [a, s], () => Promise.all([o(() => a.drain()), c(() => s.drain())]));
				} finally {
					releaseSandbox();
					i?.removeEventListener("abort", closeWork);
				}
			}
		}
	}).catch(t.reject);
	return await t.promise;
}
//#endregion
//#region src/agents/embedded-agent-runner/compact.ts
async function compactNativeCliSession(e) {
	const t = normalizeOptionalAgentRuntimeId(e.runtime);
	if (!t || e.compactParams.trigger !== "manual") return;
	const n = resolveCliBackendConfig(t, e.compactParams.config, { agentId: e.compactParams.agentId });
	if (!n?.ownsNativeCompaction) return;
	const r = n.manualCompaction;
	if (!r) return buildCompactionFailureResult(`CLI backend "${t}" owns compaction but does not support manual compaction.`);
	const i = e.compactParams.cliSessionBinding;
	const a = (i?.sessionId ?? e.compactParams.cliSessionId)?.trim();
	if (!a) return buildCompactionFailureResult(`CLI backend "${t}" cannot manually compact without a resumable native session.`);
	const { runCliAgent: o } = await import("./cli-runner-D5gydz-B.mjs");
	const s = `${e.compactParams.runId ?? e.compactParams.sessionId}:native-compact`;
	const c = resolveSessionAgentIds({
		sessionKey: e.compactParams.sessionKey,
		config: e.compactParams.config,
		agentId: e.compactParams.agentId
	}).sessionAgentId;
	let l = i?.authProfileId;
	if (!l && e.compactParams.authProfileId) {
		const n = e.compactParams.config ?? {};
		if (cliBackendAcceptsAuthProfileForwarding({
			provider: t,
			config: n,
			agentId: e.compactParams.agentId
		})) try {
			l = await resolveCliExecutionAuthProfileId({
				cliExecutionProvider: t,
				authProfileProvider: e.compactParams.provider ?? "openai",
				config: n,
				agentDir: e.compactParams.agentDir ?? resolveAgentDir(n, c),
				selected: {
					authProfileId: e.compactParams.authProfileId,
					authProfileIdSource: e.compactParams.authProfileIdSource
				},
				sessionBinding: i
			});
		} catch (r) {
			if (r instanceof CliExecutionAuthProfileError) {
				const i = buildProviderAuthRecoveryHint({
					provider: e.compactParams.provider ?? "openai",
					config: n,
					workspaceDir: e.compactParams.workspaceDir
				});
				return buildCompactionFailureResult(`CLI backend "${t}" cannot compact with the selected account: ${r.message} ${i} Or select an available account with /model, then run /compact again.`);
			}
			throw r;
		}
		else l = e.compactParams.authProfileId;
	}
	const u = prepareSystemAgentRunAdmission(e.compactParams.config ?? {}, s, c, "agents.native-compaction");
	try {
		const runControlOperation = async () => {
			await o({
				replyOperation: e.replyOperation,
				preparedRunAdmission: u,
				sessionId: e.compactParams.sessionId,
				sessionKey: e.compactParams.sessionKey,
				sessionFile: e.compactParams.sessionFile,
				agentId: e.compactParams.agentId,
				workspaceDir: e.compactParams.workspaceDir,
				cwd: e.compactParams.cwd,
				agentDir: e.compactParams.agentDir,
				config: e.compactParams.config,
				prompt: r.buildPrompt(e.compactParams.customInstructions),
				provider: t,
				modelProvider: e.compactParams.provider,
				model: e.compactParams.model,
				thinkLevel: e.compactParams.thinkLevel,
				timeoutMs: resolveCompactionTimeoutMs(e.compactParams.config),
				runId: s,
				cliSessionId: a,
				...i ? { cliSessionBinding: i } : {},
				...l ? { authProfileId: l } : {},
				...e.compactParams.sessionEntry ? { sessionEntry: e.compactParams.sessionEntry } : {},
				contextWindow: e.compactParams.sessionEntry?.contextWindow,
				trigger: "manual",
				controlOperation: "compact",
				disableCliLiveSession: true,
				cleanupCliLiveSessionOnRunEnd: true,
				allowEmptyAssistantReplyAsSilent: true,
				abortSignal: e.compactParams.abortSignal
			});
		};
		await (e.runControlOperation ? e.runControlOperation(runControlOperation) : runControlOperation());
	} catch (n) {
		const r = e.compactParams.abortSignal;
		if (r?.aborted && (isAbortError(n) || n === r.reason)) throw n;
		return buildCompactionFailureResult(`CLI backend "${t}" failed to compact its native session: ${formatErrorMessage(n)}`);
	} finally {
		u.close();
	}
	return {
		ok: true,
		compacted: true,
		reason: `CLI backend "${t}" compacted its native session.`
	};
}
function resolveCompactionFallbacksOverride(e) {
	if (e.modelSelectionLocked) return [];
	return e.modelFallbacksOverride ?? resolveRunModelFallbacksOverride({
		cfg: e.config,
		sessionKey: e.sessionKey
	});
}
/**
* Core compaction logic without lane queueing.
* Use this when already inside a session/global lane to avoid deadlocks.
*/
async function compactEmbeddedAgentSessionDirect(e, t) {
	const n = applyAgentRunSessionTargetIdentity(e);
	const r = getAsyncWorkSignal();
	const i = readCompactionAccountingRecorder(n.contextEngineRuntimeContext);
	const a = i?.memoryTranscript;
	const o = i?.preparedSession;
	a?.assertActive();
	const s = a?.sessionTarget ?? o?.sessionTarget ?? await resolveAgentRunSessionTarget({
		...n,
		missingSessionKey: "resolve-existing"
	});
	const assertReadCurrent = () => {
		r?.throwIfAborted();
		n.abortSignal?.throwIfAborted();
		a?.assertActive();
	};
	const c = o?.entry ?? await readSessionEntryReadOnlyInWorker({
		...s,
		readConsistency: "latest"
	}, assertReadCurrent);
	assertReadCurrent();
	const l = resolveSessionPinnedHarnessId(c);
	const u = {
		...n,
		sessionEntry: c ? projectExecutionSessionEntry(c) : void 0,
		agentHarnessId: l ?? n.agentHarnessId,
		modelSelectionLocked: c?.modelSelectionLocked ?? n.modelSelectionLocked,
		agentId: s.agentId,
		sessionId: s.sessionId,
		sessionKey: s.sessionKey,
		sessionTarget: {
			agentId: s.agentId,
			sessionId: s.sessionId,
			sessionKey: s.sessionKey,
			storePath: s.storePath,
			...n.sessionTarget?.threadId !== void 0 ? { threadId: n.sessionTarget.threadId } : {}
		},
		sessionFile: s.sessionKey
	};
	const d = resolveSessionAgentIds({
		sessionKey: u.sessionKey,
		config: u.config,
		agentId: u.agentId
	});
	const f = u.agentDir ?? resolveAgentDir(u.config ?? {}, d.sessionAgentId);
	const p = resolveUserPath(u.workspaceDir);
	const m = resolveUserPath(resolveAgentWorkspaceDir(u.config ?? {}, d.sessionAgentId));
	const h = resolveCompactionRuntimeSelection({
		...u,
		modelId: u.model,
		boundHarnessRuntime: u.agentHarnessId,
		preparedRuntimePlan: u.runtimePlan
	});
	const g = await compactNativeCliSession({
		replyOperation: resolveSessionControllerOperationForSignal(e.abortSignal) ?? getCurrentSessionControllerOwner(),
		runtime: h.selectedHarnessRuntime,
		compactParams: {
			...u,
			agentDir: f,
			workspaceDir: p
		}
	});
	if (g) return g;
	if (l && l !== "openclaw" && !t) return buildCompactionFailureResult(`Model selection is locked to native agent harness "${l}"; generic compaction is unavailable.`, { reason: "model_selection_locked" });
	const _ = resolveSharedPluginRuntimeWorkspace({
		...u,
		workspaceDir: p,
		agentId: d.sessionAgentId,
		isCanonicalWorkspace: p === m
	}, () => loadPluginMetadataSnapshot({
		config: u.config ?? {},
		workspaceDir: p,
		env: process.env
	}));
	return await runForegroundCompactionWork(async (e) => {
		const n = await runOutsidePluginRuntimeGenerationScope(() => acquireAgentRunPreparedModelRuntime({
			config: u.config ?? {},
			agentId: d.sessionAgentId,
			agentDir: f,
			workspaceDir: _?.workspaceDir ?? p,
			preserveWorkspaceDirOnRefresh: !_ && p !== m,
			...u.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}
		}, {
			abortSignal: u.abortSignal,
			deriveRuntimePluginSelections: ({ config: e, metadataSnapshot: n }) => {
				const r = resolveCompactionRuntimeSelection({
					...u,
					config: e,
					modelId: u.model,
					boundHarnessRuntime: u.agentHarnessId,
					preparedRuntimePlan: u.runtimePlan,
					manifestPlugins: n,
					allowPluginNormalization: false
				});
				const i = resolveModelCandidateChain({
					cfg: e,
					agentId: d.sessionAgentId,
					manifestPlugins: n,
					allowPluginNormalization: false,
					provider: r.provider,
					model: r.modelId,
					requestedRouteResolution: "resolved",
					fallbacksOverride: t ? [] : resolveCompactionFallbacksOverride({
						...u,
						config: e
					})
				});
				return [{
					provider: r.provider,
					modelId: r.modelId,
					...r.selectedHarnessRuntime ? { runtime: r.selectedHarnessRuntime } : {},
					agentId: d.sessionAgentId
				}, ...i.filter((e) => e.provider !== r.provider || e.model !== r.modelId).map((e) => ({
					provider: e.provider,
					modelId: e.model,
					agentId: d.sessionAgentId
				}))];
			}
		}));
		e.adoptLease(n);
		try {
			const r = n.snapshot;
			const i = r.config;
			const a = _ ? p : r.workspaceDir ?? p;
			const o = await prepareAgentPromptProjects({
				config: i,
				workspaceDir: a,
				cwd: u.cwd,
				sessionId: u.sessionId
			});
			const s = Object.freeze({
				...r,
				config: i,
				...o
			});
			const c = {
				...u,
				config: i,
				agentId: s.agentId ?? d.sessionAgentId,
				agentDir: s.agentDir,
				workspaceDir: a,
				preparedModelRuntime: s,
				seedCompaction: t
			};
			const compactPrepared = async () => {
				if (t || c.config?.agents?.defaults?.compaction?.model?.trim() || (resolveCompactionFallbacksOverride(c) ?? resolveAgentModelFallbackValues(c.config?.agents?.defaults?.model)).length === 0) return await compactEmbeddedAgentSessionDirectOnce(c);
				const e = resolveEmbeddedCompactionTarget({
					config: c.config,
					provider: c.provider,
					modelId: c.model,
					authProfileId: c.authProfileId,
					modelSelectionLocked: c.modelSelectionLocked,
					defaultProvider: DEFAULT_PROVIDER,
					defaultModel: DEFAULT_MODEL
				});
				const n = e.provider ?? "openai";
				const r = e.model ?? "gpt-6-astra";
				const i = c.provider?.trim() || "openai";
				const resolveAuthProvider = (e) => resolveProviderIdForAuth(e, {
					config: c.config,
					metadataSnapshot: s.metadataSnapshot
				});
				const a = new Set([n, i].map(resolveAuthProvider));
				const o = resolveCompactionFallbacksOverride(c);
				const l = resolveSessionAgentIds({
					sessionKey: c.sandboxSessionKey ?? c.sessionKey,
					config: c.config,
					agentId: c.sandboxAgentId ?? c.agentId
				}).sessionAgentId;
				const u = {
					cfg: c.config,
					agentId: l,
					manifestPlugins: s.metadataSnapshot,
					provider: n,
					model: r,
					requestedRouteResolution: "resolved",
					fallbacksOverride: o
				};
				const d = resolveModelCandidateChain(u)[0];
				const f = c.sandboxSessionKey ?? c.sessionKey ?? c.sessionId;
				return (await runWithModelFallback({
					...u,
					runId: c.runId ?? c.sessionId,
					agentDir: c.agentDir,
					sessionId: c.sessionId,
					sessionKey: f,
					userLockedAuthProfileId: c.authProfileIdSource === "user" ? c.authProfileId : void 0,
					abortSignal: c.abortSignal,
					prepareAgentHarnessRuntime: async ({ provider: e, model: t, agentHarnessRuntimeOverride: n }) => {
						await ensureSelectedAgentHarnessPlugin({
							config: c.config,
							provider: e,
							modelId: t,
							agentId: l,
							sessionKey: f,
							agentHarnessRuntimeOverride: n,
							workspaceDir: c.workspaceDir,
							pluginRegistry: s.pluginRegistry
						});
					},
					classifyResult: ({ result: e, provider: t, model: n }) => {
						const r = e.ok ? void 0 : e.reason?.trim();
						if (!r) return null;
						const i = Object.assign(new Error(e.failure?.rawError ?? r), {
							status: e.failure?.status,
							code: e.failure?.code
						});
						const a = coerceToFailoverError(i, {
							provider: t,
							model: n
						});
						return a ? { error: a } : null;
					},
					run: async (e, t) => {
						const n = e === d?.provider && t === d.model;
						const r = n || a.has(resolveAuthProvider(e));
						const i = r ? c.authProfileId : void 0;
						return await compactEmbeddedAgentSessionDirectOnce({
							...c,
							provider: e,
							model: t,
							agentHarnessId: n ? c.agentHarnessId : void 0,
							requestedRouteResolution: n ? void 0 : "resolved",
							authProfileId: i,
							authProfileIdSource: r ? c.authProfileIdSource : void 0,
							runtimeAuthPlan: n ? c.runtimeAuthPlan : void 0,
							runtimePlan: n ? c.runtimePlan : void 0
						});
					}
				})).result;
			};
			return await withPluginRuntimeGenerationScope(s, () => {
				e.captureContext();
				return compactPrepared();
			});
		} catch (e) {
			return buildCompactionFailureResult(isFallbackSummaryError(e) ? e.message : formatErrorMessage(e));
		}
	}, u.abortSignal);
}
//#endregion
export { enqueueCompactionInLanes as a, resolveCompactionRuntimeSelection as i, compactNativeCliSession as n, runForegroundCompactionWork as o, prepareCompactionHarnessAuth as r, withQueuedCompactionTurn as s, compactEmbeddedAgentSessionDirect as t };