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

100% Statements 55/55
91.3% Branches 21/23
100% Functions 5/5
100% Lines 53/53

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 2627x 7x 7x 7x 7x           7x 7x                                                                         7x 34x 34x       34x   34x   34x       2x                                                             3x                                                                         24x   24x 24x   24x 1x 1x   1x     23x         23x   4x     19x         18x 1x           17x       21x         21x 1x           20x           20x     20x     20x 2x             20x   32x 31x           31x 30x           30x 16x 16x   1x             30x 16x     30x           20x   20x                 4x 4x                        
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  PlanExecutionContext,
} from '../llm-orchestration.interfaces';
import { Session, SessionInput, SystemPrompt } from '../../core-entities';
import { GetSessionHistoryArgsDto } from './dto/get-session-history.args.dto';
 
// LlmContent interface matching what's sent to AI
interface LlmContentPart {
  text: string;
}
 
interface LlmToolCall {
  id: string;
  type: 'function' | 'web_search' | 'retrieval';
  function: {
    name: string;
    arguments: object | string;
  };
}
 
interface LlmContent {
  role: 'user' | 'model';
  parts: LlmContentPart[];
  tool_calls?: LlmToolCall[];
  thoughts?: string;
}
 
// History entry can be system prompt (with content) or user message (with content) or LlmContent (with parts)
interface SystemPromptEntry {
  role: 'system';
  content: string;
}
 
interface UserMessageEntry {
  role: 'user';
  content: string;
}
 
type HistoryEntry = SystemPromptEntry | UserMessageEntry | LlmContent;
 
@Injectable()
export class GetSessionHistoryHandler implements ActionHandler {
  readonly toolName = 'get_session_history';
  private readonly logger = new Logger(GetSessionHistoryHandler.name);
 
  constructor(
    @InjectRepository(Session)
    private readonly sessionsRepository: Repository<Session>,
    @InjectRepository(SessionInput)
    private readonly sessionInputsRepository: Repository<SessionInput>,
    @InjectRepository(SystemPrompt)
    private readonly systemPromptsRepository: Repository<SystemPrompt>,
  ) {}
 
  getMetadata() {
    return {
      name: this.toolName,
      description:
        'Returns session history in JSON format, using the same structure sent to the AI (LlmContent format)',
      arguments: [
        {
          name: 'session_id',
          type: 'string' as const,
          description:
            'Optional session ID. If not provided, uses the current session from context.',
          required: false,
        },
        {
          name: 'limit',
          type: 'number' as const,
          description:
            'Maximum number of conversation turns to return. If not provided, returns all turns.',
          required: false,
        },
        {
          name: 'include_system_prompt',
          type: 'boolean' as const,
          description:
            'Whether to include the system prompt in the returned history. Default: false',
          required: false,
        },
      ],
    };
  }
 
  getDefinition(): string {
    return `## get_session_history
 
Returns the session history in JSON format, using the same structure that is sent to the AI (LlmContent format).
 
### Parameters:
- \`session_id\` (string, optional): Session ID. If not provided, uses the current session.
- \`limit\` (number, optional): Maximum number of conversation turns to return.
- \`include_system_prompt\` (boolean, optional): Whether to include the system prompt. Default: false.
 
### Returns:
JSON array of conversation turns with the following structure:
\`\`\`json
[
  {
    "role": "system" | "user" | "model",
    "content": "text content" | [{ "text": "content" }],
    "tool_calls": [...],
    "thoughts": "reasoning content"
  }
]
\`\`\`
 
### Example:
\`\`\`typescript
tool: get_session_history
args: {
  "session_id": "session-123",
  "limit": 10,
  "include_system_prompt": false
}
\`\`\``;
  }
 
  async execute(
    args: Record<string, any>,
    context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    try {
      // Validate arguments
      const validatedArgs = plainToClass(GetSessionHistoryArgsDto, args);
      const validationErrors = await validate(validatedArgs);
 
      if (validationErrors.length > 0) {
        const errorMessages = validationErrors
          .map((err) => Object.values(err.constraints || {}).join(', '))
          .join('; ');
        throw new Error(`Validation error: ${errorMessages}`);
      }
 
      const { session_id, limit, include_system_prompt } = validatedArgs;
 
      // Determine session ID
      let targetSessionId: string;
 
      if (session_id) {
        // Explicit session_id provided, use it
        targetSessionId = session_id;
      } else {
        // No explicit session_id, check if current session has a parent
        const currentSession = await this.sessionsRepository.findOne({
          where: { id: context.session_id },
          select: ['id', 'parent_session_id'],
        });
 
        if (!currentSession) {
          throw new NotFoundException(
            `Current session "${context.session_id}" not found`,
          );
        }
 
        // Use parent session if exists, otherwise use current session
        targetSessionId = currentSession.parent_session_id || currentSession.id;
      }
 
      // Fetch session with system prompt
      const session = await this.sessionsRepository.findOne({
        where: { id: targetSessionId },
        relations: ['systemPrompt'],
      });
 
      if (!session) {
        throw new NotFoundException(
          `Session with ID "${targetSessionId}" not found`,
        );
      }
 
      // Fetch session inputs ordered by created_at
      const sessionInputs = await this.sessionInputsRepository.find({
        where: { session: { id: targetSessionId } },
        order: { created_at: 'ASC' },
      });
 
      // Apply limit if specified
      const limitedInputs = limit ? sessionInputs.slice(-limit) : sessionInputs;
 
      // Build history array
      const history: HistoryEntry[] = [];
 
      // Add system prompt if requested
      if (include_system_prompt && session.systemPrompt) {
        history.push({
          role: 'system',
          content: session.systemPrompt.prompt_content,
        });
      }
 
      // Map session inputs to LlmContent format
      for (const input of limitedInputs) {
        // User turn
        if (input.generated_context_string) {
          history.push({
            role: 'user',
            content: input.generated_context_string,
          });
 
          // Model turn (if response exists) - only add after user turn
          if (input.raw_llm_response || input.tool_calls || input.thoughts) {
            const modelTurn: LlmContent = {
              role: 'model',
              parts: [{ text: input.raw_llm_response || '' }],
            };
 
            // Add tool calls if present
            if (input.tool_calls) {
              try {
                modelTurn.tool_calls = JSON.parse(input.tool_calls);
              } catch (e) {
                this.logger.warn(
                  `Failed to parse tool_calls for input ${input.id}: ${e.message}`,
                );
              }
            }
 
            // Add thoughts if present
            if (input.thoughts) {
              modelTurn.thoughts = input.thoughts;
            }
 
            history.push(modelTurn);
          }
        }
      }
 
      // Format as JSON for the summary
      const jsonOutput = JSON.stringify(history, null, 2);
 
      return {
        status: 'SUCCESS',
        summary: `Retrieved session history for "${targetSessionId}" with ${history.length} turn(s).\n\n\`\`\`json\n${jsonOutput}\n\`\`\``,
        execution_log: {
          output: jsonOutput,
        },
        persisted_args: { session_id: targetSessionId, limit },
      };
    } catch (error) {
      this.logger.error(`Failed to get session history: ${error.message}`);
      return {
        status: 'FAILURE',
        summary: 'Failed to retrieve session history',
        error_message: error.message,
        execution_log: {
          output: '',
          error_message: error.message,
        },
      };
    }
  }
}