(
readFileState: Record<string, { content: string; timestamp: number }>,
toolUseContext: ToolUseContext,
maxFiles: number,
preservedMessages: Message[] = [],
)
| 1413 | * @returns Array of attachment messages for the most recently accessed files that fit within token budget |
| 1414 | */ |
| 1415 | export async function createPostCompactFileAttachments( |
| 1416 | readFileState: Record<string, { content: string; timestamp: number }>, |
| 1417 | toolUseContext: ToolUseContext, |
| 1418 | maxFiles: number, |
| 1419 | preservedMessages: Message[] = [], |
| 1420 | ): Promise<AttachmentMessage[]> { |
| 1421 | const preservedReadPaths = collectReadToolFilePaths(preservedMessages) |
| 1422 | const recentFiles = Object.entries(readFileState) |
| 1423 | .map(([filename, state]) => ({ filename, ...state })) |
| 1424 | .filter( |
| 1425 | file => |
| 1426 | !shouldExcludeFromPostCompactRestore( |
| 1427 | file.filename, |
| 1428 | toolUseContext.agentId, |
| 1429 | ) && !preservedReadPaths.has(expandPath(file.filename)), |
| 1430 | ) |
| 1431 | .sort((a, b) => b.timestamp - a.timestamp) |
| 1432 | .slice(0, maxFiles) |
| 1433 | |
| 1434 | const results = await Promise.all( |
| 1435 | recentFiles.map(async file => { |
| 1436 | const attachment = await generateFileAttachment( |
| 1437 | file.filename, |
| 1438 | { |
| 1439 | ...toolUseContext, |
| 1440 | fileReadingLimits: { |
| 1441 | maxTokens: POST_COMPACT_MAX_TOKENS_PER_FILE, |
| 1442 | }, |
| 1443 | }, |
| 1444 | 'tengu_post_compact_file_restore_success', |
| 1445 | 'tengu_post_compact_file_restore_error', |
| 1446 | 'compact', |
| 1447 | ) |
| 1448 | return attachment ? createAttachmentMessage(attachment) : null |
| 1449 | }), |
| 1450 | ) |
| 1451 | |
| 1452 | let usedTokens = 0 |
| 1453 | return results.filter((result): result is AttachmentMessage => { |
| 1454 | if (result === null) { |
| 1455 | return false |
| 1456 | } |
| 1457 | const attachmentTokens = roughTokenCountEstimation(jsonStringify(result)) |
| 1458 | if (usedTokens + attachmentTokens <= POST_COMPACT_TOKEN_BUDGET) { |
| 1459 | usedTokens += attachmentTokens |
| 1460 | return true |
| 1461 | } |
| 1462 | return false |
| 1463 | }) |
| 1464 | } |
| 1465 | |
| 1466 | /** |
| 1467 | * Creates a plan file attachment if a plan file exists for the current session. |
no test coverage detected