{"version":3,"file":"agent/messages/service.mjs","sources":["webpack://@agent-infra/browser-use/./src/agent/messages/service.ts"],"sourcesContent":["/**\n * The following code is modified based on\n * https://github.com/nanobrowser/nanobrowser/blob/master/chrome-extension/src/background/agent/messages/service.ts\n *\n * Apache-2.0 License\n * Copyright (c) 2024 alexchenzl\n * https://github.com/nanobrowser/nanobrowser/blob/master/LICENSE\n */\nimport {\n  type BaseMessage,\n  AIMessage,\n  HumanMessage,\n  SystemMessage,\n  ToolMessage,\n} from '@langchain/core/messages';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { z } from 'zod';\nimport {\n  MessageHistory,\n  type MessageMetadata,\n  type ManagedMessage,\n} from './views';\nimport { createLogger } from '../../utils';\nimport { ToolCall } from '@langchain/core/dist/messages/tool';\n\nconst logger = createLogger('MessageManager');\n\nexport default class MessageManager {\n  private maxInputTokens: number;\n  private history: MessageHistory;\n  private estimatedCharactersPerToken: number;\n  private readonly IMG_TOKENS: number;\n  private sensitiveData?: Record<string, string>;\n  private toolId: number;\n\n  constructor({\n    maxInputTokens = 128000,\n    estimatedCharactersPerToken = 3,\n    imageTokens = 800,\n    sensitiveData,\n  }: {\n    maxInputTokens?: number;\n    estimatedCharactersPerToken?: number;\n    imageTokens?: number;\n    sensitiveData?: Record<string, string>;\n  } = {}) {\n    this.maxInputTokens = maxInputTokens;\n    this.history = new MessageHistory();\n    this.estimatedCharactersPerToken = estimatedCharactersPerToken;\n    this.IMG_TOKENS = imageTokens;\n    this.sensitiveData = sensitiveData;\n    this.toolId = 1;\n  }\n\n  public initTaskMessages(\n    systemMessage: SystemMessage,\n    task: string,\n    messageContext?: string,\n  ): void {\n    // Add system message\n    this.addMessageWithTokens(systemMessage);\n\n    // Add context message if provided\n    if (messageContext && messageContext.length > 0) {\n      const contextMessage = new HumanMessage({\n        content: `Context for the task: ${messageContext}`,\n      });\n      this.addMessageWithTokens(contextMessage);\n    }\n\n    // Add task instructions\n    const taskMessage = MessageManager.taskInstructions(task);\n    this.addMessageWithTokens(taskMessage);\n\n    // Add sensitive data info if sensitive data is provided\n    if (this.sensitiveData) {\n      const info = `Here are placeholders for sensitive data: ${Object.keys(this.sensitiveData)}`;\n      const infoMessage = new HumanMessage({\n        content: `${info}\\nTo use them, write <secret>the placeholder name</secret>`,\n      });\n      this.addMessageWithTokens(infoMessage);\n    }\n\n    // Add example output\n    const placeholderMessage = new HumanMessage({\n      content: 'Example output:',\n    });\n    this.addMessageWithTokens(placeholderMessage);\n\n    const toolCallId = this.nextToolId();\n    const toolCalls: ToolCall[] = [\n      {\n        name: 'navigator_output',\n        // @ts-ignore\n        description: 'Navigate to the page and click on the element',\n        parameters: zodToJsonSchema(\n          // @ts-ignore\n          z.object({\n            current_state: z.object({\n              page_summary: z.string(),\n              evaluation_previous_goal: z.string(),\n              memory: z.string(),\n              next_goal: z.string(),\n            }),\n            action: z.array(\n              z.object({\n                click_element: z.object({\n                  index: z.number(),\n                }),\n              }),\n            ),\n          }),\n        ),\n        args: {\n          current_state: {\n            page_summary:\n              'On the page are company a,b,c wtih their revenue 1,2,3.',\n            evaluation_previous_goal: 'Success - I opend the first page',\n            memory: 'Starting with the new task. I have completed 1/10 steps',\n            next_goal: 'Click on company a',\n          },\n          action: [{ click_element: { index: 0 } }],\n        },\n\n        id: String(toolCallId),\n        type: 'tool_call' as const,\n      },\n    ];\n\n    const exampleToolCall = new AIMessage({\n      content: 'example tool call',\n      tool_calls: toolCalls,\n    });\n    this.addMessageWithTokens(exampleToolCall);\n\n    const toolMessage = new ToolMessage({\n      content: 'Browser started',\n      tool_call_id: String(toolCallId),\n    });\n    this.addMessageWithTokens(toolMessage);\n\n    // Add history start marker\n    const historyStartMessage = new HumanMessage({\n      content: '[Your task history memory starts here]',\n    });\n    this.addMessageWithTokens(historyStartMessage);\n  }\n\n  public nextToolId(): number {\n    const id = this.toolId;\n    this.toolId += 1;\n    return id;\n  }\n\n  /**\n   * Createthe task instructions\n   * @param task - The raw description of the task\n   * @returns A HumanMessage object containing the task instructions\n   */\n  private static taskInstructions(task: string): HumanMessage {\n    const content = `Your ultimate task is: \"\"\"${task}\"\"\". If you achieved your ultimate task, stop everything and use the done action in the next step to complete the task. If not, continue as usual.`;\n    return new HumanMessage({ content });\n  }\n\n  /**\n   * Returns the number of messages in the history\n   * @returns The number of messages in the history\n   */\n  public length(): number {\n    return this.history.messages.length;\n  }\n\n  /**\n   * Adds a new task to execute, it will be executed based on the history\n   * @param newTask - The raw description of the new task\n   */\n  public addNewTask(newTask: string): void {\n    const content = `Your new ultimate task is: \"\"\"${newTask}\"\"\". Take the previous context into account and finish your new ultimate task. `;\n    const msg = new HumanMessage({ content });\n    this.addMessageWithTokens(msg);\n  }\n\n  /**\n   * Adds a plan message to the history\n   * @param plan - The raw description of the plan\n   * @param position - The position to add the plan\n   */\n  public addPlan(plan?: string, position?: number): void {\n    if (plan) {\n      const msg = new AIMessage({ content: plan });\n      this.addMessageWithTokens(msg, position);\n    }\n  }\n\n  /**\n   * Adds a state message to the history\n   * @param stateMessage - The HumanMessage object containing the state\n   */\n  public addStateMessage(stateMessage: HumanMessage): void {\n    this.addMessageWithTokens(stateMessage);\n  }\n\n  /**\n   * Removes the last state message from the history\n   */\n  public removeLastStateMessage(): void {\n    this.history.removeLastHumanMessage();\n  }\n\n  public getMessages(): BaseMessage[] {\n    const messages = this.history.messages.map((m) => m.message);\n\n    let totalInputTokens = 0;\n    logger.debug(`Messages in history: ${this.history.messages.length}:`);\n\n    for (const m of this.history.messages) {\n      totalInputTokens += m.metadata.inputTokens;\n      // logger.debug(\n      //   `${m.message.constructor.name} - Token count: ${m.metadata.inputTokens}`,\n      // );\n    }\n\n    // logger.debug(`Total input tokens: ${totalInputTokens}`);\n    return messages;\n  }\n\n  public getMessagesWithTokens(): ManagedMessage[] {\n    return this.history.messages;\n  }\n\n  /**\n   * Adds a message to the history with the token count metadata\n   * @param message - The BaseMessage object to add\n   * @param position - The optional position to add the message, if not provided, the message will be added to the end of the history\n   */\n  public addMessageWithTokens(message: BaseMessage, position?: number): void {\n    let filteredMessage = message;\n    // filter out sensitive data if provided\n    if (this.sensitiveData) {\n      filteredMessage = this._filterSensitiveData(message);\n    }\n\n    const tokenCount = this._countTokens(filteredMessage);\n    const metadata: MessageMetadata = { inputTokens: tokenCount };\n    this.history.addMessage(filteredMessage, metadata, position);\n  }\n\n  /**\n   * Filters out sensitive data from the message\n   * @param message - The BaseMessage object to filter\n   * @returns The filtered BaseMessage object\n   */\n  private _filterSensitiveData(message: BaseMessage): BaseMessage {\n    const replaceSensitive = (value: string): string => {\n      let filteredValue = value;\n      if (!this.sensitiveData) return filteredValue;\n\n      for (const [key, val] of Object.entries(this.sensitiveData)) {\n        filteredValue = filteredValue.replace(val, `<secret>${key}</secret>`);\n      }\n      return filteredValue;\n    };\n\n    if (typeof message.content === 'string') {\n      message.content = replaceSensitive(message.content);\n    } else if (Array.isArray(message.content)) {\n      message.content = message.content.map((item) => {\n        if (typeof item === 'object' && 'text' in item) {\n          return { ...item, text: replaceSensitive(item.text) };\n        }\n        return item;\n      });\n    }\n\n    return message;\n  }\n\n  /**\n   * Counts the tokens in the message\n   * @param message - The BaseMessage object to count the tokens\n   * @returns The number of tokens in the message\n   */\n  private _countTokens(message: BaseMessage): number {\n    let tokens = 0;\n\n    if (Array.isArray(message.content)) {\n      for (const item of message.content) {\n        if ('image_url' in item) {\n          tokens += this.IMG_TOKENS;\n        } else if (typeof item === 'object' && 'text' in item) {\n          tokens += this._countTextTokens(item.text);\n        }\n      }\n    } else {\n      let msg = message.content;\n      // Check if it's an AIMessage with tool_calls\n      if ('tool_calls' in message) {\n        msg += JSON.stringify(message.tool_calls);\n      }\n      tokens += this._countTextTokens(msg);\n    }\n\n    return tokens;\n  }\n\n  /**\n   * Counts the tokens in the text\n   * Rough estimate, no tokenizer provided for now\n   * @param text - The text to count the tokens\n   * @returns The number of tokens in the text\n   */\n  private _countTextTokens(text: string): number {\n    return Math.floor(text.length / this.estimatedCharactersPerToken);\n  }\n\n  /**\n   * Cuts the last message if the total tokens exceed the max input tokens\n   *\n   * Get current message list, potentially trimmed to max tokens\n   */\n  public cutMessages(): void {\n    let diff = this.history.totalTokens - this.maxInputTokens;\n    if (diff <= 0) return;\n\n    const lastMsg = this.history.messages[this.history.messages.length - 1];\n\n    // if list with image remove image\n    if (Array.isArray(lastMsg.message.content)) {\n      let text = '';\n      lastMsg.message.content = lastMsg.message.content.filter((item) => {\n        if ('image_url' in item) {\n          diff -= this.IMG_TOKENS;\n          lastMsg.metadata.inputTokens -= this.IMG_TOKENS;\n          this.history.totalTokens -= this.IMG_TOKENS;\n          logger.debug(\n            `Removed image with ${this.IMG_TOKENS} tokens - total tokens now: ${this.history.totalTokens}/${this.maxInputTokens}`,\n          );\n          return false;\n        }\n        if ('text' in item) {\n          text += item.text;\n        }\n        return true;\n      });\n      lastMsg.message.content = text;\n      this.history.messages[this.history.messages.length - 1] = lastMsg;\n    }\n\n    if (diff <= 0) return;\n\n    // if still over, remove text from state message proportionally to the number of tokens needed with buffer\n    // Calculate the proportion of content to remove\n    const proportionToRemove = diff / lastMsg.metadata.inputTokens;\n    if (proportionToRemove > 0.99) {\n      throw new Error(\n        `Max token limit reached - history is too long - reduce the system prompt or task. proportion_to_remove: ${proportionToRemove}`,\n      );\n    }\n    logger.debug(\n      `Removing ${(proportionToRemove * 100).toFixed(2)}% of the last message (${(proportionToRemove * lastMsg.metadata.inputTokens).toFixed(2)} / ${lastMsg.metadata.inputTokens.toFixed(2)} tokens)`,\n    );\n\n    const content = lastMsg.message.content as string;\n    const charactersToRemove = Math.floor(content.length * proportionToRemove);\n    const newContent = content.slice(0, -charactersToRemove);\n\n    this.history.removeMessage(-1);\n\n    const msg = new HumanMessage({ content: newContent });\n    this.addMessageWithTokens(msg);\n\n    const finalMsg = this.history.messages[this.history.messages.length - 1];\n    logger.debug(\n      `Added message with ${finalMsg.metadata.inputTokens} tokens - total tokens now: ${this.history.totalTokens}/${this.maxInputTokens} - total messages: ${this.history.messages.length}`,\n    );\n  }\n\n  /**\n   * Converts messages for non-function-calling models\n   * @param inputMessages - The BaseMessage objects to convert\n   * @returns The converted BaseMessage objects\n   */\n  public convertMessagesForNonFunctionCallingModels(\n    inputMessages: BaseMessage[],\n  ): BaseMessage[] {\n    return inputMessages.map((message) => {\n      if (message instanceof HumanMessage || message instanceof SystemMessage) {\n        return message;\n      }\n      if (message instanceof ToolMessage) {\n        return new HumanMessage({ content: message.content });\n      }\n      if (message instanceof AIMessage) {\n        // if it's an AIMessage with tool_calls, convert it to a normal AIMessage\n        if ('tool_calls' in message) {\n          const toolCalls = JSON.stringify(message.tool_calls);\n          return new AIMessage({ content: toolCalls });\n        }\n        return message;\n      }\n      throw new Error(`Unknown message type: ${message.constructor.name}`);\n    });\n  }\n\n  /**\n   * Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one.\"\n   * @param messages - The BaseMessage objects to merge\n   * @param classToMerge - The class of the messages to merge\n   * @returns The merged BaseMessage objects\n   */\n  public mergeSuccessiveMessages(\n    messages: BaseMessage[],\n    classToMerge: typeof BaseMessage,\n  ): BaseMessage[] {\n    const mergedMessages: BaseMessage[] = [];\n    let streak = 0;\n\n    for (const message of messages) {\n      if (message instanceof classToMerge) {\n        streak += 1;\n        if (streak > 1) {\n          const lastMessage = mergedMessages[mergedMessages.length - 1];\n          if (Array.isArray(message.content)) {\n            const firstContent = message.content[0];\n            if ('text' in firstContent) {\n              lastMessage.content += firstContent.text;\n            }\n          } else {\n            lastMessage.content += message.content;\n          }\n        } else {\n          mergedMessages.push(message);\n        }\n      } else {\n        mergedMessages.push(message);\n        streak = 0;\n      }\n    }\n\n    return mergedMessages;\n  }\n}\n"],"names":["logger","createLogger","MessageManager","systemMessage","task","messageContext","contextMessage","HumanMessage","taskMessage","info","Object","infoMessage","placeholderMessage","toolCallId","toolCalls","zodToJsonSchema","z","String","exampleToolCall","AIMessage","toolMessage","ToolMessage","historyStartMessage","id","content","newTask","msg","plan","position","stateMessage","messages","m","message","filteredMessage","tokenCount","metadata","replaceSensitive","value","filteredValue","key","val","Array","item","tokens","JSON","text","Math","diff","lastMsg","proportionToRemove","Error","charactersToRemove","newContent","finalMsg","inputMessages","SystemMessage","classToMerge","mergedMessages","streak","lastMessage","firstContent","maxInputTokens","estimatedCharactersPerToken","imageTokens","sensitiveData","MessageHistory"],"mappings":";;;;;;;;;AAOC;;;;;;;;;;AAkBD,MAAMA,SAASC,aAAa;AAEb,MAAMC;IA2BZ,iBACLC,aAA4B,EAC5BC,IAAY,EACZC,cAAuB,EACjB;QAEN,IAAI,CAAC,oBAAoB,CAACF;QAG1B,IAAIE,kBAAkBA,eAAe,MAAM,GAAG,GAAG;YAC/C,MAAMC,iBAAiB,IAAIC,aAAa;gBACtC,SAAS,CAAC,sBAAsB,EAAEF,gBAAgB;YACpD;YACA,IAAI,CAAC,oBAAoB,CAACC;QAC5B;QAGA,MAAME,cAAcN,eAAe,gBAAgB,CAACE;QACpD,IAAI,CAAC,oBAAoB,CAACI;QAG1B,IAAI,IAAI,CAAC,aAAa,EAAE;YACtB,MAAMC,OAAO,CAAC,0CAA0C,EAAEC,OAAO,IAAI,CAAC,IAAI,CAAC,aAAa,GAAG;YAC3F,MAAMC,cAAc,IAAIJ,aAAa;gBACnC,SAAS,GAAGE,KAAK,0DAA0D,CAAC;YAC9E;YACA,IAAI,CAAC,oBAAoB,CAACE;QAC5B;QAGA,MAAMC,qBAAqB,IAAIL,aAAa;YAC1C,SAAS;QACX;QACA,IAAI,CAAC,oBAAoB,CAACK;QAE1B,MAAMC,aAAa,IAAI,CAAC,UAAU;QAClC,MAAMC,YAAwB;YAC5B;gBACE,MAAM;gBAEN,aAAa;gBACb,YAAYC,gBAEVC,EAAE,MAAM,CAAC;oBACP,eAAeA,EAAE,MAAM,CAAC;wBACtB,cAAcA,EAAE,MAAM;wBACtB,0BAA0BA,EAAE,MAAM;wBAClC,QAAQA,EAAE,MAAM;wBAChB,WAAWA,EAAE,MAAM;oBACrB;oBACA,QAAQA,EAAE,KAAK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