( sdk: ISdk, kv: StateKV, provider: MemoryProvider, )
| 114 | } |
| 115 | |
| 116 | export function registerSlidingWindowFunction( |
| 117 | sdk: ISdk, |
| 118 | kv: StateKV, |
| 119 | provider: MemoryProvider, |
| 120 | ): void { |
| 121 | sdk.registerFunction("mem::enrich-window", |
| 122 | async (data: { |
| 123 | observationId: string; |
| 124 | sessionId: string; |
| 125 | lookback?: number; |
| 126 | lookahead?: number; |
| 127 | }) => { |
| 128 | if ( |
| 129 | !data || |
| 130 | typeof data.sessionId !== "string" || |
| 131 | !data.sessionId.trim() || |
| 132 | typeof data.observationId !== "string" || |
| 133 | !data.observationId.trim() |
| 134 | ) { |
| 135 | return { success: false, error: "sessionId and observationId are required" }; |
| 136 | } |
| 137 | const sessionId = data.sessionId.trim(); |
| 138 | const observationId = data.observationId.trim(); |
| 139 | const hprev = data.lookback ?? 3; |
| 140 | const hnext = data.lookahead ?? 2; |
| 141 | |
| 142 | const allObs = await kv.list<CompressedObservation>( |
| 143 | KV.observations(sessionId), |
| 144 | ); |
| 145 | allObs.sort( |
| 146 | (a, b) => |
| 147 | new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(), |
| 148 | ); |
| 149 | |
| 150 | const primaryIdx = allObs.findIndex((o) => o.id === observationId); |
| 151 | if (primaryIdx === -1) { |
| 152 | return { success: false, error: "Observation not found" }; |
| 153 | } |
| 154 | |
| 155 | const primary = allObs[primaryIdx]; |
| 156 | const before = allObs.slice(Math.max(0, primaryIdx - hprev), primaryIdx); |
| 157 | const after = allObs.slice(primaryIdx + 1, primaryIdx + 1 + hnext); |
| 158 | |
| 159 | if (before.length === 0 && after.length === 0) { |
| 160 | return { |
| 161 | success: true, |
| 162 | enriched: null, |
| 163 | reason: "No adjacent context available", |
| 164 | }; |
| 165 | } |
| 166 | |
| 167 | try { |
| 168 | const prompt = buildWindowPrompt(primary, before, after); |
| 169 | const response = await provider.compress( |
| 170 | SLIDING_WINDOW_SYSTEM, |
| 171 | prompt, |
| 172 | ); |
| 173 | const parsed = parseEnrichedXml(response); |
no test coverage detected