@librechat/agents 3.1.67-dev.4 → 3.1.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +3 -23
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +0 -16
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +0 -91
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +36 -0
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/main.cjs +1 -53
  10. package/dist/cjs/main.cjs.map +1 -1
  11. package/dist/cjs/messages/format.cjs +12 -74
  12. package/dist/cjs/messages/format.cjs.map +1 -1
  13. package/dist/cjs/run.cjs +0 -111
  14. package/dist/cjs/run.cjs.map +1 -1
  15. package/dist/cjs/summarization/index.cjs +41 -0
  16. package/dist/cjs/summarization/index.cjs.map +1 -1
  17. package/dist/cjs/summarization/node.cjs +121 -63
  18. package/dist/cjs/summarization/node.cjs.map +1 -1
  19. package/dist/cjs/tools/ToolNode.cjs +140 -304
  20. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  21. package/dist/esm/agents/AgentContext.mjs +3 -23
  22. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  23. package/dist/esm/common/enum.mjs +1 -15
  24. package/dist/esm/common/enum.mjs.map +1 -1
  25. package/dist/esm/graphs/Graph.mjs +0 -91
  26. package/dist/esm/graphs/Graph.mjs.map +1 -1
  27. package/dist/esm/graphs/MultiAgentGraph.mjs +36 -0
  28. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  29. package/dist/esm/main.mjs +2 -13
  30. package/dist/esm/main.mjs.map +1 -1
  31. package/dist/esm/messages/format.mjs +4 -66
  32. package/dist/esm/messages/format.mjs.map +1 -1
  33. package/dist/esm/run.mjs +0 -111
  34. package/dist/esm/run.mjs.map +1 -1
  35. package/dist/esm/summarization/index.mjs +41 -1
  36. package/dist/esm/summarization/index.mjs.map +1 -1
  37. package/dist/esm/summarization/node.mjs +121 -63
  38. package/dist/esm/summarization/node.mjs.map +1 -1
  39. package/dist/esm/tools/ToolNode.mjs +142 -306
  40. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  41. package/dist/types/agents/AgentContext.d.ts +0 -6
  42. package/dist/types/common/enum.d.ts +1 -10
  43. package/dist/types/graphs/Graph.d.ts +0 -2
  44. package/dist/types/graphs/MultiAgentGraph.d.ts +12 -0
  45. package/dist/types/index.d.ts +0 -8
  46. package/dist/types/messages/format.d.ts +1 -2
  47. package/dist/types/run.d.ts +0 -1
  48. package/dist/types/summarization/index.d.ts +2 -0
  49. package/dist/types/summarization/node.d.ts +0 -2
  50. package/dist/types/tools/ToolNode.d.ts +2 -24
  51. package/dist/types/types/graph.d.ts +2 -61
  52. package/dist/types/types/index.d.ts +0 -1
  53. package/dist/types/types/run.d.ts +0 -20
  54. package/dist/types/types/tools.d.ts +1 -38
  55. package/package.json +1 -5
  56. package/src/agents/AgentContext.ts +2 -26
  57. package/src/common/enum.ts +0 -15
  58. package/src/graphs/Graph.ts +0 -113
  59. package/src/graphs/MultiAgentGraph.ts +39 -0
  60. package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
  61. package/src/index.ts +0 -10
  62. package/src/messages/format.ts +4 -74
  63. package/src/run.ts +0 -126
  64. package/src/summarization/__tests__/node.test.ts +42 -0
  65. package/src/summarization/__tests__/trigger.test.ts +100 -1
  66. package/src/summarization/index.ts +47 -0
  67. package/src/summarization/node.ts +149 -77
  68. package/src/tools/ToolNode.ts +169 -391
  69. package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
  70. package/src/types/graph.ts +1 -80
  71. package/src/types/index.ts +0 -1
  72. package/src/types/run.ts +0 -20
  73. package/src/types/tools.ts +1 -41
  74. package/dist/cjs/hooks/HookRegistry.cjs +0 -162
  75. package/dist/cjs/hooks/HookRegistry.cjs.map +0 -1
  76. package/dist/cjs/hooks/executeHooks.cjs +0 -276
  77. package/dist/cjs/hooks/executeHooks.cjs.map +0 -1
  78. package/dist/cjs/hooks/matchers.cjs +0 -256
  79. package/dist/cjs/hooks/matchers.cjs.map +0 -1
  80. package/dist/cjs/hooks/types.cjs +0 -27
  81. package/dist/cjs/hooks/types.cjs.map +0 -1
  82. package/dist/cjs/tools/BashExecutor.cjs +0 -175
  83. package/dist/cjs/tools/BashExecutor.cjs.map +0 -1
  84. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -296
  85. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +0 -1
  86. package/dist/cjs/tools/ReadFile.cjs +0 -43
  87. package/dist/cjs/tools/ReadFile.cjs.map +0 -1
  88. package/dist/cjs/tools/SkillTool.cjs +0 -50
  89. package/dist/cjs/tools/SkillTool.cjs.map +0 -1
  90. package/dist/cjs/tools/SubagentTool.cjs +0 -92
  91. package/dist/cjs/tools/SubagentTool.cjs.map +0 -1
  92. package/dist/cjs/tools/skillCatalog.cjs +0 -84
  93. package/dist/cjs/tools/skillCatalog.cjs.map +0 -1
  94. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +0 -511
  95. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +0 -1
  96. package/dist/esm/hooks/HookRegistry.mjs +0 -160
  97. package/dist/esm/hooks/HookRegistry.mjs.map +0 -1
  98. package/dist/esm/hooks/executeHooks.mjs +0 -273
  99. package/dist/esm/hooks/executeHooks.mjs.map +0 -1
  100. package/dist/esm/hooks/matchers.mjs +0 -251
  101. package/dist/esm/hooks/matchers.mjs.map +0 -1
  102. package/dist/esm/hooks/types.mjs +0 -25
  103. package/dist/esm/hooks/types.mjs.map +0 -1
  104. package/dist/esm/tools/BashExecutor.mjs +0 -169
  105. package/dist/esm/tools/BashExecutor.mjs.map +0 -1
  106. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -287
  107. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +0 -1
  108. package/dist/esm/tools/ReadFile.mjs +0 -38
  109. package/dist/esm/tools/ReadFile.mjs.map +0 -1
  110. package/dist/esm/tools/SkillTool.mjs +0 -45
  111. package/dist/esm/tools/SkillTool.mjs.map +0 -1
  112. package/dist/esm/tools/SubagentTool.mjs +0 -85
  113. package/dist/esm/tools/SubagentTool.mjs.map +0 -1
  114. package/dist/esm/tools/skillCatalog.mjs +0 -82
  115. package/dist/esm/tools/skillCatalog.mjs.map +0 -1
  116. package/dist/esm/tools/subagent/SubagentExecutor.mjs +0 -505
  117. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +0 -1
  118. package/dist/types/hooks/HookRegistry.d.ts +0 -56
  119. package/dist/types/hooks/executeHooks.d.ts +0 -79
  120. package/dist/types/hooks/index.d.ts +0 -6
  121. package/dist/types/hooks/matchers.d.ts +0 -95
  122. package/dist/types/hooks/types.d.ts +0 -320
  123. package/dist/types/tools/BashExecutor.d.ts +0 -45
  124. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +0 -72
  125. package/dist/types/tools/ReadFile.d.ts +0 -28
  126. package/dist/types/tools/SkillTool.d.ts +0 -40
  127. package/dist/types/tools/SubagentTool.d.ts +0 -36
  128. package/dist/types/tools/skillCatalog.d.ts +0 -19
  129. package/dist/types/tools/subagent/SubagentExecutor.d.ts +0 -137
  130. package/dist/types/tools/subagent/index.d.ts +0 -2
  131. package/dist/types/types/skill.d.ts +0 -9
  132. package/src/hooks/HookRegistry.ts +0 -208
  133. package/src/hooks/__tests__/HookRegistry.test.ts +0 -190
  134. package/src/hooks/__tests__/compactHooks.test.ts +0 -214
  135. package/src/hooks/__tests__/executeHooks.test.ts +0 -1013
  136. package/src/hooks/__tests__/integration.test.ts +0 -337
  137. package/src/hooks/__tests__/matchers.test.ts +0 -238
  138. package/src/hooks/__tests__/toolHooks.test.ts +0 -669
  139. package/src/hooks/executeHooks.ts +0 -375
  140. package/src/hooks/index.ts +0 -57
  141. package/src/hooks/matchers.ts +0 -280
  142. package/src/hooks/types.ts +0 -404
  143. package/src/messages/formatAgentMessages.skills.test.ts +0 -334
  144. package/src/scripts/multi-agent-subagent.ts +0 -246
  145. package/src/scripts/subagent-event-driven-debug.ts +0 -190
  146. package/src/scripts/subagent-tools-debug.ts +0 -160
  147. package/src/specs/subagent.test.ts +0 -305
  148. package/src/tools/BashExecutor.ts +0 -205
  149. package/src/tools/BashProgrammaticToolCalling.ts +0 -397
  150. package/src/tools/ReadFile.ts +0 -39
  151. package/src/tools/SkillTool.ts +0 -46
  152. package/src/tools/SubagentTool.ts +0 -100
  153. package/src/tools/__tests__/ReadFile.test.ts +0 -44
  154. package/src/tools/__tests__/SkillTool.test.ts +0 -442
  155. package/src/tools/__tests__/SubagentExecutor.test.ts +0 -1148
  156. package/src/tools/__tests__/SubagentTool.test.ts +0 -149
  157. package/src/tools/__tests__/skillCatalog.test.ts +0 -161
  158. package/src/tools/__tests__/subagentHooks.test.ts +0 -215
  159. package/src/tools/skillCatalog.ts +0 -126
  160. package/src/tools/subagent/SubagentExecutor.ts +0 -676
  161. package/src/tools/subagent/index.ts +0 -13
  162. package/src/types/skill.ts +0 -11
