openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
16 lines • 33.4 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{d as asPositiveFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{t as isAbortError}from"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createLazyImportLoader}from"./lazy-promise-CismJCQR.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{l as resolveAgentIdFromSessionKey,s as isUnscopedSessionKeySentinel}from"./session-key-BPgKfU2m.mjs";import{s as normalizeStaticProviderModelId}from"./model-ref-shared-T-aCqInj.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{_ as resolveDefaultAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as SessionTranscriptReadFenceError}from"./session-transcript-read-fence-error-BLqxaDE5.mjs";import{t as DEFAULT_CONTEXT_TOKENS}from"./defaults-k51tX6yK.mjs";import{a as resolveMergedModelProviderConfig,r as findConfiguredProviderModel}from"./model-provider-config-DrdykcWe.mjs";import{_ as registerAgentRunContext,o as clearAgentRunContext}from"./agent-run-registry-ONwZSqWq.mjs";import{o as resolveCliBackendConfig}from"./cli-backends-BDgFsc0L.mjs";import{r as findModelInCatalog}from"./model-catalog-lookup-bSGgKRpi.mjs";import{a as resolveModelExtraParamSources}from"./model-extra-params-CALSEb0J.mjs";import"./session-transcript-read-fence-DE07xwTs.mjs";import{o as resolveSessionStorePathForScope}from"./session-store-path-Co-EGagp.mjs";import{L as acknowledgeReplySessionTransition}from"./session-controller.state-BIDbpLPn.mjs";import{m as isRenderablePayload}from"./reply-payload-C7eQHHoS.mjs";import{i as resolveSandboxConfigForAgent}from"./config-CNA3Oz0X.mjs";import{o as resolveFreshSessionTotalTokens}from"./types-Di4kCK2F.mjs";import"./session-accessor-CY8UYP4m.mjs";import{_ as resolveCompactionThreshold}from"./agent-core-9_CCYFLw.mjs";import{h as resolveSessionPinnedHarnessId}from"./agent-harness-session-key-B6S2Sx8z.mjs";import{c as updateSessionEntry}from"./session-accessor.entry-mutation-CQIwywNM.mjs";import"./sessions-DQD7zQ95.mjs";import{r as logVerbose}from"./globals-l9I53ZKA.mjs";import{n as resolveProjectedSessionContextTokens}from"./context-token-provenance-DDRSYNJw.mjs";import{c as withSandboxRuntimeStatusInWorker}from"./runtime-status-DDAPGR6Y.mjs";import{g as resolveFollowupAbortSignal}from"./goal-continuation-return-BxOhVtGr.mjs";import"./model-selection-CNHinoVN.mjs";import{i as resolveMaxActiveTranscriptBytes,n as refreshTranscriptByteCompactionLatch}from"./transcript-byte-limit-_Kdc5zSm.mjs";import{t as isCliProvider}from"./model-selection-cli-K7oSL0Pc.mjs";import{i as isCliRuntimeAliasForProvider}from"./model-runtime-aliases-BFQ__k4Y.mjs";import{i as resolveSessionRuntimeOverrideForProvider,r as resolvePersistedSessionRuntimeId}from"./session-runtime-compat-DGwJiPrH.mjs";import{o as resolveModelContextTokenProjection}from"./context-pOKTsKY-.mjs";import{t as resolveModelContextWindowProfile}from"./model-context-window-Cum6yykz.mjs";import{o as resolveEffectiveAgentRuntime}from"./thinking-runtime-V6V09nGt.mjs";import{o as startFollowupRunPreAdoptionHeartbeat}from"./lifecycle-9W2sZTIl.mjs";import{c as refreshQueuedFollowupSession}from"./state-t6zhY2pl.mjs";import{l as isMemoryFlushPlanNativeProviderOwned}from"./memory-state-BSED9PTf.mjs";import{r as resolveCompactionTimeoutMs}from"./compaction-safety-timeout-BnvorGSI.mjs";import{r as truncateUtf16WithEllipsis}from"./text-truncate-BxVDOUs6.mjs";import{o as isBenignCompactionSkipResult}from"./compact-reasons-BG4rHaJv.mjs";import{l as readSessionMessagesAsync,m as readSessionTranscriptAccountingAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{t as resolveEffectiveCompactionReserveTokens}from"./agent-compaction-constants-BjW90tur.mjs";import{t as SessionManager}from"./session-manager-BPWwNp25.mjs";import{t as MemoryFlushToolsUnavailableError}from"./agent-tools.memory-flush-ClC79doo.mjs";import{s as resolveBootstrapWarningSignaturesSeen}from"./bootstrap-budget-DI6CkaLC.mjs";import{r as buildRunEntrySelection}from"./agent-runner-run-params-iTBH2_n4.mjs";import{i as createToolResultPromptProjectionState}from"./session-prompt-state-DFuQHUV8.mjs";import"./queue-CwAyyslb.mjs";import{n as incrementCompactionCount}from"./session-updates-CIJ1Xade.mjs";import{t as runEmbeddedAgentEntry}from"./run-entry-BzQb37h0.mjs";import{t as createDeferredEmbeddedRunLifecycleManager}from"./deferred-lifecycle-owner-JIK-FS99.mjs";import{t as resolveModelCallUrgency}from"./run-trigger-NFOOospS.mjs";import{i as exceedsContextWindow}from"./context-pressure-DK6AWz1d.mjs";import{t as resolveEmbeddedSessionContextLimits}from"./session-context-limits-Od7YmYWM.mjs";import{o as estimateMessagesTokens,t as appendPostCompactionRefreshPrompt}from"./post-compaction-context-B3ye7OA3.mjs";import{t as readCompactionTranscriptBytes}from"./compaction-transcript-bytes-D9H5HjOg.mjs";import{t as emitInternalRunUsageDiagnostic}from"./internal-run-usage-B6Co7hgC.mjs";import{t as emitAgentRunStatusEvent}from"./agent-run-status-events-DAXRdY53.mjs";import{n as buildEmbeddedRunExecutionParams,r as buildModelResolveContext,u as resolveRunThinkingLevelForFallbackCandidate}from"./agent-runner-utils-Ddz75_c7.mjs";import{i as formatCompactionModelRef,o as resolveCompactionCompletionNotice}from"./compaction-notice-C8qd2NHH.mjs";import{n as memoryFlushResultIsSilent,r as resolveMemoryFlushPlanForRun,t as isToolsMemoryFlushPlan}from"./memory-flush-plan-o13YImiu.mjs";import crypto from"node:crypto";import{resolveOpenAIResponsesServerCompactionPlan}from"@openclaw/ai/internal/openai-responses-payload-policy";import{resolveAnthropicServerCompactionPlan}from"@openclaw/ai/internal/anthropic";
//!src/auto-reply/reply/agent-runner-memory-runtime.ts
async function resolveMemoryFlushSandbox(e,t){if(!e.sessionKey)return{writable:true,toolPolicy:void 0};return await withSandboxRuntimeStatusInWorker({cfg:e.cfg,agentId:e.followupRun.run.agentId,sessionKey:e.sessionKey,classificationSessionKey:e.runtimePolicySessionKey??e.followupRun.run.runtimePolicySessionKey},{env:process.env,cwd:process.cwd(),assertCurrent:t},async({sandboxed:t,toolPolicy:n,workspaceAccess:r,classificationAgentId:i})=>({writable:!t||(r??resolveSandboxConfigForAgent(e.cfg,i).workspaceAccess)===`rw`,toolPolicy:t?n:void 0}))}function followupUsesCliRuntime(e,t){const n=e.followupRun.run.provider;if(e.agentHarnessId)return isCliRuntimeAliasForProvider({provider:n,runtime:e.agentHarnessId,cfg:e.cfg});if(isCliProvider(n,e.cfg))return true;return[resolvePersistedSessionRuntimeId(e.sessionEntry),t].some(t=>isCliRuntimeAliasForProvider({provider:n,runtime:t,cfg:e.cfg}))}function resolveFollowupAgentRuntimeId(e){if(e.agentHarnessId)return e.agentHarnessId;const t=e.sessionEntry?.sessionId===e.followupRun.run.sessionId?e.sessionEntry:void 0;return resolveEffectiveAgentRuntime({cfg:e.cfg,provider:e.followupRun.run.provider,modelId:e.followupRun.run.model,agentId:e.followupRun.run.agentId??resolveDefaultAgentId(e.cfg),sessionKey:e.sessionKey??e.followupRun.run.sessionKey,sessionEntry:t})}function followupOwnsNativeCompaction(e,t){return resolveCliBackendConfig(t,e.cfg,{agentId:e.followupRun.run.agentId})?.ownsNativeCompaction===true}function resolveFollowupContextTokens({cfg:e,followupRun:t,defaultModel:n,sessionEntry:r},i){const{provider:a}=t.run;const o=t.run.model??n;const s=findModelInCatalog((t.run.thinkingCatalog??[]).filter(e=>i===`openclaw`?!e.nativeRuntime:e.nativeRuntime===i),a,o);const c=r?.sessionId===t.run.sessionId?r:void 0;const l=resolveModelContextWindowProfile({catalogEntry:s,selected:c?.contextWindow});const u=resolveModelContextTokenProjection({cfg:e,provider:a,modelProvider:a,model:o,modelContextWindow:l.contextWindow||s?.contextWindowSource!==`synthetic`?l.contextTokens:void 0,modelContextTokens:s?.contextTokens,fallbackContextTokens:s?.contextWindow,allowAsyncLoad:false,allowCacheLookup:false});const d=resolveProjectedSessionContextTokens({entry:c?.authProfileOverride===t.run.authProfileId?c:void 0,provider:a,model:o,agentHarnessId:i,authoredContextTokens:u.authoredContextTokens,resolvedContextTokens:u.contextTokens})??2e5;return l.contextWindow&&l.contextTokens?Math.min(d,l.contextTokens):d}async function defersTokenCompactionToChatGPTBoundary(e){const[{getPreparedRuntimeAuthProfileStoreSnapshot:t},{prepareAgentRuntimeAuth:n},{resolvePreparedExtraParams:r},{isChatGPTV2CompactionEligible:i}]=await Promise.all([import(`./auth-profiles-BGlKZMbD.mjs`),import(`./prepare-auth-CjdPbnpv.mjs`),import(`./extra-params-BWTAhYCF.mjs`),import(`./chatgpt-v2-compaction-B81SkuR0.mjs`)]);let a;try{a=n({provider:e.provider,modelId:e.model,config:e.config,agentId:e.agentId,agentDir:e.agentDir,workspaceDir:e.workspaceDir,authProfileStore:t(e.agentDir),sessionAuthProfileId:e.authProfileId,sessionAuthProfileSource:e.authProfileIdSource,harnessId:`openclaw`}).plan.modelRoute}catch{return false}return a!==void 0&&i({config:e.config,model:a,extraParams:r({cfg:e.config,provider:e.provider,modelId:e.model,agentId:e.agentId,agentDir:e.agentDir,workspaceDir:e.workspaceDir}),compactionEnabled:e.config.agents?.defaults?.compaction?.enabled!==false,compactionReplayEnabled:true})}
//!src/auto-reply/reply/agent-runner-memory-transcript-context.ts
const toolResultTruncationRuntimeLoader=createLazyImportLoader(()=>import(`./tool-result-truncation-BL80VFyY.mjs`));async function readPreflightTranscriptContextMessages(e,t){const n=resolveEmbeddedSessionContextLimits({});const readLegacyProjection=async()=>{t?.throwIfAborted();const r=await readSessionMessagesAsync(e,{mode:`recent`,maxMessages:n.maxEvents,maxLines:n.maxEvents,maxBytes:n.maxBytes});t?.throwIfAborted();return r.filter(e=>!(`excludeFromContext`in e&&e.excludeFromContext===true))};if(!e.storePath||!e.sessionKey)return await readLegacyProjection();const r={...e,sessionKey:e.sessionKey,storePath:e.storePath};try{const e=await SessionManager.openModelContextAsync(r,{signal:t,limits:n});const i=e.buildSessionContext().messages;if(i.length>0||e.getEntries().length>0)return i;return await readLegacyProjection()}catch(e){if(!(e instanceof Error)||e.message!==`Persisted legacy session transcripts require doctor/import migration before runtime use`)throw e;return await readLegacyProjection()}}async function readSessionLogSnapshot(e){e.abortSignal?.throwIfAborted();const t=e.agentId??resolveAgentIdFromSessionKey(e.sessionKey);if(!e.sessionId||!e.storePath||!t)return e.includeTurnTaint?{turnTainted:true}:{};const n={agentId:t,sessionId:e.sessionId,...e.sessionKey?{sessionKey:e.sessionKey}:{},storePath:e.storePath};try{const t=await readSessionTranscriptAccountingAsync(n,{includeByteSize:e.includeByteSize,includeTurnTaint:e.includeTurnTaint,includeUsage:e.includeUsage},e.abortSignal);e.abortSignal?.throwIfAborted();return t}catch{e.abortSignal?.throwIfAborted();return e.includeTurnTaint?{turnTainted:true}:{}}}function hasUsableProviderPromptUsage(e){return e?.promptTokens!==void 0&&e.promptTokens>0}async function estimateProviderPromptTokens(e,t,n=0){if(e.length===0)return Math.ceil(n);const{truncateOversizedToolResultsInMessages:r}=await toolResultTruncationRuntimeLoader.load();const i=r(e,t,void 0,void 0,createToolResultPromptProjectionState()).messages;const a=estimateMessagesTokens(i);return Math.ceil(n)+Math.ceil(a)}async function estimateContextTokensFromSessionTranscript({abortSignal:e,...t},n){const r=normalizeOptionalString(t.sessionId);if(!r)return;try{const i=(n??await readSessionLogSnapshot({agentId:t.agentId,sessionId:r,sessionKey:t.sessionKey,storePath:t.storePath,includeByteSize:false,includeUsage:true,abortSignal:e})).usage;const a=hasUsableProviderPromptUsage(i)?i:void 0;return{contextTokens:await estimateProviderPromptTokens(a?a.trailingMessages:await readPreflightTranscriptContextMessages({...t,sessionId:r},e),t.contextWindowTokens,a?a.promptTokens+(a.outputTokens??0):0)}}catch(t){e?.throwIfAborted();return t instanceof SessionTranscriptReadFenceError?Promise.reject(t):void 0}}
//!src/auto-reply/reply/memory-flush-errors.ts
const MAX_FLUSH_ERROR_LENGTH=200;function resolveVisibleMemoryFlushErrorPayloads(e){return(e??[]).filter(e=>e.isError===true&&isRenderablePayload(e))}function buildVisibleMemoryFlushFailure(e){const t=e.map(e=>normalizeOptionalString(e.text)).filter(e=>Boolean(e)).join(`
`);return new Error(t||`Memory flush returned an error response`)}function truncateMemoryFlushErrorMessage(e){const t=normalizeOptionalString(formatErrorMessage(e))||String(e);return truncateUtf16WithEllipsis(t,MAX_FLUSH_ERROR_LENGTH)}
//!src/auto-reply/reply/memory-flush-outcome.ts
const MAX_FLUSH_FAILURES=3;async function recordMemoryFlushSuccess({sessionKey:e,storePath:t},n,r){let i=r;if(t&&e)try{i=await updateSessionEntry({storePath:t,sessionKey:e},async()=>({memoryFlush:{kind:`succeeded`,compactionCount:n}}),{skipMaintenance:true,takeCacheOwnership:true})??i}catch(e){logVerbose(`failed to persist memory flush metadata: ${String(e)}`)}return{sessionEntry:i,outcome:`completed`}}async function recordMemoryFlushFailure(e,t,n){let r=n;let i=`failed`;if((t.replyOperation?.abortSignal??t.abortSignal)?.aborted){logVerbose(`memory flush cancelled by its owner`);return{sessionEntry:r,outcome:i}}const a=truncateMemoryFlushErrorMessage(e);const{sessionKey:o,storePath:s}=t;if(!isAbortError(e)&&s&&o)try{let e=0;const n=await updateSessionEntry({storePath:s,sessionKey:o},t=>{e=(t.memoryFlush?.kind===`failed`?t.memoryFlush.failureCount:0)+1;return{memoryFlush:e>=MAX_FLUSH_FAILURES?{kind:`succeeded`,compactionCount:t.compactionCount??0}:{kind:`failed`,...t.memoryFlush?.compactionCount!==void 0?{compactionCount:t.memoryFlush.compactionCount}:{},failureCount:e}}},{skipMaintenance:true,takeCacheOwnership:true});if(n){r=n;if(t.sessionStore)t.sessionStore[o]=n}else e=0;logVerbose(`memory flush failed (attempt ${e}/${MAX_FLUSH_FAILURES}): ${a}`);if(n&&e>=MAX_FLUSH_FAILURES){i=`exhausted`;logVerbose(`memory flush exhausted: skipping flush for this compaction cycle after ${e} consecutive failures`)}}catch(e){logVerbose(`failed to persist memory flush failure metadata: ${String(e)}`)}else logVerbose(`memory flush run failed: ${String(e)}`);return{sessionEntry:r,outcome:i}}
//!src/auto-reply/reply/memory-flush.ts
function resolveProjectedPromptTokens(e,t,n){const r=e??n?.contextTokens;return r===void 0?0:Math.max(0,r)+Math.max(0,t??0)}function estimatePromptTokensForMemoryFlush(e){const t=normalizeOptionalString(e);if(!t)return;return Math.ceil(estimateMessagesTokens([{role:`user`,content:t,timestamp:Date.now()}]))}function resolveResponsesServerCompactionThreshold(e){const t=e.provider?.trim();const n=e.modelId?.trim();if(!t||!n)return;const r=normalizeProviderId(t);const normalizeModelId=e=>normalizeStaticProviderModelId(r,e).trim().toLowerCase();const i=resolveMergedModelProviderConfig(e.cfg,t);const a=findConfiguredProviderModel(i,t,n,normalizeModelId);const{defaultParams:o,modelParams:s}=resolveModelExtraParamSources({config:e.cfg,provider:t,modelId:n});const c={...o,...s};const l={provider:t,api:a?.api??i?.api,baseUrl:a?.baseUrl??i?.baseUrl,contextWindow:a?.contextWindow??e.contextWindowTokens};if(r===`anthropic`){if(c.anthropicServerCompaction!==true)return;return resolveAnthropicServerCompactionPlan({...l,api:l.api??`anthropic-messages`},c).threshold}return resolveOpenAIResponsesServerCompactionPlan({...l,api:l.api??(r===`openai`?`openai-responses`:void 0),baseUrl:l.baseUrl??(r===`openai`?`https://api.openai.com/v1`:void 0),compat:a?.compat,contextTokens:a?.contextTokens??e.contextWindowTokens},c).threshold}function settleFailedPreflightCompaction(e,t,n,r){if(exceedsContextWindow(n,r))throw new Error(`Preflight compaction required but failed: ${t}`);return e}function shouldRunPreflightCompaction(e){if(!e.entry)return false;const t=asPositiveFiniteNumber(e.tokenCount);const n=t===void 0?resolveFreshSessionTotalTokens(e.entry):Math.floor(t);return n!==void 0&&e.threshold>0&&n>=e.threshold}function hasAlreadyFlushedForCurrentCompaction(e){const t=e.compactionCount??0;return e.memoryFlush?.compactionCount===t}
//!src/auto-reply/reply/preflight-stall.ts
function startMemoryFlushStallGuard({cfg:e,replyOperation:t},n,r){if(!t)return;const i=resolveCompactionTimeoutMs(e);const a=new AbortController;let o=formatCompactionModelRef(n.provider,n.model);let s;const c=setTimeout(()=>{s=/* @__PURE__ */ new Error(`memory flush timed out on ${o} after ${Math.round(i/1e3)}s without output`);a.abort(s)},i);c.unref();return{signal:r?AbortSignal.any([r,a.signal]):a.signal,get stall(){return s},setModel(e,t){o=formatCompactionModelRef(e,t)},progress(e){if(!e.aborted&&!s){t.watchdog.progress(`semantic`,`memory_flush:model_output`);c.refresh()}},stop(){clearTimeout(c)}}}
//!src/auto-reply/reply/agent-runner-memory.ts
const preflightCompactionLog=createSubsystemLogger(`auto-reply/preflight-compaction`);const memoryFlushLog=createSubsystemLogger(`auto-reply/memory-flush`);const embeddedAgentRuntimeLoader=createLazyImportLoader(()=>import(`./embedded-agent-B_ZN5S8R.mjs`));const memoryFlushPreparationLoader=createLazyImportLoader(()=>import(`./memory-flush-prepare-CqiGrp2A.mjs`));async function runSessionCompactionIfNeeded(e){const t=e.followupRun.operatorAuthority;const assertActive=()=>{e.abortSignal?.throwIfAborted();t?.assertCurrent();if(e.authorize?.()===false)throw new Error(`Session compaction maintenance is no longer active`)};if(!e.sessionKey)return e.sessionEntry;let n=e.sessionEntry??e.sessionStore?.[e.sessionKey];if(!n?.sessionId)return n;const r={...e,sessionEntry:n};assertActive();const i=resolveFollowupAgentRuntimeId(r);const a=followupUsesCliRuntime(r,i);const o=followupOwnsNativeCompaction(r,i);if(a||o||normalizeLowercaseStringOrEmpty(i)===`codex`)return n;const s=e.sessionKey;const c=e.followupRun.run.agentId??resolveDefaultAgentId(e.cfg);const l=isUnscopedSessionKeySentinel(s)?c:resolveAgentIdFromSessionKey(s,c);const u=resolveSessionStorePathForScope({agentId:l,sessionKey:s,storePath:e.storePath??resolveSessionStorePathCore(e.cfg.session?.store,{agentId:l})});const d=e.sessionStore??{[s]:n};const f={agentId:l,sessionKey:s,storePath:u};const readTranscriptSize=async t=>readCompactionTranscriptBytes({target:{...f,sessionId:t},rawBytes:void 0,runtime:e.followupRun.run,maxBytes:y,signal:e.abortSignal});const p=resolveFollowupContextTokens(r,i);const m=(resolveMemoryFlushPlanForRun({cfg:e.cfg,contextWindowTokens:p})?.plan)?.reserveTokensFloor??resolveEffectiveCompactionReserveTokens({contextTokenBudget:p,reserveTokens:2e4});const h=resolveFreshSessionTotalTokens(n);const g=estimatePromptTokensForMemoryFlush(e.promptForEstimate??e.followupRun.prompt);const _=resolveResponsesServerCompactionThreshold({contextWindowTokens:p,cfg:e.cfg,provider:e.followupRun.run.provider,modelId:e.followupRun.run.model??e.defaultModel});const v=resolveCompactionThreshold({contextWindowTokens:p,reserveTokensFloor:m,minimumThresholdTokens:_});const y=resolveMaxActiveTranscriptBytes(e.cfg);const b=y!==void 0;const x=h!==void 0?void 0:await estimateContextTokensFromSessionTranscript({...f,abortSignal:e.abortSignal,sessionId:n.sessionId,contextWindowTokens:p});const S=b?await readTranscriptSize(n.sessionId):void 0;assertActive();const C=S!==void 0&&y!==void 0&&S>=y;let w=false;const notifyCompaction=async(t,n)=>{w=t!==`start`;try{await e.onCompactionNotice?.(t,n)}catch(e){logVerbose(`preflightCompaction notice delivery failed: ${String(e)}`)}};const T=n.transcriptByteCompactionLatch;const E=refreshTranscriptByteCompactionLatch(T,n.sessionId,y,S);const D=C&&E!==void 0;if(E!==T){const e=await incrementCompactionCount({...f,amount:0,expectedSession:n,sessionStore:d,transcriptByteCompactionLatch:E??null});assertActive();if(e===void 0)throw new Error(`Session changed before byte-compaction progress could be cleared`);n=d[s]??n}const O=C&&!D;if(D){await notifyCompaction(`context_bounded`);assertActive()}const k=resolveProjectedPromptTokens(h,g,x);const A=asPositiveFiniteNumber(k);const j=shouldRunPreflightCompaction({entry:n,tokenCount:A,threshold:v});if(!j&&!O)return n;if(e.beforeCompaction){const t=await e.beforeCompaction(n);assertActive();return runSessionCompactionIfNeeded({...e,sessionEntry:t,beforeCompaction:void 0})}if(j&&!O&&await defersTokenCompactionToChatGPTBoundary(e.followupRun.run)){assertActive();return n}const M=O?`transcript_bytes`:`tokens`;assertActive();e.onCompactionStart?.();let N=n;let P;let F=false;const recordCompactionAccounting=async(e,t,n,r=1)=>{const i=C?await readTranscriptSize(e.sessionId):void 0;assertActive();const a=i!==void 0&&y!==void 0&&i>=y?{activeBytes:i,sessionId:e.sessionId,maxBytes:y}:void 0;if(await incrementCompactionCount({...f,sessionStore:d,amount:r,tokensAfter:t,compactionKind:n,expectedSession:e,transcriptByteCompactionLatch:a??null,authorize:()=>{assertActive();return true}})===void 0)throw new Error(`Session changed before compaction maintenance could be recorded`)};const I=startFollowupRunPreAdoptionHeartbeat(e.followupRun,e.abortSignal);try{await notifyCompaction(`start`);assertActive();const r=await(await embeddedAgentRuntimeLoader.load()).compactEmbeddedAgentSession({sessionId:n.sessionId,sessionKey:s,sessionTarget:{...f,sessionId:n.sessionId},sandboxSessionKey:e.runtimePolicySessionKey,allowGatewaySubagentBinding:true,messageChannel:e.followupRun.run.messageProvider,clientCaps:e.followupRun.run.clientCaps,conversationToolPolicy:e.followupRun.run.conversationToolPolicy,requesterOrigin:e.followupRun.run.requesterOrigin,conversationId:e.followupRun.run.conversationId,messageThreadId:e.followupRun.run.messageThreadId,operatorProfileId:e.followupRun.run.operatorProfileId,senderIsOwner:e.followupRun.run.senderIsOwner,groupId:n.groupId??e.followupRun.run.groupId,groupChannel:n.groupChannel??e.followupRun.run.groupChannel,groupSpace:n.space??e.followupRun.run.groupSpace,senderId:e.followupRun.run.senderId,senderName:e.followupRun.run.senderName,senderUsername:e.followupRun.run.senderUsername,senderE164:e.followupRun.run.senderE164,inputProvenance:e.followupRun.run.inputProvenance,sessionFile:s,workspaceDir:e.followupRun.run.workspaceDir,cwd:e.followupRun.run.cwd,agentDir:e.followupRun.run.agentDir,config:e.cfg,agentAccountId:e.followupRun.run.agentAccountId,conversationRoutePeerId:e.followupRun.run.conversationRoutePeerId,chatType:e.followupRun.run.chatType,skillsSnapshot:e.followupRun.run.skillsSnapshot??n.skillsSnapshot,provider:e.followupRun.run.provider,model:e.followupRun.run.model,authProfileId:e.followupRun.run.authProfileId,authProfileIdSource:e.followupRun.run.authProfileIdSource,sessionEntry:n,agentHarnessId:e.agentHarnessId??(n.sessionId===e.followupRun.run.sessionId?n.modelSelectionLocked===true?resolvePersistedSessionRuntimeId(n):i:void 0),modelSelectionLocked:n.modelSelectionLocked===true,thinkLevel:e.followupRun.run.thinkLevel,bashElevated:e.followupRun.run.bashElevated,trigger:`budget`,modelCallUrgency:resolveModelCallUrgency({...e.followupRun.run,trigger:`user`,currentInboundEventKind:e.followupRun.currentInboundEventKind}),force:true,forcePreflight:true,preflightRequired:true,preflightCompactionTrigger:M,deferOwningContextEngineCompaction:false,contextTokenBudget:p,currentTokenCount:A??h,ownerNumbers:e.followupRun.run.ownerNumbers,abortSignal:e.abortSignal},{assertActive,sourceAuthority:{assertActive,operatorAuthority:t},requestBudget:e.compactionRequestBudget,pendingUserEntryId:e.pendingUserEntryId,onHostCompactionCommitted:async e=>{await recordCompactionAccounting(e.entry,e.tokensAfter,e.compactionKind,F?0:1);F=true},onCommitted:t=>{P=t.admissionTransition;N=t.entry;n=t.entry;d[s]=t.entry;e.onCompactionCommitted?.(t)}});if(!r?.ok||!r.compacted){assertActive();const t=(r?.ok?normalizeOptionalString(r.reason):r?.reason)??`not_compacted`;if(!C&&r&&isBenignCompactionSkipResult(r)){await notifyCompaction(`skipped`);logVerbose(`preflightCompaction skipped: sessionKey=${e.sessionKey} reason=${t}`);return n}preflightCompactionLog.warn(`preflight compaction failed: ${t}`);if(C){await recordCompactionAccounting(N,void 0,void 0,0);assertActive();await notifyCompaction(`context_bounded`);return d[s]??n}await notifyCompaction(`incomplete`);return settleFailedPreflightCompaction(n,t,A,p)}if(e.replyOperation&&P){await acknowledgeReplySessionTransition(e.replyOperation,P);assertActive()}if(!F)await recordCompactionAccounting(N,r.result?.tokensAfter,r.compactionKind);assertActive();n=d[s]??n;const a=n.transcriptByteCompactionLatch;if(a)preflightCompactionLog.warn(`byte-triggered compaction left oversized history; continuing with bounded context`,{sessionKey:s,activeTranscriptBytes:a.activeBytes,maxActiveTranscriptBytes:a.maxBytes});await appendPostCompactionRefreshPrompt({cfg:e.cfg,followupRun:e.followupRun});assertActive();const o=resolveCompactionCompletionNotice(r,Boolean(a));await notifyCompaction(o.phase,o.text);assertActive();n=d[s]??n;const c=e.followupRun.run.sessionId;e.followupRun.run.sessionId=n.sessionId;e.onSessionIdChanged?.(n.sessionId);const l=e.followupRun.run.sessionKey??e.sessionKey;if(l){e.followupRun.run.sessionFile=l;refreshQueuedFollowupSession({key:l,previousSessionId:c,nextSessionId:n.sessionId,nextSessionFile:l})}return n}catch(t){if(!w&&!e.abortSignal?.aborted)await notifyCompaction(`incomplete`);throw t}finally{I?.()}}async function runMemoryFlushIfNeeded(e){const t=resolveFollowupAbortSignal({abortSignal:e.replyOperation?.abortSignal??e.abortSignal,operatorAuthority:e.followupRun.operatorAuthority});const assertMemoryFlushCurrent=()=>{t?.throwIfAborted();e.followupRun.operatorAuthority?.assertCurrent()};const{writable:n,toolPolicy:r}=await resolveMemoryFlushSandbox(e,assertMemoryFlushCurrent);const i=e.sessionEntry??(e.sessionKey?e.sessionStore?.[e.sessionKey]:void 0);if(i?.incognito===true||isIncognitoSessionKey(e.sessionKey))return{sessionEntry:i,outcome:`skipped`};const a={...e,sessionEntry:i};const o=resolveFollowupAgentRuntimeId(a);const s=followupUsesCliRuntime(a,o)||followupOwnsNativeCompaction(a,o);if(!((n||isMemoryFlushPlanNativeProviderOwned())&&!s))return{sessionEntry:i,outcome:`skipped`};const c=crypto.randomUUID();let l=false;const recordFailure=t=>recordMemoryFlushFailure(t,e,i);const u=Math.min(resolveFollowupContextTokens(a,o),e.recoveryContextTokenBudget??Number.POSITIVE_INFINITY);let d;try{d=resolveMemoryFlushPlanForRun({cfg:e.cfg,contextWindowTokens:u})}catch(e){return await recordFailure(e)}if(!d)return{sessionEntry:i,outcome:`skipped`};const f=d.plan;if(!isToolsMemoryFlushPlan(f)&&!n)return{sessionEntry:i,outcome:`skipped`};if(!i||hasAlreadyFlushedForCurrentCompaction(i)){assertMemoryFlushCurrent();return{sessionEntry:i,outcome:`skipped`}}const p=estimatePromptTokensForMemoryFlush(e.promptForEstimate??e.followupRun.prompt);const m=resolveFreshSessionTotalTokens(i);const h=Math.max(0,resolveCompactionThreshold({contextWindowTokens:u,reserveTokensFloor:f.reserveTokensFloor})-Math.max(0,Math.floor(f.softThresholdTokens)));const g=m===void 0;const _=f.forceFlushTranscriptBytes;const v=await readSessionLogSnapshot({agentId:e.followupRun.run.agentId,sessionId:e.followupRun.run.sessionId,sessionKey:e.sessionKey??e.followupRun.run.sessionKey,storePath:e.storePath,includeByteSize:asPositiveFiniteNumber(_)!==void 0,includeTurnTaint:true,includeUsage:g,abortSignal:t});assertMemoryFlushCurrent();const y=v.byteSize;const b=y!==void 0&&y>=_;const x=g?await estimateContextTokensFromSessionTranscript({agentId:e.followupRun.run.agentId??resolveAgentIdFromSessionKey(e.sessionKey??e.followupRun.run.sessionKey),sessionId:i.sessionId,sessionKey:e.sessionKey??e.followupRun.run.sessionKey,storePath:e.storePath,contextWindowTokens:u,abortSignal:t},v):void 0;assertMemoryFlushCurrent();const S=resolveProjectedPromptTokens(asPositiveFiniteNumber(m),p,x);const C=asPositiveFiniteNumber(S);if(!(e.recoveryContextTokenBudget!==void 0||shouldRunPreflightCompaction({entry:i,tokenCount:C,threshold:h})||b))return{sessionEntry:i,outcome:`skipped`};e.replyOperation?.setPhase(`memory_flushing`);let w=resolveBootstrapWarningSignaturesSeen(i?.systemPromptReport??(e.sessionKey?e.sessionStore?.[e.sessionKey]?.systemPromptReport:void 0));let T=false;let E;try{assertMemoryFlushCurrent();E=await(await memoryFlushPreparationLoader.load()).prepareMemoryFlushAttempt({...e,sessionEntry:i,flushRunId:c,resolution:d,sandboxToolPolicy:r,abortSignal:t,assertCurrent:assertMemoryFlushCurrent,recordPersistenceToolSuccess:()=>{T=true}})}catch(e){return await recordFailure(e)}if(!E)return{sessionEntry:i,outcome:`skipped`};const{writePath:D,systemPrompt:O,selection:k,preparedRunAdmission:A,memorySession:j,memoryAudience:M,memoryFlushTools:N,maintenanceRun:P,sourcePolicySessionKey:F}=E;const I=startMemoryFlushStallGuard(e,k,t);const L=createDeferredEmbeddedRunLifecycleManager({runId:c,sessionId:j.sessionId,sessionKey:j.sessionKey,sessionFile:j.sessionFile,abortSignal:I?.signal??t});const R=i?.compactionCount??0;let z=[];const B=e.opts?.runId;if(B)emitAgentRunStatusEvent({runId:B,sessionKey:e.sessionKey,phase:`memory_flushing`});const V=startFollowupRunPreAdoptionHeartbeat(e.followupRun,t);try{if(e.sessionKey){registerAgentRunContext(c,{sessionKey:j.sessionKey,sessionId:j.sessionId,verboseLevel:e.resolvedVerboseLevel,isControlUiVisible:false,projectSessionActive:false,projectSessionLifecycle:false,projectSessionMessages:false});l=true}memoryFlushLog.debug(`memory flush dispatched`,{event:`memory_flush_dispatched`,runId:c,sessionKey:j.sessionKey,sessionId:j.sessionId,sourceSessionKey:e.sessionKey,sourceSessionId:i?.sessionId});const t=await runEmbeddedAgentEntry({preparedRunAdmission:A,modelResolve:{prompt:f.prompt,awaitSessionDiffBaseline:e.followupRun.runObservers?.awaitSessionDiffBaseline,cwd:P.cwd,modelSelectionLocked:P.modelSelectionLocked,context:buildModelResolveContext({run:P,sessionCtx:{},hasRepliedRef:void 0,trigger:`memory`})},selection:buildRunEntrySelection(k,e.followupRun.run),identity:{runId:c,agentId:e.followupRun.run.agentId,sessionId:j.sessionId,sessionKey:j.sessionKey,lane:`main`},harness:{workspaceDir:e.followupRun.run.workspaceDir,sessionKey:F,preparation:{kind:`direct`},resolveRuntimeOverride:t=>resolveSessionRuntimeOverrideForProvider({provider:t,entry:i,cfg:e.cfg})},behavior:{kind:`maintenance`},sessionOverride:{kind:`preserve`},abortSignal:L.signal,runCandidate:async(t,n,r)=>{I?.setModel(t,n);const a=r.agentHarnessRuntimeOverride;const o=resolveRunThinkingLevelForFallbackCandidate({cfg:e.cfg,provider:t,modelId:n,run:e.followupRun.run,catalog:e.followupRun.run.thinkingCatalog,agentId:e.followupRun.run.agentId,sessionKey:F,sessionEntry:i,agentRuntime:a});const s=await buildEmbeddedRunExecutionParams({run:{...P,thinkLevel:o},sessionCtx:{},hasRepliedRef:void 0,provider:t,model:n,runId:c,promptCacheKey:e.opts?.promptCacheKey,allowTransientCooldownProbe:r.allowTransientCooldownProbe});const l=await(await embeddedAgentRuntimeLoader.load()).runEmbeddedAgent({preparedRunAdmission:A,...s,awaitSessionDiffBaseline:e.followupRun.runObservers?.awaitSessionDiffBaseline,...j,onMemoryFlushModelProgress:I&&(()=>I.progress(L.signal)),agentHarnessId:resolveSessionPinnedHarnessId(i),agentHarnessRuntimeOverride:a,sandboxSessionKey:F,memoryAudience:M,allowGatewaySubagentBinding:true,silentExpected:true,allowEmptyAssistantReplyAsSilent:true,terminalReplyExpectation:`optional`,trigger:`memory`,contextTokenBudget:u,memoryFlushWritePath:D,memoryFlushTools:N,initialTurnTainted:!e.followupRun.run.senderIsOwner||v?.turnTainted===true,prompt:f.prompt,transcriptPrompt:``,extraSystemPrompt:O,isFinalFallbackAttempt:r.isFinalFallbackAttempt,resolvedModelSelection:r.resolvedModelSelection,modelFallbacksOverride:r.modelFallbacksOverride,bootstrapPromptWarningSignaturesSeen:w,bootstrapPromptWarningSignature:w.at(-1),abortSignal:L.signal,onDeferredLifecycleOwner:L.adopt,onDeferredLifecycleAbort:L.abort,onRetryWait:L.beginRetryWait,assistantErrorTranscript:r.assistantErrorTranscript,authProfileFailurePolicy:r.authProfileFailurePolicy,contextEngineLogicalTurnLease:r.contextEngineLogicalTurnLease,onContextEngineTurnCandidate:r.onContextEngineTurnCandidate});z=resolveVisibleMemoryFlushErrorPayloads(l.payloads);w=resolveBootstrapWarningSignaturesSeen(l.meta?.systemPromptReport);return l}});await emitInternalRunUsageDiagnostic(t.result,{config:e.cfg,agentId:e.followupRun.run.agentId??resolveDefaultAgentId(e.cfg),agentDir:e.followupRun.run.agentDir,sessionId:j.sessionId,sessionKey:j.sessionKey,provider:t.provider,model:t.model});L.signal.throwIfAborted();if(z.length>0)throw buildVisibleMemoryFlushFailure(z);if(N&&!T&&!memoryFlushResultIsSilent(t.result))throw new Error(`no persistence tool call succeeded`);return await recordMemoryFlushSuccess(e,R,i)}catch(e){if(e instanceof MemoryFlushToolsUnavailableError){memoryFlushLog.debug(e.message);return{sessionEntry:i,outcome:`skipped`}}return await recordFailure(I?.stall??e)}finally{I?.stop();V?.();if(B&&!t?.aborted)emitAgentRunStatusEvent({runId:B,sessionKey:e.sessionKey,phase:`preparing_context`});await L.complete();if(l)clearAgentRunContext(c);A.close();E.release()}}export{runSessionCompactionIfNeeded as n,runMemoryFlushIfNeeded as t};