UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

462 lines (461 loc) • 17.4 kB
import { v as floorPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs"; import { a as captureAsyncWorkTracker, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs"; import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs"; import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs"; import { a as normalizeOptionalAgentRuntimeId, n as OPENCLAW_AGENT_RUNTIME_ID } from "./agent-runtime-id-D8s1CaYB.mjs"; import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { o as resolveFreshSessionTotalTokens } from "./types-BUko5WqP.mjs"; import { o as resolveContextEngine } from "./registry-BNPXTWdk.mjs"; import { i as buildGenericCliContextEngineHostSupport } from "./host-compat-D2mUtPDd.mjs"; import { t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs"; import { r as resolveCompactionTimeoutMs, t as compactContextEngineWithSafetyTimeout } from "./compaction-safety-timeout-Dm_4UNnX.mjs"; import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs"; import { t as buildContextEngineRuntimeSettings } from "./runtime-settings-Dsu1-5F4.mjs"; import { r as resolveLiveToolResultMaxChars } from "./tool-result-limits-BISboI8s.mjs"; import { a as isBenignCompactionSkipReason, o as isBenignCompactionSkipResult } from "./compact-reasons-DCGXQXOD.mjs"; import { t as registerLegacyContextEngine } from "./init-CNW5HSik.mjs"; import { t as ensureSelectedAgentHarnessPlugin } from "./runtime-plugin-Cug3vi2h.mjs"; import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs"; import { a as resolveEffectiveCompactionMode, n as applyAgentAutoCompactionGuard } from "./agent-settings-Chrl5MIo.mjs"; import { t as createPreparedEmbeddedAgentSettingsManager } from "./agent-project-settings-CndET_5f.mjs"; import { t as runContextEngineMaintenance } from "./context-engine-maintenance-DsWc3w5M.mjs"; import { o as retainAgentHarnessCompactionSource } from "./host-source-authority-BR6Oinwf.mjs"; import { t as buildEmbeddedCompactionRuntimeContext } from "./compaction-runtime-context-Cqy9zW9t.mjs"; import { i as exceedsContextWindow } from "./context-pressure-CRrtrfAa.mjs"; import "./tool-result-truncation-CpAX82MP.mjs"; import { d as shouldPreemptivelyCompactBeforePrompt } from "./preemptive-compaction-DWbzXuZy.mjs"; import { t as acceptCompactionSuccessor } from "./compaction-successor-hCQ2tiCH.mjs"; import { n as clearCliSessionInStore } from "./cli-session-store-Dkejl-uo.mjs"; import { n as isRecoverableNativeHarnessBindingFailure, t as maybeCompactAgentHarnessSession } from "./compaction-BHiV5Fgc.mjs"; import { t as recordCliCompactionInStore } from "./session-store-o_Opk316.mjs"; //#region src/agents/command/cli-compaction.ts function buildCliCompactionParams(e) { return { agentId: e.sessionAgentId, config: e.cfg, sessionKey: e.sessionKey, workspaceDir: e.workspaceDir, cwd: e.cwd, agentDir: e.agentDir, provider: e.provider, model: e.model, skillsSnapshot: e.skillsSnapshot, messageChannel: e.messageChannel, agentAccountId: e.agentAccountId, senderIsOwner: e.senderIsOwner, thinkLevel: e.thinkLevel, extraSystemPrompt: e.extraSystemPrompt }; } function buildCliCompactionRuntimeContext(e) { return { ...buildEmbeddedCompactionRuntimeContext({ ...buildCliCompactionParams(e), messageProvider: e.messageChannel, authProfileId: e.authProfileId, modelId: e.model, harnessRuntime: e.harnessRuntime, modelSelectionLocked: e.modelSelectionLocked }), currentTokenCount: e.currentTokenCount, tokenBudget: e.contextTokenBudget, trigger: e.trigger }; } const CODEX_APP_SERVER_OWNS_AUTO_COMPACTION_REASON = "codex app-server owns automatic compaction"; const log = createSubsystemLogger("agents/cli-compaction"); function isNativeHarnessCompactionSession(e, t) { const n = e?.agentHarnessId?.trim().toLowerCase(); if (!n || normalizeOptionalAgentRuntimeId(n) === "openclaw") return false; const r = t.trim().toLowerCase(); return n === r || n === "copilot" && r === "github-copilot" || n === "codex" && (r === "codex" || r === "openai"); } /** Runs pre-turn compaction for a CLI session and returns the updated session entry. */ async function runCliTurnCompactionLifecycle(e, t) { const n = e.storePath; const r = floorPositiveFiniteNumber(e.sessionEntry?.contextTokens); if (!n || !r) return e.sessionEntry; return await runWithAsyncWorkResources(async (i) => { const a = t.sourceAuthority; i({ release: retainAgentHarnessCompactionSource(a), releaseBeforeResultWhenIdle: true }); const o = a.operatorAuthority; const s = a.assertActive; const c = o?.signal; const l = e.abortSignal && c ? AbortSignal.any([e.abortSignal, c]) : e.abortSignal ?? c; const u = { ...e, abortSignal: l }; const d = composeSessionSourceAssertion([ s, o?.assertCurrent, t.assertActive ], (e) => { u.abortSignal?.throwIfAborted(); e(); }); d(); const f = await readSessionEntryReadOnlyInWorker({ agentId: u.sessionAgentId, sessionKey: u.sessionKey, storePath: n, readConsistency: "latest" }, d); const p = { sessionId: u.sessionId, lifecycleRevision: f?.lifecycleRevision, activeWriterRunId: f?.activeWriterRunId }; const onCommitted = (e) => { if (u.sessionStore) u.sessionStore[u.sessionKey] = e.entry; t.onCommitted?.(e); }; const m = await SessionManager.openAsync({ agentId: u.sessionAgentId, sessionId: u.sessionId, sessionKey: u.sessionKey, storePath: n }, void 0, { compaction: true }, l); d(); const h = u.sessionKey; const g = createPreparedEmbeddedAgentSettingsManager({ agentId: u.sessionAgentId, sessionId: u.sessionId, cwd: u.cwd ?? u.workspaceDir, agentDir: u.agentDir, cfg: u.cfg, pluginMetadataSnapshot: u.pluginGeneration?.pluginMetadataSnapshot ?? getCurrentPluginMetadataSnapshot({ config: u.cfg, env: process.env, workspaceDir: u.workspaceDir }), contextTokenBudget: r }); d(); const _ = shouldPreemptivelyCompactBeforePrompt({ messages: m.buildSessionContext().messages, prompt: "", contextTokenBudget: r, reserveTokens: g.getCompactionReserveTokens(), toolResultMaxChars: resolveLiveToolResultMaxChars({ contextWindowTokens: r }) }); const v = Math.max(_.estimatedPromptTokens, floorPositiveFiniteNumber(resolveFreshSessionTotalTokens(u.sessionEntry)) ?? 0); const settleFailedMaintenance = (e) => { d(); if (exceedsContextWindow(v, r)) throw new Error(e); log.warn(`${e}; continuing because the next prompt fits the context window`); }; if (!_.shouldCompact && v <= _.promptBudgetBeforeReserve) return u.sessionEntry; const y = u.cliBackendId?.trim() || u.provider; const b = resolveCliBackendConfig(y, u.cfg); const x = isNativeHarnessCompactionSession(u.sessionEntry, u.provider) ? u.sessionEntry : void 0; const S = normalizeOptionalAgentRuntimeId(u.sessionEntry?.agentHarnessId); if (u.sessionEntry?.modelSelectionLocked === true && S !== "openclaw" && !x) throw new Error("CLI compaction cannot replace a model-locked native harness runtime"); if (b?.ownsNativeCompaction && !x) { log.info(`CLI backend "${y}" owns native compaction — deferring to backend`); return u.sessionEntry; } let C; let w; let T; let E; const D = u.sessionEntry?.authProfileOverride?.trim() || void 0; const O = new AsyncWorkScope(); const k = captureAsyncWorkTracker(); let A; let j; try { A = await O.run(async () => { if (!x) d(); const e = await resolveContextEngine(u.cfg, { initialize: registerLegacyContextEngine }); E = e; applyAgentAutoCompactionGuard({ settingsManager: g, contextEngineInfo: e.info, compactionMode: resolveEffectiveCompactionMode(u.cfg) }); if (x) { const t = x; const n = r; async function compactNativeHarnessCliTranscript() { let r; try { try { var i = _usingCtx(); const a = t.agentHarnessId?.trim(); const s = t.modelSelectionLocked === true; const c = t.authProfileOverride?.trim() || void 0; const l = i.a(await acquireAgentRunPreparedModelRuntime({ config: u.cfg, agentId: u.sessionAgentId, agentDir: u.agentDir, workspaceDir: u.workspaceDir, allowGatewaySubagentBinding: true, runtimePluginSelections: [{ provider: u.provider, modelId: u.model, agentId: u.sessionAgentId, ...a ? { runtime: a } : {} }] }, u.pluginGeneration ? { pluginGeneration: u.pluginGeneration } : {})).snapshot; r = await withPluginRuntimeGenerationScope(l, async () => { await ensureSelectedAgentHarnessPlugin({ provider: u.provider, modelId: u.model, config: u.cfg, sessionKey: u.sessionKey, workspaceDir: u.workspaceDir, agentId: u.sessionAgentId, ...a ? { agentHarnessRuntimeOverride: a } : {}, pluginRegistry: l.pluginRegistry }); d(); return await maybeCompactAgentHarnessSession({ ...buildCliCompactionParams(u), sessionId: u.sessionId, sessionFile: h, authProfileId: c, contextTokenBudget: n, currentTokenCount: v, trigger: "budget", force: true, modelSelectionLocked: s, allowGatewaySubagentBinding: true, contextEngine: e, contextEngineRuntimeContext: buildCliCompactionRuntimeContext({ ...u, contextTokenBudget: n, currentTokenCount: v, authProfileId: c, harnessRuntime: a, modelSelectionLocked: s, trigger: "cli_native_budget" }), ...a ? { agentHarnessId: a } : {}, abortSignal: u.abortSignal }, { preparedModelRuntime: l, sourceAuthority: { assertActive: d, operatorAuthority: o } }); }); } catch (e) { i.e = e; } finally { await i.d(); } } catch (e) { const t = coerceErrorMessage(e); log.warn(`CLI native harness compaction failed for ${u.provider}/${u.model}: ${t}`); return { compacted: false, failureReason: t }; } if (!r?.ok || !r.compacted) { const e = r?.reason; if (r && isBenignCompactionSkipResult(r) || r?.ok === true && r.reason === CODEX_APP_SERVER_OWNS_AUTO_COMPACTION_REASON) { log.info(`CLI native harness compaction skipped for ${u.provider}/${u.model}: ${e}`); return { compacted: false }; } const n = isRecoverableNativeHarnessBindingFailure(r); const i = t.modelSelectionLocked !== true && (r?.ok === false && r.failure?.reason === "unsupported_harness_compaction" || n); log.warn(`CLI native harness compaction did not reduce context for ${u.provider}/${u.model}: ${e}`); return { compacted: false, fallbackToContextEngine: i, clearCliSessionBinding: t.modelSelectionLocked !== true && n, failureReason: r?.reason ?? "native harness compaction did not reduce context" }; } return { compacted: true, result: r }; } T = await compactNativeHarnessCliTranscript(); if (T.compacted) C = "native-harness"; else if (!T.fallbackToContextEngine && T.failureReason) settleFailedMaintenance(`CLI native harness compaction failed for ${u.provider}/${u.model}: ${T.failureReason}`); } if (!T || T.fallbackToContextEngine) { d(); const t = r; const i = n; const a = u.sessionEntry?.agentHarnessId; const o = u.sessionEntry?.modelSelectionLocked; const s = T?.fallbackToContextEngine === true; async function compactCliTranscript() { const n = buildCliCompactionRuntimeContext({ ...u, authProfileId: D, harnessRuntime: a, modelSelectionLocked: o, contextTokenBudget: t, currentTokenCount: v, trigger: "cli_budget" }); const r = buildContextEngineRuntimeSettings({ contextEngineHost: buildGenericCliContextEngineHostSupport({ backendId: u.provider, capabilities: ["compact", "maintain"] }), provider: u.provider, requestedModel: u.model, resolvedModel: u.model, selectedContextEngineId: e.info.id, contextEngineSelectionSource: "configured", promptTokenBudget: t }); let c; d(); try { c = await compactContextEngineWithSafetyTimeout(e, { sessionId: u.sessionId, sessionKey: u.sessionKey, sessionTarget: { agentId: u.sessionAgentId, sessionId: u.sessionId, sessionKey: u.sessionKey, ...i ? { storePath: i } : {} }, tokenBudget: t, currentTokenCount: v, force: true, compactionTarget: "budget", runtimeContext: n, runtimeSettings: r }, resolveCompactionTimeoutMs(u.cfg), u.abortSignal); } catch (e) { const t = coerceErrorMessage(e); if (isBenignCompactionSkipReason(t)) { log.info(`CLI transcript compaction skipped for ${u.provider}/${u.model}: ${t}`); return { compacted: false }; } log.warn(`CLI transcript compaction failed for ${u.provider}/${u.model}: ${t}`); return { compacted: false, failureReason: t }; } if (!c.ok || !c.compacted) { const e = c.reason; if (isBenignCompactionSkipResult(c)) { log.info(`CLI transcript compaction skipped for ${u.provider}/${u.model}: ${e}`); return { compacted: false }; } log.warn(`CLI transcript compaction did not reduce context for ${u.provider}/${u.model}: ${e ?? "compaction did not reduce context"}`); return { compacted: false, failureReason: c.reason ?? "compaction did not reduce context" }; } const l = c.result; const f = await acceptCompactionSuccessor({ expectedEntry: p, assertActive: d, onCommitted, config: u.cfg, currentSessionFile: h, currentTarget: { agentId: u.sessionAgentId, sessionId: u.sessionId, sessionKey: u.sessionKey, storePath: i }, result: c }); const g = { compacted: true, accepted: f, ...l?.tokensAfter !== void 0 ? { tokensAfter: l.tokensAfter } : {} }; try { d(); await runContextEngineMaintenance({ contextEngine: e, sessionId: f.sessionId, sessionKey: u.sessionKey, sessionFile: f.sessionFile, sessionTarget: f.sessionTarget, reason: "compaction", ...f.previousSessionId ? {} : { sessionManager: m }, runtimeContext: n, runtimeSettings: r, config: u.cfg, assertActive: d }); } catch (e) { try { d(); } catch { return g; } if (!s) throw e; log.warn(`CLI transcript compaction maintenance failed after fallback for ${u.provider}/${u.model}: ${coerceErrorMessage(e)}`); } return g; } const c = await compactCliTranscript(); w = c; C = c.compacted ? "context-engine" : void 0; if (!C && c.failureReason) settleFailedMaintenance(`CLI transcript compaction failed for ${u.provider}/${u.model}: ${c.failureReason}`); } if (T?.clearCliSessionBinding && !C && u.sessionStore) { d(); return await clearCliSessionInStore({ agentId: u.sessionAgentId, provider: u.provider, sessionKey: u.sessionKey, sessionStore: u.sessionStore, storePath: n, expectedSessionId: u.sessionId, assertCommitAllowed: d }) ?? u.sessionEntry; } if (!C || !u.sessionStore) return u.sessionEntry; const t = await recordCliCompactionInStore({ agentId: u.sessionAgentId, compactionKind: C, sessionKey: u.sessionKey, sessionStore: u.sessionStore, storePath: n, tokensAfter: T?.result?.result?.tokensAfter ?? w?.tokensAfter, expectedSession: w?.accepted?.entry ?? p }); if (!t) throw new Error("Session changed before CLI compaction could be recorded"); return t; }); } catch (e) { j = { error: e }; } const cleanup = async () => { try { await AsyncWorkScope.runWhenAllIdle(() => [O], () => E?.dispose?.()); } finally { await O.run(() => O.drain()); } }; if (O.hasPendingWork) k(cleanup).catch((e) => { log.warn(`CLI compaction engine cleanup failed: ${String(e)}`); }); else try { await cleanup(); } catch (e) { j ??= { error: e }; } if (j) throw j.error; return A; }); } //#endregion export { runCliTurnCompactionLifecycle };