| 334 | } |
| 335 | |
| 336 | func RunPostCompactCleanUp(ctx context.Context, state any, recentReadFiles []map[string]string) { |
| 337 | if recentReadFiles == nil { |
| 338 | return |
| 339 | } |
| 340 | messages := getStateMessages(state) |
| 341 | start := len(messages) - 2 |
| 342 | if start < 0 { |
| 343 | start = 0 |
| 344 | } |
| 345 | |
| 346 | for _, m := range messages[start:] { |
| 347 | mj, err := json.Marshal(m) |
| 348 | if err != nil { |
| 349 | if strings.Contains(fmt.Sprintf("%v", m), "[System: Post-compact memory restoration]") { |
| 350 | return |
| 351 | } |
| 352 | continue |
| 353 | } |
| 354 | if strings.Contains(string(mj), "[System: Post-compact memory restoration]") { |
| 355 | return |
| 356 | } |
| 357 | } |
| 358 | s := len(recentReadFiles) - PostCompactMaxFilesToRestore |
| 359 | if s < 0 { |
| 360 | s = 0 |
| 361 | } |
| 362 | filesToRestore := recentReadFiles[s:] |
| 363 | restoreTextParts := []string{"[System: Post-compact memory restoration]"} |
| 364 | |
| 365 | for _, f := range filesToRestore { |
| 366 | path, ok := f["path"] |
| 367 | if !ok { |
| 368 | path = "unknown" |
| 369 | } |
| 370 | content, ok := f["content"] |
| 371 | if !ok { |
| 372 | content = "" |
| 373 | } |
| 374 | truncateContent := TruncateRunes(content, PostCompactMaxTokenPerFile*4) |
| 375 | restoreTextParts = append(restoreTextParts, fmt.Sprintf("--- File: %s ---\n%s", path, truncateContent)) |
| 376 | } |
| 377 | recoverMsg := map[string]any{ |
| 378 | "role": "user", |
| 379 | "content": []any{ |
| 380 | map[string]any{ |
| 381 | "type": "text", |
| 382 | "text": strings.Join(restoreTextParts, "\n\n"), |
| 383 | }, |
| 384 | }, |
| 385 | } |
| 386 | setStateMessages(state, append(messages, recoverMsg)) |
| 387 | } |
| 388 | |
| 389 | func getStateMessages(state any) []map[string]any { |
| 390 | value := reflectValue(state) |