All files / src/llm-orchestration/action-handlers get-messages.handler.ts

89.02% Statements 146/164
60.31% Branches 76/126
100% Functions 13/13
90.06% Lines 136/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 4238x 8x 8x           8x 8x   8x   8x     8x     8x     8x     26x 26x 26x 1x       15x   5x       1x               2x   1x   1x       1x       1x   1x                       1x     1x     1x 1x                   8x 45x 45x 3x   45x 4x   45x               8x       32x 32x   32x 46x   46x 10x       10x 36x 27x         27x 1x     27x 2x 2x           27x 27x     27x   2x 2x 2x 2x 2x         2x 2x 2x   2x 2x   2x     2x 1x 1x     1x     2x           2x           32x       8x 35x       35x 35x       1x                 3x                                                                                     33x 33x             32x   32x     32x 32x 39x 39x 39x 39x         32x 32x 32x 38x         17x 17x       32x     17x 17x 25x   17x 5x       32x     46x 19x 27x 14x 1x 15x   14x     13x 1x 12x 1x   11x       46x       46x                             32x   32x 32x 32x   32x 46x   46x   4x             4x 4x     46x 34x     46x 46x       32x   30x 30x                   32x 4x     32x 46x       32x                                   1x                        
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  PlanExecutionContext,
} from '../llm-orchestration.interfaces';
import { SessionInput, AIAction } from '../../core-entities';
import { HistoryCompressionService } from '../history-compression.service';
import { LlmContent } from '../../llm-provider/llm-provider.interface';
import { toShortId } from '../../utils';
 
const PREVIEW_MAX_LENGTH = 120;
 
/** Default chars-per-token ratio used when no input_token_count is available. */
export const DEFAULT_CHARS_PER_TOKEN = 4;
 
/** Target token count for context after discarding. */
export const CONTEXT_TARGET_TOKENS = 50000;
 
/** Minimum token count — never discard below this. */
export const CONTEXT_FLOOR_TOKENS = 30000;
 
function truncate(text: string, maxLen: number = PREVIEW_MAX_LENGTH): string {
  Iif (!text) return '';
  const cleaned = text.replace(/\n/g, ' ').trim();
  if (cleaned.length <= maxLen) return cleaned;
  return cleaned.slice(0, maxLen - 3) + '...';
}
 
function buildActionPreview(action: AIAction): string {
  switch (action.action_type) {
    case 'create_file':
      return `create_file: ${action.file_path || ''}`;
    case 'overwrite_file':
      return `overwrite_file: ${action.file_path || ''}`;
    case 'delete_file':
      return `delete_file: ${action.file_path || ''}`;
    case 'patch':
      return `patch: ${action.file_path || ''}`;
    case 'quick_edit':
      return `quick_edit: ${action.file_path || ''}`;
    case 'apply_diff':
      return `apply_diff: ${action.file_path || ''}`;
    case 'run_command':
      return `run_command: ${truncate(action.command_string || '')}`;
    case 'request_context':
      return `request_context: ${truncate(action.files || action.folders || '')}`;
    case 'execute_code':
      return `execute_code: ${truncate(action.command_string || '')}`;
    case 'invoke_subagent':
      return `invoke_subagent: ${truncate(action.arguments || '')}`;
    case 'list_sub_agents':
      return 'list_sub_agents';
    case 'new_session':
      return `new_session: ${truncate(action.handover_string || '')}`;
    case 'get_session_history':
      return 'get_session_history';
    case 'generate_title':
      return 'generate_title';
    case 'ask_user':
      return `ask_user: ${truncate(action.plain || '')}`;
    case 'write_todo':
      return `write_todo: ${action.file_path || ''}`;
    case 'howto':
      return 'howto';
    case 'get_messages':
      return 'get_messages';
    case 'discard_messages':
      return 'discard_messages';
    case 'final':
      Iif (action.selections) {
        return `final: user selection`;
      }
      return `final: ${truncate(action.plain || '')}`;
    default:
      // Handle MCP tool names with double underscore (serverName__toolName)
      if (action.action_type.includes('__')) {
        return action.action_type;
      }
      return `${action.action_type}: ${truncate(action.file_path || action.command_string || action.plain || '')}`;
  }
}
 
/**
 * Computes the character size of a compressed history turn as it would be
 * serialized by LLM providers.
 */
export function computeTurnCharSize(turn: LlmContent): number {
  let size = turn.parts.map((p) => p.text).join('').length;
  if (turn.thoughts) {
    size += turn.thoughts.length;
  }
  if (turn.tool_calls) {
    size += JSON.stringify(turn.tool_calls).length;
  }
  return size;
}
 
/**
 * Reconstructs chat history from SessionInputs, mirroring the logic in
 * chat.service.ts:getHistory(). Returns the history and a parallel array
 * mapping each turn index to the index of its source SessionInput.
 */
