{"version":3,"file":"agent/agents/validator.mjs","sources":["webpack://@agent-infra/browser-use/./src/agent/agents/validator.ts"],"sourcesContent":["/**\n * The following code is modified based on\n * https://github.com/nanobrowser/nanobrowser/blob/master/chrome-extension/src/background/agent/agents/validator.ts\n *\n * Apache-2.0 License\n * Copyright (c) 2024 alexchenzl\n * https://github.com/nanobrowser/nanobrowser/blob/master/LICENSE\n */\nimport {\n  BaseAgent,\n  type BaseAgentOptions,\n  type ExtraAgentOptions,\n} from './base';\nimport { z } from 'zod';\nimport { ActionResult, type AgentOutput } from '../types';\nimport { Actors, ExecutionState } from '../event/types';\nimport { HumanMessage } from '@langchain/core/messages';\nimport { isAuthenticationError, createLogger } from '../../utils';\nimport { ChatModelAuthError } from './errors';\nconst logger = createLogger('ValidatorAgent');\n\n// Define Zod schema for validator output\nexport const validatorOutputSchema = z.object({\n  is_valid: z.boolean(), // indicates if the output is correct\n  reason: z.string(), // explains why it is valid or not\n  answer: z.string(), // the final answer to the task if it is valid\n});\n\nexport type ValidatorOutput = z.infer<typeof validatorOutputSchema>;\n\nexport class ValidatorAgent extends BaseAgent<\n  typeof validatorOutputSchema,\n  ValidatorOutput\n> {\n  // sometimes we need to validate the output against both the current browser state and the plan\n  private plan: string | null = null;\n  constructor(\n    options: BaseAgentOptions,\n    extraOptions?: Partial<ExtraAgentOptions>,\n  ) {\n    super(validatorOutputSchema, options, { ...extraOptions, id: 'validator' });\n  }\n\n  /**\n   * Set the plan for the validator agent\n   * @param plan - The plan to set\n   */\n  setPlan(plan: string | null): void {\n    this.plan = plan;\n  }\n\n  /**\n   * Executes the validator agent\n   * @returns AgentOutput<ValidatorOutput>\n   */\n  async execute(): Promise<AgentOutput<ValidatorOutput>> {\n    try {\n      this.context.emitEvent(\n        Actors.VALIDATOR,\n        ExecutionState.STEP_START,\n        'Validating...',\n      );\n\n      let stateMessage = await this.prompt.getUserMessage(this.context);\n      if (this.plan) {\n        // merge the plan and the state message\n        const mergedMessage = new HumanMessage(\n          `${stateMessage.content}\\n\\nThe current plan is: \\n${this.plan}`,\n        );\n        stateMessage = mergedMessage;\n      }\n      const systemMessage = this.prompt.getSystemMessage();\n      const inputMessages = [systemMessage, stateMessage];\n\n      const modelOutput = await this.invoke(inputMessages);\n      if (!modelOutput) {\n        throw new Error('Failed to validate task result');\n      }\n\n      logger.info('validator output', JSON.stringify(modelOutput, null, 2));\n\n      if (!modelOutput.is_valid) {\n        // need to update the action results so that other agents can see the error\n        const msg = `The answer is not yet correct. ${modelOutput.reason}.`;\n        this.context.emitEvent(Actors.VALIDATOR, ExecutionState.STEP_FAIL, msg);\n        this.context.actionResults = [\n          new ActionResult({ extractedContent: msg, includeInMemory: true }),\n        ];\n      } else {\n        this.context.emitEvent(\n          Actors.VALIDATOR,\n          ExecutionState.STEP_OK,\n          modelOutput.answer,\n        );\n      }\n\n      return {\n        id: this.id,\n        result: modelOutput,\n      };\n    } catch (error) {\n      // Check if this is an authentication error\n      if (isAuthenticationError(error)) {\n        throw new ChatModelAuthError(\n          'Validator API Authentication failed. Please verify your API key',\n          error,\n        );\n      }\n\n      const errorMessage =\n        error instanceof Error ? error.message : String(error);\n      logger.error(`Validation failed: ${errorMessage}`);\n      this.context.emitEvent(\n        Actors.VALIDATOR,\n        ExecutionState.STEP_FAIL,\n        `Validation failed: ${errorMessage}`,\n      );\n      return {\n        id: this.id,\n        error: `Validation failed: ${errorMessage}`,\n      };\n    }\n  }\n}\n"],"names":["logger","createLogger","validatorOutputSchema","z","ValidatorAgent","BaseAgent","plan","Actors","ExecutionState","stateMessage","mergedMessage","HumanMessage","systemMessage","inputMessages","modelOutput","Error","JSON","msg","ActionResult","error","isAuthenticationError","ChatModelAuthError","errorMessage","String","options","extraOptions"],"mappings":";;;;;;;;;;;AAOC;;;;;;;;;;AAYD,MAAMA,SAASC,aAAa;AAGrB,MAAMC,wBAAwBC,EAAE,MAAM,CAAC;IAC5C,UAAUA,EAAE,OAAO;IACnB,QAAQA,EAAE,MAAM;IAChB,QAAQA,EAA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