illuma-agents 1.0.10 → 1.0.12

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 (117) hide show
  1. package/LICENSE +1 -1
  2. package/dist/cjs/agents/AgentContext.cjs +236 -27
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/enum.cjs +2 -0
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/events.cjs +3 -11
  7. package/dist/cjs/events.cjs.map +1 -1
  8. package/dist/cjs/graphs/Graph.cjs +44 -18
  9. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  10. package/dist/cjs/instrumentation.cjs +1 -3
  11. package/dist/cjs/instrumentation.cjs.map +1 -1
  12. package/dist/cjs/llm/bedrock/index.cjs +121 -6
  13. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  14. package/dist/cjs/main.cjs +18 -0
  15. package/dist/cjs/main.cjs.map +1 -1
  16. package/dist/cjs/messages/cache.cjs +149 -54
  17. package/dist/cjs/messages/cache.cjs.map +1 -1
  18. package/dist/cjs/messages/tools.cjs +85 -0
  19. package/dist/cjs/messages/tools.cjs.map +1 -0
  20. package/dist/cjs/run.cjs +0 -8
  21. package/dist/cjs/run.cjs.map +1 -1
  22. package/dist/cjs/tools/CodeExecutor.cjs +4 -0
  23. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  24. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +438 -0
  25. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
  26. package/dist/cjs/tools/ToolNode.cjs +53 -15
  27. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  28. package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
  29. package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
  30. package/dist/cjs/tools/search/schema.cjs +7 -9
  31. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  32. package/dist/cjs/utils/run.cjs +5 -1
  33. package/dist/cjs/utils/run.cjs.map +1 -1
  34. package/dist/esm/agents/AgentContext.mjs +236 -27
  35. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  36. package/dist/esm/common/enum.mjs +2 -0
  37. package/dist/esm/common/enum.mjs.map +1 -1
  38. package/dist/esm/events.mjs +4 -12
  39. package/dist/esm/events.mjs.map +1 -1
  40. package/dist/esm/graphs/Graph.mjs +45 -19
  41. package/dist/esm/graphs/Graph.mjs.map +1 -1
  42. package/dist/esm/instrumentation.mjs +1 -3
  43. package/dist/esm/instrumentation.mjs.map +1 -1
  44. package/dist/esm/llm/bedrock/index.mjs +121 -6
  45. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  46. package/dist/esm/main.mjs +3 -0
  47. package/dist/esm/main.mjs.map +1 -1
  48. package/dist/esm/messages/cache.mjs +149 -54
  49. package/dist/esm/messages/cache.mjs.map +1 -1
  50. package/dist/esm/messages/tools.mjs +82 -0
  51. package/dist/esm/messages/tools.mjs.map +1 -0
  52. package/dist/esm/run.mjs +0 -8
  53. package/dist/esm/run.mjs.map +1 -1
  54. package/dist/esm/tools/CodeExecutor.mjs +4 -0
  55. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  56. package/dist/esm/tools/ProgrammaticToolCalling.mjs +430 -0
  57. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
  58. package/dist/esm/tools/ToolNode.mjs +53 -15
  59. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  60. package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
  61. package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
  62. package/dist/esm/tools/search/schema.mjs +7 -9
  63. package/dist/esm/tools/search/schema.mjs.map +1 -1
  64. package/dist/esm/utils/run.mjs +5 -1
  65. package/dist/esm/utils/run.mjs.map +1 -1
  66. package/dist/types/agents/AgentContext.d.ts +72 -5
  67. package/dist/types/common/enum.d.ts +2 -0
  68. package/dist/types/graphs/Graph.d.ts +3 -2
  69. package/dist/types/index.d.ts +2 -0
  70. package/dist/types/llm/bedrock/index.d.ts +31 -4
  71. package/dist/types/messages/cache.d.ts +23 -8
  72. package/dist/types/messages/index.d.ts +1 -0
  73. package/dist/types/messages/tools.d.ts +17 -0
  74. package/dist/types/test/mockTools.d.ts +28 -0
  75. package/dist/types/tools/ProgrammaticToolCalling.d.ts +91 -0
  76. package/dist/types/tools/ToolNode.d.ts +10 -2
  77. package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
  78. package/dist/types/types/graph.d.ts +14 -1
  79. package/dist/types/types/tools.d.ts +138 -0
  80. package/package.json +7 -8
  81. package/src/agents/AgentContext.ts +278 -27
  82. package/src/agents/__tests__/AgentContext.test.ts +805 -0
  83. package/src/common/enum.ts +2 -0
  84. package/src/events.ts +5 -12
  85. package/src/graphs/Graph.ts +57 -19
  86. package/src/index.ts +2 -0
  87. package/src/instrumentation.ts +1 -4
  88. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +473 -0
  89. package/src/llm/bedrock/index.ts +149 -12
  90. package/src/messages/__tests__/tools.test.ts +473 -0
  91. package/src/messages/cache.ts +163 -61
  92. package/src/messages/index.ts +1 -0
  93. package/src/messages/tools.ts +99 -0
  94. package/src/run.ts +0 -9
  95. package/src/scripts/code_exec_ptc.ts +334 -0
  96. package/src/scripts/image.ts +178 -0
  97. package/src/scripts/programmatic_exec.ts +396 -0
  98. package/src/scripts/programmatic_exec_agent.ts +231 -0
  99. package/src/scripts/test-tools-before-handoff.ts +5 -1
  100. package/src/scripts/tool_search_regex.ts +162 -0
  101. package/src/scripts/tools.ts +4 -1
  102. package/src/specs/thinking-prune.test.ts +52 -118
  103. package/src/test/mockTools.ts +366 -0
  104. package/src/tools/CodeExecutor.ts +4 -0
  105. package/src/tools/ProgrammaticToolCalling.ts +558 -0
  106. package/src/tools/ToolNode.ts +59 -18
  107. package/src/tools/ToolSearchRegex.ts +535 -0
  108. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
  109. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +853 -0
  110. package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
  111. package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
  112. package/src/tools/search/jina-reranker.test.ts +16 -16
  113. package/src/tools/search/schema.ts +7 -9
  114. package/src/types/graph.ts +14 -1
  115. package/src/types/tools.ts +166 -0
  116. package/src/utils/run.ts +5 -1
  117. package/src/tools/search/direct-url.test.ts +0 -530
