{"version":3,"file":"index.cjs","names":["isAsyncGeneratorFunction","isGeneratorFunction","call","getRunnableForEntrypoint","RunnableCallable","PregelNode","START","ChannelWrite","END","PASSTHROUGH","PREVIOUS","TAG_HIDDEN","Pregel","EphemeralValue","LastValue","AsyncLocalStorageProviderSingleton","CONFIG_KEY_PREVIOUS_STATE"],"sources":["../../src/func/index.ts"],"sourcesContent":["import {\n  BaseCache,\n  BaseCheckpointSaver,\n  BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport {\n  CONFIG_KEY_PREVIOUS_STATE,\n  END,\n  PREVIOUS,\n  START,\n  TAG_HIDDEN,\n} from \"../constants.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport type { CachePolicy, RetryPolicy } from \"../pregel/utils/index.js\";\nimport { LastValue } from \"../channels/last_value.js\";\nimport {\n  EntrypointFinal,\n  EntrypointReturnT,\n  EntrypointFinalSaveT,\n  EntrypointFunc,\n  TaskFunc,\n} from \"./types.js\";\nimport { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport {\n  RunnableCallable,\n  isAsyncGeneratorFunction,\n  isGeneratorFunction,\n} from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\n\n/**\n * Options for the {@link task} function\n */\nexport interface TaskOptions {\n  /**\n   * The name of the task, analogous to the node name in {@link StateGraph}.\n   */\n  name: string;\n  /**\n   * The retry policy for the task. Configures how many times and under what conditions\n   * the task should be retried if it fails.\n   */\n  retry?: RetryPolicy;\n\n  /**\n   * The cache policy for the task. Configures how the task should be cached.\n   */\n  cachePolicy?: CachePolicy;\n}\n\n/**\n * Define a LangGraph task using the `task` function.\n *\n * Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n * A task can be called like a regular function with the following differences:\n *\n * - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n * - The wrapped function can only be called from within an entrypoint or StateGraph.\n * - Calling the function produces a promise. This makes it easy to parallelize tasks.\n *\n * @typeParam ArgsT - The type of arguments the task function accepts\n * @typeParam OutputT - The type of value the task function returns\n * @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n * @param func - The function that executes this task\n * @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n *\n * @example basic example\n * ```typescript\n * const addOne = task(\"add\", async (a: number) => a + 1);\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n *   const promises = numbers.map(n => addOne(n));\n *   const results = await Promise.all(promises);\n *   return results;\n * });\n *\n * // Call the entrypoint\n * await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n * ```\n *\n * @example using a retry policy\n * ```typescript\n * const addOne = task({\n *     name: \"add\",\n *     retry: { maxAttempts: 3 }\n *   },\n *   async (a: number) => a + 1\n * );\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n *   const promises = numbers.map(n => addOne(n));\n *   const results = await Promise.all(promises);\n *   return results;\n * });\n * ```\n * @category Functional API\n */\nexport function task<ArgsT extends unknown[], OutputT>(\n  optionsOrName: TaskOptions | string,\n  func: TaskFunc<ArgsT, OutputT>\n): (...args: ArgsT) => Promise<OutputT> {\n  const options =\n    typeof optionsOrName === \"string\"\n      ? { name: optionsOrName, retry: undefined, cachePolicy: undefined }\n      : optionsOrName;\n\n  const { name, retry } = options;\n  if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n    throw new Error(\n      \"Generators are disallowed as tasks. For streaming responses, use config.write.\"\n    );\n  }\n\n  const cachePolicy =\n    options.cachePolicy ??\n    // `cache` was mistakingly used as an alias for `cachePolicy` in v0.3.x,\n    // TODO: remove in 1.x\n    (\"cache\" in options ? (options.cache as CachePolicy) : undefined);\n\n  let cache: CachePolicy | undefined;\n  if (typeof cachePolicy === \"boolean\") {\n    cache = cachePolicy ? {} : undefined;\n  } else {\n    cache = cachePolicy;\n  }\n\n  return (...args: ArgsT) => {\n    return call({ func, name, retry, cache }, ...args);\n  };\n}\n\n/**\n * Options for the {@link entrypoint} function\n */\nexport type EntrypointOptions = {\n  /**\n   * The name of the {@link entrypoint}, analogous to the node name in {@link StateGraph}.\n   * This name is used for logging, debugging, and checkpoint identification.\n   */\n  name: string;\n  /**\n   * The checkpointer for the {@link entrypoint}. Used to save and restore state between\n   * invocations of the workflow.\n   */\n  checkpointer?: BaseCheckpointSaver;\n  /**\n   * The store for the {@link entrypoint}. Used to persist data across workflow runs.\n   */\n  store?: BaseStore;\n\n  /**\n   * The cache for the {@link entrypoint}. Used to cache values between workflow runs.\n   */\n  cache?: BaseCache;\n};\n\n/**\n * Type declaration for the entrypoint function with its properties\n * @category Functional API\n */\nexport interface EntrypointFunction {\n  <InputT, OutputT>(\n    optionsOrName: EntrypointOptions | string,\n    func: EntrypointFunc<InputT, OutputT>\n  ): Pregel<\n    Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>,\n    {\n      [START]: EphemeralValue<InputT>;\n      [END]: LastValue<EntrypointReturnT<OutputT>>;\n      [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n    },\n    Record<string, unknown>,\n    InputT,\n    EntrypointReturnT<OutputT>,\n    // Because the update type is an return type union of tasks + entrypoint,\n    // thus we can't type it properly.\n    any, // eslint-disable-line @typescript-eslint/no-explicit-any\n    Awaited<EntrypointReturnT<OutputT>>\n  >;\n\n  /**\n   * A helper utility for use with the functional API that returns a value to the caller,\n   * as well as a separate state value to persist to the checkpoint. This allows workflows\n   * to maintain state between runs while returning different values to the caller.\n   *\n   * @typeParam ValueT - The type of the value to return to the caller\n   * @typeParam SaveT - The type of the state to save to the checkpoint\n   * @param options.value - The value to return to the caller\n   * @param options.save - The value to save to the checkpoint\n   * @returns An object with the value and save properties\n   *\n   * @example\n   * ```typescript\n   * return entrypoint.final({\n   *   value: \"result for caller\",\n   *   save: { counter: currentCount + 1 }\n   * });\n   * ```\n   */\n  final<ValueT, SaveT>(options: {\n    value?: ValueT;\n    save?: SaveT;\n  }): EntrypointFinal<ValueT, SaveT>;\n}\n\n/**\n * Define a LangGraph workflow using the `entrypoint` function.\n *\n * ### Function signature\n *\n * The wrapped function must accept at most **two parameters**. The first parameter\n * is the input to the function. The second (optional) parameter is a\n * {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n * the function, you can pass them as an object.\n *\n * ### Helper functions\n *\n * #### Streaming\n * To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n * {@link LangGraphRunnableConfig.writer} property.\n *\n * #### State management\n * The {@link getPreviousState} function can be used to access the previous state\n * that was returned from the last invocation of the entrypoint on the same thread id.\n *\n * If you wish to save state other than the return value, you can use the\n * {@link entrypoint.final} function.\n *\n * @typeParam InputT - The type of input the entrypoint accepts\n * @typeParam OutputT - The type of output the entrypoint produces\n * @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n * @param func - The function that executes this entrypoint\n * @returns A {@link Pregel} instance that can be run to execute the workflow\n *\n * @example Using entrypoint and tasks\n * ```typescript\n * import { task, entrypoint } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n * import { interrupt, Command } from \"@langchain/langgraph\";\n *\n * const composeEssay = task(\"compose\", async (topic: string) => {\n *   await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n *   return `An essay about ${topic}`;\n * });\n *\n * const reviewWorkflow = entrypoint({\n *   name: \"review\",\n *   checkpointer: new MemorySaver()\n * }, async (topic: string) => {\n *   const essay = await composeEssay(topic);\n *   const humanReview = await interrupt({\n *     question: \"Please provide a review\",\n *     essay\n *   });\n *   return {\n *     essay,\n *     review: humanReview\n *   };\n * });\n *\n * // Example configuration for the workflow\n * const config = {\n *   configurable: {\n *     thread_id: \"some_thread\"\n *   }\n * };\n *\n * // Topic for the essay\n * const topic = \"cats\";\n *\n * // Stream the workflow to generate the essay and await human review\n * for await (const result of reviewWorkflow.stream(topic, config)) {\n *   console.log(result);\n * }\n *\n * // Example human review provided after the interrupt\n * const humanReview = \"This essay is great.\";\n *\n * // Resume the workflow with the provided human review\n * for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n *   console.log(result);\n * }\n * ```\n *\n * @example Accessing the previous return value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const accumulator = entrypoint({\n *   name: \"accumulator\",\n *   checkpointer: new MemorySaver()\n * }, async (input: string) => {\n *   const previous = getPreviousState<number>();\n *   return previous !== undefined ? `${previous } ${input}` : input;\n * });\n *\n * const config = {\n *   configurable: {\n *     thread_id: \"some_thread\"\n *   }\n * };\n * await accumulator.invoke(\"hello\", config); // returns \"hello\"\n * await accumulator.invoke(\"world\", config); // returns \"hello world\"\n * ```\n *\n * @example Using entrypoint.final to save a value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const myWorkflow = entrypoint({\n *   name: \"accumulator\",\n *   checkpointer: new MemorySaver()\n * }, async (num: number) => {\n *   const previous = getPreviousState<number>();\n *\n *   // This will return the previous value to the caller, saving\n *   // 2 * num to the checkpoint, which will be used in the next invocation\n *   // for the `previous` parameter.\n *   return entrypoint.final({\n *     value: previous ?? 0,\n *     save: 2 * num\n *   });\n * });\n *\n * const config = {\n *   configurable: {\n *     thread_id: \"some_thread\"\n *   }\n * };\n *\n * await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n * await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n * ```\n * @category Functional API\n */\nexport const entrypoint = function entrypoint<InputT, OutputT>(\n  optionsOrName: EntrypointOptions | string,\n  func: EntrypointFunc<InputT, OutputT>\n) {\n  const { name, checkpointer, store, cache } =\n    typeof optionsOrName === \"string\"\n      ? { name: optionsOrName, checkpointer: undefined, store: undefined }\n      : optionsOrName;\n  if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n    throw new Error(\n      \"Generators are disallowed as entrypoints. For streaming responses, use config.write.\"\n    );\n  }\n  const streamMode = \"updates\";\n  const bound = getRunnableForEntrypoint(name, func);\n\n  // Helper to check if a value is an EntrypointFinal\n  function isEntrypointFinal(\n    value: unknown\n  ): value is EntrypointFinal<unknown, unknown> {\n    return (\n      typeof value === \"object\" &&\n      value !== null &&\n      \"__lg_type\" in value &&\n      value.__lg_type === \"__pregel_final\"\n    );\n  }\n\n  // Helper function to pluck the return value from EntrypointFinal or passthrough\n  const pluckReturnValue = new RunnableCallable({\n    name: \"pluckReturnValue\",\n    func: (value: unknown) => {\n      return isEntrypointFinal(value) ? value.value : value;\n    },\n  });\n\n  // Helper function to pluck the save value from EntrypointFinal or passthrough\n  const pluckSaveValue = new RunnableCallable({\n    name: \"pluckSaveValue\",\n    func: (value: unknown) => {\n      return isEntrypointFinal(value) ? value.save : value;\n    },\n  });\n\n  const entrypointNode = new PregelNode<InputT, EntrypointReturnT<OutputT>>({\n    bound,\n    triggers: [START],\n    channels: [START],\n    writers: [\n      new ChannelWrite(\n        [\n          { channel: END, value: PASSTHROUGH, mapper: pluckReturnValue },\n          { channel: PREVIOUS, value: PASSTHROUGH, mapper: pluckSaveValue },\n        ],\n        [TAG_HIDDEN]\n      ),\n    ],\n  });\n\n  return new Pregel<\n    Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, // node types\n    {\n      [START]: EphemeralValue<InputT>;\n      [END]: LastValue<EntrypointReturnT<OutputT>>;\n      [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n    }, // channel types\n    Record<string, unknown>, // configurable types\n    InputT, // input type\n    EntrypointReturnT<OutputT> // output type\n  >({\n    name,\n    checkpointer,\n    nodes: {\n      [name]: entrypointNode,\n    },\n    channels: {\n      [START]: new EphemeralValue<InputT>(),\n      [END]: new LastValue<EntrypointReturnT<OutputT>>(),\n      [PREVIOUS]: new LastValue<EntrypointFinalSaveT<OutputT>>(),\n    },\n    inputChannels: START,\n    outputChannels: END,\n    streamChannels: END,\n    streamMode,\n    store,\n    cache,\n  });\n} as EntrypointFunction;\n\n// documented by the EntrypointFunction interface\nentrypoint.final = function final<ValueT, SaveT>({\n  value,\n  save,\n}: {\n  value?: ValueT;\n  save?: SaveT;\n}): EntrypointFinal<ValueT, SaveT> {\n  return { value, save, __lg_type: \"__pregel_final\" };\n};\n\n/**\n * A helper utility function for use with the functional API that returns the previous\n * state from the checkpoint from the last invocation of the current thread.\n *\n * This function allows workflows to access state that was saved in previous runs\n * using {@link entrypoint.final}.\n *\n * @typeParam StateT - The type of the state that was previously saved\n * @returns The previous saved state from the last invocation of the current thread\n *\n * @example\n * ```typescript\n * const previousState = getPreviousState<{ counter: number }>();\n * const newCount = (previousState?.counter ?? 0) + 1;\n * ```\n * @category Functional API\n */\nexport function getPreviousState<StateT>(): StateT {\n  const config: LangGraphRunnableConfig =\n    AsyncLocalStorageProviderSingleton.getRunnableConfig();\n  return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE] as StateT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,KACd,eACA,MACsC;CACtC,MAAM,UACJ,OAAO,kBAAkB,WACrB;EAAE,MAAM;EAAe,OAAO,KAAA;EAAW,aAAa,KAAA;EAAW,GACjE;CAEN,MAAM,EAAE,MAAM,UAAU;AACxB,KAAIA,cAAAA,yBAAyB,KAAK,IAAIC,cAAAA,oBAAoB,KAAK,CAC7D,OAAM,IAAI,MACR,iFACD;CAGH,MAAM,cACJ,QAAQ,gBAGP,WAAW,UAAW,QAAQ,QAAwB,KAAA;CAEzD,IAAI;AACJ,KAAI,OAAO,gBAAgB,UACzB,SAAQ,cAAc,EAAE,GAAG,KAAA;KAE3B,SAAQ;AAGV,SAAQ,GAAG,SAAg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