@librechat/agents 3.0.41 → 3.0.43

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 (52) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +177 -69
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +1 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +19 -36
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +5 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/tools.cjs +85 -0
  10. package/dist/cjs/messages/tools.cjs.map +1 -0
  11. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +55 -32
  12. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  13. package/dist/cjs/tools/ToolNode.cjs +30 -13
  14. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  15. package/dist/esm/agents/AgentContext.mjs +177 -69
  16. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  17. package/dist/esm/common/enum.mjs +1 -1
  18. package/dist/esm/common/enum.mjs.map +1 -1
  19. package/dist/esm/graphs/Graph.mjs +19 -36
  20. package/dist/esm/graphs/Graph.mjs.map +1 -1
  21. package/dist/esm/main.mjs +2 -1
  22. package/dist/esm/main.mjs.map +1 -1
  23. package/dist/esm/messages/tools.mjs +82 -0
  24. package/dist/esm/messages/tools.mjs.map +1 -0
  25. package/dist/esm/tools/ProgrammaticToolCalling.mjs +54 -33
  26. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  27. package/dist/esm/tools/ToolNode.mjs +30 -13
  28. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  29. package/dist/types/agents/AgentContext.d.ts +52 -16
  30. package/dist/types/common/enum.d.ts +1 -1
  31. package/dist/types/graphs/Graph.d.ts +1 -1
  32. package/dist/types/messages/index.d.ts +1 -0
  33. package/dist/types/messages/tools.d.ts +17 -0
  34. package/dist/types/tools/ProgrammaticToolCalling.d.ts +15 -23
  35. package/dist/types/tools/ToolNode.d.ts +9 -7
  36. package/dist/types/types/tools.d.ts +5 -5
  37. package/package.json +1 -1
  38. package/src/agents/AgentContext.ts +205 -80
  39. package/src/agents/__tests__/AgentContext.test.ts +805 -0
  40. package/src/common/enum.ts +1 -1
  41. package/src/graphs/Graph.ts +24 -40
  42. package/src/messages/__tests__/tools.test.ts +473 -0
  43. package/src/messages/index.ts +1 -0
  44. package/src/messages/tools.ts +99 -0
  45. package/src/scripts/code_exec_ptc.ts +78 -21
  46. package/src/scripts/programmatic_exec.ts +3 -3
  47. package/src/scripts/programmatic_exec_agent.ts +4 -4
  48. package/src/tools/ProgrammaticToolCalling.ts +71 -39
  49. package/src/tools/ToolNode.ts +33 -14
  50. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +9 -9
  51. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +180 -5
  52. package/src/types/tools.ts +3 -5
@@ -7,16 +7,6 @@ var _enum = require('../common/enum.cjs');
7
7
 
8
8
  /* eslint-disable no-console */
9
9
  // src/agents/AgentContext.ts
10
- /**
11
- * Checks if a tool allows the specified caller type.
12
- * Default is 'direct' only if allowed_callers is not specified.
13
- */
14
- function toolAllowsCaller(toolDef, caller) {
15
- if (!toolDef)
16
- return false;
17
- const allowedCallers = toolDef.allowed_callers ?? ['direct'];
18
- return allowedCallers.includes(caller);
19
- }
20
10
  /**
21
11
  * Encapsulates agent-specific state that can vary between agents in a multi-agent system
22
12
  */
@@ -44,12 +34,16 @@ class AgentContext {
44
34
  useLegacyContent,
45
35
  });
