|
| 1 | +/** |
| 2 | + * Prepares restored transcript history and applies context-engine assembly. |
| 3 | + */ |
| 4 | +import { buildHierarchyReinforcementMessage } from "../../../auto-reply/handoff-summarizer.js"; |
| 5 | +import { filterHeartbeatTranscriptArtifacts } from "../../../auto-reply/heartbeat-filter.js"; |
| 6 | +import { resolveStorePath } from "../../../config/sessions/paths.js"; |
| 7 | +import { |
| 8 | + listSessionEntries, |
| 9 | + updateSessionEntry, |
| 10 | +} from "../../../config/sessions/session-accessor.js"; |
| 11 | +import { OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST } from "../../../context-engine/host-compat.js"; |
| 12 | +import type { AssembleResult } from "../../../context-engine/types.js"; |
| 13 | +import { resolveHeartbeatSummaryForAgent } from "../../../infra/heartbeat-summary.js"; |
| 14 | +import type { createPreparedEmbeddedAgentSettingsManager } from "../../agent-project-settings.js"; |
| 15 | +import type { createCacheTrace } from "../../cache-trace.js"; |
| 16 | +import { DEFAULT_CONTEXT_TOKENS } from "../../defaults.js"; |
| 17 | +import type { AgentMessage } from "../../runtime/index.js"; |
| 18 | +import type { AgentSession, SessionManager } from "../../sessions/index.js"; |
| 19 | +import { buildActiveSubagentSystemPromptAddition } from "../../subagent-active-context.js"; |
| 20 | +import type { TranscriptPolicy } from "../../transcript-policy.js"; |
| 21 | +import { getHistoryLimitFromSessionKey, limitHistoryTurns } from "../history.js"; |
| 22 | +import { log } from "../logger.js"; |
| 23 | +import { sanitizeSessionHistory, validateReplayTurns } from "../replay-history.js"; |
| 24 | +import type { resolveOrphanRepairPlan } from "./attempt-orphan-repair.js"; |
| 25 | +import { |
| 26 | + loadAttemptSessionEntryAfterQuotaMaintenance, |
| 27 | + repairAttemptToolUseResultPairing, |
| 28 | +} from "./attempt-transcript-helpers.js"; |
| 29 | +import { |
| 30 | + assembleAttemptContextEngine, |
| 31 | + type AttemptContextEngine, |
| 32 | +} from "./attempt.context-engine-helpers.js"; |
| 33 | +import { prependSystemPromptAddition } from "./attempt.prompt-helpers.js"; |
| 34 | +import { estimateRenderedLlmBoundaryTokenPressure } from "./preemptive-compaction.js"; |
| 35 | +import type { EmbeddedRunAttemptParams } from "./types.js"; |
| 36 | + |
| 37 | +type CacheTrace = ReturnType<typeof createCacheTrace>; |
| 38 | +type OrphanRepairPlan = ReturnType<typeof resolveOrphanRepairPlan>; |
| 39 | +type SettingsManager = Pick< |
| 40 | + ReturnType<typeof createPreparedEmbeddedAgentSettingsManager>, |
| 41 | + "getCompactionReserveTokens" |
| 42 | +>; |
| 43 | + |
| 44 | +type PreparedEmbeddedAttemptHistory = { |
| 45 | + contextEnginePromptAuthority: NonNullable<AssembleResult["promptAuthority"]>; |
| 46 | + contextEngineAssemblySucceeded: boolean; |
| 47 | + unwindowedContextEngineMessagesForPrecheck?: AgentMessage[]; |
| 48 | +}; |
| 49 | + |
| 50 | +export async function prepareEmbeddedAttemptHistory(input: { |
| 51 | + attempt: EmbeddedRunAttemptParams; |
| 52 | + activeSession: AgentSession; |
| 53 | + sessionManager: SessionManager; |
| 54 | + activeContextEngine?: AttemptContextEngine; |
| 55 | + cacheTrace: CacheTrace; |
| 56 | + capabilityToolNames: ReadonlySet<string>; |
| 57 | + effectiveWorkspace: string; |
| 58 | + isOpenAIResponsesApi: boolean; |
| 59 | + isRawModelRun: boolean; |
| 60 | + orphanRepair?: OrphanRepairPlan; |
| 61 | + replayAllowedToolNames: Set<string>; |
| 62 | + sessionAgentId: string; |
| 63 | + settingsManager: SettingsManager; |
| 64 | + systemPromptText: string; |
| 65 | + transcriptPolicy: TranscriptPolicy; |
| 66 | + setActiveSessionSystemPrompt: (systemPrompt: string) => void; |
| 67 | +}): Promise<PreparedEmbeddedAttemptHistory> { |
| 68 | + const { activeSession, attempt } = input; |
| 69 | + let systemPromptText = input.systemPromptText; |
| 70 | + const setSystemPrompt = (nextSystemPrompt: string) => { |
| 71 | + systemPromptText = nextSystemPrompt; |
| 72 | + input.setActiveSessionSystemPrompt(nextSystemPrompt); |
| 73 | + }; |
| 74 | + |
| 75 | + if (input.isRawModelRun) { |
| 76 | + activeSession.agent.reset(); |
| 77 | + setSystemPrompt(""); |
| 78 | + input.cacheTrace?.recordStage("session:raw-model-run", { |
| 79 | + messages: activeSession.messages, |
| 80 | + system: systemPromptText, |
| 81 | + }); |
| 82 | + } else { |
| 83 | + const prior = await sanitizeSessionHistory({ |
| 84 | + messages: activeSession.messages, |
| 85 | + modelApi: attempt.model.api, |
| 86 | + modelId: attempt.modelId, |
| 87 | + provider: attempt.provider, |
| 88 | + allowedToolNames: input.replayAllowedToolNames, |
| 89 | + config: attempt.config, |
| 90 | + workspaceDir: input.effectiveWorkspace, |
| 91 | + env: process.env, |
| 92 | + model: attempt.model, |
| 93 | + sessionManager: input.sessionManager, |
| 94 | + sessionId: attempt.sessionId, |
| 95 | + policy: input.transcriptPolicy, |
| 96 | + }); |
| 97 | + input.cacheTrace?.recordStage("session:sanitized", { messages: prior }); |
| 98 | + const validated = await validateReplayTurns({ |
| 99 | + messages: prior, |
| 100 | + modelApi: attempt.model.api, |
| 101 | + modelId: attempt.modelId, |
| 102 | + provider: attempt.provider, |
| 103 | + config: attempt.config, |
| 104 | + workspaceDir: input.effectiveWorkspace, |
| 105 | + env: process.env, |
| 106 | + model: attempt.model, |
| 107 | + sessionId: attempt.sessionId, |
| 108 | + policy: input.transcriptPolicy, |
| 109 | + }); |
| 110 | + |
| 111 | + if (attempt.sessionKey) { |
| 112 | + const storePath = resolveStorePath(attempt.config?.session?.store, { |
| 113 | + agentId: input.sessionAgentId, |
| 114 | + }); |
| 115 | + const sessionEntry = await loadAttemptSessionEntryAfterQuotaMaintenance({ |
| 116 | + storePath, |
| 117 | + sessionKey: attempt.sessionKey, |
| 118 | + }); |
| 119 | + const suspension = sessionEntry?.quotaSuspension; |
| 120 | + if (sessionEntry && suspension?.state === "resuming") { |
| 121 | + const subagents = listSessionEntries({ storePath, clone: false }) |
| 122 | + .map(({ entry }) => entry) |
| 123 | + .filter((entry) => entry.spawnedBy === sessionEntry.sessionId) |
| 124 | + .map((entry) => ({ |
| 125 | + sessionId: entry.sessionId, |
| 126 | + role: entry.subagentRole, |
| 127 | + lastStatus: entry.status, |
| 128 | + })); |
| 129 | + validated.push( |
| 130 | + buildHierarchyReinforcementMessage({ |
| 131 | + summary: suspension.summary ?? "No recovery briefing was captured.", |
| 132 | + activeSubagents: subagents, |
| 133 | + }), |
| 134 | + ); |
| 135 | + await updateSessionEntry( |
| 136 | + { storePath, sessionKey: attempt.sessionKey }, |
| 137 | + async (entry) => { |
| 138 | + if (entry.quotaSuspension?.state !== "resuming") { |
| 139 | + return null; |
| 140 | + } |
| 141 | + return { |
| 142 | + quotaSuspension: { ...entry.quotaSuspension, state: "active" }, |
| 143 | + }; |
| 144 | + }, |
| 145 | + { skipMaintenance: true, takeCacheOwnership: true }, |
| 146 | + ); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + if (attempt.sessionKey && attempt.config) { |
| 151 | + // Capability guidance must include deferred OpenClaw tools without |
| 152 | + // interpreting arbitrary client tool names as native capabilities. |
| 153 | + const activeSubagentPromptAddition = buildActiveSubagentSystemPromptAddition({ |
| 154 | + cfg: attempt.config, |
| 155 | + controllerSessionKey: attempt.sessionKey, |
| 156 | + hasSessionsYield: input.capabilityToolNames.has("sessions_yield"), |
| 157 | + }); |
| 158 | + if (activeSubagentPromptAddition) { |
| 159 | + setSystemPrompt( |
| 160 | + prependSystemPromptAddition({ |
| 161 | + systemPrompt: systemPromptText, |
| 162 | + systemPromptAddition: activeSubagentPromptAddition, |
| 163 | + }), |
| 164 | + ); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + const heartbeatSummary = |
| 169 | + attempt.config && input.sessionAgentId |
| 170 | + ? resolveHeartbeatSummaryForAgent(attempt.config, input.sessionAgentId) |
| 171 | + : undefined; |
| 172 | + const heartbeatFiltered = filterHeartbeatTranscriptArtifacts( |
| 173 | + validated, |
| 174 | + heartbeatSummary?.ackMaxChars, |
| 175 | + heartbeatSummary?.prompt, |
| 176 | + ); |
| 177 | + const truncated = limitHistoryTurns( |
| 178 | + heartbeatFiltered, |
| 179 | + getHistoryLimitFromSessionKey(attempt.sessionKey, attempt.config), |
| 180 | + ); |
| 181 | + // Truncation can orphan tool_result blocks by removing the assistant message |
| 182 | + // that contained the matching tool_use, so repair the pairs once more. |
| 183 | + const limited = input.transcriptPolicy.repairToolUseResultPairing |
| 184 | + ? repairAttemptToolUseResultPairing(truncated, input.isOpenAIResponsesApi) |
| 185 | + : truncated; |
| 186 | + input.cacheTrace?.recordStage("session:limited", { messages: limited }); |
| 187 | + if (limited.length > 0 || prior.length > 0) { |
| 188 | + activeSession.agent.state.messages = limited; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + let contextEnginePromptAuthority: NonNullable<AssembleResult["promptAuthority"]> = "assembled"; |
| 193 | + let contextEngineAssemblySucceeded = false; |
| 194 | + let unwindowedContextEngineMessagesForPrecheck: AgentMessage[] | undefined; |
| 195 | + if (input.activeContextEngine) { |
| 196 | + try { |
| 197 | + // Assemble may window the input in place. Preserve the original history for |
| 198 | + // the overflow precheck when the engine says preassembly can still overflow. |
| 199 | + const preassemblyMessages = activeSession.messages.slice(); |
| 200 | + const reserveTokens = Math.max( |
| 201 | + 0, |
| 202 | + Math.floor(input.settingsManager.getCompactionReserveTokens()), |
| 203 | + ); |
| 204 | + const contextTokenBudget = Math.max( |
| 205 | + 1, |
| 206 | + Math.floor( |
| 207 | + attempt.contextTokenBudget ?? |
| 208 | + attempt.model.contextWindow ?? |
| 209 | + attempt.model.maxTokens ?? |
| 210 | + DEFAULT_CONTEXT_TOKENS, |
| 211 | + ), |
| 212 | + ); |
| 213 | + const promptBudget = Math.max(1, contextTokenBudget - reserveTokens); |
| 214 | + const prompt = input.orphanRepair?.contextEnginePrompt ?? attempt.prompt ?? ""; |
| 215 | + const renderedPromptTokens = estimateRenderedLlmBoundaryTokenPressure({ |
| 216 | + systemPrompt: systemPromptText, |
| 217 | + prompt, |
| 218 | + }); |
| 219 | + const messageBudget = Math.max(1, promptBudget - renderedPromptTokens); |
| 220 | + const assembled = await assembleAttemptContextEngine({ |
| 221 | + contextEngine: input.activeContextEngine, |
| 222 | + sessionId: attempt.sessionId, |
| 223 | + sessionKey: attempt.sessionKey, |
| 224 | + messages: activeSession.messages, |
| 225 | + tokenBudget: messageBudget, |
| 226 | + availableTools: new Set(input.capabilityToolNames), |
| 227 | + citationsMode: attempt.config?.memory?.citations, |
| 228 | + modelId: attempt.modelId, |
| 229 | + maxOutputTokens: reserveTokens, |
| 230 | + contextEngineHostSupport: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST, |
| 231 | + providerId: attempt.provider, |
| 232 | + requestedModelId: attempt.requestedModelId, |
| 233 | + fallbackReason: attempt.fallbackReason, |
| 234 | + degradedReason: attempt.degradedReason, |
| 235 | + ...(attempt.prompt !== undefined ? { prompt } : {}), |
| 236 | + }); |
| 237 | + if (!assembled) { |
| 238 | + throw new Error("context engine assemble returned no result"); |
| 239 | + } |
| 240 | + const assembledMessages = input.transcriptPolicy.repairToolUseResultPairing |
| 241 | + ? repairAttemptToolUseResultPairing(assembled.messages, input.isOpenAIResponsesApi) |
| 242 | + : assembled.messages; |
| 243 | + if (assembledMessages !== activeSession.messages) { |
| 244 | + activeSession.agent.state.messages = assembledMessages; |
| 245 | + } |
| 246 | + contextEnginePromptAuthority = assembled.promptAuthority ?? "assembled"; |
| 247 | + contextEngineAssemblySucceeded = true; |
| 248 | + if (contextEnginePromptAuthority === "preassembly_may_overflow") { |
| 249 | + unwindowedContextEngineMessagesForPrecheck = preassemblyMessages; |
| 250 | + } |
| 251 | + if (assembled.systemPromptAddition) { |
| 252 | + setSystemPrompt( |
| 253 | + prependSystemPromptAddition({ |
| 254 | + systemPrompt: systemPromptText, |
| 255 | + systemPromptAddition: assembled.systemPromptAddition, |
| 256 | + }), |
| 257 | + ); |
| 258 | + log.debug( |
| 259 | + `context engine: prepended system prompt addition (${assembled.systemPromptAddition.length} chars)`, |
| 260 | + ); |
| 261 | + } |
| 262 | + } catch (error) { |
| 263 | + log.warn(`context engine assemble failed, using pipeline messages: ${String(error)}`); |
| 264 | + } |
| 265 | + } |
| 266 | + |
| 267 | + return { |
| 268 | + contextEnginePromptAuthority, |
| 269 | + contextEngineAssemblySucceeded, |
| 270 | + ...(unwindowedContextEngineMessagesForPrecheck |
| 271 | + ? { unwindowedContextEngineMessagesForPrecheck } |
| 272 | + : {}), |
| 273 | + }; |
| 274 | +} |
0 commit comments