(messages: Message[])
| 132 | } |
| 133 | |
| 134 | export function shouldExtractMemory(messages: Message[]): boolean { |
| 135 | // Check if we've met the initialization threshold |
| 136 | // Uses total context window tokens (same as autocompact) for consistent behavior |
| 137 | const currentTokenCount = tokenCountWithEstimation(messages) |
| 138 | if (!isSessionMemoryInitialized()) { |
| 139 | if (!hasMetInitializationThreshold(currentTokenCount)) { |
| 140 | return false |
| 141 | } |
| 142 | markSessionMemoryInitialized() |
| 143 | } |
| 144 | |
| 145 | // Check if we've met the minimum tokens between updates threshold |
| 146 | // Uses context window growth since last extraction (same metric as init threshold) |
| 147 | const hasMetTokenThreshold = hasMetUpdateThreshold(currentTokenCount) |
| 148 | |
| 149 | // Check if we've met the tool calls threshold |
| 150 | const toolCallsSinceLastUpdate = countToolCallsSince( |
| 151 | messages, |
| 152 | lastMemoryMessageUuid, |
| 153 | ) |
| 154 | const hasMetToolCallThreshold = |
| 155 | toolCallsSinceLastUpdate >= getToolCallsBetweenUpdates() |
| 156 | |
| 157 | // Check if the last assistant turn has no tool calls (safe to extract) |
| 158 | const hasToolCallsInLastTurn = hasToolCallsInLastAssistantTurn(messages) |
| 159 | |
| 160 | // Trigger extraction when: |
| 161 | // 1. Both thresholds are met (tokens AND tool calls), OR |
| 162 | // 2. No tool calls in last turn AND token threshold is met |
| 163 | // (to ensure we extract at natural conversation breaks) |
| 164 | // |
| 165 | // IMPORTANT: The token threshold (minimumTokensBetweenUpdate) is ALWAYS required. |
| 166 | // Even if the tool call threshold is met, extraction won't happen until the |
| 167 | // token threshold is also satisfied. This prevents excessive extractions. |
| 168 | const shouldExtract = |
| 169 | (hasMetTokenThreshold && hasMetToolCallThreshold) || |
| 170 | (hasMetTokenThreshold && !hasToolCallsInLastTurn) |
| 171 | |
| 172 | if (shouldExtract) { |
| 173 | const lastMessage = messages[messages.length - 1] |
| 174 | if (lastMessage?.uuid) { |
| 175 | lastMemoryMessageUuid = lastMessage.uuid |
| 176 | } |
| 177 | return true |
| 178 | } |
| 179 | |
| 180 | return false |
| 181 | } |
| 182 | |
| 183 | async function setupSessionMemoryFile( |
| 184 | toolUseContext: ToolUseContext, |
no test coverage detected