|
| 1 | +import type { ModelMessage } from "ai" |
| 2 | +import { diffLines } from "diff" |
| 3 | +import * as Log from "@opencode-ai/core/util/log" |
| 4 | + |
| 5 | +const log = Log.create({ service: "provider.history-rewrite" }) |
| 6 | + |
| 7 | +// In-memory store of previous messages per session (deep cloned to avoid mutation issues) |
| 8 | +const previousMessages = new Map<string, ModelMessage[]>() |
| 9 | + |
| 10 | +export const DEFAULT_MAX_SESSIONS = 5 |
| 11 | + |
| 12 | +/** |
| 13 | + * Creates a stable string representation of a message for comparison. |
| 14 | + */ |
| 15 | +function messageFingerprint(msg: ModelMessage): string { |
| 16 | + const content = contentToStr(msg.content) |
| 17 | + return JSON.stringify({ |
| 18 | + role: msg.role, |
| 19 | + content, |
| 20 | + }) |
| 21 | +} |
| 22 | + |
| 23 | +function contentToStr(content: ModelMessage["content"]): string { |
| 24 | + return typeof content === "string" ? content : JSON.stringify(content) |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Truncates long strings for display in logs. |
| 29 | + */ |
| 30 | +function truncate(str: string, maxLen = 200): string { |
| 31 | + if (str.length <= maxLen) return str |
| 32 | + return str.slice(0, maxLen) + `... (+${str.length - maxLen} chars)` |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * Detects when historical messages have been rewritten between requests. |
| 37 | + * Compares the current messages against the previous request for the same session. |
| 38 | + * Returns a report of changes if any were detected. |
| 39 | + */ |
| 40 | +export function detectHistoryRewrite(sessionID: string, messages: ModelMessage[], maxSessions = DEFAULT_MAX_SESSIONS): string | undefined { |
| 41 | + const prev = previousMessages.get(sessionID) |
| 42 | + if (!prev) { |
| 43 | + previousMessages.set(sessionID, structuredClone(messages)) |
| 44 | + return undefined |
| 45 | + } |
| 46 | + |
| 47 | + // Compare message counts first |
| 48 | + if (prev.length === messages.length) { |
| 49 | + let hasChanges = false |
| 50 | + for (let i = 0; i < prev.length; i++) { |
| 51 | + if (messageFingerprint(prev[i]) !== messageFingerprint(messages[i])) { |
| 52 | + hasChanges = true |
| 53 | + break |
| 54 | + } |
| 55 | + } |
| 56 | + if (!hasChanges) { |
| 57 | + previousMessages.set(sessionID, structuredClone(messages)) |
| 58 | + return undefined |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Find which messages changed |
| 63 | + const changes: { |
| 64 | + index: number |
| 65 | + role: string |
| 66 | + diff: string |
| 67 | + oldPreview: string |
| 68 | + newPreview: string |
| 69 | + }[] = [] |
| 70 | + |
| 71 | + const minLen = Math.min(prev.length, messages.length) |
| 72 | + for (let i = 0; i < minLen; i++) { |
| 73 | + const oldFp = messageFingerprint(prev[i]) |
| 74 | + const newFp = messageFingerprint(messages[i]) |
| 75 | + if (oldFp !== newFp) { |
| 76 | + const oldContent = contentToStr(prev[i].content) |
| 77 | + const newContent = contentToStr(messages[i].content) |
| 78 | + changes.push({ |
| 79 | + index: i, |
| 80 | + role: prev[i].role, |
| 81 | + diff: diffLines(oldContent, newContent).map((h) => { |
| 82 | + const line = h.value.replace(/\n$/, "") |
| 83 | + if (h.added) return `+ ${line}` |
| 84 | + if (h.removed) return `- ${line}` |
| 85 | + return line |
| 86 | + }).join("\n"), |
| 87 | + oldPreview: truncate(oldContent, 150), |
| 88 | + newPreview: truncate(newContent, 150), |
| 89 | + }) |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Detect added/removed messages |
| 94 | + if (messages.length > prev.length) { |
| 95 | + for (let i = prev.length; i < messages.length; i++) { |
| 96 | + const content = contentToStr(messages[i].content) |
| 97 | + changes.push({ |
| 98 | + index: i, |
| 99 | + role: messages[i].role, |
| 100 | + diff: "(message added)", |
| 101 | + oldPreview: "(none)", |
| 102 | + newPreview: truncate(content, 150), |
| 103 | + }) |
| 104 | + } |
| 105 | + } else if (prev.length > messages.length) { |
| 106 | + for (let i = messages.length; i < prev.length; i++) { |
| 107 | + const content = contentToStr(prev[i].content) |
| 108 | + changes.push({ |
| 109 | + index: i, |
| 110 | + role: prev[i].role, |
| 111 | + diff: "(message removed)", |
| 112 | + oldPreview: truncate(content, 150), |
| 113 | + newPreview: "(none)", |
| 114 | + }) |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // Store current messages (bounded) |
| 119 | + if (previousMessages.size >= maxSessions) { |
| 120 | + const keys = [...previousMessages.keys()] |
| 121 | + for (const key of keys.slice(0, keys.length - maxSessions + 1)) { |
| 122 | + previousMessages.delete(key) |
| 123 | + } |
| 124 | + } |
| 125 | + previousMessages.set(sessionID, structuredClone(messages)) |
| 126 | + |
| 127 | + if (changes.length === 0) return undefined |
| 128 | + |
| 129 | + // Build report |
| 130 | + const lines: string[] = [ |
| 131 | + `History rewrite detected (session: ${sessionID})`, |
| 132 | + `${changes.length} message(s) changed:`, |
| 133 | + "", |
| 134 | + ] |
| 135 | + |
| 136 | + for (const change of changes) { |
| 137 | + lines.push(`--- Message [${change.index}] (${change.role}) ---`) |
| 138 | + lines.push(`Old: ${change.oldPreview}`) |
| 139 | + lines.push(`New: ${change.newPreview}`) |
| 140 | + if (change.diff) { |
| 141 | + lines.push("Diff:") |
| 142 | + lines.push(change.diff) |
| 143 | + } |
| 144 | + lines.push("") |
| 145 | + } |
| 146 | + |
| 147 | + return lines.join("\n") |
| 148 | +} |
| 149 | + |
| 150 | +/** |
| 151 | + * Clears the history for a session (e.g., on session close or revert). |
| 152 | + */ |
| 153 | +export function clearHistory(sessionID: string): void { |
| 154 | + previousMessages.delete(sessionID) |
| 155 | +} |
| 156 | + |
| 157 | +/** |
| 158 | + * Clears all stored history (e.g., on shutdown). |
| 159 | + */ |
| 160 | +export function clearAllHistory(): void { |
| 161 | + previousMessages.clear() |
| 162 | +} |
0 commit comments