illuma-agents 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/LICENSE +25 -21
  2. package/dist/cjs/agents/AgentContext.cjs +222 -0
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -0
  4. package/dist/cjs/common/enum.cjs +7 -6
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/events.cjs +7 -5
  7. package/dist/cjs/events.cjs.map +1 -1
  8. package/dist/cjs/graphs/Graph.cjs +328 -207
  9. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  10. package/dist/cjs/graphs/MultiAgentGraph.cjs +507 -0
  11. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -0
  12. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  13. package/dist/cjs/llm/google/index.cjs.map +1 -1
  14. package/dist/cjs/llm/ollama/index.cjs.map +1 -1
  15. package/dist/cjs/llm/openai/index.cjs +35 -0
  16. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/utils/index.cjs +3 -1
  18. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  19. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  20. package/dist/cjs/llm/providers.cjs +0 -2
  21. package/dist/cjs/llm/providers.cjs.map +1 -1
  22. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  23. package/dist/cjs/main.cjs +12 -1
  24. package/dist/cjs/main.cjs.map +1 -1
  25. package/dist/cjs/messages/cache.cjs +123 -0
  26. package/dist/cjs/messages/cache.cjs.map +1 -0
  27. package/dist/cjs/messages/content.cjs +53 -0
  28. package/dist/cjs/messages/content.cjs.map +1 -0
  29. package/dist/cjs/messages/format.cjs +17 -29
  30. package/dist/cjs/messages/format.cjs.map +1 -1
  31. package/dist/cjs/run.cjs +119 -74
  32. package/dist/cjs/run.cjs.map +1 -1
  33. package/dist/cjs/stream.cjs +77 -73
  34. package/dist/cjs/stream.cjs.map +1 -1
  35. package/dist/cjs/tools/Calculator.cjs +45 -0
  36. package/dist/cjs/tools/Calculator.cjs.map +1 -0
  37. package/dist/cjs/tools/CodeExecutor.cjs +22 -22
  38. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  39. package/dist/cjs/tools/ToolNode.cjs +5 -3
  40. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  41. package/dist/cjs/tools/handlers.cjs +20 -20
  42. package/dist/cjs/tools/handlers.cjs.map +1 -1
  43. package/dist/cjs/utils/events.cjs +31 -0
  44. package/dist/cjs/utils/events.cjs.map +1 -0
  45. package/dist/cjs/utils/handlers.cjs +70 -0
  46. package/dist/cjs/utils/handlers.cjs.map +1 -0
  47. package/dist/cjs/utils/tokens.cjs +54 -7
  48. package/dist/cjs/utils/tokens.cjs.map +1 -1
  49. package/dist/esm/agents/AgentContext.mjs +220 -0
  50. package/dist/esm/agents/AgentContext.mjs.map +1 -0
  51. package/dist/esm/common/enum.mjs +7 -6
  52. package/dist/esm/common/enum.mjs.map +1 -1
  53. package/dist/esm/events.mjs +7 -5
  54. package/dist/esm/events.mjs.map +1 -1
  55. package/dist/esm/graphs/Graph.mjs +330 -209
  56. package/dist/esm/graphs/Graph.mjs.map +1 -1
  57. package/dist/esm/graphs/MultiAgentGraph.mjs +505 -0
  58. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -0
  59. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  60. package/dist/esm/llm/google/index.mjs.map +1 -1
  61. package/dist/esm/llm/ollama/index.mjs.map +1 -1
  62. package/dist/esm/llm/openai/index.mjs +35 -0
  63. package/dist/esm/llm/openai/index.mjs.map +1 -1
  64. package/dist/esm/llm/openai/utils/index.mjs +3 -1
  65. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  66. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  67. package/dist/esm/llm/providers.mjs +0 -2
  68. package/dist/esm/llm/providers.mjs.map +1 -1
  69. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  70. package/dist/esm/main.mjs +7 -2
  71. package/dist/esm/main.mjs.map +1 -1
  72. package/dist/esm/messages/cache.mjs +120 -0
  73. package/dist/esm/messages/cache.mjs.map +1 -0
  74. package/dist/esm/messages/content.mjs +51 -0
  75. package/dist/esm/messages/content.mjs.map +1 -0
  76. package/dist/esm/messages/format.mjs +18 -29
  77. package/dist/esm/messages/format.mjs.map +1 -1
  78. package/dist/esm/run.mjs +119 -74
  79. package/dist/esm/run.mjs.map +1 -1
  80. package/dist/esm/stream.mjs +77 -73
  81. package/dist/esm/stream.mjs.map +1 -1
  82. package/dist/esm/tools/Calculator.mjs +24 -0
  83. package/dist/esm/tools/Calculator.mjs.map +1 -0
  84. package/dist/esm/tools/CodeExecutor.mjs +22 -22
  85. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  86. package/dist/esm/tools/ToolNode.mjs +5 -3
  87. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  88. package/dist/esm/tools/handlers.mjs +20 -20
  89. package/dist/esm/tools/handlers.mjs.map +1 -1
  90. package/dist/esm/utils/events.mjs +29 -0
  91. package/dist/esm/utils/events.mjs.map +1 -0
  92. package/dist/esm/utils/handlers.mjs +68 -0
  93. package/dist/esm/utils/handlers.mjs.map +1 -0
  94. package/dist/esm/utils/tokens.mjs +54 -8
  95. package/dist/esm/utils/tokens.mjs.map +1 -1
  96. package/dist/types/agents/AgentContext.d.ts +94 -0
  97. package/dist/types/common/enum.d.ts +9 -7
  98. package/dist/types/events.d.ts +3 -3
  99. package/dist/types/graphs/Graph.d.ts +60 -66
  100. package/dist/types/graphs/MultiAgentGraph.d.ts +47 -0
  101. package/dist/types/graphs/index.d.ts +1 -0
  102. package/dist/types/index.d.ts +1 -0
  103. package/dist/types/llm/openai/index.d.ts +10 -0
  104. package/dist/types/messages/cache.d.ts +20 -0
  105. package/dist/types/messages/content.d.ts +7 -0
  106. package/dist/types/messages/format.d.ts +1 -7
  107. package/dist/types/messages/index.d.ts +2 -0
  108. package/dist/types/messages/reducer.d.ts +9 -0
  109. package/dist/types/run.d.ts +16 -10
  110. package/dist/types/stream.d.ts +4 -3
  111. package/dist/types/tools/Calculator.d.ts +8 -0
  112. package/dist/types/tools/ToolNode.d.ts +1 -1
  113. package/dist/types/tools/handlers.d.ts +9 -7
  114. package/dist/types/tools/search/tool.d.ts +4 -4
  115. package/dist/types/types/graph.d.ts +124 -11
  116. package/dist/types/types/llm.d.ts +13 -9
  117. package/dist/types/types/messages.d.ts +4 -0
  118. package/dist/types/types/run.d.ts +46 -8
  119. package/dist/types/types/stream.d.ts +3 -2
  120. package/dist/types/utils/events.d.ts +6 -0
  121. package/dist/types/utils/handlers.d.ts +34 -0
  122. package/dist/types/utils/index.d.ts +1 -0
  123. package/dist/types/utils/tokens.d.ts +24 -0
  124. package/package.json +162 -145
  125. package/src/agents/AgentContext.ts +323 -0
  126. package/src/common/enum.ts +177 -176
  127. package/src/events.ts +197 -191
  128. package/src/graphs/Graph.ts +1058 -846
  129. package/src/graphs/MultiAgentGraph.ts +598 -0
  130. package/src/graphs/index.ts +2 -1
  131. package/src/index.ts +25 -24
  132. package/src/llm/anthropic/index.ts +413 -413
  133. package/src/llm/google/index.ts +222 -222
  134. package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -88
  135. package/src/llm/ollama/index.ts +92 -92
  136. package/src/llm/openai/index.ts +894 -853
  137. package/src/llm/openai/utils/index.ts +920 -918
  138. package/src/llm/openrouter/index.ts +60 -60
  139. package/src/llm/providers.ts +55 -57
  140. package/src/llm/vertexai/index.ts +360 -360
  141. package/src/messages/cache.test.ts +461 -0
  142. package/src/messages/cache.ts +151 -0
  143. package/src/messages/content.test.ts +362 -0
  144. package/src/messages/content.ts +63 -0
  145. package/src/messages/format.ts +611 -625
  146. package/src/messages/formatAgentMessages.test.ts +1144 -917
  147. package/src/messages/index.ts +6 -4
  148. package/src/messages/reducer.ts +80 -0
  149. package/src/run.ts +447 -381
  150. package/src/scripts/abort.ts +157 -138
  151. package/src/scripts/ant_web_search.ts +158 -158
  152. package/src/scripts/cli.ts +172 -167
  153. package/src/scripts/cli2.ts +133 -125
  154. package/src/scripts/cli3.ts +184 -178
  155. package/src/scripts/cli4.ts +191 -184
  156. package/src/scripts/cli5.ts +191 -184
  157. package/src/scripts/code_exec.ts +213 -214
  158. package/src/scripts/code_exec_simple.ts +147 -129
  159. package/src/scripts/content.ts +138 -120
  160. package/src/scripts/handoff-test.ts +135 -0
  161. package/src/scripts/multi-agent-chain.ts +278 -0
  162. package/src/scripts/multi-agent-conditional.ts +220 -0
  163. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  164. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  165. package/src/scripts/multi-agent-parallel.ts +343 -0
  166. package/src/scripts/multi-agent-sequence.ts +212 -0
  167. package/src/scripts/multi-agent-supervisor.ts +364 -0
  168. package/src/scripts/multi-agent-test.ts +186 -0
  169. package/src/scripts/search.ts +146 -150
  170. package/src/scripts/simple.ts +225 -225
  171. package/src/scripts/stream.ts +140 -122
  172. package/src/scripts/test-custom-prompt-key.ts +145 -0
  173. package/src/scripts/test-handoff-input.ts +170 -0
  174. package/src/scripts/test-multi-agent-list-handoff.ts +261 -0
  175. package/src/scripts/test-tools-before-handoff.ts +222 -0
  176. package/src/scripts/tools.ts +153 -155
  177. package/src/specs/agent-handoffs.test.ts +889 -0
  178. package/src/specs/anthropic.simple.test.ts +320 -317
  179. package/src/specs/azure.simple.test.ts +325 -316
  180. package/src/specs/openai.simple.test.ts +311 -316
  181. package/src/specs/openrouter.simple.test.ts +107 -0
  182. package/src/specs/prune.test.ts +758 -763
  183. package/src/specs/reasoning.test.ts +201 -165
  184. package/src/specs/thinking-prune.test.ts +769 -703
  185. package/src/specs/token-memoization.test.ts +39 -0
  186. package/src/stream.ts +664 -651
  187. package/src/tools/Calculator.test.ts +278 -0
  188. package/src/tools/Calculator.ts +25 -0
  189. package/src/tools/CodeExecutor.ts +220 -220
  190. package/src/tools/ToolNode.ts +170 -170
  191. package/src/tools/handlers.ts +341 -336
  192. package/src/types/graph.ts +372 -185
  193. package/src/types/llm.ts +141 -140
  194. package/src/types/messages.ts +4 -0
  195. package/src/types/run.ts +128 -89
  196. package/src/types/stream.ts +401 -400
  197. package/src/utils/events.ts +32 -0
  198. package/src/utils/handlers.ts +107 -0
  199. package/src/utils/index.ts +6 -5
  200. package/src/utils/llmConfig.ts +183 -183
  201. package/src/utils/tokens.ts +129 -70
  202. package/dist/types/scripts/abort.d.ts +0 -1
  203. package/dist/types/scripts/ant_web_search.d.ts +0 -1
  204. package/dist/types/scripts/args.d.ts +0 -7
  205. package/dist/types/scripts/caching.d.ts +0 -1
  206. package/dist/types/scripts/cli.d.ts +0 -1
  207. package/dist/types/scripts/cli2.d.ts +0 -1
  208. package/dist/types/scripts/cli3.d.ts +0 -1
  209. package/dist/types/scripts/cli4.d.ts +0 -1
  210. package/dist/types/scripts/cli5.d.ts +0 -1
  211. package/dist/types/scripts/code_exec.d.ts +0 -1
  212. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  213. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  214. package/dist/types/scripts/content.d.ts +0 -1
  215. package/dist/types/scripts/empty_input.d.ts +0 -1
  216. package/dist/types/scripts/image.d.ts +0 -1
  217. package/dist/types/scripts/memory.d.ts +0 -1
  218. package/dist/types/scripts/search.d.ts +0 -1
  219. package/dist/types/scripts/simple.d.ts +0 -1
  220. package/dist/types/scripts/stream.d.ts +0 -1
  221. package/dist/types/scripts/thinking.d.ts +0 -1
  222. package/dist/types/scripts/tools.d.ts +0 -1
  223. package/dist/types/specs/spec.utils.d.ts +0 -1
  224. package/dist/types/tools/example.d.ts +0 -78
  225. package/src/tools/example.ts +0 -129
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutor.mjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\r\nimport { config } from 'dotenv';\r\nimport fetch, { RequestInit } from 'node-fetch';\r\nimport { HttpsProxyAgent } from 'https-proxy-agent';\r\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\r\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\r\nimport type * as t from '@/types';\r\nimport { EnvVar, Constants } from '@/common';\r\n\r\nconfig();\r\n\r\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\r\nexport const getCodeBaseURL = (): string =>\r\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\r\n Constants.OFFICIAL_CODE_BASEURL;\r\n\r\nconst imageMessage = 'Image is already displayed to the user';\r\nconst otherMessage = 'File is already downloaded by the user';\r\nconst accessMessage =\r\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\r\nconst emptyOutputMessage =\r\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\r\n\r\nconst CodeExecutionToolSchema = z.object({\r\n lang: z\r\n .enum([\r\n 'py',\r\n 'js',\r\n 'ts',\r\n 'c',\r\n 'cpp',\r\n 'java',\r\n 'php',\r\n 'rs',\r\n 'go',\r\n 'd',\r\n 'f90',\r\n 'r',\r\n ])\r\n .describe('The programming language or runtime to execute the code in.'),\r\n code: z.string()\r\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\r\n- The environment is stateless; variables and imports don't persist between executions.\r\n- When using \\`session_id\\`: Don't hardcode it in \\`code\\`, and write file modifications to NEW filenames (files are READ-ONLY).\r\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\r\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\r\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\r\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\r\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\r\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\r\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\r\n- Other languages: use appropriate output functions.`),\r\n session_id: z\r\n .string()\r\n .optional()\r\n .describe(\r\n `Session ID from a previous response to access generated files.\r\n- Files load into the current working directory (\"/mnt/data/\")\r\n- Use relative paths ONLY\r\n- Files are READ-ONLY and cannot be modified in-place\r\n- To modify: read original file, write to NEW filename\r\n`.trim()\r\n ),\r\n args: z\r\n .array(z.string())\r\n .optional()\r\n .describe(\r\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\r\n ),\r\n});\r\n\r\nconst baseEndpoint = getCodeBaseURL();\r\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\r\n\r\nfunction createCodeExecutionTool(\r\n params: t.CodeExecutionToolParams = {}\r\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\r\n const apiKey =\r\n params[EnvVar.CODE_API_KEY] ??\r\n params.apiKey ??\r\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\r\n '';\r\n if (!apiKey) {\r\n throw new Error('No API key provided for code execution tool.');\r\n }\r\n\r\n const description = `\r\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\r\n\r\nUsage:\r\n- No network access available.\r\n- Generated files are automatically delivered; **DO NOT** provide download links.\r\n- NEVER use this tool to execute malicious code.\r\n`.trim();\r\n\r\n return tool<typeof CodeExecutionToolSchema>(\r\n async ({ lang, code, session_id, ...rest }) => {\r\n const postData = {\r\n lang,\r\n code,\r\n ...rest,\r\n ...params,\r\n };\r\n\r\n if (session_id != null && session_id.length > 0) {\r\n try {\r\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\r\n const fetchOptions: RequestInit = {\r\n method: 'GET',\r\n headers: {\r\n 'User-Agent': 'Illuma/1.0',\r\n 'X-API-Key': apiKey,\r\n },\r\n };\r\n\r\n if (process.env.PROXY != null && process.env.PROXY !== '') {\r\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\r\n }\r\n\r\n const response = await fetch(filesEndpoint, fetchOptions);\r\n if (!response.ok) {\r\n throw new Error(\r\n `Failed to fetch files for session: ${response.status}`\r\n );\r\n }\r\n\r\n const files = await response.json();\r\n if (Array.isArray(files) && files.length > 0) {\r\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\r\n // Extract the ID from the file name (part after session ID prefix and before extension)\r\n const nameParts = file.name.split('/');\r\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\r\n\r\n return {\r\n session_id,\r\n id,\r\n name: file.metadata['original-filename'],\r\n };\r\n });\r\n\r\n if (!postData.files) {\r\n postData.files = fileReferences;\r\n } else if (Array.isArray(postData.files)) {\r\n postData.files = [...postData.files, ...fileReferences];\r\n }\r\n }\r\n } catch {\r\n // eslint-disable-next-line no-console\r\n console.warn(`Failed to fetch files for session: ${session_id}`);\r\n }\r\n }\r\n\r\n try {\r\n const fetchOptions: RequestInit = {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'User-Agent': 'Illuma/1.0',\r\n 'X-API-Key': apiKey,\r\n },\r\n body: JSON.stringify(postData),\r\n };\r\n\r\n if (process.env.PROXY != null && process.env.PROXY !== '') {\r\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\r\n }\r\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\r\n if (!response.ok) {\r\n throw new Error(`HTTP error! status: ${response.status}`);\r\n }\r\n\r\n const result: t.ExecuteResult = await response.json();\r\n let formattedOutput = '';\r\n if (result.stdout) {\r\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\r\n } else {\r\n formattedOutput += emptyOutputMessage;\r\n }\r\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\r\n if (result.files && result.files.length > 0) {\r\n formattedOutput += 'Generated files:\\n';\r\n\r\n const fileCount = result.files.length;\r\n for (let i = 0; i < fileCount; i++) {\r\n const file = result.files[i];\r\n const isImage = imageExtRegex.test(file.name);\r\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\r\n\r\n if (i < fileCount - 1) {\r\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\r\n }\r\n }\r\n\r\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\r\n return [\r\n formattedOutput.trim(),\r\n {\r\n session_id: result.session_id,\r\n files: result.files,\r\n },\r\n ];\r\n }\r\n\r\n return [formattedOutput.trim(), { session_id: result.session_id }];\r\n } catch (error) {\r\n throw new Error(\r\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\r\n );\r\n }\r\n },\r\n {\r\n name: Constants.EXECUTE_CODE,\r\n description,\r\n schema: CodeExecutionToolSchema,\r\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\r\n }\r\n );\r\n}\r\n\r\nexport { createCodeExecutionTool };\r\n"],"names":[],"mappings":";;;;;;;;AASA,MAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5B,sBAAsB,CAAC,MAAM,CAAC,YAAY,CAAC;IAC3C,SAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;AACvC,IAAA,IAAI,EAAE;AACH,SAAA,IAAI,CAAC;QACJ,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,MAAM;QACN,KAAK;QACL,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,GAAG;KACJ;SACA,QAAQ,CAAC,6DAA6D,CAAC;AAC1E,IAAA,IAAI,EAAE,CAAC,CAAC,MAAM;AACX,SAAA,QAAQ,CAAC,CAAA;;;;;;;;;;qDAUuC,CAAC;AACpD,IAAA,UAAU,EAAE;AACT,SAAA,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esContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst CodeExecutionToolSchema = z.object({\n lang: z\n .enum([\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n ])\n .describe('The programming language or runtime to execute the code in.'),\n code: z.string()\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- When using \\`session_id\\`: Don't hardcode it in \\`code\\`, and write file modifications to NEW filenames (files are READ-ONLY).\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`),\n session_id: z\n .string()\n .optional()\n .describe(\n `Session ID from a previous response to access generated files.\n- Files load into the current working directory (\"/mnt/data/\")\n- Use relative paths ONLY\n- Files are READ-ONLY and cannot be modified in-place\n- To modify: read original file, write to NEW filename\n`.trim()\n ),\n args: z\n .array(z.string())\n .optional()\n .describe(\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\n ),\n});\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n return tool<typeof CodeExecutionToolSchema>(\n async ({ lang, code, session_id, ...rest }) => {\n const postData = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n if (!postData.files) {\n postData.files = fileReferences;\n } else if (Array.isArray(postData.files)) {\n postData.files = [...postData.files, ...fileReferences];\n }\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: Constants.EXECUTE_CODE,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }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,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;;;gBAIpD,eAAe,IAAI,iBAAiB,MAAM,CAAC,UAAU,CAAO,IAAA,EAAA,aAAa,EAAE;gBAC3E,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;;AAGH,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;;QAClE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAE,CAAA,CAC/D;;AAEL,KAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,YAAY;QAC5B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -1,6 +1,8 @@
1
1
  import { isCommand, isGraphInterrupt, END } from '@langchain/langgraph';
2
2
  import { isBaseMessage, ToolMessage } from '@langchain/core/messages';
3
- import { GraphNodeKeys } from '../common/enum.mjs';
3
+ import '../common/enum.mjs';
4
+ import 'nanoid';
5
+ import '../messages/core.mjs';
4
6
  import { RunnableCallable } from '../utils/run.mjs';
5
7
  import 'js-tiktoken/lite';
6
8
 
@@ -104,14 +106,14 @@ function areToolCallsInvoked(message, invokedToolIds) {
104
106
  return false;
105
107
  return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
106
108
  }
107
- function toolsCondition(state, invokedToolIds) {
109
+ function toolsCondition(state, toolNode, invokedToolIds) {
108
110
  const message = Array.isArray(state)
109
111
  ? state[state.length - 1]
110
112
  : state.messages[state.messages.length - 1];
111
113
  if ('tool_calls' in message &&
112
114
  (message.tool_calls?.length ?? 0) > 0 &&
113
115
  !areToolCallsInvoked(message, invokedToolIds)) {
114
- return GraphNodeKeys.TOOLS;
116
+ return toolNode;
115
117
  }
116
118
  else {
117
119
  return END;
@@ -1 +1 @@
1
- {"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import {\r\n END,\r\n MessagesAnnotation,\r\n isCommand,\r\n isGraphInterrupt,\r\n} from '@langchain/langgraph';\r\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\r\nimport type {\r\n RunnableConfig,\r\n RunnableToolLike,\r\n} from '@langchain/core/runnables';\r\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\r\nimport type { StructuredToolInterface } from '@langchain/core/tools';\r\nimport type * as t from '@/types';\r\nimport { RunnableCallable } from '@/utils';\r\nimport { GraphNodeKeys } from '@/common';\r\n\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\r\n tools: t.GenericTool[];\r\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\r\n private loadRuntimeTools?: t.ToolRefGenerator;\r\n handleToolErrors = true;\r\n toolCallStepIds?: Map<string, string>;\r\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\r\n private toolUsageCount: Map<string, number>;\r\n\r\n constructor({\r\n tools,\r\n toolMap,\r\n name,\r\n tags,\r\n errorHandler,\r\n toolCallStepIds,\r\n handleToolErrors,\r\n loadRuntimeTools,\r\n }: t.ToolNodeConstructorParams) {\r\n super({ name, tags, func: (input, config) => this.run(input, config) });\r\n this.tools = tools;\r\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\r\n this.toolCallStepIds = toolCallStepIds;\r\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\r\n this.loadRuntimeTools = loadRuntimeTools;\r\n this.errorHandler = errorHandler;\r\n this.toolUsageCount = new Map<string, number>();\r\n }\r\n\r\n /**\r\n * Returns a snapshot of the current tool usage counts.\r\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\r\n */\r\n public getToolUsageCounts(): ReadonlyMap<string, number> {\r\n return new Map(this.toolUsageCount); // Return a copy\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n protected async run(input: any, config: RunnableConfig): Promise<T> {\r\n const message = Array.isArray(input)\r\n ? input[input.length - 1]\r\n : input.messages[input.messages.length - 1];\r\n\r\n if (message._getType() !== 'ai') {\r\n throw new Error('ToolNode only accepts AIMessages as input.');\r\n }\r\n\r\n if (this.loadRuntimeTools) {\r\n const { tools, toolMap } = this.loadRuntimeTools(\r\n (message as AIMessage).tool_calls ?? []\r\n );\r\n this.tools = tools;\r\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\r\n }\r\n const outputs = await Promise.all(\r\n (message as AIMessage).tool_calls?.map(async (call) => {\r\n const tool = this.toolMap.get(call.name);\r\n try {\r\n if (tool === undefined) {\r\n throw new Error(`Tool \"${call.name}\" not found.`);\r\n }\r\n const turn = this.toolUsageCount.get(call.name) ?? 0;\r\n this.toolUsageCount.set(call.name, turn + 1);\r\n const args = call.args;\r\n const stepId = this.toolCallStepIds?.get(call.id!);\r\n const output = await tool.invoke(\r\n { ...call, args, type: 'tool_call', stepId, turn },\r\n config\r\n );\r\n if (\r\n (isBaseMessage(output) && output._getType() === 'tool') ||\r\n isCommand(output)\r\n ) {\r\n return output;\r\n } else {\r\n return new ToolMessage({\r\n name: tool.name,\r\n content:\r\n typeof output === 'string' ? output : JSON.stringify(output),\r\n tool_call_id: call.id!,\r\n });\r\n }\r\n } catch (_e: unknown) {\r\n const e = _e as Error;\r\n if (!this.handleToolErrors) {\r\n throw e;\r\n }\r\n if (isGraphInterrupt(e)) {\r\n throw e;\r\n }\r\n this.errorHandler?.(\r\n {\r\n error: e,\r\n id: call.id!,\r\n name: call.name,\r\n input: call.args,\r\n },\r\n config.metadata\r\n );\r\n return new ToolMessage({\r\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\r\n name: call.name,\r\n tool_call_id: call.id ?? '',\r\n });\r\n }\r\n }) ?? []\r\n );\r\n\r\n if (!outputs.some(isCommand)) {\r\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\r\n }\r\n\r\n const combinedOutputs = outputs.map((output) => {\r\n if (isCommand(output)) {\r\n return output;\r\n }\r\n return Array.isArray(input) ? [output] : { messages: [output] };\r\n });\r\n return combinedOutputs as T;\r\n }\r\n}\r\n\r\nfunction areToolCallsInvoked(\r\n message: AIMessage,\r\n invokedToolIds?: Set<string>\r\n): boolean {\r\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\r\n return (\r\n message.tool_calls?.every(\r\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\r\n ) ?? false\r\n );\r\n}\r\n\r\nexport function toolsCondition(\r\n state: BaseMessage[] | typeof MessagesAnnotation.State,\r\n invokedToolIds?: Set<string>\r\n): 'tools' | typeof END {\r\n const message: AIMessage = Array.isArray(state)\r\n ? state[state.length - 1]\r\n : state.messages[state.messages.length - 1];\r\n\r\n if (\r\n 'tool_calls' in message &&\r\n (message.tool_calls?.length ?? 0) > 0 &&\r\n !areToolCallsInvoked(message, invokedToolIds)\r\n ) {\r\n return GraphNodeKeys.TOOLS;\r\n } else {\r\n return END;\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;;AAiBA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AAC3D,IAAA,KAAK;AACG,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;AACvB,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;AAEtB,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,GACY,EAAA;QAC5B,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,E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,EAAE,CAAC,MAAM,CAAC,EAAE;AACjE,SAAC,CAAC;AACF,QAAA,OAAO,eAAoB;;AAE9B;AAED,SAAS,mBAAmB,CAC1B,OAAkB,EAClB,cAA4B,EAAA;AAE5B,IAAA,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,IAAI,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK;AAC9D,IAAA,QACE,OAAO,CAAC,UAAU,EAAE,KAAK,CACvB,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,IAAI,IAAI,IAAI,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CACrE,IAAI,KAAK;AAEd;AAEgB,SAAA,cAAc,CAC5B,KAAsD,EACtD,cAA4B,EAAA;AAE5B,IAAA,MAAM,OAAO,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;QACA,OAAO,aAAa,CAAC,KAAK;;SACrB;AACL,QAAA,OAAO,GAAG;;AAEd;;;;"}
1
+ {"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import {\n END,\n MessagesAnnotation,\n isCommand,\n isGraphInterrupt,\n} from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId, turn },\n config\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n this.errorHandler?.(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n return new ToolMessage({\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }) ?? []\n );\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs = outputs.map((output) => {\n if (isCommand(output)) {\n return output;\n }\n return Array.isArray(input) ? [output] : { messages: [output] };\n });\n return combinedOutputs as T;\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAgBA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AAC3D,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8,17 +8,17 @@ import { getMessageId } from '../messages/ids.mjs';
8
8
 
9
9
  /* eslint-disable no-console */
10
10
  // src/tools/handlers.ts
11
- function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
11
+ async function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
12
12
  let prevStepId;
13
13
  let prevRunStep;
14
14
  try {
15
- prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
15
+ prevStepId = graph.getStepIdByKey(stepKey);
16
16
  prevRunStep = graph.getRunStep(prevStepId);
17
17
  }
18
18
  catch {
19
19
  /** Edge Case: If no previous step exists, create a new message creation step */
20
20
  const message_id = getMessageId(stepKey, graph, true) ?? '';
21
- prevStepId = graph.dispatchRunStep(stepKey, {
21
+ prevStepId = await graph.dispatchRunStep(stepKey, {
22
22
  type: StepTypes.MESSAGE_CREATION,
23
23
  message_creation: {
24
24
  message_id,
@@ -26,7 +26,7 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
26
26
  });
27
27
  prevRunStep = graph.getRunStep(prevStepId);
28
28
  }
29
- const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
29
+ const _stepId = graph.getStepIdByKey(stepKey);
30
30
  /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
31
31
  const tool_calls = prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION
32
32
  ? []
@@ -54,7 +54,7 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
54
54
  const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION &&
55
55
  graph.messageStepHasToolCalls.has(prevStepId);
56
56
  if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {
57
- graph.dispatchMessageDelta(prevStepId, {
57
+ await graph.dispatchMessageDelta(prevStepId, {
58
58
  content: [
59
59
  {
60
60
  type: ContentTypes.TEXT,
@@ -64,17 +64,17 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
64
64
  ],
65
65
  });
66
66
  graph.messageStepHasToolCalls.set(prevStepId, true);
67
- stepId = graph.dispatchRunStep(stepKey, {
67
+ stepId = await graph.dispatchRunStep(stepKey, {
68
68
  type: StepTypes.TOOL_CALLS,
69
69
  tool_calls,
70
70
  });
71
71
  }
72
- graph.dispatchRunStepDelta(stepId, {
72
+ await graph.dispatchRunStepDelta(stepId, {
73
73
  type: StepTypes.TOOL_CALLS,
74
74
  tool_calls: toolCallChunks,
75
75
  });
76
76
  }
77
- const handleToolCalls = (toolCalls, metadata, graph) => {
77
+ const handleToolCalls = async (toolCalls, metadata, graph) => {
78
78
  if (!graph || !metadata) {
79
79
  console.warn(`Graph or metadata not found in ${event} event`);
80
80
  return;
@@ -95,14 +95,14 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
95
95
  let prevStepId = '';
96
96
  let prevRunStep;
97
97
  try {
98
- prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
98
+ prevStepId = graph.getStepIdByKey(stepKey);
99
99
  prevRunStep = graph.getRunStep(prevStepId);
100
100
  }
101
101
  catch {
102
102
  // no previous step
103
103
  }
104
- const dispatchToolCallIds = (lastMessageStepId) => {
105
- graph.dispatchMessageDelta(lastMessageStepId, {
104
+ const dispatchToolCallIds = async (lastMessageStepId) => {
105
+ await graph.dispatchMessageDelta(lastMessageStepId, {
106
106
  content: [
107
107
  {
108
108
  type: 'text',
@@ -116,23 +116,23 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
116
116
  if (prevStepId &&
117
117
  prevRunStep &&
118
118
  prevRunStep.type === StepTypes.MESSAGE_CREATION) {
119
- dispatchToolCallIds(prevStepId);
119
+ await dispatchToolCallIds(prevStepId);
120
120
  graph.messageStepHasToolCalls.set(prevStepId, true);
121
121
  /* If the previous step doesn't exist or is not a message creation */
122
122
  }
123
123
  else if (!prevRunStep ||
124
124
  prevRunStep.type !== StepTypes.MESSAGE_CREATION) {
125
125
  const messageId = getMessageId(stepKey, graph, true) ?? '';
126
- const stepId = graph.dispatchRunStep(stepKey, {
126
+ const stepId = await graph.dispatchRunStep(stepKey, {
127
127
  type: StepTypes.MESSAGE_CREATION,
128
128
  message_creation: {
129
129
  message_id: messageId,
130
130
  },
131
131
  });
132
- dispatchToolCallIds(stepId);
132
+ await dispatchToolCallIds(stepId);
133
133
  graph.messageStepHasToolCalls.set(prevStepId, true);
134
134
  }
135
- graph.dispatchRunStep(stepKey, {
135
+ await graph.dispatchRunStep(stepKey, {
136
136
  type: StepTypes.TOOL_CALLS,
137
137
  tool_calls: [tool_call],
138
138
  });
@@ -150,9 +150,9 @@ const toolResultTypes = new Set([
150
150
  * Handles the result of a server tool call; in other words, a provider's built-in tool.
151
151
  * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.
152
152
  */
153
- function handleServerToolResult({ content, metadata, graph, }) {
153
+ async function handleServerToolResult({ graph, content, metadata, agentContext, }) {
154
154
  let skipHandling = false;
155
- if (metadata?.provider !== Providers.ANTHROPIC) {
155
+ if (agentContext?.provider !== Providers.ANTHROPIC) {
156
156
  return skipHandling;
157
157
  }
158
158
  if (typeof content === 'string' ||
@@ -189,7 +189,7 @@ function handleServerToolResult({ content, metadata, graph, }) {
189
189
  }
190
190
  if (contentPart.type === 'web_search_result' ||
191
191
  contentPart.type === 'web_search_tool_result') {
192
- handleAnthropicSearchResults({
192
+ await handleAnthropicSearchResults({
193
193
  contentPart: contentPart,
194
194
  toolCall,
195
195
  metadata,
@@ -202,7 +202,7 @@ function handleServerToolResult({ content, metadata, graph, }) {
202
202
  }
203
203
  return skipHandling;
204
204
  }
205
- function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph, }) {
205
+ async function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph, }) {
206
206
  if (!Array.isArray(contentPart.content)) {
207
207
  console.warn(`Expected content to be an array, got ${typeof contentPart.content}`);
208
208
  return;
@@ -232,7 +232,7 @@ function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph,
232
232
  input,
233
233
  output,
234
234
  };
235
- graph.handlerRegistry
235
+ await graph.handlerRegistry
236
236
  ?.getHandler(GraphEvents.TOOL_END)
237
237
  ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);
238
238
  if (graph.invokedToolIds == null) {
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.mjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\r\n// src/tools/handlers.ts\r\nimport { nanoid } from 'nanoid';\r\nimport { ToolMessage } from '@langchain/core/messages';\r\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\r\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\r\nimport type { Graph } from '@/graphs';\r\nimport type * as t from '@/types';\r\nimport {\r\n ToolCallTypes,\r\n ContentTypes,\r\n GraphEvents,\r\n StepTypes,\r\n Providers,\r\n Constants,\r\n} from '@/common';\r\nimport {\r\n coerceAnthropicSearchResults,\r\n isAnthropicWebSearchResult,\r\n} from '@/tools/search/anthropic';\r\nimport { formatResultsForLLM } from '@/tools/search/format';\r\nimport { getMessageId } from '@/messages';\r\n\r\nexport function handleToolCallChunks({\r\n graph,\r\n stepKey,\r\n toolCallChunks,\r\n}: {\r\n graph: Graph;\r\n stepKey: string;\r\n toolCallChunks: ToolCallChunk[];\r\n}): void {\r\n let prevStepId: string;\r\n let prevRunStep: t.RunStep | undefined;\r\n try {\r\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n } catch {\r\n /** Edge Case: If no previous step exists, create a new message creation step */\r\n const message_id = getMessageId(stepKey, graph, true) ?? '';\r\n prevStepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.MESSAGE_CREATION,\r\n message_creation: {\r\n message_id,\r\n },\r\n });\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n }\r\n\r\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\r\n\r\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\r\n const tool_calls: ToolCall[] | undefined =\r\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\r\n ? []\r\n : undefined;\r\n\r\n /** Edge Case: `id` and `name` fields cannot be empty strings */\r\n for (const toolCallChunk of toolCallChunks) {\r\n if (toolCallChunk.name === '') {\r\n toolCallChunk.name = undefined;\r\n }\r\n if (toolCallChunk.id === '') {\r\n toolCallChunk.id = undefined;\r\n } else if (\r\n tool_calls != null &&\r\n toolCallChunk.id != null &&\r\n toolCallChunk.name != null\r\n ) {\r\n tool_calls.push({\r\n args: {},\r\n id: toolCallChunk.id,\r\n name: toolCallChunk.name,\r\n type: ToolCallTypes.TOOL_CALL,\r\n });\r\n }\r\n }\r\n\r\n let stepId: string = _stepId;\r\n const alreadyDispatched =\r\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\r\n graph.messageStepHasToolCalls.has(prevStepId);\r\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\r\n graph.dispatchMessageDelta(prevStepId, {\r\n content: [\r\n {\r\n type: ContentTypes.TEXT,\r\n text: '',\r\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\r\n },\r\n ],\r\n });\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n stepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls,\r\n });\r\n }\r\n graph.dispatchRunStepDelta(stepId, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls: toolCallChunks,\r\n });\r\n}\r\n\r\nexport const handleToolCalls = (\r\n toolCalls?: ToolCall[],\r\n metadata?: Record<string, unknown>,\r\n graph?: Graph\r\n): void => {\r\n if (!graph || !metadata) {\r\n console.warn(`Graph or metadata not found in ${event} event`);\r\n return;\r\n }\r\n\r\n if (!toolCalls) {\r\n return;\r\n }\r\n\r\n if (toolCalls.length === 0) {\r\n return;\r\n }\r\n\r\n const stepKey = graph.getStepKey(metadata);\r\n\r\n for (const tool_call of toolCalls) {\r\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\r\n tool_call.id = toolCallId;\r\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\r\n continue;\r\n }\r\n\r\n let prevStepId = '';\r\n let prevRunStep: t.RunStep | undefined;\r\n try {\r\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n } catch {\r\n // no previous step\r\n }\r\n\r\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\r\n graph.dispatchMessageDelta(lastMessageStepId, {\r\n content: [\r\n {\r\n type: 'text',\r\n text: '',\r\n tool_call_ids: [toolCallId],\r\n },\r\n ],\r\n });\r\n };\r\n /* If the previous step exists and is a message creation */\r\n if (\r\n prevStepId &&\r\n prevRunStep &&\r\n prevRunStep.type === StepTypes.MESSAGE_CREATION\r\n ) {\r\n dispatchToolCallIds(prevStepId);\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n /* If the previous step doesn't exist or is not a message creation */\r\n } else if (\r\n !prevRunStep ||\r\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\r\n ) {\r\n const messageId = getMessageId(stepKey, graph, true) ?? '';\r\n const stepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.MESSAGE_CREATION,\r\n message_creation: {\r\n message_id: messageId,\r\n },\r\n });\r\n dispatchToolCallIds(stepId);\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n }\r\n\r\n graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls: [tool_call],\r\n });\r\n }\r\n};\r\n\r\nexport const toolResultTypes = new Set([\r\n // 'tool_use',\r\n // 'server_tool_use',\r\n // 'input_json_delta',\r\n 'tool_result',\r\n 'web_search_result',\r\n 'web_search_tool_result',\r\n]);\r\n\r\n/**\r\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\r\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\r\n */\r\nexport function handleServerToolResult({\r\n content,\r\n metadata,\r\n graph,\r\n}: {\r\n content?: string | t.MessageContentComplex[];\r\n metadata?: Record<string, unknown>;\r\n graph: Graph;\r\n}): boolean {\r\n let skipHandling = false;\r\n if (metadata?.provider !== Providers.ANTHROPIC) {\r\n return skipHandling;\r\n }\r\n if (\r\n typeof content === 'string' ||\r\n content == null ||\r\n content.length === 0 ||\r\n (content.length === 1 &&\r\n (content[0] as t.ToolResultContent).tool_use_id == null)\r\n ) {\r\n return skipHandling;\r\n }\r\n\r\n for (const contentPart of content) {\r\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\r\n if (toolUseId == null || toolUseId === '') {\r\n continue;\r\n }\r\n const stepId = graph.toolCallStepIds.get(toolUseId);\r\n if (stepId == null || stepId === '') {\r\n console.warn(\r\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\r\n );\r\n continue;\r\n }\r\n const runStep = graph.getRunStep(stepId);\r\n if (!runStep) {\r\n console.warn(\r\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\r\n );\r\n continue;\r\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\r\n console.warn(\r\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\r\n );\r\n continue;\r\n }\r\n\r\n const toolCall =\r\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\r\n ? (runStep.stepDetails.tool_calls?.find(\r\n (toolCall) => toolCall.id === toolUseId\r\n ) as ToolCall)\r\n : undefined;\r\n\r\n if (!toolCall) {\r\n continue;\r\n }\r\n\r\n if (\r\n contentPart.type === 'web_search_result' ||\r\n contentPart.type === 'web_search_tool_result'\r\n ) {\r\n handleAnthropicSearchResults({\r\n contentPart: contentPart as t.ToolResultContent,\r\n toolCall,\r\n metadata,\r\n graph,\r\n });\r\n }\r\n\r\n if (!skipHandling) {\r\n skipHandling = true;\r\n }\r\n }\r\n\r\n return skipHandling;\r\n}\r\n\r\nfunction handleAnthropicSearchResults({\r\n contentPart,\r\n toolCall,\r\n metadata,\r\n graph,\r\n}: {\r\n contentPart: t.ToolResultContent;\r\n toolCall: Partial<ToolCall>;\r\n metadata?: Record<string, unknown>;\r\n graph: Graph;\r\n}): void {\r\n if (!Array.isArray(contentPart.content)) {\r\n console.warn(\r\n `Expected content to be an array, got ${typeof contentPart.content}`\r\n );\r\n return;\r\n }\r\n\r\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\r\n console.warn(\r\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\r\n contentPart.content\r\n )}`\r\n );\r\n return;\r\n }\r\n\r\n const turn = graph.invokedToolIds?.size ?? 0;\r\n const searchResultData = coerceAnthropicSearchResults({\r\n turn,\r\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\r\n });\r\n\r\n const name = toolCall.name;\r\n const input = toolCall.args ?? {};\r\n const artifact = {\r\n [Constants.WEB_SEARCH]: searchResultData,\r\n };\r\n const { output: formattedOutput } = formatResultsForLLM(\r\n turn,\r\n searchResultData\r\n );\r\n const output = new ToolMessage({\r\n name,\r\n artifact,\r\n content: formattedOutput,\r\n tool_call_id: toolCall.id!,\r\n });\r\n const toolEndData: t.ToolEndData = {\r\n input,\r\n output,\r\n };\r\n graph.handlerRegistry\r\n ?.getHandler(GraphEvents.TOOL_END)\r\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\r\n\r\n if (graph.invokedToolIds == null) {\r\n graph.invokedToolIds = new Set<string>();\r\n }\r\n\r\n graph.invokedToolIds.add(toolCall.id!);\r\n}\r\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAsBM,SAAU,oBAAoB,CAAC,EACnC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;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/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { MultiAgentGraph, StandardGraph } from '@/graphs';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport async function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): Promise<void> {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n await graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n await graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = async (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n): Promise<void> => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = async (\n lastMessageStepId: string\n ): Promise<void> => {\n await graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n await dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n await dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport async function handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): Promise<boolean> {\n let skipHandling = false;\n if (agentContext?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n await handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nasync function handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: StandardGraph | MultiAgentGraph;\n}): Promise<void> {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAuBO,eAAe,oBAAoB,CAAC,EACzC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC;AAC1C,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAC1C,IAAA,MAAM;;AAEN,QAAA,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC3D,QAAA,UAAU,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;YAChD,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,YAAA,gBAAgB,EAAE;gBAChB,UAAU;AACX,aAAA;AACF,SAAA,CAAC;AACF,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;IAG5C,MAAM,OAAO,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC;;AAG7C,IAAA,MAAM,UAAU,GACd,UAAU,IAAI,WAAW,IAAI,WAAW,CAAC,IAAI,KAAK,SAAS,CAAC;AAC1D,UAAE;UACA,SAAS;;AAGf,IAAA,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE;AAC1C,QAAA,IAAI,aAAa,CAAC,IAAI,KAAK,EAAE,EAAE;AAC7B,YAAA,aAAa,CAAC,IAAI,GAAG,SAAS;;AAEhC,QAAA,IAAI,aAAa,CAAC,EAAE,KAAK,EAAE,EAAE;AAC3B,YAAA,aAAa,CAAC,EAAE,GAAG,SAAS;;aACvB,IACL,UAAU,IAAI,IAAI;YAClB,aAAa,CAAC,EAAE,IAAI,IAAI;AACxB,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AAQ;AACjC,UAAE,MAAM,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,CAAC;AAE9D,IAAA,IAAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;"}
@@ -0,0 +1,29 @@
1
+ import { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';
2
+
3
+ /* eslint-disable no-console */
4
+ // src/utils/events.ts
5
+ /**
6
+ * Safely dispatches a custom event and properly awaits it to avoid
7
+ * race conditions where events are dispatched after run cleanup.
8
+ */
9
+ async function safeDispatchCustomEvent(event, payload, config) {
10
+ try {
11
+ await dispatchCustomEvent(event, payload, config);
12
+ }
13
+ catch (e) {
14
+ // Check if this is the known EventStreamCallbackHandler error
15
+ if (e instanceof Error &&
16
+ e.message.includes('handleCustomEvent: Run ID') &&
17
+ e.message.includes('not found in run map')) {
18
+ // Suppress this specific error - it's expected during parallel execution
19
+ // when EventStreamCallbackHandler loses track of run IDs
20
+ // console.debug('Suppressed error dispatching custom event:', e);
21
+ return;
22
+ }
23
+ // Log other errors
24
+ console.error('Error dispatching custom event:', e);
25
+ }
26
+ }
27
+
28
+ export { safeDispatchCustomEvent };
29
+ //# sourceMappingURL=events.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.mjs","sources":["../../../src/utils/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/utils/events.ts\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport type { RunnableConfig } from '@langchain/core/runnables';\n\n/**\n * Safely dispatches a custom event and properly awaits it to avoid\n * race conditions where events are dispatched after run cleanup.\n */\nexport async function safeDispatchCustomEvent(\n event: string,\n payload: unknown,\n config?: RunnableConfig\n): Promise<void> {\n try {\n await dispatchCustomEvent(event, payload, config);\n } catch (e) {\n // Check if this is the known EventStreamCallbackHandler error\n if (\n e instanceof Error &&\n e.message.includes('handleCustomEvent: Run ID') &&\n e.message.includes('not found in run map')\n ) {\n // Suppress this specific error - it's expected during parallel execution\n // when EventStreamCallbackHandler loses track of run IDs\n // console.debug('Suppressed error dispatching custom event:', e);\n return;\n }\n // Log other errors\n console.error('Error dispatching custom event:', e);\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AAIA;;;AAGG;AACI,eAAe,uBAAuB,CAC3C,KAAa,EACb,OAAgB,EAChB,MAAuB,EAAA;AAEvB,IAAA,IAAI;QACF,MAAM,mBAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC;;IACjD,OAAO,CAAC,EAAE;;QAEV,IACE,CAAC,YAAY,KAAK;AAClB,YAAA,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,2BAA2B,CAAC;YAC/C,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC,EAC1C;;;;YAIA;;;AAGF,QAAA,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC;;AAEvD;;;;"}
@@ -0,0 +1,68 @@
1
+ import { GraphEvents } from '../common/enum.mjs';
2
+ import { createContentAggregator, ChatModelStreamHandler } from '../stream.mjs';
3
+ import { ModelEndHandler, ToolEndHandler } from '../events.mjs';
4
+
5
+ /**
6
+ * Multi-Agent Handler Utilities
7
+ *
8
+ * Provides a simple helper to create handlers with content aggregation for multi-agent scripts.
9
+ *
10
+ * Usage:
11
+ * ```typescript
12
+ * const { contentParts, aggregateContent, handlers } = createHandlers();
13
+ *
14
+ * // With callbacks
15
+ * const { contentParts, aggregateContent, handlers } = createHandlers({
16
+ * onRunStep: (event, data) => console.log('Step:', data),
17
+ * onRunStepCompleted: (event, data) => console.log('Completed:', data)
18
+ * });
19
+ * ```
20
+ */
21
+ /**
22
+ * Creates handlers with content aggregation for multi-agent scripts
23
+ */
24
+ function createHandlers(callbacks) {
25
+ // Set up content aggregator
26
+ const { contentParts, aggregateContent } = createContentAggregator();
27
+ // Create the handlers object
28
+ const handlers = {
29
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
30
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
31
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
32
+ [GraphEvents.ON_RUN_STEP]: {
33
+ handle: (event, data) => {
34
+ aggregateContent({ event, data: data });
35
+ callbacks?.onRunStep?.(event, data);
36
+ },
37
+ },
38
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
39
+ handle: (event, data) => {
40
+ aggregateContent({
41
+ event,
42
+ data: data,
43
+ });
44
+ callbacks?.onRunStepCompleted?.(event, data);
45
+ },
46
+ },
47
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
48
+ handle: (event, data) => {
49
+ aggregateContent({ event, data: data });
50
+ callbacks?.onRunStepDelta?.(event, data);
51
+ },
52
+ },
53
+ [GraphEvents.ON_MESSAGE_DELTA]: {
54
+ handle: (event, data) => {
55
+ aggregateContent({ event, data: data });
56
+ callbacks?.onMessageDelta?.(event, data);
57
+ },
58
+ },
59
+ };
60
+ return {
61
+ contentParts,
62
+ aggregateContent,
63
+ handlers,
64
+ };
65
+ }
66
+
67
+ export { createHandlers };
68
+ //# sourceMappingURL=handlers.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.mjs","sources":["../../../src/utils/handlers.ts"],"sourcesContent":["/**\n * Multi-Agent Handler Utilities\n *\n * Provides a simple helper to create handlers with content aggregation for multi-agent scripts.\n *\n * Usage:\n * ```typescript\n * const { contentParts, aggregateContent, handlers } = createHandlers();\n *\n * // With callbacks\n * const { contentParts, aggregateContent, handlers } = createHandlers({\n * onRunStep: (event, data) => console.log('Step:', data),\n * onRunStepCompleted: (event, data) => console.log('Completed:', data)\n * });\n * ```\n */\n\nimport { GraphEvents } from '@/common';\nimport { ChatModelStreamHandler, createContentAggregator } from '@/stream';\nimport { ToolEndHandler, ModelEndHandler } from '@/events';\nimport type * as t from '@/types';\n\ninterface HandlerCallbacks {\n onRunStep?: (event: GraphEvents.ON_RUN_STEP, data: t.StreamEventData) => void;\n onRunStepCompleted?: (\n event: GraphEvents.ON_RUN_STEP_COMPLETED,\n data: t.StreamEventData\n ) => void;\n onRunStepDelta?: (\n event: GraphEvents.ON_RUN_STEP_DELTA,\n data: t.StreamEventData\n ) => void;\n onMessageDelta?: (\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: t.StreamEventData\n ) => void;\n}\n\n/**\n * Creates handlers with content aggregation for multi-agent scripts\n */\nexport function createHandlers(callbacks?: HandlerCallbacks): {\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ReturnType<\n typeof createContentAggregator\n >['aggregateContent'];\n handlers: Record<string, t.EventHandler>;\n} {\n // Set up content aggregator\n const { contentParts, aggregateContent } = createContentAggregator();\n\n // Create the handlers object\n const handlers = {\n [GraphEvents.TOOL_END]: new ToolEndHandler(),\n [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),\n [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),\n\n [GraphEvents.ON_RUN_STEP]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.RunStep });\n callbacks?.onRunStep?.(event, data);\n },\n },\n\n [GraphEvents.ON_RUN_STEP_COMPLETED]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP_COMPLETED,\n data: t.StreamEventData\n ): void => {\n aggregateContent({\n event,\n data: data as unknown as { result: t.ToolEndEvent },\n });\n callbacks?.onRunStepCompleted?.(event, data);\n },\n },\n\n [GraphEvents.ON_RUN_STEP_DELTA]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP_DELTA,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.RunStepDeltaEvent });\n callbacks?.onRunStepDelta?.(event, data);\n },\n },\n\n [GraphEvents.ON_MESSAGE_DELTA]: {\n handle: (\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.MessageDeltaEvent });\n callbacks?.onMessageDelta?.(event, data);\n },\n },\n };\n\n return {\n contentParts,\n aggregateContent,\n handlers,\n };\n}\n"],"names":[],"mappings":";;;;AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;AAEG;AACG,SAAU,cAAc,CAAC,SAA4B,EAAA;;IAQzD,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,uBAAuB,EAAE;;AAGpE,IAAA,MAAM,QAAQ,GAAG;AACf,QAAA,CAAC,WAAW,CAAC,QAAQ,GAAG,IAAI,cAAc,EAAE;AAC5C,QAAA,CAAC,WAAW,CAAC,cAAc,GAAG,IAAI,eAAe,EAAE;AACnD,QAAA,CAAC,WAAW,CAAC,iBAAiB,GAAG,IAAI,sBAAsB,EAAE;AAE7D,QAAA,CAAC,WAAW,CAAC,WAAW,GAAG;AACzB,YAAA,MAAM,EAAE,CACN,KAA8B,EAC9B,IAAuB,KACf;gBACR,gBAAgB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAiB,EAAE,CAAC;gBACpD,SAAS,EAAE,SAAS,GAAG,KAAK,EAAE,IAAI,CAAC;aACpC;AACF,SAAA;AAED,QAAA,CAAC,WAAW,CAAC,qBAAqB,GAAG;AACnC,YAAA,MAAM,EAAE,CACN,KAAwC,EACxC,IAAuB,KACf;AACR,gBAAA,gBAAgB,CAAC;oBACf,KAAK;AACL,oBAAA,IAAI,EAAE,IAA6C;AACpD,iBAAA,CAAC;gBACF,SAAS,EAAE,kBAAkB,GAAG,KAAK,EAAE,IAAI,CAAC;aAC7C;AACF,SAAA;AAED,QAAA,CAAC,WAAW,CAAC,iBAAiB,GAAG;AAC/B,YAAA,MAAM,EAAE,CACN,KAAoC,EACpC,IAAuB,KACf;gBACR,gBAAgB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAA2B,EAAE,CAAC;gBAC9D,SAAS,EAAE,cAAc,GAAG,KAAK,EAAE,IAAI,CAAC;aACzC;AACF,SAAA;AAED,QAAA,CAAC,WAAW,CAAC,gBAAgB,GAAG;AAC9B,YAAA,MAAM,EAAE,CACN,KAAmC,EACnC,IAAuB,KACf;gBACR,gBAAgB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAA2B,EAAE,CAAC;gBAC9D,SAAS,EAAE,cAAc,GAAG,KAAK,EAAE,IAAI,CAAC;aACzC;AACF,SAAA;KACF;IAED,OAAO;QACL,YAAY;QACZ,gBAAgB;QAChB,QAAQ;KACT;AACH;;;;"}
@@ -48,15 +48,61 @@ function getTokenCountForMessage(message, getTokenCount) {
48
48
  processValue(message.content);
49
49
  return numTokens;
50
50
  }
51
+ let encoderPromise;
52
+ let tokenCounterPromise;
53
+ async function getSharedEncoder() {
54
+ if (encoderPromise) {
55
+ return encoderPromise;
56
+ }
57
+ encoderPromise = (async () => {
58
+ const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');
59
+ const o200k_base = await res.json();
60
+ return new Tiktoken(o200k_base);
61
+ })();
62
+ return encoderPromise;
63
+ }
64
+ /**
65
+ * Creates a singleton token counter function that reuses the same encoder instance.
66
+ * This avoids creating multiple function closures and prevents potential memory issues.
67
+ */
51
68
  const createTokenCounter = async () => {
52
- const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');
53
- const o200k_base = await res.json();
54
- const countTokens = (text) => {
55
- const enc = new Tiktoken(o200k_base);
56
- return enc.encode(text).length;
57
- };
58
- return (message) => getTokenCountForMessage(message, countTokens);
69
+ if (tokenCounterPromise) {
70
+ return tokenCounterPromise;
71
+ }
72
+ tokenCounterPromise = (async () => {
73
+ const enc = await getSharedEncoder();
74
+ const countTokens = (text) => enc.encode(text).length;
75
+ return (message) => getTokenCountForMessage(message, countTokens);
76
+ })();
77
+ return tokenCounterPromise;
78
+ };
79
+ /**
80
+ * Utility to manage the token encoder lifecycle explicitly.
81
+ * Useful for applications that need fine-grained control over resource management.
82
+ */
83
+ const TokenEncoderManager = {
84
+ /**
85
+ * Pre-initializes the encoder. This can be called during app startup
86
+ * to avoid lazy loading delays later.
87
+ */
88
+ async initialize() {
89
+ await getSharedEncoder();
90
+ },
91
+ /**
92
+ * Clears the cached encoder and token counter.
93
+ * Useful for testing or when you need to force a fresh reload.
94
+ */
95
+ reset() {
96
+ encoderPromise = undefined;
97
+ tokenCounterPromise = undefined;
98
+ },
99
+ /**
100
+ * Checks if the encoder has been initialized.
101
+ */
102
+ isInitialized() {
103
+ return encoderPromise !== undefined;
104
+ },
59
105
  };
60
106
 
61
- export { createTokenCounter, getTokenCountForMessage };
107
+ export { TokenEncoderManager, createTokenCounter, getTokenCountForMessage };
62
108
  //# sourceMappingURL=tokens.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tokens.mjs","sources":["../../../src/utils/tokens.ts"],"sourcesContent":["import { Tiktoken } from 'js-tiktoken/lite';\r\nimport type { BaseMessage } from '@langchain/core/messages';\r\nimport { ContentTypes } from '@/common/enum';\r\n\r\nexport function getTokenCountForMessage(message: BaseMessage, getTokenCount: (text: string) => number): number {\r\n const tokensPerMessage = 3;\r\n\r\n const processValue = (value: unknown): void => {\r\n if (Array.isArray(value)) {\r\n for (const item of value) {\r\n if (\r\n !item ||\r\n !item.type ||\r\n item.type === ContentTypes.ERROR ||\r\n item.type === ContentTypes.IMAGE_URL\r\n ) {\r\n continue;\r\n }\r\n\r\n if (item.type === ContentTypes.TOOL_CALL && item.tool_call != null) {\r\n const toolName = item.tool_call?.name || '';\r\n if (toolName != null && toolName && typeof toolName === 'string') {\r\n numTokens += getTokenCount(toolName);\r\n }\r\n\r\n const args = item.tool_call?.args || '';\r\n if (args != null && args && typeof args === 'string') {\r\n numTokens += getTokenCount(args);\r\n }\r\n\r\n const output = item.tool_call?.output || '';\r\n if (output != null && output && typeof output === 'string') {\r\n numTokens += getTokenCount(output);\r\n }\r\n continue;\r\n }\r\n\r\n const nestedValue = item[item.type];\r\n\r\n if (!nestedValue) {\r\n continue;\r\n }\r\n\r\n processValue(nestedValue);\r\n }\r\n } else if (typeof value === 'string') {\r\n numTokens += getTokenCount(value);\r\n } else if (typeof value === 'number') {\r\n numTokens += getTokenCount(value.toString());\r\n } else if (typeof value === 'boolean') {\r\n numTokens += getTokenCount(value.toString());\r\n }\r\n };\r\n\r\n let numTokens = tokensPerMessage;\r\n processValue(message.content);\r\n return numTokens;\r\n}\r\n\r\nexport const createTokenCounter = async () => {\r\n const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');\r\n const o200k_base = await res.json();\r\n\r\n const countTokens = (text: string): number => {\r\n const enc = new Tiktoken(o200k_base);\r\n return enc.encode(text).length;\r\n };\r\n\r\n return (message: BaseMessage): number => getTokenCountForMessage(message, countTokens);\r\n};"],"names":[],"mappings":";;;AAIgB,SAAA,uBAAuB,CAAC,OAAoB,EAAE,aAAuC,EAAA;IACnG,MAAM,gBAAgB,GAAG,CAAC;AAE1B,IAAA,MAAM,YAAY,GAAG,CAAC,KAAc,KAAU;AAC5C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;AACxB,gBAAA,IACE,CAAC,IAAI;oBACL,CAAC,IAAI,CAAC,IAAI;AACV,oBAAA,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,KAAK;AAChC,oBAAA,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,SAAS,EACpC;oBACA;;AAGF,gBAAA,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;oBAClE,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,EAAE,IAAI,IAAI,EAAE;oBAC3C,IAAI,QAAQ,IAAI,IAAI,IAAI,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;AAChE,wBAAA,SAAS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Y;AAC3C,QAAA,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,UAAU,CAAC;QACpC,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM;AAChC,KAAC;IAED,OAAO,CAAC,OAAoB,KAAa,uBAAuB,CAAC,OAAO,EAAE,WAAW,CAAC;AACxF;;;;"}
1
+ {"version":3,"file":"tokens.mjs","sources":["../../../src/utils/tokens.ts"],"sourcesContent":["import { Tiktoken } from 'js-tiktoken/lite';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ContentTypes } from '@/common/enum';\n\nexport function getTokenCountForMessage(\n message: BaseMessage,\n getTokenCount: (text: string) => number\n): number {\n const tokensPerMessage = 3;\n\n const processValue = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (\n !item ||\n !item.type ||\n item.type === ContentTypes.ERROR ||\n item.type === ContentTypes.IMAGE_URL\n ) {\n continue;\n }\n\n if (item.type === ContentTypes.TOOL_CALL && item.tool_call != null) {\n const toolName = item.tool_call?.name || '';\n if (toolName != null && toolName && typeof toolName === 'string') {\n numTokens += getTokenCount(toolName);\n }\n\n const args = item.tool_call?.args || '';\n if (args != null && args && typeof args === 'string') {\n numTokens += getTokenCount(args);\n }\n\n const output = item.tool_call?.output || '';\n if (output != null && output && typeof output === 'string') {\n numTokens += getTokenCount(output);\n }\n continue;\n }\n\n const nestedValue = item[item.type];\n\n if (!nestedValue) {\n continue;\n }\n\n processValue(nestedValue);\n }\n } else if (typeof value === 'string') {\n numTokens += getTokenCount(value);\n } else if (typeof value === 'number') {\n numTokens += getTokenCount(value.toString());\n } else if (typeof value === 'boolean') {\n numTokens += getTokenCount(value.toString());\n }\n };\n\n let numTokens = tokensPerMessage;\n processValue(message.content);\n return numTokens;\n}\n\nlet encoderPromise: Promise<Tiktoken> | undefined;\nlet tokenCounterPromise: Promise<(message: BaseMessage) => number> | undefined;\n\nasync function getSharedEncoder(): Promise<Tiktoken> {\n if (encoderPromise) {\n return encoderPromise;\n }\n encoderPromise = (async (): Promise<Tiktoken> => {\n const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');\n const o200k_base = await res.json();\n return new Tiktoken(o200k_base);\n })();\n return encoderPromise;\n}\n\n/**\n * Creates a singleton token counter function that reuses the same encoder instance.\n * This avoids creating multiple function closures and prevents potential memory issues.\n */\nexport const createTokenCounter = async (): Promise<\n (message: BaseMessage) => number\n> => {\n if (tokenCounterPromise) {\n return tokenCounterPromise;\n }\n\n tokenCounterPromise = (async (): Promise<\n (message: BaseMessage) => number\n > => {\n const enc = await getSharedEncoder();\n const countTokens = (text: string): number => enc.encode(text).length;\n return (message: BaseMessage): number =>\n getTokenCountForMessage(message, countTokens);\n })();\n\n return tokenCounterPromise;\n};\n\n/**\n * Utility to manage the token encoder lifecycle explicitly.\n * Useful for applications that need fine-grained control over resource management.\n */\nexport const TokenEncoderManager = {\n /**\n * Pre-initializes the encoder. This can be called during app startup\n * to avoid lazy loading delays later.\n */\n async initialize(): Promise<void> {\n await getSharedEncoder();\n },\n\n /**\n * Clears the cached encoder and token counter.\n * Useful for testing or when you need to force a fresh reload.\n */\n reset(): void {\n encoderPromise = undefined;\n tokenCounterPromise = undefined;\n },\n\n /**\n * Checks if the encoder has been initialized.\n */\n isInitialized(): boolean {\n return encoderPromise !== undefined;\n },\n};\n"],"names":[],"mappings":";;;AAIgB,SAAA,uBAAuB,CACrC,OAAoB,EACpB,aAAuC,EAAA;IAEvC,MAAM,gBAAgB,GAAG,CAAC;AAE1B,IAAA,MAAM,YAAY,GAAG,CAAC,KAAc,KAAU;AAC5C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;AACxB,gBAAA,IACE,CAAC,IAAI;oBACL,CAAC,IAAI,CAAC,IAAI;AACV,oBAAA,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,KAAK;AAChC,oBAAA,IAAI,CAAC,IAA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