cu-screenshot-pruner.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /**
  2. * CU screenshot context pruner — beforeLlmCall hook.
  3. *
  4. * Scans the conversation message array for CU screenshot tool results
  5. * (desktop_screenshot / desktop_screenshot_region / desktop_zoom) that
  6. * contain ImageContent. Keeps only the N most recent screenshots with
  7. * inline images; older ones have their ImageContent replaced with a
  8. * text placeholder containing the saved file path.
  9. *
  10. * This prevents CU sessions from filling the context window with stale
  11. * screenshots. Each screenshot costs ~1000-1800 tokens; limiting to 3
  12. * keeps the overhead under ~5400 tokens while retaining the most
  13. * relevant visual context.
  14. */
  15. import type {
  16. PiBeforeLlmCallHook,
  17. PiBeforeLlmCallHookDecision,
  18. PiBeforeLlmCallHookInput,
  19. } from '@mavis/agent-core/pi-turn-runner';
  20. import type { MetricsClient } from '../common/metrics.js';
  21. function recordMetric(record: () => void): void {
  22. try {
  23. record();
  24. } catch {
  25. // Observability must never abort the before-LLM hook or provider request.
  26. }
  27. }
  28. const CU_SCREENSHOT_TOOLS = new Set([
  29. 'desktop_screenshot',
  30. 'desktop_screenshot_region',
  31. 'desktop_zoom',
  32. ]);
  33. interface MessageContentPart {
  34. type: string;
  35. text?: string;
  36. data?: string;
  37. mimeType?: string;
  38. [key: string]: unknown;
  39. }
  40. /**
  41. * Create a beforeLlmCall hook that prunes old CU screenshot images
  42. * from the conversation context, keeping at most `maxScreenshots`.
  43. */
  44. export function createCuScreenshotPrunerHook(
  45. maxScreenshots: number,
  46. metrics?: Pick<MetricsClient, 'counter' | 'histogram'>,
  47. ): PiBeforeLlmCallHook {
  48. return async (
  49. input: PiBeforeLlmCallHookInput,
  50. ): Promise<PiBeforeLlmCallHookDecision | undefined> => {
  51. if (maxScreenshots <= 0) return undefined; // disabled
  52. // Collect indices of messages that contain CU screenshot image content.
  53. // Walk backwards so we can identify the N most recent.
  54. const screenshotLocations: Array<{
  55. msgIndex: number;
  56. contentPartIndex: number;
  57. }> = [];
  58. for (let i = input.messages.length - 1; i >= 0; i--) {
  59. const msg = input.messages[i] as unknown as Record<string, unknown>;
  60. // Pi's ToolResultMessage uses role 'toolResult' / 'toolName'. Keep the
  61. // legacy role/name aliases too because persisted histories can contain
  62. // the older shape.
  63. const role = msg?.role as string | undefined;
  64. if (role !== 'toolResult' && role !== 'tool') continue;
  65. // Check if this is a CU screenshot tool result
  66. const toolName = (msg?.toolName ?? msg?.tool_name ?? msg?.name) as string | undefined;
  67. if (!toolName || !CU_SCREENSHOT_TOOLS.has(toolName)) continue;
  68. // Find image content parts in this message
  69. const content = msg?.content as MessageContentPart[] | undefined;
  70. if (!Array.isArray(content)) continue;
  71. for (let j = content.length - 1; j >= 0; j--) {
  72. if (content[j]?.type === 'image') {
  73. screenshotLocations.push({ msgIndex: i, contentPartIndex: j });
  74. }
  75. }
  76. }
  77. recordMetric(() =>
  78. metrics?.histogram(
  79. 'cu_screenshot_resident_count',
  80. Math.min(screenshotLocations.length, maxScreenshots),
  81. ),
  82. );
  83. // If within limit, nothing to prune
  84. if (screenshotLocations.length <= maxScreenshots) return undefined;
  85. // screenshotLocations is newest-first (we walked backwards).
  86. // Keep the first `maxScreenshots` entries, prune the rest.
  87. const toPrune = screenshotLocations.slice(maxScreenshots);
  88. if (toPrune.length === 0) return undefined;
  89. // Deep-clone messages so we don't mutate the original array
  90. const pruned = input.messages.map((msg) =>
  91. JSON.parse(JSON.stringify(msg)),
  92. ) as typeof input.messages;
  93. for (const { msgIndex, contentPartIndex } of toPrune) {
  94. const msg = pruned[msgIndex] as unknown as Record<string, unknown>;
  95. const content = msg.content as MessageContentPart[];
  96. const imagePart = content[contentPartIndex]!;
  97. recordMetric(() =>
  98. metrics?.counter(
  99. 'cu_screenshot_pruned_payload_bytes_total',
  100. typeof imagePart.data === 'string' ? Buffer.byteLength(imagePart.data, 'utf8') : 0,
  101. ),
  102. );
  103. // Replace image with text placeholder
  104. content[contentPartIndex] = {
  105. type: 'text',
  106. text: `[CU screenshot pruned from context to save tokens. ${
  107. imagePart.mimeType ? `Original: ${imagePart.mimeType}. ` : ''
  108. }Use desktop_screenshot to take a new screenshot if needed.]`,
  109. };
  110. }
  111. return {
  112. type: 'replaceMessages',
  113. messages: pruned,
  114. metadata: {
  115. replacementId: `cu-screenshot-prune-${Date.now()}`,
  116. strategyVersion: 'cu-screenshot-pruner-v1',
  117. summary: `Pruned ${toPrune.length} old CU screenshot(s), keeping ${maxScreenshots} most recent.`,
  118. compactedMessages: [],
  119. keptMessages: pruned,
  120. firstKeptIndex: 0,
  121. },
  122. };
  123. };
  124. }