illuma-agents 1.0.16 → 1.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +3 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +18 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +79 -32
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +5 -3
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -0
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +10 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +7 -8
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +15 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +11 -6
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +16 -8
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +9 -2
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +17 -10
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/stream.cjs +30 -16
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +209 -47
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +73 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +1 -0
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +3 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/utils/contextAnalytics.cjs +66 -0
- package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/toonFormat.cjs +388 -0
- package/dist/cjs/utils/toonFormat.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +3 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +19 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +81 -34
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +5 -3
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -0
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +10 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +7 -8
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +4 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +11 -6
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +18 -10
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +10 -3
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +19 -12
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/stream.mjs +30 -16
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +208 -48
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +73 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +1 -0
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +3 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/utils/contextAnalytics.mjs +64 -0
- package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/toonFormat.mjs +381 -0
- package/dist/esm/utils/toonFormat.mjs.map +1 -0
- package/dist/types/common/enum.d.ts +17 -0
- package/dist/types/graphs/Graph.d.ts +8 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +19 -0
- package/dist/types/types/tools.d.ts +3 -1
- package/dist/types/utils/contextAnalytics.d.ts +37 -0
- package/dist/types/utils/index.d.ts +2 -0
- package/dist/types/utils/toonFormat.d.ts +111 -0
- package/package.json +3 -2
- package/src/agents/AgentContext.ts +28 -20
- package/src/common/enum.ts +18 -0
- package/src/graphs/Graph.ts +152 -62
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +495 -473
- package/src/llm/bedrock/index.ts +47 -35
- package/src/llm/openrouter/index.ts +11 -1
- package/src/llm/vertexai/index.ts +9 -10
- package/src/messages/cache.ts +104 -55
- package/src/messages/core.ts +29 -19
- package/src/messages/format.ts +14 -3
- package/src/messages/tools.ts +20 -13
- package/src/scripts/simple.ts +1 -1
- package/src/specs/emergency-prune.test.ts +407 -355
- package/src/stream.ts +28 -20
- package/src/tools/ProgrammaticToolCalling.ts +246 -52
- package/src/tools/ToolNode.ts +78 -5
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +155 -0
- package/src/tools/search/jina-reranker.test.ts +32 -28
- package/src/tools/search/search.ts +3 -1
- package/src/tools/search/tool.ts +16 -7
- package/src/types/tools.ts +3 -1
- package/src/utils/contextAnalytics.ts +103 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/llmConfig.ts +8 -1
- package/src/utils/run.ts +5 -4
- package/src/utils/toonFormat.ts +475 -0
|
@@ -284,7 +284,9 @@ class AgentContext {
|
|
|
284
284
|
if (this.provider === _enum.Providers.BEDROCK) {
|
|
285
285
|
const bedrockOptions = this.clientOptions;
|
|
286
286
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
287
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
287
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
288
|
+
modelId.includes('anthropic') ||
|
|
289
|
+
modelId.includes('nova');
|
|
288
290
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
289
291
|
finalInstructions = {
|
|
290
292
|
content: [
|
|
@@ -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 * 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 dynamicContext,\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 dynamicContext,\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 /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: 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 /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\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 dynamicContext,\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 dynamicContext?: 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 this.dynamicContext = dynamicContext;\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 (Direct API)\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 // Handle Bedrock prompt caching (Converse API)\n // Adds cachePoint block after text content for system message caching\n // NOTE: Both Claude and Nova models support cachePoint in system and messages\n // (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)\n if (this.provider === Providers.BEDROCK) {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicInput\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching = modelId.includes('claude') || modelId.includes('anthropic') || modelId.includes('nova');\n\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n \n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n },\n {\n cachePoint: { type: 'default' },\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.toolsDetail = [];\n this.toolTokensTotal = 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 * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n this.toolsDetail = []; // Reset per-tool breakdown\n \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 const toolName = (genericTool.name as string) || 'unknown';\n const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n \n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName, tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n \n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined) this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined) this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined) this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined) this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined) this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined) this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal = \n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\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,EAChB,cAAc,GACf,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;YAChB,cAAc;AACf,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,IAAI,CAAC,MAAK;;AAET,gBAAA,YAAY,CAAC,8BAA8B,CAAC,QAAQ,CAAC;AACvD,aAAC;AACA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AAA,OAAO,cAAc;;AAExB;;;;"}
|
|
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 dynamicContext,\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 dynamicContext,\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 /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: 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 /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\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 dynamicContext,\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 dynamicContext?: 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 this.dynamicContext = dynamicContext;\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 (Direct API)\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 // Handle Bedrock prompt caching (Converse API)\n // Adds cachePoint block after text content for system message caching\n // NOTE: Both Claude and Nova models support cachePoint in system and messages\n // (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)\n if (this.provider === Providers.BEDROCK) {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicInput\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n },\n {\n cachePoint: { type: 'default' },\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.toolsDetail = [];\n this.toolTokensTotal = 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 * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n this.toolsDetail = []; // Reset per-tool breakdown\n\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 const toolName = (genericTool.name as string) || 'unknown';\n const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n\n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName, tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined)\n this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined)\n this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined)\n this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined)\n this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined)\n this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined)\n this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal =\n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\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;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;;QAG5B,IAAI,iBAAiB,EAAE;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;;;;"}
|
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -21,6 +21,8 @@ exports.GraphEvents = void 0;
|
|
|
21
21
|
GraphEvents["ON_MESSAGE_DELTA"] = "on_message_delta";
|
|
22
22
|
/** [Custom] Reasoning Delta events for messages */
|
|
23
23
|
GraphEvents["ON_REASONING_DELTA"] = "on_reasoning_delta";
|
|
24
|
+
/** [Custom] Context analytics event for traces */
|
|
25
|
+
GraphEvents["ON_CONTEXT_ANALYTICS"] = "on_context_analytics";
|
|
24
26
|
/* Official Events */
|
|
25
27
|
/** Custom event, emitted by system */
|
|
26
28
|
GraphEvents["ON_CUSTOM_EVENT"] = "on_custom_event";
|
|
@@ -162,4 +164,20 @@ exports.EnvVar = void 0;
|
|
|
162
164
|
EnvVar["CODE_API_KEY"] = "CODE_EXECUTOR_API_KEY";
|
|
163
165
|
EnvVar["CODE_BASEURL"] = "CODE_EXECUTOR_BASEURL";
|
|
164
166
|
})(exports.EnvVar || (exports.EnvVar = {}));
|
|
167
|
+
/**
|
|
168
|
+
* Message type identifiers used by LangChain's BaseMessage.getType().
|
|
169
|
+
* Use these constants instead of instanceof checks to avoid module mismatch issues
|
|
170
|
+
* when different copies of @langchain/core/messages are loaded.
|
|
171
|
+
*/
|
|
172
|
+
exports.MessageTypes = void 0;
|
|
173
|
+
(function (MessageTypes) {
|
|
174
|
+
MessageTypes["HUMAN"] = "human";
|
|
175
|
+
MessageTypes["AI"] = "ai";
|
|
176
|
+
MessageTypes["SYSTEM"] = "system";
|
|
177
|
+
MessageTypes["TOOL"] = "tool";
|
|
178
|
+
MessageTypes["FUNCTION"] = "function";
|
|
179
|
+
MessageTypes["GENERIC"] = "generic";
|
|
180
|
+
MessageTypes["DEVELOPER"] = "developer";
|
|
181
|
+
MessageTypes["REMOVE"] = "remove";
|
|
182
|
+
})(exports.MessageTypes || (exports.MessageTypes = {}));
|
|
165
183
|
//# sourceMappingURL=enum.cjs.map
|
|
@@ -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.illuma.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 = 'CODE_EXECUTOR_API_KEY',\n CODE_BASEURL = 'CODE_EXECUTOR_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,WAAA,CAAA,oBAAA,CAAA,GAAA,oBAAyC;;;AAKzC,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,qBAAwC;;AAGxC,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,sBAA0C;;AAG1C,IAAA,WAAA,CAAA,gBAAA,CAAA,GAAA,mBAAoC;;AAG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D;AAClD,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,uBAAsC;AACtC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,uBAAsC;AACxC,CAAC,EAHWA,cAAM,KAANA,cAAM,GAGjB,EAAA,CAAA,CAAA;;"}
|
|
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 /** [Custom] Context analytics event for traces */\n ON_CONTEXT_ANALYTICS = 'on_context_analytics',\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.illuma.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 = 'CODE_EXECUTOR_API_KEY',\n CODE_BASEURL = 'CODE_EXECUTOR_BASEURL',\n}\n\n/**\n * Message type identifiers used by LangChain's BaseMessage.getType().\n * Use these constants instead of instanceof checks to avoid module mismatch issues\n * when different copies of @langchain/core/messages are loaded.\n */\nexport enum MessageTypes {\n HUMAN = 'human',\n AI = 'ai',\n SYSTEM = 'system',\n TOOL = 'tool',\n FUNCTION = 'function',\n GENERIC = 'generic',\n DEVELOPER = 'developer',\n REMOVE = 'remove',\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","TitleMethod","EnvVar","MessageTypes"],"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,WAAA,CAAA,oBAAA,CAAA,GAAA,oBAAyC;;AAEzC,IAAA,WAAA,CAAA,sBAAA,CAAA,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AA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,YAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,YAAA,CAAA,UAAA,CAAA,GAAA,UAAqB;AACrB,IAAA,YAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,YAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,YAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EATWA,oBAAY,KAAZA,oBAAY,GASvB,EAAA,CAAA,CAAA;;"}
|
|
@@ -17,6 +17,8 @@ var graph = require('../utils/graph.cjs');
|
|
|
17
17
|
var llm = require('../utils/llm.cjs');
|
|
18
18
|
var run = require('../utils/run.cjs');
|
|
19
19
|
require('js-tiktoken/lite');
|
|
20
|
+
require('../utils/toonFormat.cjs');
|
|
21
|
+
var contextAnalytics = require('../utils/contextAnalytics.cjs');
|
|
20
22
|
var providers = require('../llm/providers.cjs');
|
|
21
23
|
var ToolNode = require('../tools/ToolNode.cjs');
|
|
22
24
|
var index = require('../llm/openai/index.cjs');
|
|
@@ -282,6 +284,15 @@ class StandardGraph extends Graph {
|
|
|
282
284
|
}
|
|
283
285
|
return primaryContext.getContextBreakdown();
|
|
284
286
|
}
|
|
287
|
+
/**
|
|
288
|
+
* Get the latest context analytics from the graph.
|
|
289
|
+
* Returns metrics like utilization %, TOON stats, message breakdown.
|
|
290
|
+
*/
|
|
291
|
+
getContextAnalytics() {
|
|
292
|
+
return this.lastContextAnalytics ?? null;
|
|
293
|
+
}
|
|
294
|
+
/** Store the latest context analytics for retrieval after run */
|
|
295
|
+
lastContextAnalytics = null;
|
|
285
296
|
/* Graph */
|
|
286
297
|
createSystemRunnable({ provider, clientOptions, instructions, additional_instructions, }) {
|
|
287
298
|
let finalInstructions = instructions;
|
|
@@ -470,14 +481,6 @@ class StandardGraph extends Graph {
|
|
|
470
481
|
}
|
|
471
482
|
this.config = config;
|
|
472
483
|
let messagesToUse = messages$1;
|
|
473
|
-
// Debug logging for pruneMessages creation conditions
|
|
474
|
-
const hasPruneMessages = !!agentContext.pruneMessages;
|
|
475
|
-
const hasTokenCounter = !!agentContext.tokenCounter;
|
|
476
|
-
const hasMaxContextTokens = agentContext.maxContextTokens != null;
|
|
477
|
-
const hasIndex0TokenCount = agentContext.indexTokenCountMap[0] != null;
|
|
478
|
-
if (!hasPruneMessages && hasTokenCounter && hasMaxContextTokens && !hasIndex0TokenCount) {
|
|
479
|
-
console.warn('[Graph] Cannot create pruneMessages - missing indexTokenCountMap[0]. Token map keys:', Object.keys(agentContext.indexTokenCountMap));
|
|
480
|
-
}
|
|
481
484
|
if (!agentContext.pruneMessages &&
|
|
482
485
|
agentContext.tokenCounter &&
|
|
483
486
|
agentContext.maxContextTokens != null &&
|
|
@@ -521,11 +524,12 @@ class StandardGraph extends Graph {
|
|
|
521
524
|
: null;
|
|
522
525
|
if (agentContext.provider === _enum.Providers.BEDROCK &&
|
|
523
526
|
lastMessageX instanceof messages.AIMessageChunk &&
|
|
524
|
-
lastMessageY
|
|
527
|
+
lastMessageY?.getType() === _enum.MessageTypes.TOOL &&
|
|
525
528
|
typeof lastMessageX.content === 'string') {
|
|
526
529
|
finalMessages[finalMessages.length - 2].content = '';
|
|
527
530
|
}
|
|
528
|
-
|
|
531
|
+
// Use getType() instead of instanceof to avoid module mismatch issues
|
|
532
|
+
const isLatestToolMessage = lastMessageY?.getType() === _enum.MessageTypes.TOOL;
|
|
529
533
|
if (isLatestToolMessage &&
|
|
530
534
|
agentContext.provider === _enum.Providers.ANTHROPIC) {
|
|
531
535
|
core.formatAnthropicArtifactContent(finalMessages);
|
|
@@ -536,6 +540,27 @@ class StandardGraph extends Graph {
|
|
|
536
540
|
llm.isGoogleLike(agentContext.provider))) {
|
|
537
541
|
core.formatArtifactPayload(finalMessages);
|
|
538
542
|
}
|
|
543
|
+
/**
|
|
544
|
+
* Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,
|
|
545
|
+
* convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.
|
|
546
|
+
* This is required by Anthropic/Bedrock when thinking is enabled.
|
|
547
|
+
*
|
|
548
|
+
* IMPORTANT: This MUST happen BEFORE cache control is applied.
|
|
549
|
+
* If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,
|
|
550
|
+
* the cachePoint is lost. By converting first, we ensure cache control is applied to the
|
|
551
|
+
* final message structure that will be sent to the API.
|
|
552
|
+
*/
|
|
553
|
+
const isAnthropicWithThinking = (agentContext.provider === _enum.Providers.ANTHROPIC &&
|
|
554
|
+
agentContext.clientOptions.thinking !=
|
|
555
|
+
null) ||
|
|
556
|
+
(agentContext.provider === _enum.Providers.BEDROCK &&
|
|
557
|
+
agentContext.clientOptions
|
|
558
|
+
.additionalModelRequestFields?.['thinking'] != null);
|
|
559
|
+
if (isAnthropicWithThinking) {
|
|
560
|
+
finalMessages = format.ensureThinkingBlockInMessages(finalMessages, agentContext.provider);
|
|
561
|
+
}
|
|
562
|
+
// Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost
|
|
563
|
+
// when AI messages are converted to HumanMessages
|
|
539
564
|
if (agentContext.provider === _enum.Providers.ANTHROPIC) {
|
|
540
565
|
const anthropicOptions = agentContext.clientOptions;
|
|
541
566
|
const defaultHeaders = anthropicOptions?.clientOptions
|
|
@@ -551,25 +576,13 @@ class StandardGraph extends Graph {
|
|
|
551
576
|
// Both Claude and Nova models support cachePoint in system and messages
|
|
552
577
|
// (Llama, Titan, and other models do NOT support cachePoint)
|
|
553
578
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
554
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
579
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
580
|
+
modelId.includes('anthropic') ||
|
|
581
|
+
modelId.includes('nova');
|
|
555
582
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
556
583
|
finalMessages = cache.addBedrockCacheControl(finalMessages);
|
|
557
584
|
}
|
|
558
585
|
}
|
|
559
|
-
/**
|
|
560
|
-
* Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,
|
|
561
|
-
* convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.
|
|
562
|
-
* This is required by Anthropic/Bedrock when thinking is enabled.
|
|
563
|
-
*/
|
|
564
|
-
const isAnthropicWithThinking = (agentContext.provider === _enum.Providers.ANTHROPIC &&
|
|
565
|
-
agentContext.clientOptions.thinking !=
|
|
566
|
-
null) ||
|
|
567
|
-
(agentContext.provider === _enum.Providers.BEDROCK &&
|
|
568
|
-
agentContext.clientOptions
|
|
569
|
-
.additionalModelRequestFields?.['thinking'] != null);
|
|
570
|
-
if (isAnthropicWithThinking) {
|
|
571
|
-
finalMessages = format.ensureThinkingBlockInMessages(finalMessages, agentContext.provider);
|
|
572
|
-
}
|
|
573
586
|
if (agentContext.lastStreamCall != null &&
|
|
574
587
|
agentContext.streamBuffer != null) {
|
|
575
588
|
const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;
|
|
@@ -589,6 +602,30 @@ class StandardGraph extends Graph {
|
|
|
589
602
|
info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',
|
|
590
603
|
}));
|
|
591
604
|
}
|
|
605
|
+
// Get model info for analytics
|
|
606
|
+
const bedrockOpts = agentContext.clientOptions;
|
|
607
|
+
const modelId = bedrockOpts?.model ||
|
|
608
|
+
agentContext.clientOptions
|
|
609
|
+
?.modelName;
|
|
610
|
+
const thinkingConfig = bedrockOpts?.additionalModelRequestFields?.['thinking'] ||
|
|
611
|
+
agentContext.clientOptions
|
|
612
|
+
?.thinking;
|
|
613
|
+
// Build and emit context analytics for traces
|
|
614
|
+
const contextAnalytics$1 = contextAnalytics.buildContextAnalytics(finalMessages, {
|
|
615
|
+
tokenCounter: agentContext.tokenCounter,
|
|
616
|
+
maxContextTokens: agentContext.maxContextTokens,
|
|
617
|
+
instructionTokens: agentContext.instructionTokens,
|
|
618
|
+
indexTokenCountMap: agentContext.indexTokenCountMap,
|
|
619
|
+
});
|
|
620
|
+
// Store for retrieval via getContextAnalytics() after run completes
|
|
621
|
+
this.lastContextAnalytics = contextAnalytics$1;
|
|
622
|
+
await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_CONTEXT_ANALYTICS, {
|
|
623
|
+
provider: agentContext.provider,
|
|
624
|
+
model: modelId,
|
|
625
|
+
thinkingEnabled: thinkingConfig != null,
|
|
626
|
+
cacheEnabled: bedrockOpts?.promptCache === true,
|
|
627
|
+
analytics: contextAnalytics$1,
|
|
628
|
+
}, config);
|
|
592
629
|
try {
|
|
593
630
|
result = await this.attemptInvoke({
|
|
594
631
|
currentModel: model,
|
|
@@ -599,7 +636,7 @@ class StandardGraph extends Graph {
|
|
|
599
636
|
}
|
|
600
637
|
catch (primaryError) {
|
|
601
638
|
// Check if this is a "input too long" error from Bedrock/Anthropic
|
|
602
|
-
const errorMessage = primaryError
|
|
639
|
+
const errorMessage = primaryError.message.toLowerCase() ?? '';
|
|
603
640
|
const isInputTooLongError = errorMessage.includes('too long') ||
|
|
604
641
|
errorMessage.includes('input is too long') ||
|
|
605
642
|
errorMessage.includes('context length') ||
|
|
@@ -613,7 +650,8 @@ class StandardGraph extends Graph {
|
|
|
613
650
|
hasPruneMessages: !!agentContext.pruneMessages,
|
|
614
651
|
hasTokenCounter: !!agentContext.tokenCounter,
|
|
615
652
|
maxContextTokens: agentContext.maxContextTokens,
|
|
616
|
-
indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)
|
|
653
|
+
indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)
|
|
654
|
+
.length,
|
|
617
655
|
});
|
|
618
656
|
}
|
|
619
657
|
// If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning
|
|
@@ -677,13 +715,22 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
677
715
|
let retryMessages = agentContext.useLegacyContent
|
|
678
716
|
? content.formatContentStrings(messagesWithNotice)
|
|
679
717
|
: messagesWithNotice;
|
|
680
|
-
// Apply
|
|
718
|
+
// Apply thinking block handling first (before cache control)
|
|
719
|
+
// This ensures AI+Tool sequences are converted to HumanMessages
|
|
720
|
+
// before we add cache points that could be lost in the conversion
|
|
721
|
+
if (isAnthropicWithThinking) {
|
|
722
|
+
retryMessages = format.ensureThinkingBlockInMessages(retryMessages, agentContext.provider);
|
|
723
|
+
}
|
|
724
|
+
// Apply Bedrock cache control if needed (after thinking block handling)
|
|
681
725
|
if (agentContext.provider === _enum.Providers.BEDROCK) {
|
|
682
726
|
const bedrockOptions = agentContext.clientOptions;
|
|
683
727
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
684
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
728
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
729
|
+
modelId.includes('anthropic') ||
|
|
730
|
+
modelId.includes('nova');
|
|
685
731
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
686
|
-
retryMessages =
|
|
732
|
+
retryMessages =
|
|
733
|
+
cache.addBedrockCacheControl(retryMessages);
|
|
687
734
|
}
|
|
688
735
|
}
|
|
689
736
|
try {
|
|
@@ -697,7 +744,7 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
697
744
|
console.info(`[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`);
|
|
698
745
|
}
|
|
699
746
|
catch (retryError) {
|
|
700
|
-
const retryErrorMsg = retryError
|
|
747
|
+
const retryErrorMsg = retryError.message.toLowerCase() ?? '';
|
|
701
748
|
const stillTooLong = retryErrorMsg.includes('too long') ||
|
|
702
749
|
retryErrorMsg.includes('context length') ||
|
|
703
750
|
retryErrorMsg.includes('validationexception');
|
|
@@ -705,7 +752,7 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
705
752
|
console.warn(`[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`);
|
|
706
753
|
}
|
|
707
754
|
else {
|
|
708
|
-
console.error(`[Graph] Retry at ${reductionFactor * 100}% failed:`, retryError
|
|
755
|
+
console.error(`[Graph] Retry at ${reductionFactor * 100}% failed:`, retryError.message);
|
|
709
756
|
}
|
|
710
757
|
}
|
|
711
758
|
}
|