export function buildHistory(inputs: SessionInput[]): {
  history: LlmContent[];
  turnToInputIndex: number[];
} {
  const history: LlmContent[] = [];
  const turnToInputIndex: number[] = [];
 
  for (let inputIdx = 0; inputIdx < inputs.length; inputIdx++) {
    const input = inputs[inputIdx];
 
    if (input.role === 'user' && input.generated_context_string) {
      history.push({
        role: 'user',
        parts: [{ text: input.generated_context_string }],
      });
      turnToInputIndex.push(inputIdx);
    } else if (input.role === 'model') {
      const content: LlmContent = {
        role: 'model',
        parts: [{ text: input.raw_llm_response || '' }],
      };
 
      if (input.thoughts) {
        content.thoughts = input.thoughts;
      }
 
      if (input.tool_calls) {
        try {
          content.tool_calls = JSON.parse(input.tool_calls);
        } catch (_e) {
          // Skip malformed tool_calls
        }
      }
 
      history.push(content);
      turnToInputIndex.push(inputIdx);
 
      // Add tool result turns for each tool_call
      if (content.tool_calls && content.tool_calls.length > 0) {
        // Build map of tool_call_id -> action for O(1) lookup
        const actionsByToolCallId = new Map<string, AIAction>();
        if (input.aiActions) {
          for (const action of input.aiActions) {
            if (action.tool_call_id) {
              actionsByToolCallId.set(action.tool_call_id, action);
            }
          }
        }
 
        for (const toolCall of content.tool_calls) {
          const action = actionsByToolCallId.get(toolCall.id);
          Iif (!action) continue;
 
          const output = action.executionLogs?.[0]?.output || '';
          const errorMessage = action.executionLogs?.[0]?.error_message || '';
 
          Iif (!output && !errorMessage) continue;
 
          let toolResult: string;
          if (output && errorMessage) {
            toolResult = `${output}\n\nError: ${errorMessage}`;
          } else Iif (errorMessage) {
            toolResult = `Error: ${errorMessage}`;
          } else {
            toolResult = output;
          }
 
          history.push({
            role: 'tool',
            tool_call_id: toolCall.id,
            tool_name: action.action_type,
            parts: [{ text: toolResult }],
          });
          turnToInputIndex.push(inputIdx);
        }
      }
    }
  }
 
  return { history, turnToInputIndex };
}
 
@Injectable()
export class GetMessagesHandler implements ActionHandler {
  readonly toolName = 'get_messages';
 
  constructor(
    @InjectRepository(SessionInput)
    private readonly sessionInputsRepository: Repository<SessionInput>,
    private readonly historyCompressionService: HistoryCompressionService,
  ) {}
 
  getMetadata() {
    return {
      name: this.toolName,
      description:
        'Get a summary of non-discarded messages in the current session, grouped by topic. Returns groups with labels, message counts, estimated tokens, and per-message details. Use this to identify completed work to discard from context.',
      arguments: [],
    };
  }
 
  getDefinition(): string {
    return `## get_messages
 
Get a summary of non-discarded messages in the current session, organized into logical groups. Returns groups with topic labels, message counts, estimated tokens, and individual message details. Use this to identify messages to discard from the LLM context window.
 
### Parameters:
No parameters required. Uses the current session context.
 
### Returns:
JSON object with:
- \`total_est_tokens\`: Sum of all estimated token counts across all messages
- \`target_tokens\`: Target token count after discarding (${CONTEXT_TARGET_TOKENS}). Discard until near this value.
- \`floor_tokens\`: Minimum token count (${CONTEXT_FLOOR_TOKENS}). **Never discard below this value.**
- \`groups\`: Array of logical groups, each with:
  - \`label\`: Topic label derived from the first user message in the group (e.g., "Fix auth bug", "Explore database schema")
  - \`label_suffix\`: " (ongoing)" for the most recent group, empty otherwise
  - \`message_count\`: Number of messages in this group
  - \`est_tokens\`: Total estimated tokens for this group
  - \`messages\`: Array of message summaries, each with:
    - \`short_id\`: Compact ID (first 3 + last 2 chars of UUID, e.g. "a1b90") — use this with \`discard_messages\`
    - \`role\`: "user" or "model"
    - \`preview\`: brief description (user prompt text or tool name + args)
    - \`est_tokens\`: estimated token count for this message
 
### Token Estimation:
Token counts are estimated by:
1. Reconstructing chat history from session inputs (same format sent to LLM)
2. Applying history compression (redacting older file contents)
3. Computing \`char_size\` from compressed history for each message
4. Deriving a \`char/token ratio\` from the last model input with a known \`input_token_count\` (cumulative tokens)
5. Using a fallback ratio of 4 chars/token if no token count is available
6. \`est_tokens = round(char_size / ratio)\`
 
### Example:
\`\`\`typescript
tool: get_messages
args: {}
\`\`\``;
  }
 
