illuma-agents 1.0.65 → 1.0.67
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.
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +3 -132
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +47 -4
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +0 -50
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/prompts/collab.cjs +11 -0
- package/dist/cjs/prompts/collab.cjs.map +1 -0
- package/dist/cjs/prompts/taskmanager.cjs +66 -0
- package/dist/cjs/prompts/taskmanager.cjs.map +1 -0
- package/dist/cjs/prompts/taskplanning.cjs +99 -0
- package/dist/cjs/prompts/taskplanning.cjs.map +1 -0
- package/dist/cjs/tools/Calculator.cjs +23 -2
- package/dist/cjs/tools/Calculator.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +19 -1
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/TaskProgress.cjs +172 -0
- package/dist/cjs/tools/TaskProgress.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +2 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/schema.cjs +45 -0
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +3 -132
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +8 -3
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +2 -51
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/prompts/collab.mjs +9 -0
- package/dist/esm/prompts/collab.mjs.map +1 -0
- package/dist/esm/prompts/taskmanager.mjs +60 -0
- package/dist/esm/prompts/taskmanager.mjs.map +1 -0
- package/dist/esm/prompts/taskplanning.mjs +94 -0
- package/dist/esm/prompts/taskplanning.mjs.map +1 -0
- package/dist/esm/tools/Calculator.mjs +20 -3
- package/dist/esm/tools/Calculator.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +16 -2
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/TaskProgress.mjs +163 -0
- package/dist/esm/tools/TaskProgress.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +2 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/schema.mjs +42 -1
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/messages/format.d.ts +0 -9
- package/dist/types/prompts/index.d.ts +1 -0
- package/dist/types/prompts/taskplanning.d.ts +54 -0
- package/dist/types/tools/Calculator.d.ts +26 -0
- package/dist/types/tools/CodeExecutor.d.ts +51 -0
- package/dist/types/tools/TaskProgress.d.ts +142 -0
- package/dist/types/tools/search/index.d.ts +1 -0
- package/dist/types/tools/search/schema.d.ts +69 -0
- package/package.json +1 -1
- package/src/common/enum.ts +2 -0
- package/src/graphs/Graph.ts +5 -160
- package/src/index.ts +4 -0
- package/src/messages/format.ts +0 -60
- package/src/prompts/index.ts +2 -1
- package/src/prompts/taskplanning.ts +96 -0
- package/src/specs/task-progress.test.ts +330 -0
- package/src/tools/Calculator.ts +24 -3
- package/src/tools/CodeExecutor.ts +19 -2
- package/src/tools/TaskProgress.ts +247 -0
- package/src/tools/ToolNode.ts +2 -1
- package/src/tools/search/index.ts +1 -0
- package/src/tools/search/schema.ts +45 -0
- package/src/tools/search/tool.ts +3 -3
|
@@ -22,6 +22,23 @@ function _interopNamespaceDefault(e) {
|
|
|
22
22
|
|
|
23
23
|
var math__namespace = /*#__PURE__*/_interopNamespaceDefault(math);
|
|
24
24
|
|
|
25
|
+
const CalculatorToolName = 'calculator';
|
|
26
|
+
const CalculatorToolDescription = 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';
|
|
27
|
+
const CalculatorSchema = {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
input: {
|
|
31
|
+
type: 'string',
|
|
32
|
+
description: 'A valid mathematical expression to evaluate',
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
required: ['input'],
|
|
36
|
+
};
|
|
37
|
+
const CalculatorToolDefinition = {
|
|
38
|
+
name: CalculatorToolName,
|
|
39
|
+
description: CalculatorToolDescription,
|
|
40
|
+
schema: CalculatorSchema,
|
|
41
|
+
};
|
|
25
42
|
class Calculator extends tools.Tool {
|
|
26
43
|
static lc_name() {
|
|
27
44
|
return 'Calculator';
|
|
@@ -29,7 +46,7 @@ class Calculator extends tools.Tool {
|
|
|
29
46
|
get lc_namespace() {
|
|
30
47
|
return [...super.lc_namespace, 'calculator'];
|
|
31
48
|
}
|
|
32
|
-
name =
|
|
49
|
+
name = CalculatorToolName;
|
|
33
50
|
async _call(input) {
|
|
34
51
|
try {
|
|
35
52
|
return math__namespace.evaluate(input).toString();
|
|
@@ -38,8 +55,12 @@ class Calculator extends tools.Tool {
|
|
|
38
55
|
return 'I don\'t know how to do that.';
|
|
39
56
|
}
|
|
40
57
|
}
|
|
41
|
-
description =
|
|
58
|
+
description = CalculatorToolDescription;
|
|
42
59
|
}
|
|
43
60
|
|
|
44
61
|
exports.Calculator = Calculator;
|
|
62
|
+
exports.CalculatorSchema = CalculatorSchema;
|
|
63
|
+
exports.CalculatorToolDefinition = CalculatorToolDefinition;
|
|
64
|
+
exports.CalculatorToolDescription = CalculatorToolDescription;
|
|
65
|
+
exports.CalculatorToolName = CalculatorToolName;
|
|
45
66
|
//# sourceMappingURL=Calculator.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Calculator.cjs","sources":["../../../src/tools/Calculator.ts"],"sourcesContent":["import { Tool } from '@langchain/core/tools';\nimport * as math from 'mathjs';\n\nexport class Calculator extends Tool {\n static lc_name(): string {\n return 'Calculator';\n }\n\n get lc_namespace(): string[] {\n return [...super.lc_namespace, 'calculator'];\n }\n\n name =
|
|
1
|
+
{"version":3,"file":"Calculator.cjs","sources":["../../../src/tools/Calculator.ts"],"sourcesContent":["import { Tool } from '@langchain/core/tools';\nimport * as math from 'mathjs';\n\nexport const CalculatorToolName = 'calculator';\n\nexport const CalculatorToolDescription =\n 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';\n\nexport const CalculatorSchema = {\n type: 'object',\n properties: {\n input: {\n type: 'string',\n description: 'A valid mathematical expression to evaluate',\n },\n },\n required: ['input'],\n} as const;\n\nexport const CalculatorToolDefinition = {\n name: CalculatorToolName,\n description: CalculatorToolDescription,\n schema: CalculatorSchema,\n} as const;\n\nexport class Calculator extends Tool {\n static lc_name(): string {\n return 'Calculator';\n }\n\n get lc_namespace(): string[] {\n return [...super.lc_namespace, 'calculator'];\n }\n\n name = CalculatorToolName;\n\n async _call(input: string): Promise<string> {\n try {\n return math.evaluate(input).toString();\n } catch {\n return 'I don\\'t know how to do that.';\n }\n }\n\n description = CalculatorToolDescription;\n}\n"],"names":["Tool","math"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGO,MAAM,kBAAkB,GAAG;AAE3B,MAAM,yBAAyB,GACpC;AAEW,MAAA,gBAAgB,GAAG;AAC9B,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,6CAA6C;AAC3D,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,OAAO,CAAC;;AAGR,MAAA,wBAAwB,GAAG;AACtC,IAAA,IAAI,EAAE,kBAAkB;AACxB,IAAA,WAAW,EAAE,yBAAyB;AACtC,IAAA,MAAM,EAAE,gBAAgB;;AAGpB,MAAO,UAAW,SAAQA,UAAI,CAAA;AAClC,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,YAAY;;AAGrB,IAAA,IAAI,YAAY,GAAA;QACd,OAAO,CAAC,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC;;IAG9C,IAAI,GAAG,kBAAkB;IAEzB,MAAM,KAAK,CAAC,KAAa,EAAA;AACvB,QAAA,IAAI;YACF,OAAOC,eAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE;;AACtC,QAAA,MAAM;AACN,YAAA,OAAO,+BAA+B;;;IAI1C,WAAW,GAAG,yBAAyB;AACxC;;;;;;;;"}
|
|
@@ -62,6 +62,20 @@ const CodeExecutionToolSchema = {
|
|
|
62
62
|
};
|
|
63
63
|
const baseEndpoint = getCodeBaseURL();
|
|
64
64
|
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
65
|
+
const CodeExecutionToolDescription = `
|
|
66
|
+
Runs 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.
|
|
67
|
+
|
|
68
|
+
Usage:
|
|
69
|
+
- No network access available.
|
|
70
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
71
|
+
- NEVER use this tool to execute malicious code.
|
|
72
|
+
`.trim();
|
|
73
|
+
const CodeExecutionToolName = _enum.Constants.EXECUTE_CODE;
|
|
74
|
+
const CodeExecutionToolDefinition = {
|
|
75
|
+
name: CodeExecutionToolName,
|
|
76
|
+
description: CodeExecutionToolDescription,
|
|
77
|
+
schema: CodeExecutionToolSchema,
|
|
78
|
+
};
|
|
65
79
|
function createCodeExecutionTool(params = {}) {
|
|
66
80
|
const apiKey = params[_enum.EnvVar.CODE_API_KEY] ??
|
|
67
81
|
params.apiKey ??
|
|
@@ -203,13 +217,17 @@ Rules:
|
|
|
203
217
|
throw new Error(`Execution error:\n\n${error?.message}`);
|
|
204
218
|
}
|
|
205
219
|
}, {
|
|
206
|
-
name:
|
|
220
|
+
name: CodeExecutionToolName,
|
|
207
221
|
description,
|
|
208
222
|
schema: CodeExecutionToolSchema,
|
|
209
223
|
responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
|
|
210
224
|
});
|
|
211
225
|
}
|
|
212
226
|
|
|
227
|
+
exports.CodeExecutionToolDefinition = CodeExecutionToolDefinition;
|
|
228
|
+
exports.CodeExecutionToolDescription = CodeExecutionToolDescription;
|
|
229
|
+
exports.CodeExecutionToolName = CodeExecutionToolName;
|
|
230
|
+
exports.CodeExecutionToolSchema = CodeExecutionToolSchema;
|
|
213
231
|
exports.createCodeExecutionTool = createCodeExecutionTool;
|
|
214
232
|
exports.getCodeBaseURL = getCodeBaseURL;
|
|
215
233
|
exports.imageExtRegex = imageExtRegex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutor.cjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { 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 from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst SUPPORTED_LANGUAGES = [\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] as const;\n\nconst CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `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- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\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 },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\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 required: ['lang', 'code'],\n} as const;\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\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 = `\n⛔ STOP! Before using this tool, ask: \"Does user need a DOWNLOADABLE FILE?\"\n- If NO (dashboard, chart, visualization, UI) → DO NOT USE THIS TOOL. Use :::artifact instead.\n- If YES (.pptx, .docx, .pdf, .xlsx) → Use this tool.\n\nRuns code in a stateless execution environment. Each execution is isolated.\n\n🚫 NEVER USE FOR:\n- Dashboards, charts, visualizations → Use :::artifact with React/Chart.js\n- \"Mock data\" or \"sample data\" for display → Hardcode data in artifact\n- UI components, HTML pages, React apps → Use :::artifact\n\n✅ ONLY USE FOR:\n- File generation: PowerPoint (.pptx), Word (.docx), PDF (.pdf), Excel (.xlsx)\n- Processing uploaded files (CSV, Excel analysis)\n- Heavy computation requiring Python\n\nRules:\n- No network access available\n- Generated files auto-delivered (no download links needed)\n`.trim();\n\n return tool(\n async (rawInput, config) => {\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: For API to associate with previous session\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition)\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\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 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 postData.files = fileReferences;\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 += `\\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 }\n );\n}\n\nexport { createCodeExecutionT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7C,oBAAA,eAAe,IAAI,CAAe,YAAA,EAAA,IAAI,CAAC,IAAI,MAAM,OAAO,GAAG,YAAY,GAAG,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;;;AAIpD,gBAAA,eAAe,IAAI,CAAA,IAAA,EAAO,aAAa,CAAA,CAAE;gBACzC,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,EAAEF,eAAS,CAAC,YAAY;QAC5B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;"}
|
|
1
|
+
{"version":3,"file":"CodeExecutor.cjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { 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 from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst SUPPORTED_LANGUAGES = [\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] as const;\n\nexport const CodeExecutionToolSchema = {\n type: 'object',\n properties: {\n lang: {\n type: 'string',\n enum: SUPPORTED_LANGUAGES,\n description:\n 'The programming language or runtime to execute the code in.',\n },\n code: {\n type: 'string',\n description: `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- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\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 },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\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 required: ['lang', 'code'],\n} as const;\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\ntype SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];\n\nexport const CodeExecutionToolDescription = `\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\nexport const CodeExecutionToolName = Constants.EXECUTE_CODE;\n\nexport const CodeExecutionToolDefinition = {\n name: CodeExecutionToolName,\n description: CodeExecutionToolDescription,\n schema: CodeExecutionToolSchema,\n} as const;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool {\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 = `\n⛔ STOP! Before using this tool, ask: \"Does user need a DOWNLOADABLE FILE?\"\n- If NO (dashboard, chart, visualization, UI) → DO NOT USE THIS TOOL. Use :::artifact instead.\n- If YES (.pptx, .docx, .pdf, .xlsx) → Use this tool.\n\nRuns code in a stateless execution environment. Each execution is isolated.\n\n🚫 NEVER USE FOR:\n- Dashboards, charts, visualizations → Use :::artifact with React/Chart.js\n- \"Mock data\" or \"sample data\" for display → Hardcode data in artifact\n- UI components, HTML pages, React apps → Use :::artifact\n\n✅ ONLY USE FOR:\n- File generation: PowerPoint (.pptx), Word (.docx), PDF (.pdf), Excel (.xlsx)\n- Processing uploaded files (CSV, Excel analysis)\n- Heavy computation requiring Python\n\nRules:\n- No network access available\n- Generated files auto-delivered (no download links needed)\n`.trim();\n\n return tool(\n async (rawInput, config) => {\n const { lang, code, ...rest } = rawInput as {\n lang: SupportedLanguage;\n code: string;\n args?: string[];\n };\n /**\n * Extract session context from config.toolCall (injected by ToolNode).\n * - session_id: For API to associate with previous session\n * - _injected_files: File refs to pass directly (avoids /files endpoint race condition)\n */\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n /** Fallback: fetch from /files endpoint (may have race condition issues) */\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 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 postData.files = fileReferences;\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 += `\\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: CodeExecutionToolName,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":["config","getEnvironmentVariable","EnvVar","Constants","tool","HttpsProxyAgent"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,mBAAmB,GAAG;IAC1B,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK;IACL,GAAG;CACK;AAEG,MAAA,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,IAAI,EAAE,mBAAmB;AACzB,YAAA,WAAW,EACT,6DAA6D;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AE,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;AACE,QAAA,IAAI,EAAE,qBAAqB;QAC3B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEF,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var tools = require('@langchain/core/tools');
|
|
6
|
+
var events = require('../utils/events.cjs');
|
|
7
|
+
var _enum = require('../common/enum.cjs');
|
|
8
|
+
|
|
9
|
+
// src/tools/TaskProgress.ts
|
|
10
|
+
/**
|
|
11
|
+
* Tool name constant - matches what AI calls
|
|
12
|
+
*/
|
|
13
|
+
const TaskProgressToolName = 'manage_todo_list';
|
|
14
|
+
/**
|
|
15
|
+
* Tool description for the AI
|
|
16
|
+
*/
|
|
17
|
+
const TaskProgressToolDescription = `Manage a structured todo list to track progress and plan tasks throughout your session.
|
|
18
|
+
|
|
19
|
+
**When to use this tool:**
|
|
20
|
+
- Complex multi-step work requiring planning and tracking (3+ steps)
|
|
21
|
+
- When breaking down larger tasks into smaller actionable steps
|
|
22
|
+
- Before starting work on any todo (mark as in-progress)
|
|
23
|
+
- Immediately after completing each todo (mark as completed)
|
|
24
|
+
- To give users visibility into your progress and planning
|
|
25
|
+
|
|
26
|
+
**When NOT to use:**
|
|
27
|
+
- Single, trivial tasks completed in one step
|
|
28
|
+
- Purely conversational/informational requests
|
|
29
|
+
- Simple file reads or searches
|
|
30
|
+
|
|
31
|
+
**Critical workflow:**
|
|
32
|
+
1. Plan tasks by creating todo list with specific, actionable items
|
|
33
|
+
2. Mark ONE todo as in-progress before starting work
|
|
34
|
+
3. Complete the work (may involve multiple tool calls)
|
|
35
|
+
4. Mark that todo as completed IMMEDIATELY
|
|
36
|
+
5. Move to next todo and repeat
|
|
37
|
+
|
|
38
|
+
**Todo states:**
|
|
39
|
+
- not-started: Todo not yet begun
|
|
40
|
+
- in-progress: Currently working (limit ONE at a time)
|
|
41
|
+
- completed: Finished successfully
|
|
42
|
+
- failed: Task could not be completed
|
|
43
|
+
|
|
44
|
+
**Important:** Mark todos completed as soon as they are done. Do not batch completions.`;
|
|
45
|
+
/**
|
|
46
|
+
* JSON Schema for the tool input
|
|
47
|
+
*/
|
|
48
|
+
const TaskProgressToolSchema = {
|
|
49
|
+
type: 'object',
|
|
50
|
+
properties: {
|
|
51
|
+
todoList: {
|
|
52
|
+
type: 'array',
|
|
53
|
+
description: 'Complete array of all todo items. Must include ALL items - both existing and new.',
|
|
54
|
+
items: {
|
|
55
|
+
type: 'object',
|
|
56
|
+
properties: {
|
|
57
|
+
id: {
|
|
58
|
+
type: 'number',
|
|
59
|
+
description: 'Unique identifier for the todo. Use sequential numbers starting from 1.',
|
|
60
|
+
},
|
|
61
|
+
title: {
|
|
62
|
+
type: 'string',
|
|
63
|
+
description: 'Concise action-oriented todo label (3-7 words). Displayed in UI.',
|
|
64
|
+
},
|
|
65
|
+
status: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
enum: ['not-started', 'in-progress', 'completed', 'failed'],
|
|
68
|
+
description: 'not-started: Not begun | in-progress: Currently working (max 1) | completed: Fully finished | failed: Could not complete',
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
required: ['id', 'title', 'status'],
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
required: ['todoList'],
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Tool definition for registration/export
|
|
79
|
+
*/
|
|
80
|
+
const TaskProgressToolDefinition = {
|
|
81
|
+
name: TaskProgressToolName,
|
|
82
|
+
description: TaskProgressToolDescription,
|
|
83
|
+
schema: TaskProgressToolSchema,
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Creates a TaskProgress tool that allows the AI to manage a todo list
|
|
87
|
+
* and emits events for the UI to display progress.
|
|
88
|
+
*
|
|
89
|
+
* This tool is designed for ephemeral agents doing complex, multi-step work.
|
|
90
|
+
* It should NOT be included for:
|
|
91
|
+
* - Persistent workflow agents
|
|
92
|
+
* - Simple tool-calling agents
|
|
93
|
+
* - No-code/low-code builder workflows (unless explicitly enabled)
|
|
94
|
+
*
|
|
95
|
+
* @param params - Optional parameters including external callback
|
|
96
|
+
* @returns DynamicStructuredTool that can be added to agent tools
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* // Add to agent tools for ephemeral research/planning agents
|
|
101
|
+
* const tools = [
|
|
102
|
+
* createTaskProgressTool(),
|
|
103
|
+
* // ... other tools
|
|
104
|
+
* ];
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
function createTaskProgressTool(params = {}) {
|
|
108
|
+
const { onTaskUpdate } = params;
|
|
109
|
+
return tools.tool(async (rawInput, config) => {
|
|
110
|
+
const { todoList } = rawInput;
|
|
111
|
+
// Validate input
|
|
112
|
+
if (!Array.isArray(todoList)) {
|
|
113
|
+
return 'Error: todoList must be an array of task items.';
|
|
114
|
+
}
|
|
115
|
+
// Validate each task
|
|
116
|
+
for (const task of todoList) {
|
|
117
|
+
if (typeof task.id !== 'number') {
|
|
118
|
+
return `Error: Task id must be a number. Got: ${typeof task.id}`;
|
|
119
|
+
}
|
|
120
|
+
if (typeof task.title !== 'string' || task.title.trim() === '') {
|
|
121
|
+
return `Error: Task title must be a non-empty string for task ${task.id}`;
|
|
122
|
+
}
|
|
123
|
+
if (!['not-started', 'in-progress', 'completed', 'failed'].includes(task.status)) {
|
|
124
|
+
return `Error: Invalid status "${task.status}" for task ${task.id}. Must be one of: not-started, in-progress, completed, failed`;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// Check for multiple in-progress tasks (warning, not error)
|
|
128
|
+
const inProgressCount = todoList.filter((t) => t.status === 'in-progress').length;
|
|
129
|
+
const warning = inProgressCount > 1
|
|
130
|
+
? `\nWarning: ${inProgressCount} tasks marked as in-progress. Best practice is to work on one task at a time.`
|
|
131
|
+
: '';
|
|
132
|
+
// Check if all tasks are complete
|
|
133
|
+
const allComplete = todoList.length > 0 &&
|
|
134
|
+
todoList.every((t) => t.status === 'completed' || t.status === 'failed');
|
|
135
|
+
// Create the payload for SSE event
|
|
136
|
+
const payload = {
|
|
137
|
+
tasks: todoList,
|
|
138
|
+
timestamp: new Date().toISOString(),
|
|
139
|
+
isComplete: allComplete,
|
|
140
|
+
};
|
|
141
|
+
// Dispatch SSE event for UI to consume
|
|
142
|
+
await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_TASK_PROGRESS, payload, config);
|
|
143
|
+
// Call external callback if provided
|
|
144
|
+
if (onTaskUpdate) {
|
|
145
|
+
try {
|
|
146
|
+
await onTaskUpdate(todoList);
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
// Don't fail the tool call if callback fails
|
|
150
|
+
// eslint-disable-next-line no-console
|
|
151
|
+
console.warn('TaskProgress callback error:', e);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Build response message
|
|
155
|
+
const completed = todoList.filter((t) => t.status === 'completed').length;
|
|
156
|
+
const inProgress = todoList.filter((t) => t.status === 'in-progress').length;
|
|
157
|
+
const notStarted = todoList.filter((t) => t.status === 'not-started').length;
|
|
158
|
+
return `Todo list updated successfully. Status: ${completed}/${todoList.length} completed, ${inProgress} in progress, ${notStarted} remaining.${warning}`;
|
|
159
|
+
}, {
|
|
160
|
+
name: TaskProgressToolName,
|
|
161
|
+
description: TaskProgressToolDescription,
|
|
162
|
+
schema: TaskProgressToolSchema,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
exports.TaskProgressToolDefinition = TaskProgressToolDefinition;
|
|
167
|
+
exports.TaskProgressToolDescription = TaskProgressToolDescription;
|
|
168
|
+
exports.TaskProgressToolName = TaskProgressToolName;
|
|
169
|
+
exports.TaskProgressToolSchema = TaskProgressToolSchema;
|
|
170
|
+
exports.createTaskProgressTool = createTaskProgressTool;
|
|
171
|
+
exports.default = createTaskProgressTool;
|
|
172
|
+
//# sourceMappingURL=TaskProgress.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TaskProgress.cjs","sources":["../../../src/tools/TaskProgress.ts"],"sourcesContent":["// src/tools/TaskProgress.ts\r\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\r\nimport { safeDispatchCustomEvent } from '@/utils/events';\r\nimport { GraphEvents } from '@/common';\r\n\r\n/**\r\n * Task status enum matching the UI component expectations\r\n */\r\nexport type TaskStatus = 'not-started' | 'in-progress' | 'completed' | 'failed';\r\n\r\n/**\r\n * Individual task item in the todo list\r\n */\r\nexport interface TaskItem {\r\n /** Unique identifier for the task (sequential number starting from 1) */\r\n id: number;\r\n /** Short, action-oriented title (3-7 words) */\r\n title: string;\r\n /** Current status of the task */\r\n status: TaskStatus;\r\n /** Optional message for additional context */\r\n message?: string;\r\n}\r\n\r\n/**\r\n * Payload sent via SSE event for task progress updates\r\n * This matches the format expected by the Ranger UI\r\n */\r\nexport interface TaskProgressPayload {\r\n /** Complete list of all tasks */\r\n tasks: TaskItem[];\r\n /** Timestamp of the update */\r\n timestamp: string;\r\n /** Optional title for the task group */\r\n title?: string;\r\n /** Whether all tasks are complete */\r\n isComplete?: boolean;\r\n}\r\n\r\n/**\r\n * Tool name constant - matches what AI calls\r\n */\r\nexport const TaskProgressToolName = 'manage_todo_list';\r\n\r\n/**\r\n * Tool description for the AI\r\n */\r\nexport const TaskProgressToolDescription = `Manage a structured todo list to track progress and plan tasks throughout your session.\r\n\r\n**When to use this tool:**\r\n- Complex multi-step work requiring planning and tracking (3+ steps)\r\n- When breaking down larger tasks into smaller actionable steps\r\n- Before starting work on any todo (mark as in-progress)\r\n- Immediately after completing each todo (mark as completed)\r\n- To give users visibility into your progress and planning\r\n\r\n**When NOT to use:**\r\n- Single, trivial tasks completed in one step\r\n- Purely conversational/informational requests\r\n- Simple file reads or searches\r\n\r\n**Critical workflow:**\r\n1. Plan tasks by creating todo list with specific, actionable items\r\n2. Mark ONE todo as in-progress before starting work\r\n3. Complete the work (may involve multiple tool calls)\r\n4. Mark that todo as completed IMMEDIATELY\r\n5. Move to next todo and repeat\r\n\r\n**Todo states:**\r\n- not-started: Todo not yet begun\r\n- in-progress: Currently working (limit ONE at a time)\r\n- completed: Finished successfully\r\n- failed: Task could not be completed\r\n\r\n**Important:** Mark todos completed as soon as they are done. Do not batch completions.`;\r\n\r\n/**\r\n * JSON Schema for the tool input\r\n */\r\nexport const TaskProgressToolSchema = {\r\n type: 'object',\r\n properties: {\r\n todoList: {\r\n type: 'array',\r\n description:\r\n 'Complete array of all todo items. Must include ALL items - both existing and new.',\r\n items: {\r\n type: 'object',\r\n properties: {\r\n id: {\r\n type: 'number',\r\n description:\r\n 'Unique identifier for the todo. Use sequential numbers starting from 1.',\r\n },\r\n title: {\r\n type: 'string',\r\n description:\r\n 'Concise action-oriented todo label (3-7 words). Displayed in UI.',\r\n },\r\n status: {\r\n type: 'string',\r\n enum: ['not-started', 'in-progress', 'completed', 'failed'],\r\n description:\r\n 'not-started: Not begun | in-progress: Currently working (max 1) | completed: Fully finished | failed: Could not complete',\r\n },\r\n },\r\n required: ['id', 'title', 'status'],\r\n },\r\n },\r\n },\r\n required: ['todoList'],\r\n} as const;\r\n\r\n/**\r\n * Tool definition for registration/export\r\n */\r\nexport const TaskProgressToolDefinition = {\r\n name: TaskProgressToolName,\r\n description: TaskProgressToolDescription,\r\n schema: TaskProgressToolSchema,\r\n} as const;\r\n\r\n/**\r\n * Parameters for creating the TaskProgress tool\r\n */\r\nexport interface TaskProgressToolParams {\r\n /**\r\n * Optional callback to handle task updates externally\r\n * Called with the task list whenever it's updated\r\n */\r\n onTaskUpdate?: (tasks: TaskItem[]) => void | Promise<void>;\r\n}\r\n\r\n/**\r\n * Creates a TaskProgress tool that allows the AI to manage a todo list\r\n * and emits events for the UI to display progress.\r\n *\r\n * This tool is designed for ephemeral agents doing complex, multi-step work.\r\n * It should NOT be included for:\r\n * - Persistent workflow agents\r\n * - Simple tool-calling agents\r\n * - No-code/low-code builder workflows (unless explicitly enabled)\r\n *\r\n * @param params - Optional parameters including external callback\r\n * @returns DynamicStructuredTool that can be added to agent tools\r\n *\r\n * @example\r\n * ```typescript\r\n * // Add to agent tools for ephemeral research/planning agents\r\n * const tools = [\r\n * createTaskProgressTool(),\r\n * // ... other tools\r\n * ];\r\n * ```\r\n */\r\nexport function createTaskProgressTool(\r\n params: TaskProgressToolParams = {}\r\n): DynamicStructuredTool {\r\n const { onTaskUpdate } = params;\r\n\r\n return tool(\r\n async (rawInput, config) => {\r\n const { todoList } = rawInput as { todoList: TaskItem[] };\r\n\r\n // Validate input\r\n if (!Array.isArray(todoList)) {\r\n return 'Error: todoList must be an array of task items.';\r\n }\r\n\r\n // Validate each task\r\n for (const task of todoList) {\r\n if (typeof task.id !== 'number') {\r\n return `Error: Task id must be a number. Got: ${typeof task.id}`;\r\n }\r\n if (typeof task.title !== 'string' || task.title.trim() === '') {\r\n return `Error: Task title must be a non-empty string for task ${task.id}`;\r\n }\r\n if (\r\n !['not-started', 'in-progress', 'completed', 'failed'].includes(\r\n task.status\r\n )\r\n ) {\r\n return `Error: Invalid status \"${task.status}\" for task ${task.id}. Must be one of: not-started, in-progress, completed, failed`;\r\n }\r\n }\r\n\r\n // Check for multiple in-progress tasks (warning, not error)\r\n const inProgressCount = todoList.filter(\r\n (t) => t.status === 'in-progress'\r\n ).length;\r\n const warning =\r\n inProgressCount > 1\r\n ? `\\nWarning: ${inProgressCount} tasks marked as in-progress. Best practice is to work on one task at a time.`\r\n : '';\r\n\r\n // Check if all tasks are complete\r\n const allComplete =\r\n todoList.length > 0 &&\r\n todoList.every(\r\n (t) => t.status === 'completed' || t.status === 'failed'\r\n );\r\n\r\n // Create the payload for SSE event\r\n const payload: TaskProgressPayload = {\r\n tasks: todoList,\r\n timestamp: new Date().toISOString(),\r\n isComplete: allComplete,\r\n };\r\n\r\n // Dispatch SSE event for UI to consume\r\n await safeDispatchCustomEvent(\r\n GraphEvents.ON_TASK_PROGRESS,\r\n payload,\r\n config\r\n );\r\n\r\n // Call external callback if provided\r\n if (onTaskUpdate) {\r\n try {\r\n await onTaskUpdate(todoList);\r\n } catch (e) {\r\n // Don't fail the tool call if callback fails\r\n // eslint-disable-next-line no-console\r\n console.warn('TaskProgress callback error:', e);\r\n }\r\n }\r\n\r\n // Build response message\r\n const completed = todoList.filter((t) => t.status === 'completed').length;\r\n const inProgress = todoList.filter(\r\n (t) => t.status === 'in-progress'\r\n ).length;\r\n const notStarted = todoList.filter(\r\n (t) => t.status === 'not-started'\r\n ).length;\r\n\r\n return `Todo list updated successfully. Status: ${completed}/${todoList.length} completed, ${inProgress} in progress, ${notStarted} remaining.${warning}`;\r\n },\r\n {\r\n name: TaskProgressToolName,\r\n description: TaskProgressToolDescription,\r\n schema: TaskProgressToolSchema,\r\n }\r\n );\r\n}\r\n\r\nexport default createTaskProgressTool;\r\n"],"names":["tool","safeDispatchCustomEvent","GraphEvents"],"mappings":";;;;;;;;AAAA;AAuCA;;AAEG;AACI,MAAM,oBAAoB,GAAG;AAEpC;;AAEG;AACU,MAAA,2BAA2B,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6B3C;;AAEG;AACU,MAAA,sBAAsB,GAAG;AACpC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,QAAQ,EAAE;AACR,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,WAAW,EACT,mFAAmF;AACrF,YAAA,KAAK,EAAE;AACL,gBAAA,IAAI,EAAE,QAAQ;AACd,gBAAA,UAAU,EAAE;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M,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,MAAM;AACzE,QAAA,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAChC,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,aAAa,CAClC,CAAC,MAAM;AACR,QAAA,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAChC,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,aAAa,CAClC,CAAC,MAAM;AAER,QAAA,OAAO,CAA2C,wCAAA,EAAA,SAAS,CAAI,CAAA,EAAA,QAAQ,CAAC,MAAM,CAAe,YAAA,EAAA,UAAU,CAAiB,cAAA,EAAA,UAAU,CAAc,WAAA,EAAA,OAAO,EAAE;AAC3J,KAAC,EACD;AACE,QAAA,IAAI,EAAE,oBAAoB;AAC1B,QAAA,WAAW,EAAE,2BAA2B;AACxC,QAAA,MAAM,EAAE,sBAAsB;AAC/B,KAAA,CACF;AACH;;;;;;;;;"}
|
|
@@ -329,8 +329,9 @@ class ToolNode extends run.RunnableCallable {
|
|
|
329
329
|
: JSON.stringify(result.content);
|
|
330
330
|
toolMessage = new messages.ToolMessage({
|
|
331
331
|
status: 'success',
|
|
332
|
-
content: contentString,
|
|
333
332
|
name: toolName,
|
|
333
|
+
content: contentString,
|
|
334
|
+
artifact: result.artifact,
|
|
334
335
|
tool_call_id: result.toolCallId,
|
|
335
336
|
});
|
|
336
337
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\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';\nimport { processToolOutput } from '@/utils/toonFormat';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\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 this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\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 /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\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\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\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 * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\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":["Send","RunnableCallable","Constants","isCommand","isBaseMessage","processToolOutput","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;AA0BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;;AAIhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC1B,MAAM,SAAS,GAAa,EAAE;AAC9B,QAAA,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE;AAC3B,YAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,gBAAA,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;;AAChB,iBAAA,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;;gBAE7C,MAAM,GAAG,GAAG,KAAgC;AAC5C,gBAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;AACvD,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;;AACnB,qBAAA,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;;AAEvC,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;;;;AAI9B,QAAA,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;AACxB,YAAA,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;;;;AAK/B,IAAA,OAAO,IAAI,CAAC,SAAS,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all } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\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';\nimport { processToolOutput } from '@/utils/toonFormat';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n/**\n * Extract text content from a ToolMessage content field.\n * Handles both string and MessageContentComplex[] formats.\n * For array content (e.g., from content_and_artifact tools), extracts text from text blocks.\n */\nfunction extractStringContent(content: unknown): string {\n // Already a string - return as is\n if (typeof content === 'string') {\n return content;\n }\n\n // Array of content blocks - extract text from each\n if (Array.isArray(content)) {\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if (block && typeof block === 'object') {\n // Handle {type: 'text', text: '...'} format\n const obj = block as Record<string, unknown>;\n if (obj.type === 'text' && typeof obj.text === 'string') {\n textParts.push(obj.text);\n } else if (typeof obj.text === 'string') {\n // Just has 'text' property\n textParts.push(obj.text);\n }\n }\n }\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n // Fallback: stringify whatever it is\n return JSON.stringify(content);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\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 this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\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 /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\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\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n\n // Handle Command outputs directly\n if (isCommand(output)) {\n return output;\n }\n\n // ========================================================================\n // TOOL OUTPUT PROCESSING - Single point for all tools (MCP and non-MCP)\n // 1. Extract string content from any output format\n // 2. Apply TOON conversion if content contains JSON\n // 3. Apply truncation if still too large\n // 4. Return ToolMessage with processed string content\n // ========================================================================\n\n // Step 1: Extract string content from the output\n let rawContent: string;\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n rawContent = extractStringContent(toolMsg.content);\n } else {\n rawContent = extractStringContent(output);\n }\n\n // Step 2 & 3: Apply TOON conversion and truncation\n const processed = processToolOutput(rawContent, {\n maxLength: 100000, // 100K char limit\n enableToon: true,\n minSizeForToon: 1000,\n minReductionPercent: 10, // Only apply TOON when clearly beneficial\n });\n\n // Step 4: Return ToolMessage with processed string content\n if (isBaseMessage(output) && output._getType() === 'tool') {\n const toolMsg = output as ToolMessage;\n return new ToolMessage({\n status: toolMsg.status,\n name: toolMsg.name,\n content: processed.content,\n tool_call_id: toolMsg.tool_call_id,\n });\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: processed.content,\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 if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\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 * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\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":["Send","RunnableCallable","Constants","isCommand","isBaseMessage","processToolOutput","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;;AA0BA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;AAC9B;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAgB,EAAA;;AAE5C,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;;AAIhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC1B,MAAM,SAAS,GAAa,EAAE;AAC9B,QAAA,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE;AAC3B,YAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,gBAAA,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC;;AAChB,iBAAA,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;;gBAE7C,MAAM,GAAG,GAAG,KAAgC;AAC5C,gBAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;AACvD,oBAAA,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;;AACnB,qBAAA,IAAI,OAAO,GAAG,CAAC,IAAI,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B,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAOS,aAAG;;AAEd;;;;;"}
|
|
@@ -60,9 +60,54 @@ const newsSchema = {
|
|
|
60
60
|
type: 'boolean',
|
|
61
61
|
description: 'Whether to also run a news search.',
|
|
62
62
|
};
|
|
63
|
+
/** Combined web search tool schema with all properties */
|
|
64
|
+
const WebSearchToolSchema = {
|
|
65
|
+
type: 'object',
|
|
66
|
+
properties: {
|
|
67
|
+
query: querySchema,
|
|
68
|
+
date: dateSchema,
|
|
69
|
+
country: countrySchema,
|
|
70
|
+
images: imagesSchema,
|
|
71
|
+
videos: videosSchema,
|
|
72
|
+
news: newsSchema,
|
|
73
|
+
},
|
|
74
|
+
required: ['query'],
|
|
75
|
+
};
|
|
76
|
+
const WebSearchToolName = 'web_search';
|
|
77
|
+
const WebSearchToolDescription = `Real-time search. Results have required citation anchors.
|
|
78
|
+
|
|
79
|
+
Note: Use ONCE per reply unless instructed otherwise.
|
|
80
|
+
|
|
81
|
+
Anchors:
|
|
82
|
+
- \\ue202turnXtypeY
|
|
83
|
+
- X = turn idx, type = 'search' | 'news' | 'image' | 'ref', Y = item idx
|
|
84
|
+
|
|
85
|
+
Special Markers:
|
|
86
|
+
- \\ue203...\\ue204 — highlight start/end of cited text (for Standalone or Group citations)
|
|
87
|
+
- \\ue200...\\ue201 — group block (e.g. \\ue200\\ue202turn0search1\\ue202turn0news2\\ue201)
|
|
88
|
+
|
|
89
|
+
**CITE EVERY NON-OBVIOUS FACT/QUOTE:**
|
|
90
|
+
Use anchor marker(s) immediately after the statement:
|
|
91
|
+
- Standalone: "Pure functions produce same output. \\ue202turn0search0"
|
|
92
|
+
- Standalone (multiple): "Today's News \\ue202turn0search0\\ue202turn0news0"
|
|
93
|
+
- Highlight: "\\ue203Highlight text.\\ue204\\ue202turn0news1"
|
|
94
|
+
- Group: "Sources. \\ue200\\ue202turn0search0\\ue202turn0news1\\ue201"
|
|
95
|
+
- Group Highlight: "\\ue203Highlight for group.\\ue204 \\ue200\\ue202turn0search0\\ue202turn0news1\\ue201"
|
|
96
|
+
- Image: "See photo \\ue202turn0image0."
|
|
97
|
+
|
|
98
|
+
**NEVER use markdown links, [1], or footnotes. CITE ONLY with anchors provided.**`;
|
|
99
|
+
const WebSearchToolDefinition = {
|
|
100
|
+
name: WebSearchToolName,
|
|
101
|
+
description: WebSearchToolDescription,
|
|
102
|
+
schema: WebSearchToolSchema,
|
|
103
|
+
};
|
|
63
104
|
|
|
64
105
|
exports.DEFAULT_COUNTRY_DESCRIPTION = DEFAULT_COUNTRY_DESCRIPTION;
|
|
65
106
|
exports.DEFAULT_QUERY_DESCRIPTION = DEFAULT_QUERY_DESCRIPTION;
|
|
107
|
+
exports.WebSearchToolDefinition = WebSearchToolDefinition;
|
|
108
|
+
exports.WebSearchToolDescription = WebSearchToolDescription;
|
|
109
|
+
exports.WebSearchToolName = WebSearchToolName;
|
|
110
|
+
exports.WebSearchToolSchema = WebSearchToolSchema;
|
|
66
111
|
exports.countrySchema = countrySchema;
|
|
67
112
|
exports.dateSchema = dateSchema;
|
|
68
113
|
exports.imagesSchema = imagesSchema;
|