|
| 1 | +import crypto from "node:crypto"; |
| 2 | +import { resolveAgentModelFallbacksOverride } from "../../agents/agent-scope.js"; |
| 3 | +import { runWithModelFallback } from "../../agents/model-fallback.js"; |
| 4 | +import { isCliProvider } from "../../agents/model-selection.js"; |
| 5 | +import { runEmbeddedPiAgent } from "../../agents/pi-embedded.js"; |
| 6 | +import { |
| 7 | + resolveSandboxConfigForAgent, |
| 8 | + resolveSandboxRuntimeStatus, |
| 9 | +} from "../../agents/sandbox.js"; |
| 10 | +import type { ClawdbotConfig } from "../../config/config.js"; |
| 11 | +import { |
| 12 | + resolveAgentIdFromSessionKey, |
| 13 | + type SessionEntry, |
| 14 | + updateSessionStoreEntry, |
| 15 | +} from "../../config/sessions.js"; |
| 16 | +import { logVerbose } from "../../globals.js"; |
| 17 | +import { registerAgentRunContext } from "../../infra/agent-events.js"; |
| 18 | +import type { TemplateContext } from "../templating.js"; |
| 19 | +import type { VerboseLevel } from "../thinking.js"; |
| 20 | +import type { GetReplyOptions } from "../types.js"; |
| 21 | +import { |
| 22 | + buildThreadingToolContext, |
| 23 | + resolveEnforceFinalTag, |
| 24 | +} from "./agent-runner-utils.js"; |
| 25 | +import { |
| 26 | + resolveMemoryFlushContextWindowTokens, |
| 27 | + resolveMemoryFlushSettings, |
| 28 | + shouldRunMemoryFlush, |
| 29 | +} from "./memory-flush.js"; |
| 30 | +import type { FollowupRun } from "./queue.js"; |
| 31 | +import { incrementCompactionCount } from "./session-updates.js"; |
| 32 | + |
| 33 | +export async function runMemoryFlushIfNeeded(params: { |
| 34 | + cfg: ClawdbotConfig; |
| 35 | + followupRun: FollowupRun; |
| 36 | + sessionCtx: TemplateContext; |
| 37 | + opts?: GetReplyOptions; |
| 38 | + defaultModel: string; |
| 39 | + agentCfgContextTokens?: number; |
| 40 | + resolvedVerboseLevel: VerboseLevel; |
| 41 | + sessionEntry?: SessionEntry; |
| 42 | + sessionStore?: Record<string, SessionEntry>; |
| 43 | + sessionKey?: string; |
| 44 | + storePath?: string; |
| 45 | + isHeartbeat: boolean; |
| 46 | +}): Promise<SessionEntry | undefined> { |
| 47 | + const memoryFlushSettings = resolveMemoryFlushSettings(params.cfg); |
| 48 | + if (!memoryFlushSettings) return params.sessionEntry; |
| 49 | + |
| 50 | + const memoryFlushWritable = (() => { |
| 51 | + if (!params.sessionKey) return true; |
| 52 | + const runtime = resolveSandboxRuntimeStatus({ |
| 53 | + cfg: params.cfg, |
| 54 | + sessionKey: params.sessionKey, |
| 55 | + }); |
| 56 | + if (!runtime.sandboxed) return true; |
| 57 | + const sandboxCfg = resolveSandboxConfigForAgent( |
| 58 | + params.cfg, |
| 59 | + runtime.agentId, |
| 60 | + ); |
| 61 | + return sandboxCfg.workspaceAccess === "rw"; |
| 62 | + })(); |
| 63 | + |
| 64 | + const shouldFlushMemory = |
| 65 | + memoryFlushSettings && |
| 66 | + memoryFlushWritable && |
| 67 | + !params.isHeartbeat && |
| 68 | + !isCliProvider(params.followupRun.run.provider, params.cfg) && |
| 69 | + shouldRunMemoryFlush({ |
| 70 | + entry: |
| 71 | + params.sessionEntry ?? |
| 72 | + (params.sessionKey |
| 73 | + ? params.sessionStore?.[params.sessionKey] |
| 74 | + : undefined), |
| 75 | + contextWindowTokens: resolveMemoryFlushContextWindowTokens({ |
| 76 | + modelId: params.followupRun.run.model ?? params.defaultModel, |
| 77 | + agentCfgContextTokens: params.agentCfgContextTokens, |
| 78 | + }), |
| 79 | + reserveTokensFloor: memoryFlushSettings.reserveTokensFloor, |
| 80 | + softThresholdTokens: memoryFlushSettings.softThresholdTokens, |
| 81 | + }); |
| 82 | + |
| 83 | + if (!shouldFlushMemory) return params.sessionEntry; |
| 84 | + |
| 85 | + let activeSessionEntry = params.sessionEntry; |
| 86 | + const activeSessionStore = params.sessionStore; |
| 87 | + const flushRunId = crypto.randomUUID(); |
| 88 | + if (params.sessionKey) { |
| 89 | + registerAgentRunContext(flushRunId, { |
| 90 | + sessionKey: params.sessionKey, |
| 91 | + verboseLevel: params.resolvedVerboseLevel, |
| 92 | + }); |
| 93 | + } |
| 94 | + let memoryCompactionCompleted = false; |
| 95 | + const flushSystemPrompt = [ |
| 96 | + params.followupRun.run.extraSystemPrompt, |
| 97 | + memoryFlushSettings.systemPrompt, |
| 98 | + ] |
| 99 | + .filter(Boolean) |
| 100 | + .join("\n\n"); |
| 101 | + try { |
| 102 | + await runWithModelFallback({ |
| 103 | + cfg: params.followupRun.run.config, |
| 104 | + provider: params.followupRun.run.provider, |
| 105 | + model: params.followupRun.run.model, |
| 106 | + fallbacksOverride: resolveAgentModelFallbacksOverride( |
| 107 | + params.followupRun.run.config, |
| 108 | + resolveAgentIdFromSessionKey(params.followupRun.run.sessionKey), |
| 109 | + ), |
| 110 | + run: (provider, model) => |
| 111 | + runEmbeddedPiAgent({ |
| 112 | + sessionId: params.followupRun.run.sessionId, |
| 113 | + sessionKey: params.sessionKey, |
| 114 | + messageProvider: |
| 115 | + params.sessionCtx.Provider?.trim().toLowerCase() || undefined, |
| 116 | + agentAccountId: params.sessionCtx.AccountId, |
| 117 | + // Provider threading context for tool auto-injection |
| 118 | + ...buildThreadingToolContext({ |
| 119 | + sessionCtx: params.sessionCtx, |
| 120 | + config: params.followupRun.run.config, |
| 121 | + hasRepliedRef: params.opts?.hasRepliedRef, |
| 122 | + }), |
| 123 | + sessionFile: params.followupRun.run.sessionFile, |
| 124 | + workspaceDir: params.followupRun.run.workspaceDir, |
| 125 | + agentDir: params.followupRun.run.agentDir, |
| 126 | + config: params.followupRun.run.config, |
| 127 | + skillsSnapshot: params.followupRun.run.skillsSnapshot, |
| 128 | + prompt: memoryFlushSettings.prompt, |
| 129 | + extraSystemPrompt: flushSystemPrompt, |
| 130 | + ownerNumbers: params.followupRun.run.ownerNumbers, |
| 131 | + enforceFinalTag: resolveEnforceFinalTag( |
| 132 | + params.followupRun.run, |
| 133 | + provider, |
| 134 | + ), |
| 135 | + provider, |
| 136 | + model, |
| 137 | + authProfileId: params.followupRun.run.authProfileId, |
| 138 | + thinkLevel: params.followupRun.run.thinkLevel, |
| 139 | + verboseLevel: params.followupRun.run.verboseLevel, |
| 140 | + reasoningLevel: params.followupRun.run.reasoningLevel, |
| 141 | + bashElevated: params.followupRun.run.bashElevated, |
| 142 | + timeoutMs: params.followupRun.run.timeoutMs, |
| 143 | + runId: flushRunId, |
| 144 | + onAgentEvent: (evt) => { |
| 145 | + if (evt.stream === "compaction") { |
| 146 | + const phase = |
| 147 | + typeof evt.data.phase === "string" ? evt.data.phase : ""; |
| 148 | + const willRetry = Boolean(evt.data.willRetry); |
| 149 | + if (phase === "end" && !willRetry) { |
| 150 | + memoryCompactionCompleted = true; |
| 151 | + } |
| 152 | + } |
| 153 | + }, |
| 154 | + }), |
| 155 | + }); |
| 156 | + let memoryFlushCompactionCount = |
| 157 | + activeSessionEntry?.compactionCount ?? |
| 158 | + (params.sessionKey |
| 159 | + ? activeSessionStore?.[params.sessionKey]?.compactionCount |
| 160 | + : 0) ?? |
| 161 | + 0; |
| 162 | + if (memoryCompactionCompleted) { |
| 163 | + const nextCount = await incrementCompactionCount({ |
| 164 | + sessionEntry: activeSessionEntry, |
| 165 | + sessionStore: activeSessionStore, |
| 166 | + sessionKey: params.sessionKey, |
| 167 | + storePath: params.storePath, |
| 168 | + }); |
| 169 | + if (typeof nextCount === "number") { |
| 170 | + memoryFlushCompactionCount = nextCount; |
| 171 | + } |
| 172 | + } |
| 173 | + if (params.storePath && params.sessionKey) { |
| 174 | + try { |
| 175 | + const updatedEntry = await updateSessionStoreEntry({ |
| 176 | + storePath: params.storePath, |
| 177 | + sessionKey: params.sessionKey, |
| 178 | + update: async () => ({ |
| 179 | + memoryFlushAt: Date.now(), |
| 180 | + memoryFlushCompactionCount, |
| 181 | + }), |
| 182 | + }); |
| 183 | + if (updatedEntry) { |
| 184 | + activeSessionEntry = updatedEntry; |
| 185 | + } |
| 186 | + } catch (err) { |
| 187 | + logVerbose(`failed to persist memory flush metadata: ${String(err)}`); |
| 188 | + } |
| 189 | + } |
| 190 | + } catch (err) { |
| 191 | + logVerbose(`memory flush run failed: ${String(err)}`); |
| 192 | + } |
| 193 | + |
| 194 | + return activeSessionEntry; |
| 195 | +} |
0 commit comments