validateResumeAgainstHistory function

void validateResumeAgainstHistory(
  1. AgentResume resume,
  2. List<Message> history
)

Validates that every resume.restart and resume.respond entry references a tool request that actually exists in the session history.

Implementation

void validateResumeAgainstHistory(AgentResume resume, List<Message> history) {
  final allToolRequests = <ToolRequest>[];
  for (final msg in history) {
    if (msg.role == Role.model) {
      for (final part in msg.content) {
        if (part.isToolRequest) {
          allToolRequests.add(part.toolRequest!);
        }
      }
    }
  }

  for (final restart in resume.restart ?? const <ToolRequestPart>[]) {
    final tr = restart.toolRequest;
    ToolRequest? match;
    for (final x in allToolRequests) {
      if (x.name == tr.name && x.ref == tr.ref) {
        match = x;
        break;
      }
    }
    if (match == null) {
      throw GenkitException(
        "resume.restart references tool '${tr.name}'"
        '${tr.ref != null ? ' (ref: ${tr.ref})' : ''}'
        ' which was not found in session history.',
        status: StatusCodes.INVALID_ARGUMENT,
      );
    }
    if (!_deepEqual(tr.input, match.input)) {
      throw GenkitException(
        "resume.restart for tool '${tr.name}'"
        '${tr.ref != null ? ' (ref: ${tr.ref})' : ''}'
        ' has modified inputs that do not match the original tool request '
        'in session history. Restart inputs must exactly match the '
        'interrupted tool request.',
        status: StatusCodes.INVALID_ARGUMENT,
      );
    }
  }

  for (final respond in resume.respond ?? const <ToolResponsePart>[]) {
    final tr = respond.toolResponse;
    ToolRequest? match;
    for (final x in allToolRequests) {
      if (x.name == tr.name && x.ref == tr.ref) {
        match = x;
        break;
      }
    }
    if (match == null) {
      throw GenkitException(
        "resume.respond references tool '${tr.name}'"
        '${tr.ref != null ? ' (ref: ${tr.ref})' : ''}'
        ' which was not found in session history.',
        status: StatusCodes.INVALID_ARGUMENT,
      );
    }
  }
}