{"version":3,"file":"message.cjs","names":["coerceMessageLikeToMessage","removeAllIdx: number | undefined","StateGraph","ensureLangGraphConfig","stateKey: string | undefined"],"sources":["../../src/graph/message.ts"],"sourcesContent":["import {\n  BaseMessage,\n  BaseMessageLike,\n  coerceMessageLikeToMessage,\n} from \"@langchain/core/messages\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { v4 } from \"uuid\";\nimport { StateGraph } from \"./state.js\";\nimport { ensureLangGraphConfig } from \"../pregel/utils/config.js\";\nimport type { StreamMessagesHandler } from \"../pregel/messages.js\";\n\nexport const REMOVE_ALL_MESSAGES = \"__remove_all__\";\n\nexport type Messages =\n  | Array<BaseMessage | BaseMessageLike>\n  | BaseMessage\n  | BaseMessageLike;\n\n/**\n * Prebuilt reducer that combines returned messages.\n * Can handle standard messages and special modifiers like {@link RemoveMessage}\n * instances.\n */\nexport function messagesStateReducer(\n  left: Messages,\n  right: Messages\n): BaseMessage[] {\n  const leftArray = Array.isArray(left) ? left : [left];\n  const rightArray = Array.isArray(right) ? right : [right];\n  // coerce to message\n  const leftMessages = (leftArray as BaseMessageLike[]).map(\n    coerceMessageLikeToMessage\n  );\n  const rightMessages = (rightArray as BaseMessageLike[]).map(\n    coerceMessageLikeToMessage\n  );\n  // assign missing ids\n  for (const m of leftMessages) {\n    if (m.id === null || m.id === undefined) {\n      m.id = v4();\n      m.lc_kwargs.id = m.id;\n    }\n  }\n\n  let removeAllIdx: number | undefined;\n  for (let i = 0; i < rightMessages.length; i += 1) {\n    const m = rightMessages[i];\n    if (m.id === null || m.id === undefined) {\n      m.id = v4();\n      m.lc_kwargs.id = m.id;\n    }\n\n    if (m.getType() === \"remove\" && m.id === REMOVE_ALL_MESSAGES) {\n      removeAllIdx = i;\n    }\n  }\n\n  if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1);\n\n  // merge\n  const merged = [...leftMessages];\n  const mergedById = new Map(merged.map((m, i) => [m.id, i]));\n  const idsToRemove = new Set();\n  for (const m of rightMessages) {\n    const existingIdx = mergedById.get(m.id);\n    if (existingIdx !== undefined) {\n      if (m.getType() === \"remove\") {\n        idsToRemove.add(m.id);\n      } else {\n        idsToRemove.delete(m.id);\n        merged[existingIdx] = m;\n      }\n    } else {\n      if (m.getType() === \"remove\") {\n        throw new Error(\n          `Attempting to delete a message with an ID that doesn't exist ('${m.id}')`\n        );\n      }\n      mergedById.set(m.id, merged.length);\n      merged.push(m);\n    }\n  }\n  return merged.filter((m) => !idsToRemove.has(m.id));\n}\n\n/** @ignore */\nexport class MessageGraph extends StateGraph<\n  BaseMessage[],\n  BaseMessage[],\n  Messages\n> {\n  constructor() {\n    super({\n      channels: {\n        __root__: {\n          reducer: messagesStateReducer,\n          default: () => [],\n        },\n      },\n    });\n  }\n}\n\n/**\n * Manually push a message to a message stream.\n *\n * This is useful when you need to push a manually created message before the node\n * has finished executing.\n *\n * When a message is pushed, it will be automatically persisted to the state after the node has finished executing.\n * To disable persisting, set `options.stateKey` to `null`.\n *\n * @param message The message to push. The message must have an ID set, otherwise an error will be thrown.\n * @param options RunnableConfig / Runtime coming from node context.\n */\nexport function pushMessage(\n  message: BaseMessage | BaseMessageLike,\n  options?: RunnableConfig & {\n    /**\n     * The key of the state to push the message to. Set to `null` to avoid persisting.\n     * @default \"messages\"\n     */\n    stateKey?: string | null;\n  }\n) {\n  const { stateKey: userStateKey, ...userConfig } = options ?? {};\n  const config = ensureLangGraphConfig(userConfig);\n\n  let stateKey: string | undefined = userStateKey ?? \"messages\";\n  if (userStateKey === null) stateKey = undefined;\n\n  // coerce to message\n  const validMessage = coerceMessageLikeToMessage(message);\n  if (!validMessage.id) throw new Error(\"Message ID is required.\");\n\n  const callbacks = (() => {\n    if (Array.isArray(config.callbacks)) {\n      return config.callbacks;\n    }\n\n    if (typeof config.callbacks !== \"undefined\") {\n      return config.callbacks.handlers;\n    }\n\n    return [];\n  })();\n\n  const messagesHandler = callbacks.find(\n    (cb): cb is StreamMessagesHandler =>\n      \"name\" in cb && cb.name === \"StreamMessagesHandler\"\n  );\n\n  if (messagesHandler) {\n    const metadata = config.metadata ?? {};\n    const namespace = (\n      (metadata.langgraph_checkpoint_ns ?? \"\") as string\n    ).split(\"|\");\n\n    messagesHandler._emit(\n      [namespace, metadata],\n      validMessage,\n      undefined,\n      false\n    );\n  }\n\n  if (stateKey) {\n    config.configurable?.__pregel_send?.([[stateKey, validMessage]]);\n  }\n\n  return validMessage;\n}\n"],"mappings":";;;;;;;AAWA,MAAa,sBAAsB;;;;;;AAYnC,SAAgB,qBACd,MACA,OACe;CACf,MAAM,YAAY,MAAM,QAAQ,QAAQ,OAAO,CAAC;CAChD,MAAM,aAAa,MAAM,QAAQ,SAAS,QAAQ,CAAC;CAEnD,MAAM,eAAgB,UAAgC,IACpDA;CAEF,MAAM,gBAAiB,WAAiC,IACtDA;AAGF,MAAK,MAAM,KAAK,aACd,KAAI,EAAE,OAAO,QAAQ,EAAE,OAAO,QAAW;AACvC,IAAE;AACF,IAAE,UAAU,KAAK,EAAE;;CAIvB,IAAIC;AACJ,MAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK,GAAG;EAChD,MAAM,IAAI,cAAc;AACxB,MAAI,EAAE,OAAO,QAAQ,EAAE,OAAO,QAAW;AACvC,KAAE;AACF,KAAE,UAAU,KAAK,EAAE;;AAGrB,MAAI,EAAE,cAAc,YAAY,EAAE,OAAO,oBACvC,gBAAe;;AAInB,KAAI,gBAAgB,KAAM,QAAO,cAAc,MAAM,eAAe;CAGpE,MAAM,SAAS,CAAC,GAAG;CACnB,MAAM,aAAa,IAAI,IAAI,OAAO,KAAK,GAAG,MAAM,CAAC,EAAE,IAAI;CACvD,MAAM,8BAAc,IAAI;AACxB,MAAK,MAAM,KAAK,eAAe;EAC7B,MAAM,cAAc,WAAW,IAAI,EAAE;AACrC,MAAI,gBAAgB,OAClB,KAAI,EAAE,cAAc,SAClB,aAAY,IAAI,EAAE;OACb;AACL,eAAY,OAAO,EAAE;AACrB,UAAO,eA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