46
36
  if (tokenCounter) {
37
+ // Initialize system runnable BEFORE async tool token calculation
38
+ // This ensures system message tokens are in instructionTokens before
39
+ // updateTokenMapWithInstructions is called
40
+ agentContext.initializeSystemRunnable();
47
41
  const tokenMap = indexTokenCountMap || {};
48
42
  agentContext.indexTokenCountMap = tokenMap;
49
43
  agentContext.tokenCalculationPromise = agentContext
50
44
  .calculateInstructionTokens(tokenCounter)
51
45
  .then(() => {
52
- // Update token map with instruction tokens
46
+ // Update token map with instruction tokens (includes system + tool tokens)
53
47
  agentContext.updateTokenMapWithInstructions(tokenMap);
54
48
  })
55
49
  .catch((err) => {
@@ -92,6 +86,8 @@ class AgentContext {
92
86
  * Used for tool search and programmatic tool calling.
93
87
  */
94
88
  toolRegistry;
89
+ /** Set of tool names discovered via tool search (to be loaded) */
90
+ discoveredToolNames = new Set();
95
91
  /** Instructions for this agent */
96
92
  instructions;
97
93
  /** Additional instructions for this agent */
@@ -106,8 +102,12 @@ class AgentContext {
106
102
  currentTokenType = _enum.ContentTypes.TEXT;
107
103
  /** Whether tools should end the workflow */
108
104
  toolEnd = false;
109
- /** System runnable for this agent */
110
- systemRunnable;
105
+ /** Cached system runnable (created lazily) */
106
+ cachedSystemRunnable;
107
+ /** Whether system runnable needs rebuild (set when discovered tools change) */
108
+ systemRunnableStale = true;
109
+ /** Cached system message token count (separate from tool tokens) */
110
+ systemMessageTokens = 0;
111
111
  /** Promise for token calculation initialization */
112
112
  tokenCalculationPromise;
113
113
  /** Format content blocks as strings (for legacy compatibility) */
@@ -134,24 +134,112 @@ class AgentContext {
134
134
  this.instructionTokens = instructionTokens;
135
135
  }
136
136
  this.useLegacyContent = useLegacyContent ?? false;
137
- this.systemRunnable = this.createSystemRunnable();
138
137
  }
139
138
  /**
140
- * Create system runnable from instructions and calculate tokens if tokenCounter is available
139
+ * Builds instructions text for tools that are ONLY callable via programmatic code execution.
140
+ * These tools cannot be called directly by the LLM but are available through the
141
+ * run_tools_with_code tool.
142
+ *
143
+ * Includes:
144
+ * - Code_execution-only tools that are NOT deferred
145
+ * - Code_execution-only tools that ARE deferred but have been discovered via tool search
146
+ */
147
+ buildProgrammaticOnlyToolsInstructions() {
148
+ if (!this.toolRegistry)
149
+ return '';
150
+ const programmaticOnlyTools = [];
151
+ for (const [name, toolDef] of this.toolRegistry) {
152
+ const allowedCallers = toolDef.allowed_callers ?? ['direct'];
153
+ const isCodeExecutionOnly = allowedCallers.includes('code_execution') &&
154
+ !allowedCallers.includes('direct');
155
+ if (!isCodeExecutionOnly)
156
+ continue;
157
+ // Include if: not deferred OR deferred but discovered
158
+ const isDeferred = toolDef.defer_loading === true;
159
+ const isDiscovered = this.discoveredToolNames.has(name);
160
+ if (!isDeferred || isDiscovered) {
161
+ programmaticOnlyTools.push(toolDef);
162
+ }
163
+ }
164
+ if (programmaticOnlyTools.length === 0)
165
+ return '';
166
+ const toolDescriptions = programmaticOnlyTools
167
+ .map((tool) => {
168
+ let desc = `- **${tool.name}**`;
169
+ if (tool.description != null && tool.description !== '') {
170
+ desc += `: ${tool.description}`;
171
+ }
172
+ if (tool.parameters) {
173
+ desc += `\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\n/g, '\n ')}`;
174
+ }
175
+ return desc;
176
+ })
177
+ .join('\n\n');
178
+ return ('\n\n## Programmatic-Only Tools\n\n' +
179
+ 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +
180
+ 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\n\n' +
181
+ toolDescriptions);
182
+ }
183
+ /**
184
+ * Gets the system runnable, creating it lazily if needed.
185
+ * Includes instructions, additional instructions, and programmatic-only tools documentation.
186
+ * Only rebuilds when marked stale (via markToolsAsDiscovered).
187
+ */
188
+ get systemRunnable() {
189
+ // Return cached if not stale
190
+ if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
191
+ return this.cachedSystemRunnable;
192
+ }
193
+ // Stale or first access - rebuild
194
+ const instructionsString = this.buildInstructionsString();
195
+ this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
196
+ this.systemRunnableStale = false;
197
+ return this.cachedSystemRunnable;
198
+ }
199
+ /**
200
+ * Explicitly initializes the system runnable.
201
+ * Call this before async token calculation to ensure system message tokens are counted first.
141
202
  */
142
- createSystemRunnable() {
143
- let finalInstructions = this.instructions;
203
+ initializeSystemRunnable() {
204
+ if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
205
+ const instructionsString = this.buildInstructionsString();
206
+ this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
207
+ this.systemRunnableStale = false;
208
+ }
209
+ }
210
+ /**
211
+ * Builds the raw instructions string (without creating SystemMessage).
212
+ */
213
+ buildInstructionsString() {
214
+ let result = this.instructions ?? '';
144
215
  if (this.additionalInstructions != null &&
145
216
  this.additionalInstructions !== '') {
146
- finalInstructions =
147
- finalInstructions != null && finalInstructions
148
- ? `${finalInstructions}\n\n${this.additionalInstructions}`
149
- : this.additionalInstructions;
217
+ result = result
218
+ ? `${result}\n\n${this.additionalInstructions}`
219
+ : this.additionalInstructions;
220
+ }
221
+ const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
222
+ if (programmaticToolsDoc) {
223
+ result = result
224
+ ? `${result}${programmaticToolsDoc}`
225
+ : programmaticToolsDoc;
150
226
  }
227
+ return result;
228
+ }
229
+ /**
230
+ * Build system runnable from pre-built instructions string.
231
+ * Only called when content has actually changed.
232
+ */
233
+ buildSystemRunnable(instructionsString) {
234
+ if (!instructionsString) {
235
+ // Remove previous tokens if we had a system message before
236
+ this.instructionTokens -= this.systemMessageTokens;
237
+ this.systemMessageTokens = 0;
238
+ return undefined;
239
+ }
240
+ let finalInstructions = instructionsString;
151
241
  // Handle Anthropic prompt caching
152
- if (finalInstructions != null &&
153
- finalInstructions !== '' &&
154
- this.provider === _enum.Providers.ANTHROPIC) {
242
+ if (this.provider === _enum.Providers.ANTHROPIC) {
155
243
  const anthropicOptions = this.clientOptions;
156
244
  const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders;
157
245
  const anthropicBeta = defaultHeaders?.['anthropic-beta'];
@@ -161,29 +249,32 @@ class AgentContext {
161
249
  content: [
162
250
  {
163
251
  type: 'text',
164
- text: this.instructions,
252
+ text: instructionsString,
165
253
  cache_control: { type: 'ephemeral' },
166
254
  },
167
255
  ],
168
256
  };
169
257
  }
170
258
  }
171
- if (finalInstructions != null && finalInstructions !== '') {
172
- const systemMessage = new messages.SystemMessage(finalInstructions);
173
- if (this.tokenCounter) {
174
- this.instructionTokens += this.tokenCounter(systemMessage);
175
- }
176
- return runnables.RunnableLambda.from((messages) => {
177
- return [systemMessage, ...messages];
178
- }).withConfig({ runName: 'prompt' });
259
+ const systemMessage = new messages.SystemMessage(finalInstructions);
260
+ // Update token counts (subtract old, add new)
261
+ if (this.tokenCounter) {
262
+ this.instructionTokens -= this.systemMessageTokens;
263
+ this.systemMessageTokens = this.tokenCounter(systemMessage);
264
+ this.instructionTokens += this.systemMessageTokens;
179
265
  }
180
- return undefined;
266
+ return runnables.RunnableLambda.from((messages) => {
267
+ return [systemMessage, ...messages];
268
+ }).withConfig({ runName: 'prompt' });
181
269
  }
182
270
  /**
183
271
  * Reset context for a new run
184
272
  */
185
273
  reset() {
186
274
  this.instructionTokens = 0;
275
+ this.systemMessageTokens = 0;
276
+ this.cachedSystemRunnable = undefined;
277
+ this.systemRunnableStale = true;
187
278
  this.lastToken = undefined;
188
279
  this.indexTokenCountMap = {};
189
280
  this.currentUsage = undefined;
@@ -191,6 +282,7 @@ class AgentContext {
191
282
  this.lastStreamCall = undefined;
192
283
  this.tokenTypeSwitch = undefined;
193
284
  this.currentTokenType = _enum.ContentTypes.TEXT;
285
+ this.discoveredToolNames.clear();
194
286
  }
195
287
  /**
196
288
  * Update the token count map with instruction tokens
@@ -233,41 +325,6 @@ class AgentContext {
233
325
  // Add tool tokens to existing instruction tokens (which may already include system message tokens)
234
326
  this.instructionTokens += toolTokens;
235
327
  }
236
- /**
237
- * Gets a map of tools that allow programmatic (code_execution) calling.
238
- * Filters toolMap based on toolRegistry's allowed_callers settings.
239
- * @returns ToolMap containing only tools that allow code_execution
240
- */
241
- getProgrammaticToolMap() {
242
- const programmaticMap = new Map();
243
- if (!this.toolMap) {
244
- return programmaticMap;
245
- }
246
- for (const [name, tool] of this.toolMap) {
247
- const toolDef = this.toolRegistry?.get(name);
248
- if (toolAllowsCaller(toolDef, 'code_execution')) {
249
- programmaticMap.set(name, tool);
250
- }
251
- }
252
- return programmaticMap;
253
- }
254
- /**
255
- * Gets tool definitions for tools that allow programmatic calling.
256
- * Used to send to the Code API for stub generation.
257
- * @returns Array of LCTool definitions for programmatic tools
258
- */
259
- getProgrammaticToolDefs() {
260
- if (!this.toolRegistry) {
261
- return [];
262
- }
263
- const defs = [];
264
- for (const [_name, toolDef] of this.toolRegistry) {
265
- if (toolAllowsCaller(toolDef, 'code_execution')) {
266
- defs.push(toolDef);
267
- }
268
- }
269
- return defs;
270
- }
271
328
  /**
272
329
  * Gets the tool registry for deferred tools (for tool search).
273
330
  * @param onlyDeferred If true, only returns tools with defer_loading=true
@@ -285,6 +342,57 @@ class AgentContext {
285
342
  }
286
343
  return registry;
287
344
  }
345
+ /**
346
+ * Marks tools as discovered via tool search.
347
+ * Discovered tools will be included in the next model binding.
348
+ * Only marks system runnable stale if NEW tools were actually added.
349
+ * @param toolNames - Array of discovered tool names
350
+ * @returns true if any new tools were discovered
351
+ */
352
+ markToolsAsDiscovered(toolNames) {
353
+ let hasNewDiscoveries = false;
354
+ for (const name of toolNames) {
355
+ if (!this.discoveredToolNames.has(name)) {
356
+ this.discoveredToolNames.add(name);
357
+ hasNewDiscoveries = true;
358
+ }
359
+ }
360
+ if (hasNewDiscoveries) {
361
+ this.systemRunnableStale = true;
362
+ }
363
+ return hasNewDiscoveries;
364
+ }
365
+ /**
366
+ * Gets tools that should be bound to the LLM.
367
+ * Includes:
368
+ * 1. Non-deferred tools with allowed_callers: ['direct']
369
+ * 2. Discovered tools (from tool search)
370
+ * @returns Array of tools to bind to model
371
+ */
372
+ getToolsForBinding() {
373
+ if (!this.tools || !this.toolRegistry) {
374
+ return this.tools;
375
+ }
376
+ const toolsToInclude = this.tools.filter((tool) => {
377
+ if (!('name' in tool)) {
378
+ return true; // No name, include by default
379
+ }
380
+ const toolDef = this.toolRegistry?.get(tool.name);
381
+ if (!toolDef) {
382
+ return true; // Not in registry, include by default
383
+ }
384
+ // Check if discovered (overrides defer_loading)
385
+ if (this.discoveredToolNames.has(tool.name)) {
386
+ // Discovered tools must still have allowed_callers: ['direct']
387
+ const allowedCallers = toolDef.allowed_callers ?? ['direct'];
388
+ return allowedCallers.includes('direct');
389
+ }
390
+ // Not discovered: must be direct-callable AND not deferred
391
+ const allowedCallers = toolDef.allowed_callers ?? ['direct'];
392
+ return (allowedCallers.includes('direct') && toolDef.defer_loading !== true);
393
+ });
394
+ return toolsToInclude;
395
+ }
288
396
  }
289
397
 
290
398
  exports.AgentContext = AgentContext;
@@ -1 +1 @@
1
- {"version":3,"file":"AgentContext.cjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Checks if a tool allows the specified caller type.\n * Default is 'direct' only if allowed_callers is not specified.\n */\nfunction toolAllowsCaller(\n toolDef: t.LCTool | undefined,\n caller: t.AllowedCaller\n): boolean {\n if (!toolDef) return false;\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes(caller);\n}\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** System runnable for this agent */\n systemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n this.systemRunnable = this.createSystemRunnable();\n }\n\n /**\n * Create system runnable from instructions and calculate tokens if tokenCounter is available\n */\n private createSystemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n this.instructions;\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n // Handle Anthropic prompt caching\n if (\n finalInstructions != null &&\n finalInstructions !== '' &&\n this.provider === Providers.ANTHROPIC\n ) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: this.instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n\n if (this.tokenCounter) {\n this.instructionTokens += this.tokenCounter(systemMessage);\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n return undefined;\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets a map of tools that allow programmatic (code_execution) calling.\n * Filters toolMap based on toolRegistry's allowed_callers settings.\n * @returns ToolMap containing only tools that allow code_execution\n */\n getProgrammaticToolMap(): t.ToolMap {\n const programmaticMap: t.ToolMap = new Map();\n\n if (!this.toolMap) {\n return programmaticMap;\n }\n\n for (const [name, tool] of this.toolMap) {\n const toolDef = this.toolRegistry?.get(name);\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n programmaticMap.set(name, tool);\n }\n }\n\n return programmaticMap;\n }\n\n /**\n * Gets tool definitions for tools that allow programmatic calling.\n * Used to send to the Code API for stub generation.\n * @returns Array of LCTool definitions for programmatic tools\n */\n getProgrammaticToolDefs(): t.LCTool[] {\n if (!this.toolRegistry) {\n return [];\n }\n\n const defs: t.LCTool[] = [];\n for (const [_name, toolDef] of this.toolRegistry) {\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n defs.push(toolDef);\n }\n }\n\n return defs;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n}\n"],"names":["ContentTypes","Providers","SystemMessage","RunnableLambda","zodToJsonSchema"],"mappings":";;;;;;;AAAA;AACA;AAcA;;;AAGG;AACH,SAAS,gBAAgB,CACvB,OAA6B,EAC7B,MAAuB,EAAA;AAEvB,IAAA,IAAI,CAAC,OAAO;AAAE,QAAA,OAAO,KAAK;IAC1B,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,IAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC;AACxC;AAEA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,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AAgB,CAAC,EAAE;AAC/C,gBAAA,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;;;AAItB,QAAA,OAAO,IAAI;;AAGb;;;;AAIG;IACH,uBAAuB,CAAC,eAAwB,IAAI,EAAA;AAClD,QAAA,MAAM,QAAQ,GAAqB,IAAI,GAAG,EAAE;AAE5C,QAAA,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;AACtB,YAAA,OAAO,QAAQ;;QAGjB,KAAK,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,YAAY,EAAE;YAC/C,IAAI,CAAC,YAAY,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI,EAAE;AACnD,gBAAA,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC;;;AAI/B,QAAA,OAAO,QAAQ;;AAElB;;;;"}
1
+ {"version":3,"file":"AgentContext.cjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":["ContentTypes","Providers","SystemMessage","RunnableLambda","zodToJsonSchema"],"mappings":";;;;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;AACjB,SAAA,CAAC;QAEF,IAAI,YAAY,EAAE;;;;YAIhB,YAAY,CAAC,wBAAwB,EAAE;AAEvC,YAAA,MAAM,QAAQ,GAAG,kBAAkB,IAAI,EAAE;AACzC,YAAA,YAAY,CAAC,kBAAkB,GAAG,QAAQ;YAC1C,YAAY,CAAC,uBAAuB,GAAG;iBACpC,0BAA0B,CAAC,YAAY;iBACvC,IAA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AE;AACrB,YAAA,IAAI,CAAC,mBAAmB,GAAG,IAAI;;AAEjC,QAAA,OAAO,iBAAiB;;AAG1B;;;;;;AAMG;IACH,kBAAkB,GAAA;QAChB,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACrC,OAAO,IAAI,CAAC,KAAK;;QAGnB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;AAChD,YAAA,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,EAAE;gBACrB,OAAO,IAAI,CAAC;;AAGd,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,IAAI,CAAC;;;YAId,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
@@ -146,7 +146,7 @@ exports.Constants = void 0;
146
146
  Constants["OFFICIAL_CODE_BASEURL"] = "https://api.librechat.ai/v1";
147
147
  Constants["EXECUTE_CODE"] = "execute_code";
148
148
  Constants["TOOL_SEARCH_REGEX"] = "tool_search_regex";
149
- Constants["PROGRAMMATIC_TOOL_CALLING"] = "programmatic_code_execution";
149
+ Constants["PROGRAMMATIC_TOOL_CALLING"] = "run_tools_with_code";
150
150
  Constants["WEB_SEARCH"] = "web_search";
151
151
  Constants["CONTENT_AND_ARTIFACT"] = "content_and_artifact";
152
152
  Constants["LC_TRANSFER_TO_"] = "lc_transfer_to_";
@@ -1 +1 @@
1
- {"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = 'programmatic_code_execution',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n}\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","TitleMethod","EnvVar"],"mappings":";;AAAA;;;;;AAKG;AACSA;AAAZ,CAAA,UAAY,WAAW,EAAA;;;AAIrB,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;;AAE3B,IAAA,WAAA,CAAA,mBAAA,CAAA,G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
+ {"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n}\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","TitleMethod","EnvVar"],"mappings":";;AAAA;;;;;AAKG;AACSA;AAAZ,CAAA,UAAY,WAAW,EAAA;;;AAIrB,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;;AAE3B,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;;AAEvC,IAAA,WAAA,CAAA,uBAAA,CAAA,GAAA,uBAA+C;;AAE/C,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;;AAErC,IAAA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,UAAA,CAAA,GAAA,eAA0B;AAC1B,IAAA,QAAA,CAAA,cAAA,CAAA,GAAA,mBAAkC;AAClC;;;;;;;;;;;;;;;AAeE;AACJ,CAAC,EArBWA,gBAAQ,KAARA,gBAAQ,GAqBnB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,SAAS,EAAA;AACnB,IAAA,SAAA,CAAA,uBAAA,CAAA,GAAA,6BAAqD;AACrD,IAAA,SAAA,CAAA,cAAA,CAAA,GAAA,cAA6B;AAC7B,IAAA,SAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,SAAA,CAAA,2BAAA,CAAA,GAAA,qBAAiD;AACjD,IAAA,SAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,SAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,SAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;AACrC,CAAC,EARWA,iBAAS,KAATA,iBAAS,GAQpB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,WAAW,EAAA;AACrB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AAC3B,CAAC,EAJWA,mBAAW,KAAXA,mBAAW,GAItB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACvC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACzC,CAAC,EAHWA,cAAM,KAANA,cAAM,GAGjB,EAAA,CAAA,CAAA;;"}
@@ -12,6 +12,7 @@ var prune = require('../messages/prune.cjs');
12
12
  var format = require('../messages/format.cjs');
13
13
  var cache = require('../messages/cache.cjs');
14
14
  var content = require('../messages/content.cjs');
15
+ var tools = require('../messages/tools.cjs');
15
16
  var graph = require('../utils/graph.cjs');
16
17
  var llm = require('../utils/llm.cjs');
17
18
  var run = require('../utils/run.cjs');
@@ -271,8 +272,6 @@ class StandardGraph extends Graph {
271
272
  toolCallStepIds: this.toolCallStepIds,
272
273
  errorHandler: (data, metadata) => StandardGraph.handleToolCallErrorStatic(this, data, metadata),
273
274
  toolRegistry: agentContext?.toolRegistry,
274
- programmaticToolMap: agentContext?.getProgrammaticToolMap(),
275
- programmaticToolDefs: agentContext?.getProgrammaticToolDefs(),
276
275
  });
277
276
  }
278
277
  initializeModel({ provider, tools, clientOptions, }) {
@@ -369,7 +368,7 @@ class StandardGraph extends Graph {
369
368
  this.signal.removeEventListener('abort', client.abortHandler);
370
369
  client.abortHandler = undefined;
371
370
  }
372
- createCallModel(agentId = 'default', currentModel) {
371
+ createCallModel(agentId = 'default') {
373
372
  return async (state, config) => {
374
373
  /**
375
374
  * Get agent context - it must exist by this point
@@ -378,14 +377,25 @@ class StandardGraph extends Graph {
378
377
  if (!agentContext) {
379
378
  throw new Error(`Agent context not found for agentId: ${agentId}`);
380
379
  }
381
- const model = this.overrideModel ?? currentModel;
382
- if (!model) {
383
- throw new Error('No Graph model found');
384
- }
385
380
  if (!config) {
386
381
  throw new Error('No config provided');
387
382
  }
388
- // Ensure token calculations are complete before proceeding
383
+ const { messages: messages$1 } = state;
384
+ // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)
385
+ const discoveredNames = tools.extractToolDiscoveries(messages$1);
386
+ if (discoveredNames.length > 0) {
387
+ agentContext.markToolsAsDiscovered(discoveredNames);
388
+ }
389
+ const toolsForBinding = agentContext.getToolsForBinding();
390
+ let model = this.overrideModel ??
391
+ this.initializeModel({
392
+ tools: toolsForBinding,
393
+ provider: agentContext.provider,
394
+ clientOptions: agentContext.clientOptions,
395
+ });
396
+ if (agentContext.systemRunnable) {
397
+ model = agentContext.systemRunnable.pipe(model);
398
+ }
389
399
  if (agentContext.tokenCalculationPromise) {
390
400
  await agentContext.tokenCalculationPromise;
391
401
  }
@@ -393,7 +403,6 @@ class StandardGraph extends Graph {
393
403
  config.signal = this.signal;
394
404
  }
395
405
  this.config = config;
396
- const { messages: messages$1 } = state;
397
406
  let messagesToUse = messages$1;
398
407
  if (!agentContext.pruneMessages &&
399
408
  agentContext.tokenCounter &&
@@ -553,32 +562,6 @@ class StandardGraph extends Graph {
553
562
  if (!agentContext) {
554
563
  throw new Error(`Agent context not found for agentId: ${agentId}`);
555
564
  }
556
- // Filter tools for LLM binding: only tools with allowed_callers including 'direct'
557
- // Default: if allowed_callers is not specified, tool is bound to LLM (direct)
558
- let toolsForLLM = agentContext.tools;
559
- if (agentContext.toolRegistry != null && agentContext.tools != null) {
560
- toolsForLLM = agentContext.tools.filter((tool) => {
561
- const toolDef = 'name' in tool
562
- ? agentContext.toolRegistry?.get(tool.name)
563
- : undefined;
564
- if (!toolDef) {
565
- // Tool not in registry - bind to LLM by default
566
- return true;
567
- }
568
- if (!toolDef.allowed_callers) {
569
- return true;
570
- }
571
- return toolDef.allowed_callers.includes('direct');
572
- });
573
- }
574
- let currentModel = this.initializeModel({
575
- tools: toolsForLLM,
576
- provider: agentContext.provider,
577
- clientOptions: agentContext.clientOptions,
578
- });
579
- if (agentContext.systemRunnable) {
580
- currentModel = agentContext.systemRunnable.pipe(currentModel);
581
- }
582
565
  const agentNode = `${AGENT}${agentId}`;
583
566
  const toolNode = `${TOOLS}${agentId}`;
584
567
  const routeMessage = (state, config) => {
@@ -592,7 +575,7 @@ class StandardGraph extends Graph {
592
575
  }),
593
576
  });
594
577
  const workflow = new langgraph.StateGraph(StateAnnotation)
595
- .addNode(agentNode, this.createCallModel(agentId, currentModel))
578
+ .addNode(agentNode, this.createCallModel(agentId))
596
579
  .addNode(toolNode, this.initializeTools({
597
580
  currentTools: agentContext.tools,
598
581
  currentToolMap: agentContext.toolMap,