@librechat/agents 3.1.66-dev.0 → 3.1.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/agents/AgentContext.cjs +24 -15
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +0 -13
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +0 -3
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +0 -40
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +12 -74
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +0 -111
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +140 -304
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +24 -15
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -12
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +0 -3
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -10
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +4 -66
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +0 -111
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +142 -306
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +1 -7
- package/dist/types/graphs/Graph.d.ts +0 -2
- package/dist/types/index.d.ts +0 -6
- package/dist/types/messages/format.d.ts +1 -2
- package/dist/types/run.d.ts +0 -1
- package/dist/types/tools/ToolNode.d.ts +2 -24
- package/dist/types/types/index.d.ts +0 -1
- package/dist/types/types/llm.d.ts +14 -2
- package/dist/types/types/run.d.ts +0 -20
- package/dist/types/types/tools.d.ts +1 -38
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +28 -15
- package/src/agents/__tests__/AgentContext.test.ts +110 -0
- package/src/common/enum.ts +0 -12
- package/src/graphs/Graph.ts +0 -4
- package/src/index.ts +0 -8
- package/src/messages/format.ts +4 -74
- package/src/run.ts +0 -126
- package/src/tools/ToolNode.ts +169 -391
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/types/index.ts +0 -1
- package/src/types/llm.ts +16 -2
- package/src/types/run.ts +0 -20
- package/src/types/tools.ts +1 -41
- package/dist/cjs/hooks/HookRegistry.cjs +0 -162
- package/dist/cjs/hooks/HookRegistry.cjs.map +0 -1
- package/dist/cjs/hooks/executeHooks.cjs +0 -276
- package/dist/cjs/hooks/executeHooks.cjs.map +0 -1
- package/dist/cjs/hooks/matchers.cjs +0 -256
- package/dist/cjs/hooks/matchers.cjs.map +0 -1
- package/dist/cjs/hooks/types.cjs +0 -27
- package/dist/cjs/hooks/types.cjs.map +0 -1
- package/dist/cjs/tools/BashExecutor.cjs +0 -175
- package/dist/cjs/tools/BashExecutor.cjs.map +0 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +0 -296
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +0 -1
- package/dist/cjs/tools/ReadFile.cjs +0 -43
- package/dist/cjs/tools/ReadFile.cjs.map +0 -1
- package/dist/cjs/tools/SkillTool.cjs +0 -50
- package/dist/cjs/tools/SkillTool.cjs.map +0 -1
- package/dist/cjs/tools/skillCatalog.cjs +0 -84
- package/dist/cjs/tools/skillCatalog.cjs.map +0 -1
- package/dist/esm/hooks/HookRegistry.mjs +0 -160
- package/dist/esm/hooks/HookRegistry.mjs.map +0 -1
- package/dist/esm/hooks/executeHooks.mjs +0 -273
- package/dist/esm/hooks/executeHooks.mjs.map +0 -1
- package/dist/esm/hooks/matchers.mjs +0 -251
- package/dist/esm/hooks/matchers.mjs.map +0 -1
- package/dist/esm/hooks/types.mjs +0 -25
- package/dist/esm/hooks/types.mjs.map +0 -1
- package/dist/esm/tools/BashExecutor.mjs +0 -169
- package/dist/esm/tools/BashExecutor.mjs.map +0 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +0 -287
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +0 -1
- package/dist/esm/tools/ReadFile.mjs +0 -38
- package/dist/esm/tools/ReadFile.mjs.map +0 -1
- package/dist/esm/tools/SkillTool.mjs +0 -45
- package/dist/esm/tools/SkillTool.mjs.map +0 -1
- package/dist/esm/tools/skillCatalog.mjs +0 -82
- package/dist/esm/tools/skillCatalog.mjs.map +0 -1
- package/dist/types/hooks/HookRegistry.d.ts +0 -56
- package/dist/types/hooks/executeHooks.d.ts +0 -79
- package/dist/types/hooks/index.d.ts +0 -6
- package/dist/types/hooks/matchers.d.ts +0 -95
- package/dist/types/hooks/types.d.ts +0 -309
- package/dist/types/tools/BashExecutor.d.ts +0 -45
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +0 -72
- package/dist/types/tools/ReadFile.d.ts +0 -28
- package/dist/types/tools/SkillTool.d.ts +0 -40
- package/dist/types/tools/skillCatalog.d.ts +0 -19
- package/dist/types/types/skill.d.ts +0 -9
- package/src/hooks/HookRegistry.ts +0 -208
- package/src/hooks/__tests__/HookRegistry.test.ts +0 -190
- package/src/hooks/__tests__/executeHooks.test.ts +0 -1013
- package/src/hooks/__tests__/integration.test.ts +0 -337
- package/src/hooks/__tests__/matchers.test.ts +0 -238
- package/src/hooks/__tests__/toolHooks.test.ts +0 -669
- package/src/hooks/executeHooks.ts +0 -375
- package/src/hooks/index.ts +0 -55
- package/src/hooks/matchers.ts +0 -280
- package/src/hooks/types.ts +0 -388
- package/src/messages/formatAgentMessages.skills.test.ts +0 -334
- package/src/tools/BashExecutor.ts +0 -205
- package/src/tools/BashProgrammaticToolCalling.ts +0 -397
- package/src/tools/ReadFile.ts +0 -39
- package/src/tools/SkillTool.ts +0 -46
- package/src/tools/__tests__/ReadFile.test.ts +0 -44
- package/src/tools/__tests__/SkillTool.test.ts +0 -442
- package/src/tools/__tests__/skillCatalog.test.ts +0 -161
- package/src/tools/skillCatalog.ts +0 -126
- package/src/types/skill.ts +0 -11
|
@@ -1,287 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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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,IAAI,EAAE,EACzB,OAAO,CACR;AAED,gBAAA,QAAQ,GAAG,MAAM,WAAW,CAC1B,aAAa,EACb,MAAM,EACN;oBACE,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;AAC/C,oBAAA,YAAY,EAAE,WAAW;iBAC1B,EACD,KAAK,CACN;YACH;;;;AAMA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,EAAE;AACnC,gBAAA,OAAO,uBAAuB,CAAC,QAAQ,CAAC;YAC1C;AAEA,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAA,CAAE;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAA;AACjC,0BAAE,EAAE,CAAC,CACV;YACH;YAEA,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAE,CAAC;QACnE;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oCAAA,EAAwC,KAAe,CAAC,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;;;;"}
|
|
@@ -1,38 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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;;;;;"}
|
|
@@ -1,45 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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;;;;;"}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
const HEADER = '## Available Skills';
|
|
2
|
-
const DEFAULT_CONTEXT_WINDOW_TOKENS = 200_000;
|
|
3
|
-
const DEFAULT_BUDGET_PERCENT = 0.01;
|
|
4
|
-
const DEFAULT_MAX_ENTRY_CHARS = 250;
|
|
5
|
-
const DEFAULT_MIN_DESC_LENGTH = 20;
|
|
6
|
-
const DEFAULT_CHARS_PER_TOKEN = 4;
|
|
7
|
-
/**
|
|
8
|
-
* Formats a skill catalog for injection into agent context.
|
|
9
|
-
* Uses a truncation ladder: full descriptions, proportional truncation, names-only.
|
|
10
|
-
* Returns empty string for empty input.
|
|
11
|
-
*/
|
|
12
|
-
function formatSkillCatalog(skills, opts) {
|
|
13
|
-
if (skills.length === 0)
|
|
14
|
-
return '';
|
|
15
|
-
const contextWindowTokens = opts?.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS;
|
|
16
|
-
const budgetPercent = opts?.budgetPercent ?? DEFAULT_BUDGET_PERCENT;
|
|
17
|
-
const maxEntryChars = Math.max(1, opts?.maxEntryChars ?? DEFAULT_MAX_ENTRY_CHARS);
|
|
18
|
-
const minDescLength = opts?.minDescLength ?? DEFAULT_MIN_DESC_LENGTH;
|
|
19
|
-
const charsPerToken = opts?.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
20
|
-
const budgetChars = Math.floor(contextWindowTokens * budgetPercent * charsPerToken);
|
|
21
|
-
const capped = skills.map((s) => ({
|
|
22
|
-
name: s.name,
|
|
23
|
-
description: s.description.length > maxEntryChars
|
|
24
|
-
? s.description.slice(0, maxEntryChars - 1) + '\u2026'
|
|
25
|
-
: s.description,
|
|
26
|
-
}));
|
|
27
|
-
const fullOutput = formatEntries(capped);
|
|
28
|
-
if (fullOutput.length <= budgetChars)
|
|
29
|
-
return fullOutput;
|
|
30
|
-
const headerLen = HEADER.length + 2;
|
|
31
|
-
const newlineChars = capped.length > 1 ? capped.length - 1 : 0;
|
|
32
|
-
const availableChars = budgetChars - headerLen - newlineChars;
|
|
33
|
-
const perEntryOverhead = 4;
|
|
34
|
-
const nameCharsTotal = capped.reduce((sum, s) => sum + s.name.length + perEntryOverhead, 0);
|
|
35
|
-
const availableForDescs = availableChars - nameCharsTotal;
|
|
36
|
-
if (availableForDescs <= 0) {
|
|
37
|
-
return fitNamesOnly(capped, budgetChars);
|
|
38
|
-
}
|
|
39
|
-
const maxDescPerEntry = Math.floor(availableForDescs / capped.length);
|
|
40
|
-
if (maxDescPerEntry < minDescLength) {
|
|
41
|
-
return fitNamesOnly(capped, budgetChars);
|
|
42
|
-
}
|
|
43
|
-
const truncated = capped.map((s) => ({
|
|
44
|
-
name: s.name,
|
|
45
|
-
description: s.description.length > maxDescPerEntry
|
|
46
|
-
? s.description.slice(0, maxDescPerEntry - 1) + '\u2026'
|
|
47
|
-
: s.description,
|
|
48
|
-
}));
|
|
49
|
-
const result = formatEntries(truncated);
|
|
50
|
-
if (result.length <= budgetChars)
|
|
51
|
-
return result;
|
|
52
|
-
return fitNamesOnly(capped, budgetChars);
|
|
53
|
-
}
|
|
54
|
-
function formatEntries(entries) {
|
|
55
|
-
const lines = entries.map((e) => e.description ? `- ${e.name}: ${e.description}` : `- ${e.name}`);
|
|
56
|
-
return `${HEADER}\n\n${lines.join('\n')}`;
|
|
57
|
-
}
|
|
58
|
-
/** Names-only fallback that drops trailing entries if the list still exceeds budget. */
|
|
59
|
-
function fitNamesOnly(entries, budgetChars) {
|
|
60
|
-
// Format: "HEADER\n\n- name1\n- name2\n..."
|
|
61
|
-
// Running sum avoids O(n²) repeated string construction.
|
|
62
|
-
const prefix = HEADER.length + 2; // "HEADER\n\n"
|
|
63
|
-
const entryOverhead = 2; // "- "
|
|
64
|
-
let total = prefix;
|
|
65
|
-
let fitCount = 0;
|
|
66
|
-
for (let i = 0; i < entries.length; i++) {
|
|
67
|
-
const added = (i > 0 ? 1 : 0) + entryOverhead + entries[i].name.length;
|
|
68
|
-
if (total + added > budgetChars)
|
|
69
|
-
break;
|
|
70
|
-
total += added;
|
|
71
|
-
fitCount = i + 1;
|
|
72
|
-
}
|
|
73
|
-
if (fitCount === 0)
|
|
74
|
-
return '';
|
|
75
|
-
const namesOnly = entries
|
|
76
|
-
.slice(0, fitCount)
|
|
77
|
-
.map((s) => ({ name: s.name, description: '' }));
|
|
78
|
-
return formatEntries(namesOnly);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export { formatSkillCatalog };
|
|
82
|
-
//# sourceMappingURL=skillCatalog.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"skillCatalog.mjs","sources":["../../../src/tools/skillCatalog.ts"],"sourcesContent":["// src/tools/skillCatalog.ts\nimport type { SkillCatalogEntry } from '@/types';\n\nconst HEADER = '## Available Skills';\nconst DEFAULT_CONTEXT_WINDOW_TOKENS = 200_000;\nconst DEFAULT_BUDGET_PERCENT = 0.01;\nconst DEFAULT_MAX_ENTRY_CHARS = 250;\nconst DEFAULT_MIN_DESC_LENGTH = 20;\nconst DEFAULT_CHARS_PER_TOKEN = 4;\n\nexport type SkillCatalogOptions = {\n /** Total context window in tokens. Default: 200_000 */\n contextWindowTokens?: number;\n /** Fraction of context budget for catalog. Default: 0.01 (1%) */\n budgetPercent?: number;\n /** Max chars per entry description. Default: 250 */\n maxEntryChars?: number;\n /** Descriptions below this length trigger names-only fallback. Default: 20 */\n minDescLength?: number;\n /** Approximate chars per token for budget calculation. Default: 4 */\n charsPerToken?: number;\n};\n\n/**\n * Formats a skill catalog for injection into agent context.\n * Uses a truncation ladder: full descriptions, proportional truncation, names-only.\n * Returns empty string for empty input.\n */\nexport function formatSkillCatalog(\n skills: SkillCatalogEntry[],\n opts?: SkillCatalogOptions\n): string {\n if (skills.length === 0) return '';\n\n const contextWindowTokens =\n opts?.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS;\n const budgetPercent = opts?.budgetPercent ?? DEFAULT_BUDGET_PERCENT;\n const maxEntryChars = Math.max(\n 1,\n opts?.maxEntryChars ?? DEFAULT_MAX_ENTRY_CHARS\n );\n const minDescLength = opts?.minDescLength ?? DEFAULT_MIN_DESC_LENGTH;\n const charsPerToken = opts?.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;\n\n const budgetChars = Math.floor(\n contextWindowTokens * budgetPercent * charsPerToken\n );\n\n const capped = skills.map((s) => ({\n name: s.name,\n description:\n s.description.length > maxEntryChars\n ? s.description.slice(0, maxEntryChars - 1) + '\\u2026'\n : s.description,\n }));\n\n const fullOutput = formatEntries(capped);\n if (fullOutput.length <= budgetChars) return fullOutput;\n\n const headerLen = HEADER.length + 2;\n const newlineChars = capped.length > 1 ? capped.length - 1 : 0;\n const availableChars = budgetChars - headerLen - newlineChars;\n const perEntryOverhead = 4;\n const nameCharsTotal = capped.reduce(\n (sum, s) => sum + s.name.length + perEntryOverhead,\n 0\n );\n const availableForDescs = availableChars - nameCharsTotal;\n\n if (availableForDescs <= 0) {\n return fitNamesOnly(capped, budgetChars);\n }\n\n const maxDescPerEntry = Math.floor(availableForDescs / capped.length);\n\n if (maxDescPerEntry < minDescLength) {\n return fitNamesOnly(capped, budgetChars);\n }\n\n const truncated = capped.map((s) => ({\n name: s.name,\n description:\n s.description.length > maxDescPerEntry\n ? s.description.slice(0, maxDescPerEntry - 1) + '\\u2026'\n : s.description,\n }));\n\n const result = formatEntries(truncated);\n if (result.length <= budgetChars) return result;\n return fitNamesOnly(capped, budgetChars);\n}\n\nfunction formatEntries(\n entries: { name: string; description: string }[]\n): string {\n const lines = entries.map((e) =>\n e.description ? `- ${e.name}: ${e.description}` : `- ${e.name}`\n );\n return `${HEADER}\\n\\n${lines.join('\\n')}`;\n}\n\n/** Names-only fallback that drops trailing entries if the list still exceeds budget. */\nfunction fitNamesOnly(\n entries: { name: string }[],\n budgetChars: number\n): string {\n // Format: \"HEADER\\n\\n- name1\\n- name2\\n...\"\n // Running sum avoids O(n²) repeated string construction.\n const prefix = HEADER.length + 2; // \"HEADER\\n\\n\"\n const entryOverhead = 2; // \"- \"\n let total = prefix;\n let fitCount = 0;\n\n for (let i = 0; i < entries.length; i++) {\n const added = (i > 0 ? 1 : 0) + entryOverhead + entries[i].name.length;\n if (total + added > budgetChars) break;\n total += added;\n fitCount = i + 1;\n }\n\n if (fitCount === 0) return '';\n const namesOnly = entries\n .slice(0, fitCount)\n .map((s) => ({ name: s.name, description: '' }));\n return formatEntries(namesOnly);\n}\n"],"names":[],"mappings":"AAGA,MAAM,MAAM,GAAG,qBAAqB;AACpC,MAAM,6BAA6B,GAAG,OAAO;AAC7C,MAAM,sBAAsB,GAAG,IAAI;AACnC,MAAM,uBAAuB,GAAG,GAAG;AACnC,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,uBAAuB,GAAG,CAAC;AAejC;;;;AAIG;AACG,SAAU,kBAAkB,CAChC,MAA2B,EAC3B,IAA0B,EAAA;AAE1B,IAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,EAAE;AAElC,IAAA,MAAM,mBAAmB,GACvB,IAAI,EAAE,mBAAmB,IAAI,6BAA6B;AAC5D,IAAA,MAAM,aAAa,GAAG,IAAI,EAAE,aAAa,IAAI,sBAAsB;AACnE,IAAA,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAC5B,CAAC,EACD,IAAI,EAAE,aAAa,IAAI,uBAAuB,CAC/C;AACD,IAAA,MAAM,aAAa,GAAG,IAAI,EAAE,aAAa,IAAI,uBAAuB;AACpE,IAAA,MAAM,aAAa,GAAG,IA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G,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACvC,MAAM,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,aAAa,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;AACtE,QAAA,IAAI,KAAK,GAAG,KAAK,GAAG,WAAW;YAAE;QACjC,KAAK,IAAI,KAAK;AACd,QAAA,QAAQ,GAAG,CAAC,GAAG,CAAC;IAClB;IAEA,IAAI,QAAQ,KAAK,CAAC;AAAE,QAAA,OAAO,EAAE;IAC7B,MAAM,SAAS,GAAG;AACf,SAAA,KAAK,CAAC,CAAC,EAAE,QAAQ;SACjB,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;AAClD,IAAA,OAAO,aAAa,CAAC,SAAS,CAAC;AACjC;;;;"}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import type { HookEvent, HookMatcher } from './types';
|
|
2
|
-
/**
|
|
3
|
-
* Run-scoped storage for hook matchers with an additional layer for
|
|
4
|
-
* session-scoped matchers that should be cleaned up between sessions.
|
|
5
|
-
*
|
|
6
|
-
* Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is
|
|
7
|
-
* scoped) and register global matchers + per-session matchers against it.
|
|
8
|
-
* Registration is strictly additive — nothing in this class mutates a
|
|
9
|
-
* matcher's callbacks or flags after insertion.
|
|
10
|
-
*
|
|
11
|
-
* ## Why `Map<sessionId, MatcherBucket>` and not `Record`
|
|
12
|
-
*
|
|
13
|
-
* LibreChat runs thousands of parallel sessions in one Node process, and
|
|
14
|
-
* hook registration happens inside hot paths (tool loading, agent spawning).
|
|
15
|
-
* A `Record<sessionId, ...>` has to be spread on every insertion, which is
|
|
16
|
-
* O(n) per call and O(n²) total for a batch of parallel registrations. A
|
|
17
|
-
* Map mutates in place, keeping insertions O(1). This mirrors the reasoning
|
|
18
|
-
* Claude Code documents at `utils/hooks/sessionHooks.ts:62`.
|
|
19
|
-
*/
|
|
20
|
-
export declare class HookRegistry {
|
|
21
|
-
private readonly global;
|
|
22
|
-
private readonly sessions;
|
|
23
|
-
/**
|
|
24
|
-
* Register a matcher for the lifetime of this registry (= one Run).
|
|
25
|
-
* Returns an unregister function that removes the matcher by reference.
|
|
26
|
-
*/
|
|
27
|
-
register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void;
|
|
28
|
-
/**
|
|
29
|
-
* Register a matcher for a specific session. Cleared automatically when
|
|
30
|
-
* `clearSession(sessionId)` is called, or can be removed directly via the
|
|
31
|
-
* returned unregister function.
|
|
32
|
-
*/
|
|
33
|
-
registerSession<E extends HookEvent>(sessionId: string, event: E, matcher: HookMatcher<E>): () => void;
|
|
34
|
-
/**
|
|
35
|
-
* Returns all matchers registered for `event`, concatenating global first
|
|
36
|
-
* and then session-specific (when `sessionId` is supplied). The caller
|
|
37
|
-
* receives a fresh array, so iterating it is safe even if a matcher is
|
|
38
|
-
* removed mid-iteration (e.g. via `once: true`).
|
|
39
|
-
*/
|
|
40
|
-
getMatchers<E extends HookEvent>(event: E, sessionId?: string): HookMatcher<E>[];
|
|
41
|
-
/**
|
|
42
|
-
* Removes `matcher` by reference from global storage first, falling back
|
|
43
|
-
* to the session bucket when `sessionId` is supplied. Used by
|
|
44
|
-
* `executeHooks` to drop `once: true` matchers after they fire.
|
|
45
|
-
*/
|
|
46
|
-
removeMatcher<E extends HookEvent>(event: E, matcher: HookMatcher<E>, sessionId?: string): boolean;
|
|
47
|
-
/**
|
|
48
|
-
* Drops every session-scoped matcher for `sessionId`. Call this in the
|
|
49
|
-
* `finally` block around a Run so a `once: true` hook that never fired
|
|
50
|
-
* cannot leak into the next session on the same registry.
|
|
51
|
-
*/
|
|
52
|
-
clearSession(sessionId: string): void;
|
|
53
|
-
/** True if at least one matcher exists for `event` (global + session). */
|
|
54
|
-
hasHookFor(event: HookEvent, sessionId?: string): boolean;
|
|
55
|
-
private ensureSessionBucket;
|
|
56
|
-
}
|