@@ -1,205 +0,0 @@
1
- import { config } from 'dotenv';
2
- import fetch, { RequestInit } from 'node-fetch';
3
- import { HttpsProxyAgent } from 'https-proxy-agent';
4
- import { tool, DynamicStructuredTool } from '@langchain/core/tools';
5
- import { getEnvironmentVariable } from '@langchain/core/utils/env';
6
- import type * as t from '@/types';
7
- import { imageExtRegex, getCodeBaseURL } from './CodeExecutor';
8
- import { EnvVar, Constants } from '@/common';
9
-
10
- config();
11
-
12
- const imageMessage = 'Image is already displayed to the user';
13
- const otherMessage = 'File is already downloaded by the user';
14
- const accessMessage =
15
- 'Note: Files from previous executions are automatically available and can be modified.';
16
- const emptyOutputMessage =
17
- 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
18
-
19
- const baseEndpoint = getCodeBaseURL();
20
- const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
21
-
22
- export const BashExecutionToolSchema = {
23
- type: 'object',
24
- properties: {
25
- command: {
26
- type: 'string',
27
- description: `The bash command or script to execute.
28
- - The environment is stateless; variables and state don't persist between executions.
29
- - Generated files from previous executions are automatically available in "/mnt/data/".
30
- - Files from previous executions are automatically available and can be modified in place.
31
- - Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
32
- - Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
33
- - IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
34
- - Use \`echo\`, \`printf\`, or \`cat\` for all outputs.`,
35
- },
36
- args: {
37
- type: 'array',
38
- items: { type: 'string' },
39
- description:
40
- 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',
41
- },
42
- },
43
- required: ['command'],
44
- } as const;
45
-
46
- export const BashExecutionToolDescription = `
47
- 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.
48
-
49
- Usage:
50
- - No network access available.
51
- - Generated files are automatically delivered; **DO NOT** provide download links.
52
- - NEVER use this tool to execute malicious commands.
53
- `.trim();
54
-
55
- export const BashExecutionToolName = Constants.BASH_TOOL;
56
-
57
- export const BashExecutionToolDefinition = {
58
- name: BashExecutionToolName,
59
- description: BashExecutionToolDescription,
60
- schema: BashExecutionToolSchema,
61
- } as const;
62
-
63
- function createBashExecutionTool(
64
- params: t.BashExecutionToolParams = {}
65
- ): DynamicStructuredTool {
66
- const apiKey =
67
- params[EnvVar.CODE_API_KEY] ??
68
- params.apiKey ??
69
- getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
70
- '';
71
- if (!apiKey) {
72
- throw new Error('No API key provided for bash execution tool.');
73
- }
74
-
75
- return tool(
76
- async (rawInput, config) => {
77
- const { command, ...rest } = rawInput as {
78
- command: string;
79
- args?: string[];
80
- };
81
- const { session_id, _injected_files } = (config.toolCall ?? {}) as {
82
- session_id?: string;
83
- _injected_files?: t.CodeEnvFile[];
84
- };
85
-
86
- const postData: Record<string, unknown> = {
87
- lang: 'bash',
88
- code: command,
89
- ...rest,
90
- ...params,
91
- };
92
-
93
- if (_injected_files && _injected_files.length > 0) {
94
- postData.files = _injected_files;
95
- } else if (session_id != null && session_id.length > 0) {
96
- try {
97
- const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
98
- const fetchOptions: RequestInit = {
99
- method: 'GET',
100
- headers: {
101
- 'User-Agent': 'LibreChat/1.0',
102
- 'X-API-Key': apiKey,
103
- },
104
- };
105
-
106
- if (process.env.PROXY != null && process.env.PROXY !== '') {
107
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
108
- }
109
-
110
- const response = await fetch(filesEndpoint, fetchOptions);
111
- if (!response.ok) {
112
- throw new Error(
113
- `Failed to fetch files for session: ${response.status}`
114
- );
115
- }
116
-
117
- const files = await response.json();
118
- if (Array.isArray(files) && files.length > 0) {
119
- const fileReferences: t.CodeEnvFile[] = files.map((file) => {
120
- const nameParts = file.name.split('/');
121
- const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
122
-
123
- return {
124
- session_id,
125
- id,
126
- name: file.metadata['original-filename'],
127
- };
128
- });
129
-
130
- postData.files = fileReferences;
131
- }
132
- } catch {
133
- // eslint-disable-next-line no-console
134
- console.warn(`Failed to fetch files for session: ${session_id}`);
135
- }
136
- }
137
-
138
- try {
139
- const fetchOptions: RequestInit = {
140
- method: 'POST',
141
- headers: {
142
- 'Content-Type': 'application/json',
143
- 'User-Agent': 'LibreChat/1.0',
144
- 'X-API-Key': apiKey,
145
- },
146
- body: JSON.stringify(postData),
147
- };
148
-
149
- if (process.env.PROXY != null && process.env.PROXY !== '') {
150
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
151
- }
152
- const response = await fetch(EXEC_ENDPOINT, fetchOptions);
153
- if (!response.ok) {
154
- throw new Error(`HTTP error! status: ${response.status}`);
155
- }
156
-
157
- const result: t.ExecuteResult = await response.json();
158
- let formattedOutput = '';
159
- if (result.stdout) {
160
- formattedOutput += `stdout:\n${result.stdout}\n`;
161
- } else {
162
- formattedOutput += emptyOutputMessage;
163
- }
164
- if (result.stderr) formattedOutput += `stderr:\n${result.stderr}\n`;
165
- if (result.files && result.files.length > 0) {
166
- formattedOutput += 'Generated files:\n';
167
-
168
- const fileCount = result.files.length;
169
- for (let i = 0; i < fileCount; i++) {
170
- const file = result.files[i];
171
- const isImage = imageExtRegex.test(file.name);
172
- formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
173
-
174
- if (i < fileCount - 1) {
175
- formattedOutput += fileCount <= 3 ? ', ' : ',\n';
176
- }
177
- }
178
-
179
- formattedOutput += `\n\n${accessMessage}`;
180
- return [
181
- formattedOutput.trim(),
182
- {
183
- session_id: result.session_id,
184
- files: result.files,
185
- },
186
- ];
187
- }
188
-
189
- return [formattedOutput.trim(), { session_id: result.session_id }];
190
- } catch (error) {
191
- throw new Error(
192
- `Execution error:\n\n${(error as Error | undefined)?.message}`
193
- );
194
- }
195
- },
196
- {
197
- name: BashExecutionToolName,
198
- description: BashExecutionToolDescription,
199
- schema: BashExecutionToolSchema,
200
- responseFormat: Constants.CONTENT_AND_ARTIFACT,
201
- }
202
- );
203
- }
204
-
205
- export { createBashExecutionTool };
@@ -1,397 +0,0 @@
1
- import { config } from 'dotenv';
2
- import { getEnvironmentVariable } from '@langchain/core/utils/env';
3
- import { tool, DynamicStructuredTool } from '@langchain/core/tools';
4
- import type { ToolCall } from '@langchain/core/messages/tool';
5
- import type * as t from '@/types';
6
- import {
7
- makeRequest,
8
- executeTools,
9
- fetchSessionFiles,
10
- formatCompletedResponse,
11
- } from './ProgrammaticToolCalling';
12
- import { getCodeBaseURL } from './CodeExecutor';
13
- import { EnvVar, Constants } from '@/common';
14
-
15
- config();
16
-
17
- // ============================================================================
18
- // Constants
19
- // ============================================================================
20
-
21
- const DEFAULT_MAX_ROUND_TRIPS = 20;
22
- const DEFAULT_TIMEOUT = 60000;
23
-
24
- /** Bash reserved words that get `_tool` suffix when used as function names */
25
- const BASH_RESERVED = new Set([
26
- 'if',
27
- 'then',
28
- 'else',
29
- 'elif',
30
- 'fi',
31
- 'case',
32
- 'esac',
33
- 'for',
34
- 'while',
35
- 'until',
36
- 'do',
37
- 'done',
38
- 'in',
39
- 'function',
40
- 'select',
41
- 'time',
42
- 'coproc',
43
- 'declare',
44
- 'typeset',
45
- 'local',
46
- 'readonly',
47
- 'export',
48
- 'unset',
49
- ]);
50
-
51
- // ============================================================================
52
- // Description Components
53
- // ============================================================================
54
-
55
- const STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:
56
- Each call is a fresh bash shell. Variables and state do NOT persist between calls.
57
- You MUST complete your entire workflow in ONE code block.
58
- DO NOT split work across multiple calls expecting to reuse variables.`;
59
-
60
- const CORE_RULES = `Rules:
61
- - EVERYTHING in one call—no state persists between executions
62
- - Tools are pre-defined as bash functions—DO NOT redefine them
63
- - Each tool function accepts a JSON string argument
64
- - Only echo/printf output returns to the model
65
- - Generated files are automatically available in /mnt/data/ for subsequent executions`;
66
-
67
- const ADDITIONAL_RULES =
68
- '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';
69
-
70
- const EXAMPLES = `Example (Complete workflow in one call):
71
- # Query data and process
72
- data=$(query_database '{"sql": "SELECT * FROM users"}')
73
- echo "$data" | jq '.[] | .name'
74
-
75
- Example (Parallel calls):
76
- web_search '{"query": "SF weather"}' > /tmp/sf.txt &
77
- web_search '{"query": "NY weather"}' > /tmp/ny.txt &
78
- wait
79
- echo "SF: $(cat /tmp/sf.txt)"
80
- echo "NY: $(cat /tmp/ny.txt)"`;
81
-
82
- const CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.
83
-
84
- ${STATELESS_WARNING}
85
-
86
- Each tool function accepts a JSON string as its argument.
87
- Example: tool_name '{"key": "value"}'
88
-
89
- ${EXAMPLES}
90
-
91
- ${CORE_RULES}`;
92
-
93
- // ============================================================================
94
- // Schema
95
- // ============================================================================
96
-
97
- export const BashProgrammaticToolCallingSchema = {
98
- type: 'object',
99
- properties: {
100
- code: {
101
- type: 'string',
102
- minLength: 1,
103
- description: CODE_PARAM_DESCRIPTION,
104
- },
105
- timeout: {
106
- type: 'integer',
107
- minimum: 1000,
108
- maximum: 300000,
109
- default: DEFAULT_TIMEOUT,
110
- description:
111
- 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',
112
- },
113
- },
114
- required: ['code'],
115
- } as const;
116
-
117
- export const BashProgrammaticToolCallingName =
118
- Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
119
-
120
- export const BashProgrammaticToolCallingDescription = `
121
- Run tools via bash code. Tools are available as bash functions that accept JSON string arguments.
122
-
123
- ${STATELESS_WARNING}
124
-
125
- ${CORE_RULES}
126
- ${ADDITIONAL_RULES}
127
-
128
- When to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.
129
-
130
- ${EXAMPLES}
131
- `.trim();
132
-
133
- export const BashProgrammaticToolCallingDefinition = {
134
- name: BashProgrammaticToolCallingName,
135
- description: BashProgrammaticToolCallingDescription,
136
- schema: BashProgrammaticToolCallingSchema,
137
- } as const;
138
-
139
- // ============================================================================
140
- // Helper Functions
141
- // ============================================================================
142
-
143
- /**
144
- * Normalizes a tool name to a valid bash function identifier.
145
- * 1. Replace hyphens, spaces, dots with underscores
146
- * 2. Remove any other invalid characters
147
- * 3. Prefix with underscore if starts with number
148
- * 4. Append `_tool` if it's a bash reserved word
149
- */
150
- export function normalizeToBashIdentifier(name: string): string {
151
- let normalized = name.replace(/[-\s.]/g, '_');
152
- normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');
153
-
154
- if (/^[0-9]/.test(normalized)) {
155
- normalized = '_' + normalized;
156
- }
157
-
158
- if (BASH_RESERVED.has(normalized)) {
159
- normalized = normalized + '_tool';
160
- }
161
-
162
- return normalized;
163
- }
164
-
165
- /**
166
- * Extracts tool names that are actually called in the bash code.
167
- * Bash functions are invoked as commands (no parentheses), so we match
168
- * the normalized name as a word boundary.
169
- */
170
- export function extractUsedBashToolNames(
171
- code: string,
172
- toolNameMap: Map<string, string>
173
- ): Set<string> {
174
- const usedTools = new Set<string>();
175
-
176
- for (const [bashName, originalName] of toolNameMap) {
177
- const escapedName = bashName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
178
- const pattern = new RegExp(`\\b${escapedName}\\b`, 'g');
179
-
180
- if (pattern.test(code)) {
181
- usedTools.add(originalName);
182
- }
183
- }
184
-
185
- return usedTools;
186
- }
187
-
188
- /**
189
- * Filters tool definitions to only include tools actually used in the bash code.
190
- */
191
- export function filterBashToolsByUsage(
192
- toolDefs: t.LCTool[],
193
- code: string,
194
- debug = false
195
- ): t.LCTool[] {
196
- const toolNameMap = new Map<string, string>();
197
- for (const def of toolDefs) {
198
- const bashName = normalizeToBashIdentifier(def.name);
199
- toolNameMap.set(bashName, def.name);
200
- }
201
-
202
- const usedToolNames = extractUsedBashToolNames(code, toolNameMap);
203
-
204
- if (debug) {
205
- // eslint-disable-next-line no-console
206
- console.log(
207
- `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`
208
- );
209
- if (usedToolNames.size > 0) {
210
- // eslint-disable-next-line no-console
211
- console.log(
212
- `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`
213
- );
214
- }
215
- }
216
-
217
- if (usedToolNames.size === 0) {
218
- if (debug) {
219
- // eslint-disable-next-line no-console
220
- console.log(
221
- '[BashPTC Debug] No tools detected in code - sending all tools as fallback'
222
- );
223
- }
224
- return toolDefs;
225
- }
226
-
227
- return toolDefs.filter((def) => usedToolNames.has(def.name));
228
- }
229
-
230
- // ============================================================================
231
- // Tool Factory
232
- // ============================================================================
233
-
234
- /**
235
- * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.
236
- *
237
- * This tool enables AI agents to write bash scripts that orchestrate multiple
238
- * tool calls programmatically via the remote Code API, reducing LLM round-trips.
239
- *
240
- * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).
241
- */
242
- export function createBashProgrammaticToolCallingTool(
243
- initParams: t.BashProgrammaticToolCallingParams = {}
244
- ): DynamicStructuredTool {
245
- const apiKey =
246
- (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??
247
- initParams.apiKey ??
248
- getEnvironmentVariable(EnvVar.CODE_API_KEY) ??
249
- '';
250
-
251
- if (!apiKey) {
252
- throw new Error(
253
- 'No API key provided for bash programmatic tool calling. ' +
254
- 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'
255
- );
256
- }
257
-
258
- const baseUrl = initParams.baseUrl ?? getCodeBaseURL();
259
- const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
260
- const proxy = initParams.proxy ?? process.env.PROXY;
261
- const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';
262
- const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
263
-
264
- return tool(
265
- async (rawParams, config) => {
266
- const params = rawParams as { code: string; timeout?: number };
267
- const { code, timeout = DEFAULT_TIMEOUT } = params;
268
-
269
- const { toolMap, toolDefs, session_id, _injected_files } =
270
- (config.toolCall ?? {}) as ToolCall &
271
- Partial<t.ProgrammaticCache> & {
272
- session_id?: string;
273
- _injected_files?: t.CodeEnvFile[];
274
- };
275
-
276
- if (toolMap == null || toolMap.size === 0) {
277
- throw new Error(
278
- 'No toolMap provided. ' +
279
- 'ToolNode should inject this from AgentContext when invoked through the graph.'
280
- );
281
- }
282
-
283
- if (toolDefs == null || toolDefs.length === 0) {
284
- throw new Error(
285
- 'No tool definitions provided. ' +
286
- 'Either pass tools in the input or ensure ToolNode injects toolDefs.'
287
- );
288
- }
289
-
290
- let roundTrip = 0;
291
-
292
- try {
293
- // ====================================================================
294
- // Phase 1: Filter tools and make initial request
295
- // ====================================================================
296
-
297
- const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);
298
-
299
- if (debug) {
300
- // eslint-disable-next-line no-console
301
- console.log(
302
- `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +
303
- `(filtered from ${toolDefs.length})`
304
- );
305
- }
306
-
307
- let files: t.CodeEnvFile[] | undefined;
308
- if (_injected_files && _injected_files.length > 0) {
309
- files = _injected_files;
310
- } else if (session_id != null && session_id.length > 0) {
311
- files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
312
- }
313
-
314
- let response = await makeRequest(
315
- EXEC_ENDPOINT,
316
- apiKey,
317
- {
318
- lang: 'bash',
319
- code,
320
- tools: effectiveTools,
321
- session_id,
322
- timeout,
323
- ...(files && files.length > 0 ? { files } : {}),
324
- },
325
- proxy
326
- );
327
-
328
- // ====================================================================
329
- // Phase 2: Handle response loop
330
- // ====================================================================
331
-
332
- while (response.status === 'tool_call_required') {
333
- roundTrip++;
334
-
335
- if (roundTrip > maxRoundTrips) {
336
- throw new Error(
337
- `Exceeded maximum round trips (${maxRoundTrips}). ` +
338
- 'This may indicate an infinite loop, excessive tool calls, ' +
339
- 'or a logic error in your code.'
340
- );
341
- }
342
-
343
- if (debug) {
344
- // eslint-disable-next-line no-console
345
- console.log(
346
- `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`
347
- );
348
- }
349
-
350
- const toolResults = await executeTools(
351
- response.tool_calls ?? [],
352
- toolMap
353
- );
354
-
355
- response = await makeRequest(
356
- EXEC_ENDPOINT,
357
- apiKey,
358
- {
359
- continuation_token: response.continuation_token,
360
- tool_results: toolResults,
361
- },
362
- proxy
363
- );
364
- }
365
-
366
- // ====================================================================
367
- // Phase 3: Handle final state
368
- // ====================================================================
369
-
370
- if (response.status === 'completed') {
371
- return formatCompletedResponse(response);
372
- }
373
-
374
- if (response.status === 'error') {
375
- throw new Error(
376
- `Execution error: ${response.error}` +
377
- (response.stderr != null && response.stderr !== ''
378
- ? `\n\nStderr:\n${response.stderr}`
379
- : '')
380
- );
381
- }
382
-
383
- throw new Error(`Unexpected response status: ${response.status}`);
384
- } catch (error) {
385
- throw new Error(
386
- `Bash programmatic execution failed: ${(error as Error).message}`
387
- );
388
- }
389
- },
390
- {
391
- name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
392
- description: BashProgrammaticToolCallingDescription,
393
- schema: BashProgrammaticToolCallingSchema,
394
- responseFormat: Constants.CONTENT_AND_ARTIFACT,
395
- }
396
- );
397
- }
@@ -1,39 +0,0 @@
1
- // src/tools/ReadFile.ts
2
- import { Constants } from '@/common';
3
-
4
- export const ReadFileToolName = Constants.READ_FILE;
5
-
6
- export const ReadFileToolDescription = `Read the contents of a file. Returns text content with line numbers for easy reference.
7
-
8
- For skill files, use the path format: {skillName}/{filePath} (e.g. "pdf-analyzer/src/utils.py", "code-review/SKILL.md").
9
-
10
- BEHAVIOR:
11
- - Text files: returned with numbered lines.
12
- - Images (png, jpeg, gif, webp): returned as visual content the model can see.
13
- - PDFs: returned as document content.
14
- - Other binary files: metadata returned with a note to use bash for processing.
15
- - Large files (>256KB text, >10MB binary): metadata only.
16
- - SKILL.md: returns the skill's instructions directly.
17
-
18
- CONSTRAINTS:
19
- - Only files from invoked skills or code execution output are accessible.
20
- - Do not guess file paths. Use paths from the skill documentation or tool output.`;
21
-
22
- export const ReadFileToolSchema = {
23
- type: 'object',
24
- properties: {
25
- file_path: {
26
- type: 'string',
27
- description:
28
- '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.',
29
- },
30
- },
31
- required: ['file_path'],
32
- } as const;
33
-
34
- export const ReadFileToolDefinition = {
35
- name: ReadFileToolName,
36
- description: ReadFileToolDescription,
37
- parameters: ReadFileToolSchema,
38
- responseFormat: 'content_and_artifact' as const,
39
- } as const;
@@ -1,46 +0,0 @@
1
- // src/tools/SkillTool.ts
2
- import { Constants } from '@/common';
3
-
4
- export const SkillToolName = Constants.SKILL_TOOL;
5
-
6
- export 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.
7
-
8
- WHEN TO USE:
9
- - The user's request matches a skill listed in the "Available Skills" section of the system prompt.
10
- - You MUST invoke the matching skill BEFORE attempting the task yourself.
11
-
12
- WHAT HAPPENS:
13
- - The skill's full instructions are loaded into the conversation as context.
14
- - Files bundled with the skill may become accessible via available tools.
15
- - Follow the skill's instructions to complete the task.
16
-
17
- CONSTRAINTS:
18
- - Do not invoke a skill that is already active in this conversation.
19
- - Skill names come from the catalog only. Do not guess names.`;
20
-
21
- /**
22
- * JSON Schema for the SkillTool parameters.
23
- * Single source of truth used by both SkillToolDefinition (LCTool registry)
24
- * and createSkillTool() (DynamicStructuredTool instance).
25
- */
26
- export const SkillToolSchema = {
27
- type: 'object',
28
- properties: {
29
- skillName: {
30
- type: 'string',
31
- description:
32
- 'The kebab-case identifier of the skill to invoke (e.g. "financial-analyzer", "meeting-notes"). Must match a name from the "Available Skills" section.',
33
- },
34
- args: {
35
- type: 'string',
36
- description: 'Optional freeform arguments string passed to the skill.',
37
- },
38
- },
39
- required: ['skillName'],
40
- } as const;
41
-
42
- export const SkillToolDefinition = {
43
- name: SkillToolName,
44
- description: SkillToolDescription,
45
- parameters: SkillToolSchema,
46
- } as const;