// packages/core — "이 창에서 조금 전에 쓴 글" 기억 (메모리 전용, 순수 로직). // // 왜 필요한가: 채팅·메신저는 보내는 순간 입력칸이 빈다. 그래서 다음 메시지를 쓸 때 커서 앞 // 텍스트에는 방금 보낸 말이 없고, 모델은 대화가 어디까지 왔는지 모른다("ㅇㅋ 그럼 나도 " 만 보고 // 엉뚱한 말을 잇는다). 입력칸이 비워지는 순간 직전 내용을 "보낸 글" 로 잠시 기억했다가 같은 창의 // 다음 제안 문맥에 넣는다. // // 저장하지 않는다 — 프로세스 메모리에만, 짧게(기본 30분) 둔다. export interface RecentWriteMeta { windowHandle: number | null appName: string | null windowTitle: string | null } export interface RecentWrite extends RecentWriteMeta { text: string at: number } export interface RecentWritesOptions { ttlMs?: number maxEntries?: number maxChars?: number } const DEFAULT_TTL_MS = 30 * 60_000 const DEFAULT_MAX_ENTRIES = 24 const DEFAULT_MAX_CHARS = 600 function sameWindow(a: RecentWriteMeta, b: RecentWriteMeta): boolean { if (a.windowHandle !== null && b.windowHandle !== null && a.windowHandle === b.windowHandle) return true const appA = a.appName?.trim().toLowerCase() const appB = b.appName?.trim().toLowerCase() return Boolean(appA) && appA === appB && Boolean(a.windowTitle) && a.windowTitle === b.windowTitle } export class RecentWritesBuffer { private _entries: RecentWrite[] = [] private _fieldKey = '' private _fieldText = '' private readonly _ttlMs: number private readonly _maxEntries: number private readonly _maxChars: number constructor(options: RecentWritesOptions = {}) { this._ttlMs = options.ttlMs ?? DEFAULT_TTL_MS this._maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES this._maxChars = options.maxChars ?? DEFAULT_MAX_CHARS } /** * 입력칸 스냅샷을 본다. 같은 칸에서 내용이 있던 칸이 비워지면(보냄) 직전 내용을 기억한다. * * 칸이 바뀌면 기준만 다시 잡는다 — 다른 칸으로 옮겨 간 것은 "보냄" 이 아니다. * 일부만 지운 경우(고쳐 쓰기)도 보냄이 아니다: 남은 글이 없을 때만 기록한다. */ observe(fieldKey: string, text: string, meta: RecentWriteMeta, now: number): RecentWrite | null { if (fieldKey !== this._fieldKey) { this._fieldKey = fieldKey this._fieldText = text return null } const previous = this._fieldText.trim() this._fieldText = text if (text.trim().length > 0 || previous.length < 2) return null const entry: RecentWrite = { ...meta, text: previous.length > this._maxChars ? previous.slice(-this._maxChars) : previous, at: now } this._prune(now) this._entries.push(entry) if (this._entries.length > this._maxEntries) this._entries.splice(0, this._entries.length - this._maxEntries) return entry } /** 같은 창에서 조금 전에 쓴 글 (오래된 것부터, 최대 limit 개). */ listFor(meta: RecentWriteMeta, now: number, limit = 4): RecentWrite[] { this._prune(now) return this._entries.filter((entry) => sameWindow(entry, meta)).slice(-limit) } clear(): void { this._entries = [] this._fieldKey = '' this._fieldText = '' } private _prune(now: number): void { this._entries = this._entries.filter((entry) => now - entry.at <= this._ttlMs) } }