@librechat/agents 3.1.67 → 3.1.68-dev.0
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/agents/AgentContext.cjs +23 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +16 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +91 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +36 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/main.cjs +54 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +111 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/index.cjs +41 -0
- package/dist/cjs/summarization/index.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +165 -19
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +175 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +296 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +92 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +304 -140
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +23 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +15 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +91 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +36 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/main.mjs +13 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +111 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/index.mjs +41 -1
- package/dist/esm/summarization/index.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +165 -19
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +169 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +287 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +85 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +306 -142
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +10 -1
- package/dist/types/graphs/Graph.d.ts +2 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +12 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +1 -0
- package/dist/types/summarization/index.d.ts +2 -0
- package/dist/types/summarization/node.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +45 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +24 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/types/graph.d.ts +61 -2
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/run.d.ts +20 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +38 -1
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +15 -0
- package/src/graphs/Graph.ts +113 -0
- package/src/graphs/MultiAgentGraph.ts +39 -0
- package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.ts +10 -0
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/run.ts +126 -0
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/__tests__/node.test.ts +42 -0
- package/src/summarization/__tests__/trigger.test.ts +100 -1
- package/src/summarization/index.ts +47 -0
- package/src/summarization/node.ts +202 -24
- package/src/tools/BashExecutor.ts +205 -0
- package/src/tools/BashProgrammaticToolCalling.ts +397 -0
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.ts +391 -169
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +215 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +676 -0
- package/src/tools/subagent/index.ts +13 -0
- package/src/types/graph.ts +80 -1
- package/src/types/index.ts +1 -0
- package/src/types/run.ts +20 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +41 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { config } from 'dotenv';
|
|
2
|
+
import fetch from 'node-fetch';
|
|
3
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
4
|
+
import { tool } from '@langchain/core/tools';
|
|
5
|
+
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
6
|
+
import { getCodeBaseURL, imageExtRegex } from './CodeExecutor.mjs';
|
|
7
|
+
import { Constants, EnvVar } from '../common/enum.mjs';
|
|
8
|
+
|
|
9
|
+
config();
|
|
10
|
+
const imageMessage = 'Image is already displayed to the user';
|
|
11
|
+
const otherMessage = 'File is already downloaded by the user';
|
|
12
|
+
const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
|
|
13
|
+
const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
14
|
+
const baseEndpoint = getCodeBaseURL();
|
|
15
|
+
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
16
|
+
const BashExecutionToolSchema = {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
command: {
|
|
20
|
+
type: 'string',
|
|
21
|
+
description: `The bash command or script to execute.
|
|
22
|
+
- The environment is stateless; variables and state don't persist between executions.
|
|
23
|
+
- Generated files from previous executions are automatically available in "/mnt/data/".
|
|
24
|
+
- Files from previous executions are automatically available and can be modified in place.
|
|
25
|
+
- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
|
|
26
|
+
- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
|
|
27
|
+
- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
|
|
28
|
+
- Use \`echo\`, \`printf\`, or \`cat\` for all outputs.`,
|
|
29
|
+
},
|
|
30
|
+
args: {
|
|
31
|
+
type: 'array',
|
|
32
|
+
items: { type: 'string' },
|
|
33
|
+
description: 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
required: ['command'],
|
|
37
|
+
};
|
|
38
|
+
const BashExecutionToolDescription = `
|
|
39
|
+
Runs bash commands 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.
|
|
40
|
+
|
|
41
|
+
Usage:
|
|
42
|
+
- No network access available.
|
|
43
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
44
|
+
- NEVER use this tool to execute malicious commands.
|
|
45
|
+
`.trim();
|
|
46
|
+
const BashExecutionToolName = Constants.BASH_TOOL;
|
|
47
|
+
const BashExecutionToolDefinition = {
|
|
48
|
+
name: BashExecutionToolName,
|
|
49
|
+
description: BashExecutionToolDescription,
|
|
50
|
+
schema: BashExecutionToolSchema,
|
|
51
|
+
};
|
|
52
|
+
function createBashExecutionTool(params = {}) {
|
|
53
|
+
const apiKey = params[EnvVar.CODE_API_KEY] ??
|
|
54
|
+
params.apiKey ??
|
|
55
|
+
getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
|
|
56
|
+
'';
|
|
57
|
+
if (!apiKey) {
|
|
58
|
+
throw new Error('No API key provided for bash execution tool.');
|
|
59
|
+
}
|
|
60
|
+
return tool(async (rawInput, config) => {
|
|
61
|
+
const { command, ...rest } = rawInput;
|
|
62
|
+
const { session_id, _injected_files } = (config.toolCall ?? {});
|
|
63
|
+
const postData = {
|
|
64
|
+
lang: 'bash',
|
|
65
|
+
code: command,
|
|
66
|
+
...rest,
|
|
67
|
+
...params,
|
|
68
|
+
};
|
|
69
|
+
if (_injected_files && _injected_files.length > 0) {
|
|
70
|
+
postData.files = _injected_files;
|
|
71
|
+
}
|
|
72
|
+
else if (session_id != null && session_id.length > 0) {
|
|
73
|
+
try {
|
|
74
|
+
const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
|
|
75
|
+
const fetchOptions = {
|
|
76
|
+
method: 'GET',
|
|
77
|
+
headers: {
|
|
78
|
+
'User-Agent': 'LibreChat/1.0',
|
|
79
|
+
'X-API-Key': apiKey,
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
83
|
+
fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
84
|
+
}
|
|
85
|
+
const response = await fetch(filesEndpoint, fetchOptions);
|
|
86
|
+
if (!response.ok) {
|
|
87
|
+
throw new Error(`Failed to fetch files for session: ${response.status}`);
|
|
88
|
+
}
|
|
89
|
+
const files = await response.json();
|
|
90
|
+
if (Array.isArray(files) && files.length > 0) {
|
|
91
|
+
const fileReferences = files.map((file) => {
|
|
92
|
+
const nameParts = file.name.split('/');
|
|
93
|
+
const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
|
|
94
|
+
return {
|
|
95
|
+
session_id,
|
|
96
|
+
id,
|
|
97
|
+
name: file.metadata['original-filename'],
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
postData.files = fileReferences;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// eslint-disable-next-line no-console
|
|
105
|
+
console.warn(`Failed to fetch files for session: ${session_id}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const fetchOptions = {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
headers: {
|
|
112
|
+
'Content-Type': 'application/json',
|
|
113
|
+
'User-Agent': 'LibreChat/1.0',
|
|
114
|
+
'X-API-Key': apiKey,
|
|
115
|
+
},
|
|
116
|
+
body: JSON.stringify(postData),
|
|
117
|
+
};
|
|
118
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
119
|
+
fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
120
|
+
}
|
|
121
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
122
|
+
if (!response.ok) {
|
|
123
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
124
|
+
}
|
|
125
|
+
const result = await response.json();
|
|
126
|
+
let formattedOutput = '';
|
|
127
|
+
if (result.stdout) {
|
|
128
|
+
formattedOutput += `stdout:\n${result.stdout}\n`;
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
formattedOutput += emptyOutputMessage;
|
|
132
|
+
}
|
|
133
|
+
if (result.stderr)
|
|
134
|
+
formattedOutput += `stderr:\n${result.stderr}\n`;
|
|
135
|
+
if (result.files && result.files.length > 0) {
|
|
136
|
+
formattedOutput += 'Generated files:\n';
|
|
137
|
+
const fileCount = result.files.length;
|
|
138
|
+
for (let i = 0; i < fileCount; i++) {
|
|
139
|
+
const file = result.files[i];
|
|
140
|
+
const isImage = imageExtRegex.test(file.name);
|
|
141
|
+
formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
|
|
142
|
+
if (i < fileCount - 1) {
|
|
143
|
+
formattedOutput += fileCount <= 3 ? ', ' : ',\n';
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
formattedOutput += `\n\n${accessMessage}`;
|
|
147
|
+
return [
|
|
148
|
+
formattedOutput.trim(),
|
|
149
|
+
{
|
|
150
|
+
session_id: result.session_id,
|
|
151
|
+
files: result.files,
|
|
152
|
+
},
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
return [formattedOutput.trim(), { session_id: result.session_id }];
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
throw new Error(`Execution error:\n\n${error?.message}`);
|
|
159
|
+
}
|
|
160
|
+
}, {
|
|
161
|
+
name: BashExecutionToolName,
|
|
162
|
+
description: BashExecutionToolDescription,
|
|
163
|
+
schema: BashExecutionToolSchema,
|
|
164
|
+
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, createBashExecutionTool };
|
|
169
|
+
//# sourceMappingURL=BashExecutor.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BashExecutor.mjs","sources":["../../../src/tools/BashExecutor.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 { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\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 baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state 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- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands 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 commands.\n`.trim();\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\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 bash execution tool.');\n }\n\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\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: 'bash',\n code: command,\n ...rest,\n ...params,\n };\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 try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/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': 'LibreChat/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: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.C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A,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;YACH;AAEA,YAAA,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACpE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { config } from 'dotenv';
|
|
2
|
+
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
3
|
+
import { tool } from '@langchain/core/tools';
|
|
4
|
+
import { fetchSessionFiles, makeRequest, executeTools, formatCompletedResponse } from './ProgrammaticToolCalling.mjs';
|
|
5
|
+
import { getCodeBaseURL } from './CodeExecutor.mjs';
|
|
6
|
+
import { Constants, EnvVar } from '../common/enum.mjs';
|
|
7
|
+
|
|
8
|
+
config();
|
|
9
|
+
// ============================================================================
|
|
10
|
+
// Constants
|
|
11
|
+
// ============================================================================
|
|
12
|
+
const DEFAULT_MAX_ROUND_TRIPS = 20;
|
|
13
|
+
const DEFAULT_TIMEOUT = 60000;
|
|
14
|
+
/** Bash reserved words that get `_tool` suffix when used as function names */
|
|
15
|
+
const BASH_RESERVED = new Set([
|
|
16
|
+
'if',
|
|
17
|
+
'then',
|
|
18
|
+
'else',
|
|
19
|
+
'elif',
|
|
20
|
+
'fi',
|
|
21
|
+
'case',
|
|
22
|
+
'esac',
|
|
23
|
+
'for',
|
|
24
|
+
'while',
|
|
25
|
+
'until',
|
|
26
|
+
'do',
|
|
27
|
+
'done',
|
|
28
|
+
'in',
|
|
29
|
+
'function',
|
|
30
|
+
'select',
|
|
31
|
+
'time',
|
|
32
|
+
'coproc',
|
|
33
|
+
'declare',
|
|
34
|
+
'typeset',
|
|
35
|
+
'local',
|
|
36
|
+
'readonly',
|
|
37
|
+
'export',
|
|
38
|
+
'unset',
|
|
39
|
+
]);
|
|
40
|
+
// ============================================================================
|
|
41
|
+
// Description Components
|
|
42
|
+
// ============================================================================
|
|
43
|
+
const STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:
|
|
44
|
+
Each call is a fresh bash shell. Variables and state do NOT persist between calls.
|
|
45
|
+
You MUST complete your entire workflow in ONE code block.
|
|
46
|
+
DO NOT split work across multiple calls expecting to reuse variables.`;
|
|
47
|
+
const CORE_RULES = `Rules:
|
|
48
|
+
- EVERYTHING in one call—no state persists between executions
|
|
49
|
+
- Tools are pre-defined as bash functions—DO NOT redefine them
|
|
50
|
+
- Each tool function accepts a JSON string argument
|
|
51
|
+
- Only echo/printf output returns to the model
|
|
52
|
+
- Generated files are automatically available in /mnt/data/ for subsequent executions`;
|
|
53
|
+
const ADDITIONAL_RULES = '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';
|
|
54
|
+
const EXAMPLES = `Example (Complete workflow in one call):
|
|
55
|
+
# Query data and process
|
|
56
|
+
data=$(query_database '{"sql": "SELECT * FROM users"}')
|
|
57
|
+
echo "$data" | jq '.[] | .name'
|
|
58
|
+
|
|
59
|
+
Example (Parallel calls):
|
|
60
|
+
web_search '{"query": "SF weather"}' > /tmp/sf.txt &
|
|
61
|
+
web_search '{"query": "NY weather"}' > /tmp/ny.txt &
|
|
62
|
+
wait
|
|
63
|
+
echo "SF: $(cat /tmp/sf.txt)"
|
|
64
|
+
echo "NY: $(cat /tmp/ny.txt)"`;
|
|
65
|
+
const CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.
|
|
66
|
+
|
|
67
|
+
${STATELESS_WARNING}
|
|
68
|
+
|
|
69
|
+
Each tool function accepts a JSON string as its argument.
|
|
70
|
+
Example: tool_name '{"key": "value"}'
|
|
71
|
+
|
|
72
|
+
${EXAMPLES}
|
|
73
|
+
|
|
74
|
+
${CORE_RULES}`;
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// Schema
|
|
77
|
+
// ============================================================================
|
|
78
|
+
const BashProgrammaticToolCallingSchema = {
|
|
79
|
+
type: 'object',
|
|
80
|
+
properties: {
|
|
81
|
+
code: {
|
|
82
|
+
type: 'string',
|
|
83
|
+
minLength: 1,
|
|
84
|
+
description: CODE_PARAM_DESCRIPTION,
|
|
85
|
+
},
|
|
86
|
+
timeout: {
|
|
87
|
+
type: 'integer',
|
|
88
|
+
minimum: 1000,
|
|
89
|
+
maximum: 300000,
|
|
90
|
+
default: DEFAULT_TIMEOUT,
|
|
91
|
+
description: 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
required: ['code'],
|
|
95
|
+
};
|
|
96
|
+
const BashProgrammaticToolCallingName = Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
|
|
97
|
+
const BashProgrammaticToolCallingDescription = `
|
|
98
|
+
Run tools via bash code. Tools are available as bash functions that accept JSON string arguments.
|
|
99
|
+
|
|
100
|
+
${STATELESS_WARNING}
|
|
101
|
+
|
|
102
|
+
${CORE_RULES}
|
|
103
|
+
${ADDITIONAL_RULES}
|
|
104
|
+
|
|
105
|
+
When to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.
|
|
106
|
+
|
|
107
|
+
${EXAMPLES}
|
|
108
|
+
`.trim();
|
|
109
|
+
const BashProgrammaticToolCallingDefinition = {
|
|
110
|
+
name: BashProgrammaticToolCallingName,
|
|
111
|
+
description: BashProgrammaticToolCallingDescription,
|
|
112
|
+
schema: BashProgrammaticToolCallingSchema,
|
|
113
|
+
};
|
|
114
|
+
// ============================================================================
|
|
115
|
+
// Helper Functions
|
|
116
|
+
// ============================================================================
|
|
117
|
+
/**
|
|
118
|
+
* Normalizes a tool name to a valid bash function identifier.
|
|
119
|
+
* 1. Replace hyphens, spaces, dots with underscores
|
|
120
|
+
* 2. Remove any other invalid characters
|
|
121
|
+
* 3. Prefix with underscore if starts with number
|
|
122
|
+
* 4. Append `_tool` if it's a bash reserved word
|
|
123
|
+
*/
|
|
124
|
+
function normalizeToBashIdentifier(name) {
|
|
125
|
+
let normalized = name.replace(/[-\s.]/g, '_');
|
|
126
|
+
normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');
|
|
127
|
+
if (/^[0-9]/.test(normalized)) {
|
|
128
|
+
normalized = '_' + normalized;
|
|
129
|
+
}
|
|
130
|
+
if (BASH_RESERVED.has(normalized)) {
|
|
131
|
+
normalized = normalized + '_tool';
|
|
132
|
+
}
|
|
133
|
+
return normalized;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Extracts tool names that are actually called in the bash code.
|
|
137
|
+
* Bash functions are invoked as commands (no parentheses), so we match
|
|
138
|
+
* the normalized name as a word boundary.
|
|
139
|
+
*/
|
|
140
|
+
function extractUsedBashToolNames(code, toolNameMap) {
|
|
141
|
+
const usedTools = new Set();
|
|
142
|
+
for (const [bashName, originalName] of toolNameMap) {
|
|
143
|
+
const escapedName = bashName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
144
|
+
const pattern = new RegExp(`\\b${escapedName}\\b`, 'g');
|
|
145
|
+
if (pattern.test(code)) {
|
|
146
|
+
usedTools.add(originalName);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return usedTools;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Filters tool definitions to only include tools actually used in the bash code.
|
|
153
|
+
*/
|
|
154
|
+
function filterBashToolsByUsage(toolDefs, code, debug = false) {
|
|
155
|
+
const toolNameMap = new Map();
|
|
156
|
+
for (const def of toolDefs) {
|
|
157
|
+
const bashName = normalizeToBashIdentifier(def.name);
|
|
158
|
+
toolNameMap.set(bashName, def.name);
|
|
159
|
+
}
|
|
160
|
+
const usedToolNames = extractUsedBashToolNames(code, toolNameMap);
|
|
161
|
+
if (debug) {
|
|
162
|
+
// eslint-disable-next-line no-console
|
|
163
|
+
console.log(`[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`);
|
|
164
|
+
if (usedToolNames.size > 0) {
|
|
165
|
+
// eslint-disable-next-line no-console
|
|
166
|
+
console.log(`[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (usedToolNames.size === 0) {
|
|
170
|
+
if (debug) {
|
|
171
|
+
// eslint-disable-next-line no-console
|
|
172
|
+
console.log('[BashPTC Debug] No tools detected in code - sending all tools as fallback');
|
|
173
|
+
}
|
|
174
|
+
return toolDefs;
|
|
175
|
+
}
|
|
176
|
+
return toolDefs.filter((def) => usedToolNames.has(def.name));
|
|
177
|
+
}
|
|
178
|
+
// ============================================================================
|
|
179
|
+
// Tool Factory
|
|
180
|
+
// ============================================================================
|
|
181
|
+
/**
|
|
182
|
+
* Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.
|
|
183
|
+
*
|
|
184
|
+
* This tool enables AI agents to write bash scripts that orchestrate multiple
|
|
185
|
+
* tool calls programmatically via the remote Code API, reducing LLM round-trips.
|
|
186
|
+
*
|
|
187
|
+
* The tool map must be provided at runtime via config.toolCall (injected by ToolNode).
|
|
188
|
+
*/
|
|
189
|
+
function createBashProgrammaticToolCallingTool(initParams = {}) {
|
|
190
|
+
const apiKey = initParams[EnvVar.CODE_API_KEY] ??
|
|
191
|
+
initParams.apiKey ??
|
|
192
|
+
getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
|
|
193
|
+
'';
|
|
194
|
+
if (!apiKey) {
|
|
195
|
+
throw new Error('No API key provided for bash programmatic tool calling. ' +
|
|
196
|
+
'Set CODE_API_KEY environment variable or pass apiKey in initParams.');
|
|
197
|
+
}
|
|
198
|
+
const baseUrl = initParams.baseUrl ?? getCodeBaseURL();
|
|
199
|
+
const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
|
|
200
|
+
const proxy = initParams.proxy ?? process.env.PROXY;
|
|
201
|
+
const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';
|
|
202
|
+
const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
|
|
203
|
+
return tool(async (rawParams, config) => {
|
|
204
|
+
const params = rawParams;
|
|
205
|
+
const { code, timeout = DEFAULT_TIMEOUT } = params;
|
|
206
|
+
const { toolMap, toolDefs, session_id, _injected_files } = (config.toolCall ?? {});
|
|
207
|
+
if (toolMap == null || toolMap.size === 0) {
|
|
208
|
+
throw new Error('No toolMap provided. ' +
|
|
209
|
+
'ToolNode should inject this from AgentContext when invoked through the graph.');
|
|
210
|
+
}
|
|
211
|
+
if (toolDefs == null || toolDefs.length === 0) {
|
|
212
|
+
throw new Error('No tool definitions provided. ' +
|
|
213
|
+
'Either pass tools in the input or ensure ToolNode injects toolDefs.');
|
|
214
|
+
}
|
|
215
|
+
let roundTrip = 0;
|
|
216
|
+
try {
|
|
217
|
+
// ====================================================================
|
|
218
|
+
// Phase 1: Filter tools and make initial request
|
|
219
|
+
// ====================================================================
|
|
220
|
+
const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);
|
|
221
|
+
if (debug) {
|
|
222
|
+
// eslint-disable-next-line no-console
|
|
223
|
+
console.log(`[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +
|
|
224
|
+
`(filtered from ${toolDefs.length})`);
|
|
225
|
+
}
|
|
226
|
+
let files;
|
|
227
|
+
if (_injected_files && _injected_files.length > 0) {
|
|
228
|
+
files = _injected_files;
|
|
229
|
+
}
|
|
230
|
+
else if (session_id != null && session_id.length > 0) {
|
|
231
|
+
files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
|
|
232
|
+
}
|
|
233
|
+
let response = await makeRequest(EXEC_ENDPOINT, apiKey, {
|
|
234
|
+
lang: 'bash',
|
|
235
|
+
code,
|
|
236
|
+
tools: effectiveTools,
|
|
237
|
+
session_id,
|
|
238
|
+
timeout,
|
|
239
|
+
...(files && files.length > 0 ? { files } : {}),
|
|
240
|
+
}, proxy);
|
|
241
|
+
// ====================================================================
|
|
242
|
+
// Phase 2: Handle response loop
|
|
243
|
+
// ====================================================================
|
|
244
|
+
while (response.status === 'tool_call_required') {
|
|
245
|
+
roundTrip++;
|
|
246
|
+
if (roundTrip > maxRoundTrips) {
|
|
247
|
+
throw new Error(`Exceeded maximum round trips (${maxRoundTrips}). ` +
|
|
248
|
+
'This may indicate an infinite loop, excessive tool calls, ' +
|
|
249
|
+
'or a logic error in your code.');
|
|
250
|
+
}
|
|
251
|
+
if (debug) {
|
|
252
|
+
// eslint-disable-next-line no-console
|
|
253
|
+
console.log(`[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`);
|
|
254
|
+
}
|
|
255
|
+
const toolResults = await executeTools(response.tool_calls ?? [], toolMap);
|
|
256
|
+
response = await makeRequest(EXEC_ENDPOINT, apiKey, {
|
|
257
|
+
continuation_token: response.continuation_token,
|
|
258
|
+
tool_results: toolResults,
|
|
259
|
+
}, proxy);
|
|
260
|
+
}
|
|
261
|
+
// ====================================================================
|
|
262
|
+
// Phase 3: Handle final state
|
|
263
|
+
// ====================================================================
|
|
264
|
+
if (response.status === 'completed') {
|
|
265
|
+
return formatCompletedResponse(response);
|
|
266
|
+
}
|
|
267
|
+
if (response.status === 'error') {
|
|
268
|
+
throw new Error(`Execution error: ${response.error}` +
|
|
269
|
+
(response.stderr != null && response.stderr !== ''
|
|
270
|
+
? `\n\nStderr:\n${response.stderr}`
|
|
271
|
+
: ''));
|
|
272
|
+
}
|
|
273
|
+
throw new Error(`Unexpected response status: ${response.status}`);
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
throw new Error(`Bash programmatic execution failed: ${error.message}`);
|
|
277
|
+
}
|
|
278
|
+
}, {
|
|
279
|
+
name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
|
|
280
|
+
description: BashProgrammaticToolCallingDescription,
|
|
281
|
+
schema: BashProgrammaticToolCallingSchema,
|
|
282
|
+
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export { BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, extractUsedBashToolNames, filterBashToolsByUsage, normalizeToBashIdentifier };
|
|
287
|
+
//# sourceMappingURL=BashProgrammaticToolCalling.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n fetchSessionFiles,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_TIMEOUT = 60000;\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const BashProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for bash programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n const { toolMap, toolDefs, session_id, _injected_files } =\n (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;;AAcA,MAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;IACP,OAAO;IACP,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,UAAU;IACV,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IACP,UAAU;IACV,QAAQ;IACR,OAAO;AACR,CAAA,CAAC;AAEF;AACA;AACA;AAEA,MAAM,iBAAiB,GAAG,CAAA;;;sEAG4C;AAEtE,MAAM,UAAU,GAAG,CAAA;;;;;sFAKmE;AAEtF,MAAM,gBAAgB,GACpB,iFAAiF;AAEnF,MAAM,QAAQ,GAAG,CAAA;;;;;;;;;;gCAUe;AAEhC,MAAM,sBAAsB,GAAG,CAAA;;EAE7B,iBAAiB;;;;;EAKjB,QAAQ;;AAER,EAAA,UAAU,EAAE;AAEd;AACA;AACA;AAEO,MAAM,iCAAiC,GAAG;AAC/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C,OAAO,CAAA,CAAE,CAClE;QACH;AACF,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Constants } from '../common/enum.mjs';
|
|
2
|
+
|
|
3
|
+
// src/tools/ReadFile.ts
|
|
4
|
+
const ReadFileToolName = Constants.READ_FILE;
|
|
5
|
+
const ReadFileToolDescription = `Read the contents of a file. Returns text content with line numbers for easy reference.
|
|
6
|
+
|
|
7
|
+
For skill files, use the path format: {skillName}/{filePath} (e.g. "pdf-analyzer/src/utils.py", "code-review/SKILL.md").
|
|
8
|
+
|
|
9
|
+
BEHAVIOR:
|
|
10
|
+
- Text files: returned with numbered lines.
|
|
11
|
+
- Images (png, jpeg, gif, webp): returned as visual content the model can see.
|
|
12
|
+
- PDFs: returned as document content.
|
|
13
|
+
- Other binary files: metadata returned with a note to use bash for processing.
|
|
14
|
+
- Large files (>256KB text, >10MB binary): metadata only.
|
|
15
|
+
- SKILL.md: returns the skill's instructions directly.
|
|
16
|
+
|
|
17
|
+
CONSTRAINTS:
|
|
18
|
+
- Only files from invoked skills or code execution output are accessible.
|
|
19
|
+
- Do not guess file paths. Use paths from the skill documentation or tool output.`;
|
|
20
|
+
const ReadFileToolSchema = {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
file_path: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Path to the file. For skill files: "{skillName}/{path}" (e.g. "pdf-analyzer/src/utils.py"). For code execution output: the path as returned by the execution tool.',
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
required: ['file_path'],
|
|
29
|
+
};
|
|
30
|
+
const ReadFileToolDefinition = {
|
|
31
|
+
name: ReadFileToolName,
|
|
32
|
+
description: ReadFileToolDescription,
|
|
33
|
+
parameters: ReadFileToolSchema,
|
|
34
|
+
responseFormat: 'content_and_artifact',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export { ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema };
|
|
38
|
+
//# sourceMappingURL=ReadFile.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ReadFile.mjs","sources":["../../../src/tools/ReadFile.ts"],"sourcesContent":["// src/tools/ReadFile.ts\nimport { Constants } from '@/common';\n\nexport const ReadFileToolName = Constants.READ_FILE;\n\nexport const ReadFileToolDescription = `Read the contents of a file. Returns text content with line numbers for easy reference.\n\nFor skill files, use the path format: {skillName}/{filePath} (e.g. \"pdf-analyzer/src/utils.py\", \"code-review/SKILL.md\").\n\nBEHAVIOR:\n- Text files: returned with numbered lines.\n- Images (png, jpeg, gif, webp): returned as visual content the model can see.\n- PDFs: returned as document content.\n- Other binary files: metadata returned with a note to use bash for processing.\n- Large files (>256KB text, >10MB binary): metadata only.\n- SKILL.md: returns the skill's instructions directly.\n\nCONSTRAINTS:\n- Only files from invoked skills or code execution output are accessible.\n- Do not guess file paths. Use paths from the skill documentation or tool output.`;\n\nexport const ReadFileToolSchema = {\n type: 'object',\n properties: {\n file_path: {\n type: 'string',\n description:\n 'Path to the file. For skill files: \"{skillName}/{path}\" (e.g. \"pdf-analyzer/src/utils.py\"). For code execution output: the path as returned by the execution tool.',\n },\n },\n required: ['file_path'],\n} as const;\n\nexport const ReadFileToolDefinition = {\n name: ReadFileToolName,\n description: ReadFileToolDescription,\n parameters: ReadFileToolSchema,\n responseFormat: 'content_and_artifact' as const,\n} as const;\n"],"names":[],"mappings":";;AAAA;AAGO,MAAM,gBAAgB,GAAG,SAAS,CAAC;AAEnC,MAAM,uBAAuB,GAAG,CAAA;;;;;;;;;;;;;;;AAgBhC,MAAM,kBAAkB,GAAG;AAChC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,SAAS,EAAE;AACT,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EACT,oKAAoK;AACvK,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,WAAW,CAAC;;AAGlB,MAAM,sBAAsB,GAAG;AACpC,IAAA,IAAI,EAAE,gBAAgB;AACtB,IAAA,WAAW,EAAE,uBAAuB;AACpC,IAAA,UAAU,EAAE,kBAAkB;AAC9B,IAAA,cAAc,EAAE,sBAA+B;;;;;"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Constants } from '../common/enum.mjs';
|
|
2
|
+
|
|
3
|
+
// src/tools/SkillTool.ts
|
|
4
|
+
const SkillToolName = Constants.SKILL_TOOL;
|
|
5
|
+
const SkillToolDescription = `Invoke a skill from the user's library. Skills provide domain-specific instructions loaded into the conversation context, and may also provide files accessible via available tools depending on the runtime environment.
|
|
6
|
+
|
|
7
|
+
WHEN TO USE:
|
|
8
|
+
- The user's request matches a skill listed in the "Available Skills" section of the system prompt.
|
|
9
|
+
- You MUST invoke the matching skill BEFORE attempting the task yourself.
|
|
10
|
+
|
|
11
|
+
WHAT HAPPENS:
|
|
12
|
+
- The skill's full instructions are loaded into the conversation as context.
|
|
13
|
+
- Files bundled with the skill may become accessible via available tools.
|
|
14
|
+
- Follow the skill's instructions to complete the task.
|
|
15
|
+
|
|
16
|
+
CONSTRAINTS:
|
|
17
|
+
- Do not invoke a skill that is already active in this conversation.
|
|
18
|
+
- Skill names come from the catalog only. Do not guess names.`;
|
|
19
|
+
/**
|
|
20
|
+
* JSON Schema for the SkillTool parameters.
|
|
21
|
+
* Single source of truth used by both SkillToolDefinition (LCTool registry)
|
|
22
|
+
* and createSkillTool() (DynamicStructuredTool instance).
|
|
23
|
+
*/
|
|
24
|
+
const SkillToolSchema = {
|
|
25
|
+
type: 'object',
|
|
26
|
+
properties: {
|
|
27
|
+
skillName: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
description: 'The kebab-case identifier of the skill to invoke (e.g. "financial-analyzer", "meeting-notes"). Must match a name from the "Available Skills" section.',
|
|
30
|
+
},
|
|
31
|
+
args: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'Optional freeform arguments string passed to the skill.',
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
required: ['skillName'],
|
|
37
|
+
};
|
|
38
|
+
const SkillToolDefinition = {
|
|
39
|
+
name: SkillToolName,
|
|
40
|
+
description: SkillToolDescription,
|
|
41
|
+
parameters: SkillToolSchema,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export { SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema };
|
|
45
|
+
//# sourceMappingURL=SkillTool.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SkillTool.mjs","sources":["../../../src/tools/SkillTool.ts"],"sourcesContent":["// src/tools/SkillTool.ts\nimport { Constants } from '@/common';\n\nexport const SkillToolName = Constants.SKILL_TOOL;\n\nexport const SkillToolDescription = `Invoke a skill from the user's library. Skills provide domain-specific instructions loaded into the conversation context, and may also provide files accessible via available tools depending on the runtime environment.\n\nWHEN TO USE:\n- The user's request matches a skill listed in the \"Available Skills\" section of the system prompt.\n- You MUST invoke the matching skill BEFORE attempting the task yourself.\n\nWHAT HAPPENS:\n- The skill's full instructions are loaded into the conversation as context.\n- Files bundled with the skill may become accessible via available tools.\n- Follow the skill's instructions to complete the task.\n\nCONSTRAINTS:\n- Do not invoke a skill that is already active in this conversation.\n- Skill names come from the catalog only. Do not guess names.`;\n\n/**\n * JSON Schema for the SkillTool parameters.\n * Single source of truth used by both SkillToolDefinition (LCTool registry)\n * and createSkillTool() (DynamicStructuredTool instance).\n */\nexport const SkillToolSchema = {\n type: 'object',\n properties: {\n skillName: {\n type: 'string',\n description:\n 'The kebab-case identifier of the skill to invoke (e.g. \"financial-analyzer\", \"meeting-notes\"). Must match a name from the \"Available Skills\" section.',\n },\n args: {\n type: 'string',\n description: 'Optional freeform arguments string passed to the skill.',\n },\n },\n required: ['skillName'],\n} as const;\n\nexport const SkillToolDefinition = {\n name: SkillToolName,\n description: SkillToolDescription,\n parameters: SkillToolSchema,\n} as const;\n"],"names":[],"mappings":";;AAAA;AAGO,MAAM,aAAa,GAAG,SAAS,CAAC;AAEhC,MAAM,oBAAoB,GAAG,CAAA;;;;;;;;;;;;;;AAepC;;;;AAIG;AACI,MAAM,eAAe,GAAG;AAC7B,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,SAAS,EAAE;AACT,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EACT,uJAAuJ;AAC1J,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,yDAAyD;AACvE,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,WAAW,CAAC;;AAGlB,MAAM,mBAAmB,GAAG;AACjC,IAAA,IAAI,EAAE,aAAa;AACnB,IAAA,WAAW,EAAE,oBAAoB;AACjC,IAAA,UAAU,EAAE,eAAe;;;;;"}
|