@illuma-ai/agents 1.5.1 → 2.1.1

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 (319) hide show
  1. package/README.md +0 -62
  2. package/dist/cjs/agents/AgentContext.cjs +160 -259
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/enum.cjs +12 -12
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/graphs/Graph.cjs +30 -13
  7. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  10. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs +1 -1
  11. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs.map +1 -1
  12. package/dist/cjs/hooks/HookRegistry.cjs +1 -1
  13. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  14. package/dist/cjs/hooks/matchers.cjs +2 -2
  15. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  16. package/dist/cjs/hooks/types.cjs +1 -1
  17. package/dist/cjs/hooks/types.cjs.map +1 -1
  18. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -5
  19. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  20. package/dist/cjs/llm/bedrock/index.cjs +33 -61
  21. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  22. package/dist/cjs/llm/openai/index.cjs +1 -1
  23. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  24. package/dist/cjs/llm/openai/utils/index.cjs +10 -27
  25. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  26. package/dist/cjs/main.cjs +3 -84
  27. package/dist/cjs/main.cjs.map +1 -1
  28. package/dist/cjs/memory/citations.cjs +4 -4
  29. package/dist/cjs/memory/citations.cjs.map +1 -1
  30. package/dist/cjs/memory/constants.cjs +17 -17
  31. package/dist/cjs/memory/constants.cjs.map +1 -1
  32. package/dist/cjs/memory/mmr.cjs +1 -1
  33. package/dist/cjs/memory/mmr.cjs.map +1 -1
  34. package/dist/cjs/memory/paths.cjs +1 -1
  35. package/dist/cjs/memory/paths.cjs.map +1 -1
  36. package/dist/cjs/memory/recallTracking.cjs +3 -3
  37. package/dist/cjs/memory/recallTracking.cjs.map +1 -1
  38. package/dist/cjs/memory/temporalDecay.cjs +2 -2
  39. package/dist/cjs/memory/temporalDecay.cjs.map +1 -1
  40. package/dist/cjs/messages/cache.cjs +0 -89
  41. package/dist/cjs/messages/cache.cjs.map +1 -1
  42. package/dist/cjs/messages/format.cjs +13 -71
  43. package/dist/cjs/messages/format.cjs.map +1 -1
  44. package/dist/cjs/tools/BashExecutor.cjs +11 -21
  45. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  46. package/dist/cjs/tools/CodeExecutor.cjs +13 -41
  47. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  48. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +11 -16
  49. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  50. package/dist/cjs/tools/ToolNode.cjs +78 -13
  51. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  52. package/dist/cjs/tools/memory/memoryAppendTool.cjs +1 -1
  53. package/dist/cjs/tools/memory/memoryAppendTool.cjs.map +1 -1
  54. package/dist/cjs/tools/memory/memoryGetTool.cjs +2 -2
  55. package/dist/cjs/tools/memory/memoryGetTool.cjs.map +1 -1
  56. package/dist/cjs/tools/memory/memorySearchTool.cjs +3 -3
  57. package/dist/cjs/tools/memory/memorySearchTool.cjs.map +1 -1
  58. package/dist/cjs/tools/memory/shared.cjs +1 -1
  59. package/dist/cjs/tools/memory/shared.cjs.map +1 -1
  60. package/dist/cjs/tools/search/search.cjs +3 -11
  61. package/dist/cjs/tools/search/search.cjs.map +1 -1
  62. package/dist/cjs/tools/search/tool.cjs +4 -28
  63. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  64. package/dist/cjs/tools/search/utils.cjs +3 -10
  65. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  66. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +48 -0
  67. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  68. package/dist/cjs/types/graph.cjs.map +1 -1
  69. package/dist/esm/agents/AgentContext.mjs +160 -259
  70. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  71. package/dist/esm/common/enum.mjs +12 -12
  72. package/dist/esm/common/enum.mjs.map +1 -1
  73. package/dist/esm/graphs/Graph.mjs +30 -13
  74. package/dist/esm/graphs/Graph.mjs.map +1 -1
  75. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  76. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  77. package/dist/esm/graphs/phases/memoryFlushPhase.mjs +1 -1
  78. package/dist/esm/graphs/phases/memoryFlushPhase.mjs.map +1 -1
  79. package/dist/esm/hooks/HookRegistry.mjs +1 -1
  80. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  81. package/dist/esm/hooks/matchers.mjs +2 -2
  82. package/dist/esm/hooks/matchers.mjs.map +1 -1
  83. package/dist/esm/hooks/types.mjs +1 -1
  84. package/dist/esm/hooks/types.mjs.map +1 -1
  85. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -5
  86. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  87. package/dist/esm/llm/bedrock/index.mjs +34 -61
  88. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  89. package/dist/esm/llm/openai/index.mjs +1 -1
  90. package/dist/esm/llm/openai/index.mjs.map +1 -1
  91. package/dist/esm/llm/openai/utils/index.mjs +10 -27
  92. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  93. package/dist/esm/main.mjs +1 -5
  94. package/dist/esm/main.mjs.map +1 -1
  95. package/dist/esm/memory/citations.mjs +4 -4
  96. package/dist/esm/memory/citations.mjs.map +1 -1
  97. package/dist/esm/memory/constants.mjs +17 -17
  98. package/dist/esm/memory/constants.mjs.map +1 -1
  99. package/dist/esm/memory/mmr.mjs +1 -1
  100. package/dist/esm/memory/mmr.mjs.map +1 -1
  101. package/dist/esm/memory/paths.mjs +1 -1
  102. package/dist/esm/memory/paths.mjs.map +1 -1
  103. package/dist/esm/memory/recallTracking.mjs +3 -3
  104. package/dist/esm/memory/recallTracking.mjs.map +1 -1
  105. package/dist/esm/memory/temporalDecay.mjs +2 -2
  106. package/dist/esm/memory/temporalDecay.mjs.map +1 -1
  107. package/dist/esm/messages/cache.mjs +0 -89
  108. package/dist/esm/messages/cache.mjs.map +1 -1
  109. package/dist/esm/messages/format.mjs +13 -71
  110. package/dist/esm/messages/format.mjs.map +1 -1
  111. package/dist/esm/tools/BashExecutor.mjs +12 -22
  112. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  113. package/dist/esm/tools/CodeExecutor.mjs +14 -41
  114. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  115. package/dist/esm/tools/ProgrammaticToolCalling.mjs +12 -17
  116. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  117. package/dist/esm/tools/ToolNode.mjs +78 -13
  118. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  119. package/dist/esm/tools/memory/memoryAppendTool.mjs +1 -1
  120. package/dist/esm/tools/memory/memoryAppendTool.mjs.map +1 -1
  121. package/dist/esm/tools/memory/memoryGetTool.mjs +2 -2
  122. package/dist/esm/tools/memory/memoryGetTool.mjs.map +1 -1
  123. package/dist/esm/tools/memory/memorySearchTool.mjs +3 -3
  124. package/dist/esm/tools/memory/memorySearchTool.mjs.map +1 -1
  125. package/dist/esm/tools/memory/shared.mjs +1 -1
  126. package/dist/esm/tools/memory/shared.mjs.map +1 -1
  127. package/dist/esm/tools/search/search.mjs +3 -11
  128. package/dist/esm/tools/search/search.mjs.map +1 -1
  129. package/dist/esm/tools/search/tool.mjs +4 -28
  130. package/dist/esm/tools/search/tool.mjs.map +1 -1
  131. package/dist/esm/tools/search/utils.mjs +3 -10
  132. package/dist/esm/tools/search/utils.mjs.map +1 -1
  133. package/dist/esm/tools/subagent/SubagentExecutor.mjs +48 -0
  134. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  135. package/dist/esm/types/graph.mjs.map +1 -1
  136. package/dist/types/agents/AgentContext.d.ts +25 -95
  137. package/dist/types/common/enum.d.ts +12 -12
  138. package/dist/types/graphs/Graph.d.ts +2 -2
  139. package/dist/types/graphs/phases/memoryFlushPhase.d.ts +2 -2
  140. package/dist/types/hooks/HookRegistry.d.ts +1 -1
  141. package/dist/types/hooks/matchers.d.ts +2 -2
  142. package/dist/types/hooks/types.d.ts +1 -1
  143. package/dist/types/index.d.ts +0 -1
  144. package/dist/types/llm/bedrock/index.d.ts +1 -54
  145. package/dist/types/llm/openai/index.d.ts +1 -1
  146. package/dist/types/memory/citations.d.ts +4 -4
  147. package/dist/types/memory/constants.d.ts +17 -17
  148. package/dist/types/memory/mmr.d.ts +3 -3
  149. package/dist/types/memory/paths.d.ts +1 -1
  150. package/dist/types/memory/temporalDecay.d.ts +2 -2
  151. package/dist/types/memory/types.d.ts +3 -3
  152. package/dist/types/messages/format.d.ts +2 -5
  153. package/dist/types/tools/CodeExecutor.d.ts +0 -6
  154. package/dist/types/tools/ToolNode.d.ts +3 -3
  155. package/dist/types/tools/memory/shared.d.ts +1 -1
  156. package/dist/types/tools/search/test.d.ts +1 -0
  157. package/dist/types/tools/search/types.d.ts +5 -99
  158. package/dist/types/tools/search/utils.d.ts +2 -2
  159. package/dist/types/tools/subagent/SubagentExecutor.d.ts +29 -0
  160. package/dist/types/types/graph.d.ts +30 -34
  161. package/dist/types/types/index.d.ts +0 -1
  162. package/dist/types/types/messages.d.ts +1 -1
  163. package/dist/types/types/run.d.ts +1 -3
  164. package/dist/types/types/tools.d.ts +5 -14
  165. package/package.json +1 -61
  166. package/src/agents/AgentContext.test.ts +176 -0
  167. package/src/agents/AgentContext.ts +179 -305
  168. package/src/agents/__tests__/AgentContext.test.ts +0 -632
  169. package/src/common/__tests__/enum.test.ts +1 -1
  170. package/src/common/enum.ts +12 -12
  171. package/src/graphs/Graph.ts +32 -13
  172. package/src/graphs/MultiAgentGraph.ts +1 -1
  173. package/src/graphs/gapFeatures.test.ts +1 -1
  174. package/src/graphs/phases/__tests__/memoryFlushPhase.test.ts +1 -1
  175. package/src/graphs/phases/memoryFlushPhase.ts +2 -2
  176. package/src/hooks/HookRegistry.ts +1 -1
  177. package/src/hooks/index.ts +1 -1
  178. package/src/hooks/matchers.ts +2 -2
  179. package/src/hooks/types.ts +1 -1
  180. package/src/index.ts +0 -6
  181. package/src/llm/anthropic/utils/message_inputs.ts +1 -10
  182. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +18 -166
  183. package/src/llm/bedrock/index.ts +41 -116
  184. package/src/llm/openai/index.ts +2 -2
  185. package/src/llm/openai/utils/index.ts +14 -31
  186. package/src/memory/citations.ts +4 -4
  187. package/src/memory/constants.ts +17 -17
  188. package/src/memory/mmr.ts +3 -3
  189. package/src/memory/paths.ts +1 -1
  190. package/src/memory/recallTracking.ts +3 -3
  191. package/src/memory/temporalDecay.ts +2 -2
  192. package/src/memory/types.ts +3 -3
  193. package/src/messages/cache.test.ts +24 -62
  194. package/src/messages/cache.ts +0 -112
  195. package/src/messages/ensureThinkingBlock.test.ts +1 -1
  196. package/src/messages/format.ts +13 -92
  197. package/src/messages/formatAgentMessages.test.ts +1 -1
  198. package/src/scripts/subagent-configurable-inheritance.ts +263 -0
  199. package/src/scripts/subagent-event-driven-debug.ts +2 -2
  200. package/src/specs/anthropic.simple.test.ts +0 -61
  201. package/src/specs/prune.orphans.test.ts +1 -1
  202. package/src/tools/BashExecutor.ts +13 -37
  203. package/src/tools/CodeExecutor.ts +14 -59
  204. package/src/tools/ProgrammaticToolCalling.ts +14 -29
  205. package/src/tools/ToolNode.ts +75 -14
  206. package/src/tools/__tests__/CodeExecutor.test.ts +3 -3
  207. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -60
  208. package/src/tools/__tests__/SubagentExecutor.test.ts +157 -0
  209. package/src/tools/memory/memoryAppendTool.ts +1 -1
  210. package/src/tools/memory/memoryGetTool.ts +2 -2
  211. package/src/tools/memory/memorySearchTool.ts +3 -3
  212. package/src/tools/memory/shared.ts +1 -1
  213. package/src/tools/search/output.md +2775 -0
  214. package/src/tools/search/search.ts +2 -12
  215. package/src/tools/search/test.html +884 -0
  216. package/src/tools/search/test.md +643 -0
  217. package/src/tools/search/test.ts +159 -0
  218. package/src/tools/search/tool.ts +2 -36
  219. package/src/tools/search/types.ts +8 -133
  220. package/src/tools/search/utils.ts +5 -13
  221. package/src/tools/subagent/SubagentExecutor.ts +78 -0
  222. package/src/types/graph.ts +27 -34
  223. package/src/types/index.ts +0 -1
  224. package/src/types/messages.ts +1 -1
  225. package/src/types/run.ts +1 -3
  226. package/src/types/tools.ts +5 -14
  227. package/dist/cjs/langchain/google-common.cjs +0 -3
  228. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  229. package/dist/cjs/langchain/index.cjs +0 -86
  230. package/dist/cjs/langchain/index.cjs.map +0 -1
  231. package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
  232. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  233. package/dist/cjs/langchain/messages/tool.cjs +0 -3
  234. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  235. package/dist/cjs/langchain/messages.cjs +0 -51
  236. package/dist/cjs/langchain/messages.cjs.map +0 -1
  237. package/dist/cjs/langchain/openai.cjs +0 -3
  238. package/dist/cjs/langchain/openai.cjs.map +0 -1
  239. package/dist/cjs/langchain/prompts.cjs +0 -11
  240. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  241. package/dist/cjs/langchain/runnables.cjs +0 -19
  242. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  243. package/dist/cjs/langchain/tools.cjs +0 -23
  244. package/dist/cjs/langchain/tools.cjs.map +0 -1
  245. package/dist/cjs/langchain/utils/env.cjs +0 -11
  246. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  247. package/dist/cjs/llm/bedrock/cacheSupport.cjs +0 -55
  248. package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +0 -1
  249. package/dist/cjs/tools/search/tavily-scraper.cjs +0 -189
  250. package/dist/cjs/tools/search/tavily-scraper.cjs.map +0 -1
  251. package/dist/cjs/tools/search/tavily-search.cjs +0 -372
  252. package/dist/cjs/tools/search/tavily-search.cjs.map +0 -1
  253. package/dist/cjs/types/agent-cache.cjs +0 -54
  254. package/dist/cjs/types/agent-cache.cjs.map +0 -1
  255. package/dist/esm/langchain/google-common.mjs +0 -2
  256. package/dist/esm/langchain/google-common.mjs.map +0 -1
  257. package/dist/esm/langchain/index.mjs +0 -5
  258. package/dist/esm/langchain/index.mjs.map +0 -1
  259. package/dist/esm/langchain/language_models/chat_models.mjs +0 -2
  260. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  261. package/dist/esm/langchain/messages/tool.mjs +0 -2
  262. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  263. package/dist/esm/langchain/messages.mjs +0 -2
  264. package/dist/esm/langchain/messages.mjs.map +0 -1
  265. package/dist/esm/langchain/openai.mjs +0 -2
  266. package/dist/esm/langchain/openai.mjs.map +0 -1
  267. package/dist/esm/langchain/prompts.mjs +0 -2
  268. package/dist/esm/langchain/prompts.mjs.map +0 -1
  269. package/dist/esm/langchain/runnables.mjs +0 -2
  270. package/dist/esm/langchain/runnables.mjs.map +0 -1
  271. package/dist/esm/langchain/tools.mjs +0 -2
  272. package/dist/esm/langchain/tools.mjs.map +0 -1
  273. package/dist/esm/langchain/utils/env.mjs +0 -2
  274. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  275. package/dist/esm/llm/bedrock/cacheSupport.mjs +0 -52
  276. package/dist/esm/llm/bedrock/cacheSupport.mjs.map +0 -1
  277. package/dist/esm/tools/search/tavily-scraper.mjs +0 -186
  278. package/dist/esm/tools/search/tavily-scraper.mjs.map +0 -1
  279. package/dist/esm/tools/search/tavily-search.mjs +0 -370
  280. package/dist/esm/tools/search/tavily-search.mjs.map +0 -1
  281. package/dist/esm/types/agent-cache.mjs +0 -52
  282. package/dist/esm/types/agent-cache.mjs.map +0 -1
  283. package/dist/types/langchain/google-common.d.ts +0 -1
  284. package/dist/types/langchain/index.d.ts +0 -8
  285. package/dist/types/langchain/language_models/chat_models.d.ts +0 -1
  286. package/dist/types/langchain/messages/tool.d.ts +0 -1
  287. package/dist/types/langchain/messages.d.ts +0 -2
  288. package/dist/types/langchain/openai.d.ts +0 -1
  289. package/dist/types/langchain/prompts.d.ts +0 -1
  290. package/dist/types/langchain/runnables.d.ts +0 -2
  291. package/dist/types/langchain/tools.d.ts +0 -2
  292. package/dist/types/langchain/utils/env.d.ts +0 -1
  293. package/dist/types/llm/bedrock/cacheSupport.d.ts +0 -35
  294. package/dist/types/tools/search/tavily-scraper.d.ts +0 -19
  295. package/dist/types/tools/search/tavily-search.d.ts +0 -4
  296. package/dist/types/tools/subagent/types.d.ts +0 -84
  297. package/dist/types/types/agent-cache.d.ts +0 -71
  298. package/src/agents/__tests__/AgentContext.cacheTtl.live.test.ts +0 -259
  299. package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +0 -266
  300. package/src/agents/__tests__/AgentContext.crossUserCache.live.test.ts +0 -342
  301. package/src/langchain/google-common.ts +0 -1
  302. package/src/langchain/index.ts +0 -8
  303. package/src/langchain/language_models/chat_models.ts +0 -1
  304. package/src/langchain/messages/tool.ts +0 -5
  305. package/src/langchain/messages.ts +0 -21
  306. package/src/langchain/openai.ts +0 -1
  307. package/src/langchain/prompts.ts +0 -1
  308. package/src/langchain/runnables.ts +0 -7
  309. package/src/langchain/tools.ts +0 -8
  310. package/src/langchain/utils/env.ts +0 -1
  311. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +0 -436
  312. package/src/llm/bedrock/cacheSupport.test.ts +0 -99
  313. package/src/llm/bedrock/cacheSupport.ts +0 -53
  314. package/src/tools/search/tavily-scraper.ts +0 -235
  315. package/src/tools/search/tavily-search.ts +0 -424
  316. package/src/tools/search/tavily.test.ts +0 -965
  317. package/src/tools/subagent/types.test.ts +0 -70
  318. package/src/tools/subagent/types.ts +0 -115
  319. package/src/types/agent-cache.ts +0 -74