@@ -38,10 +38,23 @@ export declare class AgentContext {
38
38
  tools?: t.GraphTools;
39
39
  /** Tool map for this agent */
40
40
  toolMap?: t.ToolMap;
41
+ /**
42
+ * Tool definitions registry (includes deferred and programmatic tool metadata).
43
+ * Used for tool search and programmatic tool calling.
44
+ */
45
+ toolRegistry?: t.LCToolRegistry;
46
+ /** Set of tool names discovered via tool search (to be loaded) */
47
+ discoveredToolNames: Set<string>;
41
48
  /** Instructions for this agent */
42
49
  instructions?: string;
43
50
  /** Additional instructions for this agent */
44
51
  additionalInstructions?: string;
52
+ /**
53
+ * Dynamic context that changes per-request (e.g., current time, user info).
54
+ * This is NOT included in the system message to preserve cache.
55
+ * Instead, it's injected as a user message at the start of the conversation.
56
+ */
57
+ dynamicContext?: string;
45
58
  /** Reasoning key for this agent */
46
59
  reasoningKey: 'reasoning_content' | 'reasoning';
47
60
  /** Last token for reasoning detection */
@@ -52,13 +65,17 @@ export declare class AgentContext {
52
65
  currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text';
53
66
  /** Whether tools should end the workflow */
54
67
  toolEnd: boolean;
55
- /** System runnable for this agent */
56
- systemRunnable?: Runnable<BaseMessage[], (BaseMessage | SystemMessage)[], RunnableConfig<Record<string, unknown>>>;
68
+ /** Cached system runnable (created lazily) */
69
+ private cachedSystemRunnable?;
70
+ /** Whether system runnable needs rebuild (set when discovered tools change) */
71
+ private systemRunnableStale;
72
+ /** Cached system message token count (separate from tool tokens) */
73
+ private systemMessageTokens;
57
74
  /** Promise for token calculation initialization */
58
75
  tokenCalculationPromise?: Promise<void>;
59
76
  /** Format content blocks as strings (for legacy compatibility) */
60
77
  useLegacyContent: boolean;
61
- constructor({ agentId, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, instructions, additionalInstructions, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }: {
78
+ constructor({ agentId, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, }: {
62
79
  agentId: string;
63
80
  provider: Providers;
64
81
  clientOptions?: t.ClientOptions;
@@ -67,17 +84,45 @@ export declare class AgentContext {
67
84
  tokenCounter?: t.TokenCounter;
68
85
  tools?: t.GraphTools;
69
86
  toolMap?: t.ToolMap;
87
+ toolRegistry?: t.LCToolRegistry;
70
88
  instructions?: string;
71
89
  additionalInstructions?: string;
90
+ dynamicContext?: string;
72
91
  reasoningKey?: 'reasoning_content' | 'reasoning';
73
92
  toolEnd?: boolean;
74
93
  instructionTokens?: number;
75
94
  useLegacyContent?: boolean;
76
95
  });
77
96
  /**
78
- * Create system runnable from instructions and calculate tokens if tokenCounter is available
97
+ * Builds instructions text for tools that are ONLY callable via programmatic code execution.
98
+ * These tools cannot be called directly by the LLM but are available through the
99
+ * run_tools_with_code tool.
100
+ *
101
+ * Includes:
102
+ * - Code_execution-only tools that are NOT deferred
103
+ * - Code_execution-only tools that ARE deferred but have been discovered via tool search
104
+ */
105
+ private buildProgrammaticOnlyToolsInstructions;
106
+ /**
107
+ * Gets the system runnable, creating it lazily if needed.
108
+ * Includes instructions, additional instructions, and programmatic-only tools documentation.
109
+ * Only rebuilds when marked stale (via markToolsAsDiscovered).
110
+ */
111
+ get systemRunnable(): Runnable<BaseMessage[], (BaseMessage | SystemMessage)[], RunnableConfig<Record<string, unknown>>> | undefined;
112
+ /**
113
+ * Explicitly initializes the system runnable.
114
+ * Call this before async token calculation to ensure system message tokens are counted first.
115
+ */
116
+ initializeSystemRunnable(): void;
117
+ /**
118
+ * Builds the raw instructions string (without creating SystemMessage).
119
+ */
120
+ private buildInstructionsString;
121
+ /**
122
+ * Build system runnable from pre-built instructions string.
123
+ * Only called when content has actually changed.
79
124
  */
80
- private createSystemRunnable;
125
+ private buildSystemRunnable;
81
126
  /**
82
127
  * Reset context for a new run
83
128
  */
@@ -91,4 +136,26 @@ export declare class AgentContext {
91
136
  * Note: System message tokens are calculated during systemRunnable creation
92
137
  */
93
138
  calculateInstructionTokens(tokenCounter: t.TokenCounter): Promise<void>;
139
+ /**
140
+ * Gets the tool registry for deferred tools (for tool search).
141
+ * @param onlyDeferred If true, only returns tools with defer_loading=true
142
+ * @returns LCToolRegistry with tool definitions
143
+ */
144
+ getDeferredToolRegistry(onlyDeferred?: boolean): t.LCToolRegistry;
145
+ /**
146
+ * Marks tools as discovered via tool search.
147
+ * Discovered tools will be included in the next model binding.
148
+ * Only marks system runnable stale if NEW tools were actually added.
149
+ * @param toolNames - Array of discovered tool names
150
+ * @returns true if any new tools were discovered
151
+ */
152
+ markToolsAsDiscovered(toolNames: string[]): boolean;
153
+ /**
154
+ * Gets tools that should be bound to the LLM.
155
+ * Includes:
156
+ * 1. Non-deferred tools with allowed_callers: ['direct']
157
+ * 2. Discovered tools (from tool search)
158
+ * @returns Array of tools to bind to model
159
+ */
160
+ getToolsForBinding(): t.GraphTools | undefined;
94
161
  }
@@ -114,6 +114,8 @@ export declare enum Callback {
114
114
  export declare enum Constants {
115
115
  OFFICIAL_CODE_BASEURL = "https://api.illuma.ai/v1",
116
116
  EXECUTE_CODE = "execute_code",
117
+ TOOL_SEARCH_REGEX = "tool_search_regex",
118
+ PROGRAMMATIC_TOOL_CALLING = "run_tools_with_code",
117
119
  WEB_SEARCH = "web_search",
118
120
  CONTENT_AND_ARTIFACT = "content_and_artifact",
119
121
  LC_TRANSFER_TO_ = "lc_transfer_to_"
@@ -91,9 +91,10 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
91
91
  instructions?: string;
92
92
  additional_instructions?: string;
93
93
  }): t.SystemRunnable | undefined;
94
- initializeTools({ currentTools, currentToolMap, }: {
94
+ initializeTools({ currentTools, currentToolMap, agentContext, }: {
95
95
  currentTools?: t.GraphTools;
96
96
  currentToolMap?: t.ToolMap;
97
+ agentContext?: AgentContext;
97
98
  }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState>;
98
99
  initializeModel({ provider, tools, clientOptions, }: {
99
100
  provider: Providers;
@@ -109,7 +110,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
109
110
  /** Execute model invocation with streaming support */
110
111
  private attemptInvoke;
111
112
  cleanupSignalListener(currentModel?: t.ChatModel): void;
112
- createCallModel(agentId?: string, currentModel?: t.ChatModel): (state: t.BaseGraphState, config?: RunnableConfig) => Promise<Partial<t.BaseGraphState>>;
113
+ createCallModel(agentId?: string): (state: t.BaseGraphState, config?: RunnableConfig) => Promise<Partial<t.BaseGraphState>>;
113
114
  createAgentNode(agentId: string): t.CompiledAgentWorfklow;
114
115
  createWorkflow(): t.CompiledStateWorkflow;
115
116
  /**
@@ -6,6 +6,8 @@ export * from './messages';
6
6
  export * from './graphs';
7
7
  export * from './tools/Calculator';
8
8
  export * from './tools/CodeExecutor';
9
+ export * from './tools/ProgrammaticToolCalling';
10
+ export * from './tools/ToolSearchRegex';
9
11
  export * from './tools/handlers';
10
12
  export * from './tools/search';
11
13
  export * from './common';
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts
3
+ * and adds prompt caching support for Bedrock Converse API.
3
4
  *
4
5
  * Bedrock sends the same contentBlockIndex for both text and tool_use content blocks,
5
6
  * causing LangChain's merge logic to fail with "field[contentBlockIndex] already exists"
@@ -9,19 +10,45 @@
9
10
  * The contentBlockIndex field is only used internally by Bedrock's streaming protocol
10
11
  * and isn't needed by application logic - the index field on tool_call_chunks serves
11
12
  * the purpose of tracking tool call ordering.
13
+ *
14
+ * PROMPT CACHING:
15
+ * When promptCache: true is set, this wrapper adds cachePoint markers to the tools array
16
+ * to enable Bedrock prompt caching for tool definitions. This allows tool schemas to be
17
+ * cached and reused across requests, reducing latency and costs.
18
+ *
19
+ * CACHE TOKEN EXTRACTION:
20
+ * LangChain AWS doesn't extract cacheReadInputTokens/cacheWriteInputTokens from Bedrock's
21
+ * response. This wrapper adds input_token_details to usage_metadata with cache information.
12
22
  */
13
23
  import { ChatBedrockConverse } from '@langchain/aws';
14
24
  import type { ChatBedrockConverseInput } from '@langchain/aws';
15
25
  import type { BaseMessage } from '@langchain/core/messages';
16
26
  import { ChatGenerationChunk } from '@langchain/core/outputs';
17
27
  import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
28
+ /** Extended input type with promptCache option */
29
+ export interface CustomChatBedrockConverseInput extends ChatBedrockConverseInput {
30
+ promptCache?: boolean;
31
+ }
18
32
  export declare class CustomChatBedrockConverse extends ChatBedrockConverse {
19
- constructor(fields?: ChatBedrockConverseInput);
33
+ promptCache: boolean;
34
+ constructor(fields?: CustomChatBedrockConverseInput);
20
35
  static lc_name(): string;
21
36
  /**
22
- * Override _streamResponseChunks to strip contentBlockIndex from response_metadata
23
- * This prevents LangChain's merge conflicts when the same index is used for
24
- * different content types (text vs tool calls)
37
+ * Override invocationParams to add cachePoint to tools when promptCache is enabled.
38
+ * This enables Bedrock prompt caching for tool definitions.
39
+ *
40
+ * STRATEGY: Separate cachePoints for core tools and MCP tools
41
+ * - Core tools (web_search, execute_code, etc.) are stable → cache first
42
+ * - MCP tools (have '_mcp_' in name) are dynamic → cache separately after
43
+ * - This allows core tools to stay cached when MCP selection changes
44
+ *
45
+ * NOTE: Only Claude models support cachePoint - Nova and other models will reject it.
46
+ */
47
+ invocationParams(options?: this['ParsedCallOptions']): ReturnType<ChatBedrockConverse['invocationParams']>;
48
+ /**
49
+ * Override _streamResponseChunks to:
50
+ * 1. Strip contentBlockIndex from response_metadata to prevent merge conflicts
51
+ * 2. Extract cacheReadInputTokens/cacheWriteInputTokens and add to usage_metadata
25
52
  */
26
53
  _streamResponseChunks(messages: BaseMessage[], options: this['ParsedCallOptions'], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
27
54
  /**
@@ -23,14 +23,29 @@ export declare function stripAnthropicCacheControl<T extends MessageWithContent>
23
23
  */
24
24
  export declare function stripBedrockCacheControl<T extends MessageWithContent>(messages: T[]): T[];
25
25
  /**
26
- * Adds Bedrock Converse API cache points to the last two messages.
27
- * Inserts `{ cachePoint: { type: 'default' } }` as a separate content block
28
- * immediately after the last text block in each targeted message.
29
- * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,
30
- * then adds fresh cache points to the last 2 messages in a single backward pass.
31
- * This ensures we don't accumulate stale cache points across multiple turns.
32
- * @param messages - The array of message objects.
33
- * @returns - The updated array of message objects with cache points added.
26
+ * Adds Bedrock Converse API cache points using "Stable Prefix Caching" strategy.
27
+ *
28
+ * STRATEGY: Place cache point after the LAST ASSISTANT message only.
29
+ * This ensures the prefix (everything before the cache point) remains STABLE
30
+ * as the conversation grows, maximizing cache hits.
31
+ *
32
+ * Why this works:
33
+ * - System message has its own cachePoint (added in AgentContext)
34
+ * - Tools have their own cachePoint (added in CustomChatBedrockConverse)
35
+ * - Conversation history grows, but the PREFIX stays the same
36
+ * - Only the NEW user message is uncached (it's always different)
37
+ *
38
+ * Example conversation flow:
39
+ * Request 1: [System+cachePoint][Tools+cachePoint][User1] → No conversation cache yet
40
+ * Request 2: [System][Tools][User1][Assistant1+cachePoint][User2] → Cache User1+Assistant1
41
+ * Request 3: [System][Tools][User1][Assistant1][User2][Assistant2+cachePoint][User3]
42
+ * → Cache reads User1+A1+User2+A2, cache writes new portion
43
+ *
44
+ * Claude's "Simplified Cache Management" automatically looks back up to 20 content
45
+ * blocks from the cache checkpoint to find the longest matching prefix.
46
+ *
47
+ * @param messages - The array of message objects (excluding system message).
48
+ * @returns - The updated array with a single cache point after the last assistant message.
34
49
  */
35
50
  export declare function addBedrockCacheControl<T extends Partial<BaseMessage> & MessageWithContent>(messages: T[]): T[];
36
51
  export {};
@@ -4,3 +4,4 @@ export * from './prune';
4
4
  export * from './format';
5
5
  export * from './cache';
6
6
  export * from './content';
7
+ export * from './tools';
@@ -0,0 +1,17 @@
1
+ import type { BaseMessage } from '@langchain/core/messages';
2
+ /**
3
+ * Extracts discovered tool names from tool search results in the current turn.
4
+ * Only processes tool search messages after the latest AI message with tool calls.
5
+ *
6
+ * Similar pattern to formatArtifactPayload - finds relevant messages efficiently
7
+ * by identifying the latest AI parent and only processing subsequent tool messages.
8
+ *
9
+ * @param messages - All messages in the conversation
10
+ * @returns Array of discovered tool names (empty if no new discoveries)
11
+ */
12
+ export declare function extractToolDiscoveries(messages: BaseMessage[]): string[];
13
+ /**
14
+ * Checks if the current turn has any tool search results.
15
+ * Quick check to avoid full extraction when not needed.
16
+ */
17
+ export declare function hasToolSearchInCurrentTurn(messages: BaseMessage[]): boolean;
@@ -0,0 +1,28 @@
1
+ import type { StructuredToolInterface } from '@langchain/core/tools';
2
+ import type { LCToolRegistry } from '@/types';
3
+ /**
4
+ * Mock get_team_members tool - returns list of team members
5
+ */
6
+ export declare function createGetTeamMembersTool(): StructuredToolInterface;
7
+ /**
8
+ * Mock get_expenses tool - returns expense records for a user
9
+ */
10
+ export declare function createGetExpensesTool(): StructuredToolInterface;
11
+ /**
12
+ * Mock get_weather tool - returns weather data for a city
13
+ */
14
+ export declare function createGetWeatherTool(): StructuredToolInterface;
15
+ /**
16
+ * Mock calculator tool - evaluates mathematical expressions
17
+ */
18
+ export declare function createCalculatorTool(): StructuredToolInterface;
19
+ /**
20
+ * Creates a tool registry for programmatic tool calling tests.
21
+ * Tools are configured with allowed_callers to demonstrate classification.
22
+ */
23
+ export declare function createProgrammaticToolRegistry(): LCToolRegistry;
24
+ /**
25
+ * Creates a sample tool registry for tool search tests.
26
+ * Includes mix of deferred and non-deferred tools.
27
+ */
28
+ export declare function createToolSearchToolRegistry(): LCToolRegistry;
@@ -0,0 +1,91 @@
1
+ import { z } from 'zod';
2
+ import { DynamicStructuredTool } from '@langchain/core/tools';
3
+ import type * as t from '@/types';
4
+ declare const ProgrammaticToolCallingSchema: z.ZodObject<{
5
+ code: z.ZodString;
6
+ session_id: z.ZodOptional<z.ZodString>;
7
+ timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
8
+ }, "strip", z.ZodTypeAny, {
9
+ code: string;
10
+ timeout: number;
11
+ session_id?: string | undefined;
12
+ }, {
13
+ code: string;
14
+ timeout?: number | undefined;
15
+ session_id?: string | undefined;
16
+ }>;
17
+ /**
18
+ * Normalizes a tool name to Python identifier format.
19
+ * Must match the Code API's `normalizePythonFunctionName` exactly:
20
+ * 1. Replace hyphens and spaces with underscores
21
+ * 2. Remove any other invalid characters
22
+ * 3. Prefix with underscore if starts with number
23
+ * 4. Append `_tool` if it's a Python keyword
24
+ * @param name - The tool name to normalize
25
+ * @returns Normalized Python-safe identifier
26
+ */
27
+ export declare function normalizeToPythonIdentifier(name: string): string;
28
+ /**
29
+ * Extracts tool names that are actually called in the Python code.
30
+ * Handles hyphen/underscore conversion since Python identifiers use underscores.
31
+ * @param code - The Python code to analyze
32
+ * @param toolNameMap - Map from normalized Python name to original tool name
33
+ * @returns Set of original tool names found in the code
34
+ */
35
+ export declare function extractUsedToolNames(code: string, toolNameMap: Map<string, string>): Set<string>;
36
+ /**
37
+ * Filters tool definitions to only include tools actually used in the code.
38
+ * Handles the hyphen-to-underscore conversion for Python compatibility.
39
+ * @param toolDefs - All available tool definitions
40
+ * @param code - The Python code to analyze
41
+ * @param debug - Enable debug logging
42
+ * @returns Filtered array of tool definitions
43
+ */
44
+ export declare function filterToolsByUsage(toolDefs: t.LCTool[], code: string, debug?: boolean): t.LCTool[];
45
+ /**
46
+ * Makes an HTTP request to the Code API.
47
+ * @param endpoint - The API endpoint URL
48
+ * @param apiKey - The API key for authentication
49
+ * @param body - The request body
50
+ * @param proxy - Optional HTTP proxy URL
51
+ * @returns The parsed API response
52
+ */
53
+ export declare function makeRequest(endpoint: string, apiKey: string, body: Record<string, unknown>, proxy?: string): Promise<t.ProgrammaticExecutionResponse>;
54
+ /**
55
+ * Executes tools in parallel when requested by the API.
56
+ * Uses Promise.all for parallel execution, catching individual errors.
57
+ * @param toolCalls - Array of tool calls from the API
58
+ * @param toolMap - Map of tool names to executable tools
59
+ * @returns Array of tool results
60
+ */
61
+ export declare function executeTools(toolCalls: t.PTCToolCall[], toolMap: t.ToolMap): Promise<t.PTCToolResult[]>;
62
+ /**
63
+ * Formats the completed response for the agent.
64
+ * @param response - The completed API response
65
+ * @returns Tuple of [formatted string, artifact]
66
+ */
67
+ export declare function formatCompletedResponse(response: t.ProgrammaticExecutionResponse): [string, t.ProgrammaticExecutionArtifact];
68
+ /**
69
+ * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.
70
+ *
71
+ * This tool enables AI agents to write Python code that orchestrates multiple
72
+ * tool calls programmatically, reducing LLM round-trips and token usage.
73
+ *
74
+ * The tool map must be provided at runtime via config.configurable.toolMap.
75
+ *
76
+ * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)
77
+ * @returns A LangChain DynamicStructuredTool for programmatic tool calling
78
+ *
79
+ * @example
80
+ * const ptcTool = createProgrammaticToolCallingTool({
81
+ * apiKey: process.env.CODE_API_KEY,
82
+ * maxRoundTrips: 20
83
+ * });
84
+ *
85
+ * const [output, artifact] = await ptcTool.invoke(
86
+ * { code, tools },
87
+ * { configurable: { toolMap } }
88
+ * );
89
+ */
90
+ export declare function createProgrammaticToolCallingTool(initParams?: t.ProgrammaticToolCallingParams): DynamicStructuredTool<typeof ProgrammaticToolCallingSchema>;
91
+ export {};
@@ -5,7 +5,6 @@ import type { BaseMessage } from '@langchain/core/messages';
5
5
  import type * as t from '@/types';
6
6
  import { RunnableCallable } from '@/utils';
7
7
  export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
8
- tools: t.GenericTool[];
9
8
  private toolMap;
10
9
  private loadRuntimeTools?;
11
10
  handleToolErrors: boolean;
@@ -13,7 +12,16 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
13
12
  toolCallStepIds?: Map<string, string>;
14
13
  errorHandler?: t.ToolNodeConstructorParams['errorHandler'];
15
14
  private toolUsageCount;
16
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, }: t.ToolNodeConstructorParams);
15
+ /** Tool registry for filtering (lazy computation of programmatic maps) */
16
+ private toolRegistry?;
17
+ /** Cached programmatic tools (computed once on first PTC call) */
18
+ private programmaticCache?;
19
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, }: t.ToolNodeConstructorParams);
20
+ /**
21
+ * Returns cached programmatic tools, computing once on first access.
22
+ * Single iteration builds both toolMap and toolDefs simultaneously.
23
+ */
24
+ private getProgrammaticTools;
17
25
  /**
18
26
  * Returns a snapshot of the current tool usage counts.
19
27
  * @returns A ReadonlyMap where keys are tool names and values are their usage counts.
@@ -0,0 +1,80 @@
1
+ import { z } from 'zod';
2
+ import { DynamicStructuredTool } from '@langchain/core/tools';
3
+ import type * as t from '@/types';
4
+ declare const ToolSearchRegexSchema: z.ZodObject<{
5
+ query: z.ZodString;
6
+ fields: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodEnum<["name", "description", "parameters"]>, "many">>>;
7
+ max_results: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
8
+ }, "strip", z.ZodTypeAny, {
9
+ query: string;
10
+ fields: ("name" | "description" | "parameters")[];
11
+ max_results: number;
12
+ }, {
13
+ query: string;
14
+ fields?: ("name" | "description" | "parameters")[] | undefined;
15
+ max_results?: number | undefined;
16
+ }>;
17
+ /**
18
+ * Escapes special regex characters in a string to use as a literal pattern.
19
+ * @param pattern - The string to escape
20
+ * @returns The escaped string safe for use in a RegExp
21
+ */
22
+ declare function escapeRegexSpecialChars(pattern: string): string;
23
+ /**
24
+ * Counts the maximum nesting depth of groups in a regex pattern.
25
+ * @param pattern - The regex pattern to analyze
26
+ * @returns The maximum nesting depth
27
+ */
28
+ declare function countNestedGroups(pattern: string): number;
29
+ /**
30
+ * Detects nested quantifiers that can cause catastrophic backtracking.
31
+ * Patterns like (a+)+, (a*)*, (a+)*, etc.
32
+ * @param pattern - The regex pattern to check
33
+ * @returns True if nested quantifiers are detected
34
+ */
35
+ declare function hasNestedQuantifiers(pattern: string): boolean;
36
+ /**
37
+ * Checks if a regex pattern contains potentially dangerous constructs.
38
+ * @param pattern - The regex pattern to validate
39
+ * @returns True if the pattern is dangerous
40
+ */
41
+ declare function isDangerousPattern(pattern: string): boolean;
42
+ /**
43
+ * Sanitizes a regex pattern for safe execution.
44
+ * If the pattern is dangerous, it will be escaped to a literal string search.
45
+ * @param pattern - The regex pattern to sanitize
46
+ * @returns Object containing the safe pattern and whether it was escaped
47
+ */
48
+ declare function sanitizeRegex(pattern: string): {
49
+ safe: string;
50
+ wasEscaped: boolean;
51
+ };
52
+ /**
53
+ * Creates a Tool Search Regex tool for discovering tools from a large registry.
54
+ *
55
+ * This tool enables AI agents to dynamically discover tools from a large library
56
+ * without loading all tool definitions into the LLM context window. The agent
57
+ * can search for relevant tools on-demand using regex patterns.
58
+ *
59
+ * The tool registry can be provided either:
60
+ * 1. At initialization time via params.toolRegistry
61
+ * 2. At runtime via config.configurable.toolRegistry when invoking
62
+ *
63
+ * @param params - Configuration parameters for the tool (toolRegistry is optional)
64
+ * @returns A LangChain DynamicStructuredTool for tool searching
65
+ *
66
+ * @example
67
+ * // Option 1: Registry at initialization
68
+ * const tool = createToolSearchRegexTool({ apiKey, toolRegistry });
69
+ * await tool.invoke({ query: 'expense' });
70
+ *
71
+ * @example
72
+ * // Option 2: Registry at runtime
73
+ * const tool = createToolSearchRegexTool({ apiKey });
74
+ * await tool.invoke(
75
+ * { query: 'expense' },
76
+ * { configurable: { toolRegistry, onlyDeferred: true } }
77
+ * );
78
+ */
79
+ declare function createToolSearchRegexTool(initParams?: t.ToolSearchRegexParams): DynamicStructuredTool<typeof ToolSearchRegexSchema>;
80
+ export { createToolSearchRegexTool, sanitizeRegex, escapeRegexSpecialChars, isDangerousPattern, countNestedGroups, hasNestedQuantifiers, };
@@ -4,7 +4,7 @@ import type { BaseMessage, AIMessageChunk, SystemMessage } from '@langchain/core
4
4
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
5
5
  import type { ChatGenerationChunk } from '@langchain/core/outputs';
6
6
  import type { GoogleAIToolType } from '@langchain/google-common';
7
- import type { ToolMap, ToolEndEvent, GenericTool } from '@/types/tools';
7
+ import type { ToolMap, ToolEndEvent, GenericTool, LCTool } from '@/types/tools';
8
8
  import type { Providers, Callback, GraphNodeKeys } from '@/common';
9
9
  import type { StandardGraph, MultiAgentGraph } from '@/graphs';
10
10
  import type { ClientOptions } from '@/types/llm';
@@ -248,4 +248,17 @@ export interface AgentInputs {
248
248
  reasoningKey?: 'reasoning_content' | 'reasoning';
249
249
  /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */
250
250
  useLegacyContent?: boolean;
251
+ /**
252
+ * Tool definitions for all tools, including deferred and programmatic.
253
+ * Used for tool search and programmatic tool calling.
254
+ * Maps tool name to LCTool definition.
255
+ */
256
+ toolRegistry?: Map<string, LCTool>;
257
+ /**
258
+ * Dynamic context that changes per-request (e.g., current time, user info).
259
+ * This is injected as a user message rather than system prompt to preserve cache.
260
+ * Keeping this separate from instructions ensures the system message stays static
261
+ * and can be cached by Bedrock/Anthropic prompt caching.
262
+ */
263
+ dynamicContext?: string;
251
264
  }