  async execute(
    _args: Record<string, any>,
    context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    try {
      const inputs = await this.sessionInputsRepository.find({
        where: { session: { id: context.session_id }, is_discarded: false },
        relations: ['aiActions', 'aiActions.executionLogs'],
        order: { sequence_number: 'ASC' },
      });
 
      // Build history and compress it (same as what the LLM actually receives)
      const { history, turnToInputIndex } = buildHistory(inputs);
      const compressedHistory =
        await this.historyCompressionService.compress(history);
 
      // Compute compressed char_size per SessionInput
      const compressedCharSizes = new Array<number>(inputs.length).fill(0);
      for (let i = 0; i < compressedHistory.length; i++) {
        const turnCharSize = computeTurnCharSize(compressedHistory[i]);
        const inputIdx = turnToInputIndex[i];
        if (inputIdx >= 0 && inputIdx < inputs.length) {
          compressedCharSizes[inputIdx] += turnCharSize;
        }
      }
 
      // Derive char/token ratio from last model input with input_token_count
      let ratio = DEFAULT_CHARS_PER_TOKEN;
      let ratioInputIndex = -1;
      for (let i = inputs.length - 1; i >= 0; i--) {
        if (
          inputs[i].role === 'model' &&
          inputs[i].input_token_count != null &&
          inputs[i].input_token_count > 0
        ) {
          ratioInputIndex = i;
          break;
        }
      }
 
      if (ratioInputIndex >= 0) {
        // input_token_count is cumulative (total tokens of entire conversation)
        // Sum all compressed char_sizes up to and including that input
        let cumulativeChars = 0;
        for (let i = 0; i <= ratioInputIndex; i++) {
          cumulativeChars += compressedCharSizes[i];
        }
        if (cumulativeChars > 0) {
          ratio = cumulativeChars / inputs[ratioInputIndex].input_token_count!;
        }
      }
 
      const summaries = inputs.map((input, index) => {
        let preview: string;
 
        if (input.role === 'user') {
          preview = truncate(input.user_prompt || '');
        } else if (input.aiActions && input.aiActions.length > 0) {
          preview = input.aiActions
            .sort((a, b) => a.order_of_execution - b.order_of_execution)
            .map((a) => buildActionPreview(a))
            .join(', ');
          Iif (preview.length > PREVIEW_MAX_LENGTH) {
            preview = preview.slice(0, PREVIEW_MAX_LENGTH - 3) + '...';
          }
        } else if (input.error_message) {
          preview = `error: ${truncate(input.error_message)}`;
        } else if (input.llm_response_explanation) {
          preview = truncate(input.llm_response_explanation);
        } else {
          preview = '(empty response)';
        }
 
        const estTokens =
          compressedCharSizes[index] > 0
            ? Math.round(compressedCharSizes[index] / ratio)
            : 0;
 
        return {
          short_id: toShortId(input.id),
          role: input.role || 'user',
          preview,
          est_tokens: estTokens,
        };
      });
 
      // Group messages by topic (user message starts a new group)
      const groups: Array<{
        label: string;
        label_suffix: string;
        message_count: number;
        est_tokens: number;
        messages: typeof summaries;
      }> = [];
 
      let currentGroup: (typeof summaries)[number][] = [];
      let currentLabel = '';
      let currentGroupTokens = 0;
 
      for (let i = 0; i < summaries.length; i++) {
        const summary = summaries[i];
 
        if (summary.role === 'user' && currentGroup.length > 0) {
          // Close current group
          groups.push({
            label: currentLabel,
            label_suffix: '',
            message_count: currentGroup.length,
            est_tokens: currentGroupTokens,
            messages: currentGroup,
          });
          currentGroup = [];
          currentGroupTokens = 0;
        }
 
        if (summary.role === 'user' || currentGroup.length === 0) {
          currentLabel = summary.preview || 'User message';
        }
 
        currentGroup.push(summary);
        currentGroupTokens += summary.est_tokens;
      }
 
      // Push last group
      if (currentGroup.length > 0) {
        // Mark the most recent group as ongoing
        const isOngoing = true; // last group is always the current one
        groups.push({
          label: currentLabel,
          label_suffix: isOngoing ? ' (ongoing)' : '',
          message_count: currentGroup.length,
          est_tokens: currentGroupTokens,
          messages: currentGroup,
        });
      }
 
      // For all but the last group, label_suffix is empty
      for (let i = 0; i < groups.length - 1; i++) {
        groups[i].label_suffix = '';
      }
 
      const totalEstTokens = summaries.reduce(
        (sum, s) => sum + s.est_tokens,
        0,
      );
 
      return {
        status: 'SUCCESS',
        summary: `${summaries.length} messages in ${groups.length} groups, ~${totalEstTokens} est tokens`,
        execution_log: {
          output: JSON.stringify(
            {
              total_est_tokens: totalEstTokens,
              target_tokens: CONTEXT_TARGET_TOKENS,
              floor_tokens: CONTEXT_FLOOR_TOKENS,
              groups,
            },
            null,
            2,
          ),
        },
        persisted_args: {},
      };
    } catch (error) {
      return {
        status: 'FAILURE',
        summary: 'Failed to get messages',
        error_message: error.message,
        execution_log: {
          output: '',
          error_message: error.message,
        },
      };
    }
  }
}