@@ -3,8 +3,6 @@ import { RunnableLambda } from '@langchain/core/runnables';
3
3
  import { createSchemaOnlyTools } from '../tools/schema.mjs';
4
4
  import { ContentTypes, Providers } from '../common/enum.mjs';
5
5
  import '../tools/approval/constants.mjs';
6
- import { MAX_SYSTEM_CACHE_BLOCKS } from '../types/agent-cache.mjs';
7
- import { isBedrockCacheSupported } from '../llm/bedrock/cacheSupport.mjs';
8
6
  import { toJsonSchema } from '../utils/schema.mjs';
9
7
 
10
8
  /* eslint-disable no-console */
@@ -17,7 +15,7 @@ class AgentContext {
17
15
  * Create an AgentContext from configuration with token accounting initialization
18
16
  */
19
17
  static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
20
- const { agentId, name, description, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, system_cache_blocks, instructions, instructions_cache_ttl, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, dynamicContext, structuredOutput: structuredOutputCamel, structured_output: structuredOutputSnake, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, fileManifest, } = agentConfig;
18
+ const { agentId, name, description, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, dynamicContext, structuredOutput: structuredOutputCamel, structured_output: structuredOutputSnake, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, fileManifest, system_cache_blocks, instructions_cache_ttl, } = agentConfig;
21
19
  // Normalize structured output: support both camelCase and snake_case inputs
22
20
  // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)
23
21
  let structuredOutput;
@@ -47,9 +45,7 @@ class AgentContext {
47
45
  toolMap,
48
46
  toolRegistry,
49
47
  toolDefinitions,
50
- systemCacheBlocks: system_cache_blocks,
51
48
  instructions,
52
- instructionsCacheTtl: instructions_cache_ttl,
53
49
  additionalInstructions: additional_instructions,
54
50
  reasoningKey,
55
51
  toolEnd,
@@ -63,9 +59,11 @@ class AgentContext {
63
59
  persistedSummary,
64
60
  summarizationConfig,
65
61
  fileManifest,
62
+ systemCacheBlocks: system_cache_blocks,
63
+ instructionsCacheTtl: instructions_cache_ttl,
66
64
  });
67
65
  /**
68
- * Track subagent inputs on the context. `_sourceInputs`
66
+ * Track upstream-aligned subagent inputs on the context. `_sourceInputs`
69
67
  * preserves the original AgentInputs so SubagentExecutor can self-spawn
70
68
  * (`SubagentConfig.self === true`) without separate config; the other
71
69
  * two flow straight from agentConfig.
@@ -143,18 +141,9 @@ class AgentContext {
143
141
  toolDefinitions;
144
142
  /** Set of tool names discovered via tool search (to be loaded) */
145
143
  discoveredToolNames = new Set();
146
- /**
147
- * Cacheable system content blocks emitted before `instructions`. Each
148
- * gets its own cache marker (cachePoint on Bedrock, cache_control on
149
- * Anthropic). Earlier entries = wider cache key (best for cross-tenant
150
- * sharing). See `src/types/agent-cache.ts`.
151
- */
152
- systemCacheBlocks;
153
- /** Stable/cacheable instructions for this agent (gets trailing marker). */
144
+ /** Instructions for this agent */
154
145
  instructions;
155
- /** TTL for the trailing instructions cache marker. Defaults to '5m'. */
156
- instructionsCacheTtl;
157
- /** Dynamic system tail (per-user / per-message — never cached). */
146
+ /** Additional instructions for this agent */
158
147
  additionalInstructions;
159
148
  /**
160
149
  * Dynamic context that changes per-request (e.g., current time, user info).
@@ -216,13 +205,22 @@ class AgentContext {
216
205
  summarizationConfig;
217
206
  /** Lightweight file manifest for file-aware compaction (IDs and names only, no content) */
218
207
  fileManifest;
208
+ /**
209
+ * Workspace-shared system-message tiers. When set, each entry becomes a
210
+ * separate text block in the SystemMessage with its own cachePoint /
211
+ * cache_control marker, BEFORE the per-agent `instructions` block.
212
+ * See {@link t.AgentInputs.system_cache_blocks} for full semantics.
213
+ */
214
+ systemCacheBlocks;
215
+ /** TTL hint for the per-agent instructions cache marker. Defaults to '5m'. */
216
+ instructionsCacheTtl;
219
217
  /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */
220
218
  _sourceInputs;
221
219
  /** Subagent configurations for hierarchical delegation. */
222
220
  subagentConfigs;
223
221
  /** Maximum subagent nesting depth. */
224
222
  maxSubagentDepth;
225
- constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, systemCacheBlocks, instructions, instructionsCacheTtl, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, fileManifest, }) {
223
+ constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, fileManifest, systemCacheBlocks, instructionsCacheTtl, }) {
226
224
  this.agentId = agentId;
227
225
  this.name = name;
228
226
  this.description = description;
@@ -235,16 +233,7 @@ class AgentContext {
235
233
  this.toolMap = toolMap;
236
234
  this.toolRegistry = toolRegistry;
237
235
  this.toolDefinitions = toolDefinitions;
238
- if (systemCacheBlocks &&
239
- systemCacheBlocks.length > MAX_SYSTEM_CACHE_BLOCKS) {
240
- throw new Error(`system_cache_blocks supports at most ${MAX_SYSTEM_CACHE_BLOCKS} entries ` +
241
- `(received ${systemCacheBlocks.length}); excess entries would exceed ` +
242
- `Bedrock's 4-cachePoint per-request budget once the tools array and ` +
243
- `trailing 'instructions' marker are counted. See src/types/agent-cache.ts.`);
244
- }
245
- this.systemCacheBlocks = systemCacheBlocks;
246
236
  this.instructions = instructions;
247
- this.instructionsCacheTtl = instructionsCacheTtl;
248
237
  this.additionalInstructions = additionalInstructions;
249
238
  this.dynamicContext = dynamicContext;
250
239
  this.structuredOutput = structuredOutput;
@@ -252,6 +241,12 @@ class AgentContext {
252
241
  this.persistedSummary = persistedSummary;
253
242
  this.summarizationConfig = summarizationConfig;
254
243
  this.fileManifest = fileManifest;
244
+ if (systemCacheBlocks && systemCacheBlocks.length > 0) {
245
+ this.systemCacheBlocks = systemCacheBlocks;
246
+ }
247
+ if (instructionsCacheTtl) {
248
+ this.instructionsCacheTtl = instructionsCacheTtl;
249
+ }
255
250
  if (reasoningKey) {
256
251
  this.reasoningKey = reasoningKey;
257
252
  }
@@ -435,11 +430,8 @@ class AgentContext {
435
430
  return this.cachedSystemRunnable;
436
431
  }
437
432
  // Stale or first access - rebuild
438
- this.cachedSystemRunnable = this.buildSystemRunnable({
439
- systemCacheBlocks: this.systemCacheBlocks ?? [],
440
- stableInstructions: this.buildStableInstructionsString(),
441
- dynamicInstructions: this.buildDynamicInstructionsString(),
442
- });
433
+ const instructionsString = this.buildInstructionsString();
434
+ this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
443
435
  this.systemRunnableStale = false;
444
436
  return this.cachedSystemRunnable;
445
437
  }
@@ -449,26 +441,16 @@ class AgentContext {
449
441
  */
450
442
  initializeSystemRunnable() {
451
443
  if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
452
- this.cachedSystemRunnable = this.buildSystemRunnable({
453
- systemCacheBlocks: this.systemCacheBlocks ?? [],
454
- stableInstructions: this.buildStableInstructionsString(),
455
- dynamicInstructions: this.buildDynamicInstructionsString(),
456
- });
444
+ const instructionsString = this.buildInstructionsString();
445
+ this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
457
446
  this.systemRunnableStale = false;
458
447
  }
459
448
  }
460
449
  /**
461
- * Builds the cacheable instructions string (without creating SystemMessage).
462
- * Includes agent identity preamble, the agent's static instructions, and
463
- * programmatic-only tool documentation. This is the part of the system
464
- * message that stays byte-stable across turns and across users for the
465
- * same agent — the prompt cache prefix.
466
- *
467
- * Per-user/per-message dynamic context belongs in
468
- * `buildDynamicInstructionsString()` so it does not invalidate the cache
469
- * marker. (See `feedback_cache_stability_invariant` for the rule.)
450
+ * Builds the raw instructions string (without creating SystemMessage).
451
+ * Includes agent identity preamble and handoff context when available.
470
452
  */
471
- buildStableInstructionsString() {
453
+ buildInstructionsString() {
472
454
  const parts = [];
473
455
  /** Build agent identity and handoff context preamble */
474
456
  const identityPreamble = this.buildIdentityPreamble();
@@ -479,6 +461,11 @@ class AgentContext {
479
461
  if (this.instructions != null && this.instructions !== '') {
480
462
  parts.push(this.instructions);
481
463
  }
464
+ /** Add additional instructions */
465
+ if (this.additionalInstructions != null &&
466
+ this.additionalInstructions !== '') {
467
+ parts.push(this.additionalInstructions);
468
+ }
482
469
  /** Add programmatic tools documentation */
483
470
  const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
484
471
  if (programmaticToolsDoc) {
@@ -486,23 +473,6 @@ class AgentContext {
486
473
  }
487
474
  return parts.join('\n\n');
488
475
  }
489
- /**
490
- * Builds the dynamic system-tail string (without creating SystemMessage).
491
- * Keep this out of prompt-cache-marked content so volatile per-call
492
- * context does not invalidate the stable prefix.
493
- *
494
- * `additional_instructions` is treated as dynamic (per-user/per-message
495
- * memory, runtime context, etc.) and intentionally excluded from the
496
- * cacheable prefix.
497
- */
498
- buildDynamicInstructionsString() {
499
- const parts = [];
500
- if (this.additionalInstructions != null &&
501
- this.additionalInstructions !== '') {
502
- parts.push(this.additionalInstructions);
503
- }
504
- return parts.join('\n\n');
505
- }
506
476
  /**
507
477
  * Builds the agent identity preamble including handoff context if present.
508
478
  * This helps the agent understand its role in the multi-agent workflow.
@@ -540,136 +510,107 @@ class AgentContext {
540
510
  return lines.join('\n');
541
511
  }
542
512
  /**
543
- * True when Anthropic prompt caching is enabled for this agent.
544
- * Used by `buildSystemRunnable` to decide whether to emit a cache_control
545
- * marker on the stable instructions prefix.
513
+ * Build system runnable from pre-built instructions string.
514
+ * Only called when content has actually changed.
546
515
  */
547
- hasAnthropicPromptCache() {
548
- if (this.provider !== Providers.ANTHROPIC) {
549
- return false;
550
- }
551
- const anthropicOptions = this.clientOptions;
552
- return anthropicOptions?.promptCache === true;
553
- }
554
- /**
555
- * True when Bedrock prompt caching is enabled for this agent AND the
556
- * configured model supports `cachePoint` blocks. Only Claude (and Nova)
557
- * models on Bedrock honour cachePoint — Llama / Titan reject it.
558
- *
559
- * Used by `buildSystemRunnable` to inline a `cachePoint` block right
560
- * after the stable system text so the system prefix is cached at the
561
- * AWS account level (cross-user, cross-conversation).
562
- */
563
- hasBedrockPromptCache() {
564
- if (this.provider !== Providers.BEDROCK) {
565
- return false;
566
- }
567
- const bedrockOptions = this.clientOptions;
568
- if (bedrockOptions?.promptCache !== true) {
569
- return false;
570
- }
571
- /* Allowlist-based check (see src/llm/bedrock/cacheSupport.ts). The
572
- * `bedrockCacheModelPatterns` clientOption lets consumers add new
573
- * model patterns without forking the library — useful when AWS adds
574
- * a new family before the next library release. */
575
- return isBedrockCacheSupported(bedrockOptions.model, bedrockOptions.bedrockCacheModelPatterns);
576
- }
577
- /**
578
- * Build system runnable from cacheable blocks + the trailing
579
- * `instructions` block + optional dynamic tail.
580
- *
581
- * ┌──────────────────────────────────────────┐
582
- * │ system_cache_blocks[0].text │ ← consumer-defined block 0
583
- * ├──── cache marker (TTL = blocks[0].ttl) ──┤
584
- * │ system_cache_blocks[1].text │ ← consumer-defined block 1
585
- * ├──── cache marker (TTL = blocks[1].ttl) ──┤
586
- * │ instructions │ ← per-agent stable
587
- * ├──── cache marker (TTL = instructionsCacheTtl) ┤
588
- * │ additional_instructions │ ← dynamic (uncached)
589
- * └──────────────────────────────────────────┘
590
- *
591
- * If `system_cache_blocks` is empty, behavior reduces to the 2-tier
592
- * (instructions + dynamic) path used by simpler consumers.
593
- *
594
- * Provider-specific cache marker:
595
- * - Anthropic: `cache_control: { type: 'ephemeral', ttl?: '1h'|'5m' }` on
596
- * each cacheable text block. Up to 4 cache breakpoints per workspace.
597
- * - Bedrock (Claude/Nova): a `{ cachePoint: { type: 'default', ttl?: '1h'|'5m' } }`
598
- * block inserted after each cacheable section. Up to 4 cachePoints per
599
- * request, of which the tools array can consume up to 2.
600
- *
601
- * Cache key composition: every byte from message start to a given cache
602
- * marker forms that marker's cache key. Earlier blocks = wider cache key
603
- * = more cross-tenant share. Place the most stable content first.
604
- */
605
- buildSystemRunnable({ systemCacheBlocks, stableInstructions, dynamicInstructions, }) {
606
- const hasAnyCacheBlocks = systemCacheBlocks.length > 0;
607
- if (!hasAnyCacheBlocks && !stableInstructions && !dynamicInstructions) {
516
+ buildSystemRunnable(instructionsString) {
517
+ if (!instructionsString) {
608
518
  // Remove previous tokens if we had a system message before
609
519
  this.instructionTokens -= this.systemMessageTokens;
610
520
  this.systemMessageTokens = 0;
611
521
  return undefined;
612
522
  }
613
- const useAnthropicCache = this.hasAnthropicPromptCache();
614
- const useBedrockCache = this.hasBedrockPromptCache();
615
- const instructionsTtl = this.instructionsCacheTtl ?? '5m';
616
- let finalInstructions;
617
- if (useAnthropicCache) {
618
- const content = [];
619
- // Emit each system_cache_blocks entry with its own cache_control.
620
- for (const block of systemCacheBlocks) {
621
- if (!block.text)
622
- continue;
623
- content.push({
624
- type: 'text',
625
- text: block.text,
626
- cache_control: { type: 'ephemeral', ttl: block.ttl ?? '5m' },
627
- });
628
- }
629
- // Trailing stable instructions block (also cacheable).
630
- if (stableInstructions) {
631
- content.push({
632
- type: 'text',
633
- text: stableInstructions,
634
- cache_control: { type: 'ephemeral', ttl: instructionsTtl },
635
- });
636
- }
637
- if (dynamicInstructions) {
638
- // Dynamic tail: NO cache_control so it doesn't shift the cache prefix.
639
- content.push({ type: 'text', text: dynamicInstructions });
640
- }
641
- finalInstructions = { content };
642
- }
643
- else if (useBedrockCache && (hasAnyCacheBlocks || stableInstructions)) {
644
- const content = [];
645
- // Emit each system_cache_blocks entry as text + cachePoint pair.
646
- for (const block of systemCacheBlocks) {
647
- if (!block.text)
648
- continue;
649
- content.push({ type: 'text', text: block.text });
650
- content.push({
651
- cachePoint: { type: 'default', ttl: block.ttl ?? '5m' },
652
- });
653
- }
654
- if (stableInstructions) {
655
- content.push({ type: 'text', text: stableInstructions });
656
- content.push({
657
- cachePoint: { type: 'default', ttl: instructionsTtl },
658
- });
659
- }
660
- if (dynamicInstructions) {
661
- content.push({ type: 'text', text: dynamicInstructions });
523
+ let finalInstructions = instructionsString;
524
+ /**
525
+ * Tiered system-message assembly. When `systemCacheBlocks` is set, build
526
+ * a multi-block SystemMessage so each tier has its own cache breakpoint:
527
+ *
528
+ * [tier1_block_1][tier1_cachePoint]...[tier1_block_N][tier1_cachePoint]
529
+ * [instructions][instructions_cachePoint]
530
+ *
531
+ * Forward-prefix-hash means agents in the same workspace whose tier-1
532
+ * bytes are identical share the platform cache entry; only the per-agent
533
+ * `instructions` block invalidates per-agent.
534
+ *
535
+ * - Bedrock: emit `cachePoint: { type: 'default' }` blocks (handled by
536
+ * `convertSystemMessageToConverseMessage`).
537
+ * - Anthropic: emit `cache_control: { type: 'ephemeral' }` on each text
538
+ * block. (TTL hints are dropped for Anthropic — the SDK currently
539
+ * only supports `'ephemeral'`. Bedrock cachePoint has no TTL knob.)
540
+ */
541
+ const hasTieredCache = Array.isArray(this.systemCacheBlocks) &&
542
+ this.systemCacheBlocks.length > 0;
543
+ const isBedrock = this.provider === Providers.BEDROCK;
544
+ const isAnthropic = this.provider === Providers.ANTHROPIC;
545
+ const anthropicCacheEnabled = isAnthropic &&
546
+ this.clientOptions
547
+ ?.promptCache === true;
548
+ /**
549
+ * Bedrock cachePoint is Claude-only — Nova/Llama/Titan reject it.
550
+ * Mirrors the model check in `IllumaBedrockConverse.invocationParams`
551
+ * (src/llm/bedrock/index.ts:186-189).
552
+ */
553
+ const bedrockCacheEnabled = isBedrock &&
554
+ (() => {
555
+ const opts = this.clientOptions;
556
+ const modelId = (opts?.model ?? '').toLowerCase();
557
+ const isClaudeModel = modelId.includes('claude') || modelId.includes('anthropic');
558
+ return opts?.promptCache === true && isClaudeModel;
559
+ })();
560
+ if (hasTieredCache && (bedrockCacheEnabled || anthropicCacheEnabled)) {
561
+ /**
562
+ * Anthropic / Bedrock cap cache breakpoints at 4 per request. The
563
+ * lib already emits one for tools and up to two for messages, so we
564
+ * have at most 1 left for the system block. We spend it on Tier 1
565
+ * (the workspace-shared bytes) per-agent Tier 2 caching is still
566
+ * achieved implicitly via the tools breakpoint that follows, since
567
+ * cache lookups are forward-prefix-hash.
568
+ *
569
+ * Tier 1 may itself be emitted as multiple text blocks (one per
570
+ * `systemCacheBlocks` entry); only the LAST gets the cache marker,
571
+ * the rest are plain text inside the same cached prefix.
572
+ */
573
+ const contentBlocks = [];
574
+ const tier1Blocks = this.systemCacheBlocks.filter((b) => b?.text);
575
+ tier1Blocks.forEach((block, idx) => {
576
+ const isLast = idx === tier1Blocks.length - 1;
577
+ if (bedrockCacheEnabled) {
578
+ contentBlocks.push({ type: 'text', text: block.text });
579
+ if (isLast) {
580
+ contentBlocks.push({ cachePoint: { type: 'default' } });
581
+ }
582
+ }
583
+ else if (isLast) {
584
+ contentBlocks.push({
585
+ type: 'text',
586
+ text: block.text,
587
+ cache_control: { type: 'ephemeral' },
588
+ });
589
+ }
590
+ else {
591
+ contentBlocks.push({ type: 'text', text: block.text });
592
+ }
593
+ });
594
+ if (instructionsString) {
595
+ // No cache marker on the trailing per-agent block — tools'
596
+ // breakpoint covers it.
597
+ contentBlocks.push({ type: 'text', text: instructionsString });
662
598
  }
663
- finalInstructions = { content };
599
+ finalInstructions = {
600
+ content: contentBlocks,
601
+ };
664
602
  }
665
- else {
666
- finalInstructions = [
667
- ...systemCacheBlocks.map((b) => b.text),
668
- stableInstructions,
669
- dynamicInstructions,
670
- ]
671
- .filter((part) => part !== '')
672
- .join('\n\n');
603
+ else if (anthropicCacheEnabled) {
604
+ // Legacy single-block Anthropic caching (preserved for back-compat).
605
+ finalInstructions = {
606
+ content: [
607
+ {
608
+ type: 'text',
609
+ text: instructionsString,
610
+ cache_control: { type: 'ephemeral' },
611
+ },
612
+ ],
613
+ };
673
614
  }
674
615
  const systemMessage = new SystemMessage(finalInstructions);
675
616
  // Update token counts (subtract old, add new)
@@ -738,45 +679,6 @@ class AgentContext {
738
679
  this.indexTokenCountMap = { ...baseTokenMap };
739
680
  }
740
681
  }
741
- /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries
742
- * and definitions whose `allowed_callers` exclude `'direct'`). Mirrors the gate
743
- * `getEventDrivenToolsForBinding` applies so accounting and binding stay aligned. */
744
- getActiveToolDefinitions() {
745
- if (!this.toolDefinitions) {
746
- return [];
747
- }
748
- return this.toolDefinitions.filter((def) => {
749
- const allowedCallers = def.allowed_callers ?? ['direct'];
750
- if (!allowedCallers.includes('direct')) {
751
- return false;
752
- }
753
- return (def.defer_loading !== true || this.discoveredToolNames.has(def.name));
754
- });
755
- }
756
- /**
757
- * Single source of truth for "which entries of `this.tools` should be
758
- * treated as actually bound". Callers:
759
- * - `getToolsForBinding` (non-event-driven branch)
760
- * - `getEventDrivenToolsForBinding` (appends instance tools alongside
761
- * schema-only definitions)
762
- * - `calculateInstructionTokens` (counts schema bytes for accounting)
763
- *
764
- * In event-driven mode (`toolDefinitions` present) instance tools are
765
- * appended unfiltered; outside event-driven mode they pass through
766
- * `filterToolsForBinding`. Centralizing the decision here prevents the
767
- * accounting/binding paths from drifting apart, which was the root
768
- * cause of the original miscount (Fixes #121).
769
- */
770
- getEffectiveInstanceTools() {
771
- if (!this.tools) {
772
- return undefined;
773
- }
774
- const isEventDriven = (this.toolDefinitions?.length ?? 0) > 0;
775
- if (isEventDriven || !this.toolRegistry) {
776
- return this.tools;
777
- }
778
- return this.filterToolsForBinding(this.tools);
779
- }
780
682
  /**
781
683
  * Calculate tool tokens and add to instruction tokens
782
684
  * Note: System message tokens are calculated during systemRunnable creation
@@ -790,16 +692,9 @@ class AgentContext {
790
692
  const countedToolNames = new Set();
791
693
  // Reset per-tool breakdown
792
694
  this.toolsDetail = [];
793
- /* Use `getEffectiveInstanceTools()` so accounting reflects exactly the
794
- * subset that `getToolsForBinding` would emit — preventing the
795
- * worst-case-ceiling miscount that triggered spurious `empty_messages`
796
- * preflight rejections at low `maxContextTokens`. Deferred and
797
- * non-`'direct'` `toolDefinitions` are excluded by
798
- * `getActiveToolDefinitions()` below. */
799
- const effectiveInstanceTools = this.getEffectiveInstanceTools();
800
695
  // Count tokens for bound tools (StructuredTool instances with .schema)
801
- if (effectiveInstanceTools && effectiveInstanceTools.length > 0) {
802
- for (const tool of effectiveInstanceTools) {
696
+ if (this.tools && this.tools.length > 0) {
697
+ for (const tool of this.tools) {
803
698
  const genericTool = tool;
804
699
  if (genericTool.schema != null &&
805
700
  typeof genericTool.schema === 'object') {
@@ -818,25 +713,23 @@ class AgentContext {
818
713
  // Count tokens for tool definitions (MCP / event-driven tools).
819
714
  // These are sent to the provider API as tool schemas alongside bound tools.
820
715
  // Both can be populated simultaneously (graph tools + MCP tools).
821
- // Use `getActiveToolDefinitions()` so programmatic-only definitions
822
- // (e.g. `allowed_callers: ['code_execution']`) and deferred-and-
823
- // -undiscovered ones don't inflate `toolSchemaTokens` while never
824
- // being bound to the model.
825
- for (const def of this.getActiveToolDefinitions()) {
826
- if (countedToolNames.has(def.name)) {
827
- continue; // Already counted via this.tools
716
+ if (this.toolDefinitions && this.toolDefinitions.length > 0) {
717
+ for (const def of this.toolDefinitions) {
718
+ if (countedToolNames.has(def.name)) {
719
+ continue; // Already counted via this.tools
720
+ }
721
+ const schema = {
722
+ name: def.name,
723
+ description: def.description ?? '',
724
+ parameters: def.parameters ?? {},
725
+ };
726
+ const defTokens = tokenCounter(new SystemMessage(JSON.stringify(schema)));
727
+ this.toolsDetail.push({
728
+ name: def.name || 'unknown',
729
+ tokens: defTokens,
730
+ });
731
+ toolTokens += defTokens;
828
732
  }
829
- const schema = {
830
- name: def.name,
831
- description: def.description ?? '',
832
- parameters: def.parameters ?? {},
833
- };
834
- const defTokens = tokenCounter(new SystemMessage(JSON.stringify(schema)));
835
- this.toolsDetail.push({
836
- name: def.name || 'unknown',
837
- tokens: defTokens,
838
- });
839
- toolTokens += defTokens;
840
733
  }
841
734
  // Store total tool tokens for breakdown reporting
842
735
  this.toolTokensTotal = toolTokens;
@@ -968,7 +861,9 @@ class AgentContext {
968
861
  return this.getEventDrivenToolsForBinding();
969
862
  }
970
863
  /** Traditional mode: filter actual tool instances */
971
- const filtered = this.getEffectiveInstanceTools();
864
+ const filtered = !this.tools || !this.toolRegistry
865
+ ? this.tools
866
+ : this.filterToolsForBinding(this.tools);
972
867
  if (this.graphTools && this.graphTools.length > 0) {
973
868
  return [...(filtered ?? []), ...this.graphTools];
974
869
  }
@@ -979,16 +874,22 @@ class AgentContext {
979
874
  if (!this.toolDefinitions) {
980
875
  return this.graphTools ?? [];
981
876
  }
982
- /* Reuse `getActiveToolDefinitions()` so the binding gate matches the
983
- * accounting filter exactly (single source of truth). */
984
- const schemaTools = createSchemaOnlyTools(this.getActiveToolDefinitions());
877
+ const defsToInclude = this.toolDefinitions.filter((def) => {
878
+ const allowedCallers = def.allowed_callers ?? ['direct'];
879
+ if (!allowedCallers.includes('direct')) {
880
+ return false;
881
+ }
882
+ if (def.defer_loading === true &&
883
+ !this.discoveredToolNames.has(def.name)) {
884
+ return false;
885
+ }
886
+ return true;
887
+ });
888
+ const schemaTools = createSchemaOnlyTools(defsToInclude);
985
889
  const allTools = [...schemaTools];
986
890
  if (this.graphTools && this.graphTools.length > 0) {
987
891
  allTools.push(...this.graphTools);
988
892
  }
989
- /* In event-driven mode, instance tools are appended UNFILTERED (matching
990
- * `getEffectiveInstanceTools()`'s event-driven branch). Deferred /
991
- * non-direct logic is represented in `toolDefinitions`, not here. */
992
893
  if (this.tools && this.tools.length > 0) {
993
894
  allTools.push(...this.tools);
994
895
  }