(
readFileState: Record<string, { content: string; timestamp: number }>,
toolUseContext: ToolUseContext,
maxFiles: number,
preservedMessages: Message[] = [],
)
| 1488 | * @returns Array of attachment messages for the most recently accessed files that fit within token budget |
| 1489 | */ |
| 1490 | export async function createPostCompactFileAttachments( |
| 1491 | readFileState: Record<string, { content: string; timestamp: number }>, |
| 1492 | toolUseContext: ToolUseContext, |
| 1493 | maxFiles: number, |
| 1494 | preservedMessages: Message[] = [], |
| 1495 | ): Promise<AttachmentMessage[]> { |
| 1496 | const preservedReadPaths = collectReadToolFilePaths(preservedMessages) |
| 1497 | const recentFiles = Object.entries(readFileState) |
| 1498 | .map(([filename, state]) => ({ filename, ...state })) |
| 1499 | .filter( |
| 1500 | file => |
| 1501 | !shouldExcludeFromPostCompactRestore( |
| 1502 | file.filename, |
| 1503 | toolUseContext.agentId, |
| 1504 | ) && !preservedReadPaths.has(expandPath(file.filename)), |
| 1505 | ) |
| 1506 | .sort((a, b) => b.timestamp - a.timestamp) |
| 1507 | .slice(0, maxFiles) |
| 1508 | |
| 1509 | const results = await Promise.all( |
| 1510 | recentFiles.map(async file => { |
| 1511 | const attachment = await generateFileAttachment( |
| 1512 | file.filename, |
| 1513 | { |
| 1514 | ...toolUseContext, |
| 1515 | fileReadingLimits: { |
| 1516 | maxTokens: POST_COMPACT_MAX_TOKENS_PER_FILE, |
| 1517 | }, |
| 1518 | }, |
| 1519 | 'ncode_post_compact_file_restore_success', |
| 1520 | 'ncode_post_compact_file_restore_error', |
| 1521 | 'compact', |
| 1522 | ) |
| 1523 | return attachment ? createAttachmentMessage(attachment) : null |
| 1524 | }), |
| 1525 | ) |
| 1526 | |
| 1527 | let usedTokens = 0 |
| 1528 | return results.filter((result): result is AttachmentMessage => { |
| 1529 | if (result === null) { |
| 1530 | return false |
| 1531 | } |
| 1532 | const attachmentTokens = roughTokenCountEstimation(jsonStringify(result)) |
| 1533 | if (usedTokens + attachmentTokens <= POST_COMPACT_TOKEN_BUDGET) { |
| 1534 | usedTokens += attachmentTokens |
| 1535 | return true |
| 1536 | } |
| 1537 | return false |
| 1538 | }) |
| 1539 | } |
| 1540 | |
| 1541 | /** |
| 1542 | * Creates a plan file attachment if a plan file exists for the current session. |
no test coverage detected