(msgs: Iterable<WithParts>)
| 519 | }) |
| 520 | |
| 521 | export function filterCompacted(msgs: Iterable<WithParts>) { |
| 522 | const result = [] as WithParts[] |
| 523 | const completed = new Set<string>() |
| 524 | let retain: MessageID | undefined |
| 525 | for (const msg of msgs) { |
| 526 | result.push(msg) |
| 527 | if (retain) { |
| 528 | if (msg.info.id === retain) break |
| 529 | continue |
| 530 | } |
| 531 | if (msg.info.role === "user" && completed.has(msg.info.id)) { |
| 532 | const part = msg.parts.find((item): item is CompactionPart => item.type === "compaction") |
| 533 | if (!part) continue |
| 534 | if (!part.tail_start_id) break |
| 535 | retain = part.tail_start_id |
| 536 | if (msg.info.id === retain) break |
| 537 | continue |
| 538 | } |
| 539 | if (msg.info.role === "user" && completed.has(msg.info.id) && msg.parts.some((part) => part.type === "compaction")) |
| 540 | break |
| 541 | if (msg.info.role === "assistant" && msg.info.summary && msg.info.finish && !msg.info.error) |
| 542 | completed.add(msg.info.parentID) |
| 543 | } |
| 544 | result.reverse() |
| 545 | const compactionIndex = result.findLastIndex( |
| 546 | (msg) => |
| 547 | msg.info.role === "user" && |
| 548 | msg.parts.some((item): item is CompactionPart => item.type === "compaction" && item.tail_start_id !== undefined), |
| 549 | ) |
| 550 | const compaction = result[compactionIndex] |
| 551 | const part = compaction?.parts.find( |
| 552 | (item): item is CompactionPart => item.type === "compaction" && item.tail_start_id !== undefined, |
| 553 | ) |
| 554 | const summaryIndex = compaction |
| 555 | ? result.findIndex( |
| 556 | (msg, index) => |
| 557 | index > compactionIndex && |
| 558 | msg.info.role === "assistant" && |
| 559 | msg.info.summary && |
| 560 | msg.info.parentID === compaction.info.id, |
| 561 | ) |
| 562 | : -1 |
| 563 | const tailIndex = part?.tail_start_id ? result.findIndex((msg) => msg.info.id === part.tail_start_id) : -1 |
| 564 | if (tailIndex >= 0 && tailIndex < compactionIndex && summaryIndex > compactionIndex) { |
| 565 | return [ |
| 566 | ...result.slice(compactionIndex, summaryIndex + 1), |
| 567 | ...result.slice(tailIndex, compactionIndex), |
| 568 | ...result.slice(summaryIndex + 1), |
| 569 | ] |
| 570 | } |
| 571 | return result |
| 572 | } |
| 573 | |
| 574 | export const filterCompactedEffect = Effect.fnUntraced(function* (sessionID: SessionID) { |
| 575 | return filterCompacted(yield* stream(sessionID)) |
no test coverage detected