illuma-agents 1.0.51 → 1.0.52

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.
@@ -456,29 +456,32 @@ class StandardGraph extends Graph {
456
456
  }
457
457
  const { name = 'StructuredResponse', mode = 'auto', includeRaw = false, handleErrors = true, maxRetries = 2, } = structuredOutputConfig;
458
458
  // Determine the method based on mode and provider
459
- // - 'tool': Use tool calling (works well with OpenAI)
460
- // - 'json_mode': Use JSON mode (works well with Bedrock/Anthropic)
459
+ // - 'tool' / 'functionCalling': Use tool calling (works with OpenAI, Bedrock)
460
+ // - 'provider' / 'jsonMode': Use native JSON mode (OpenAI, Anthropic direct - NOT Bedrock)
461
461
  // - 'auto': Auto-detect based on provider
462
+ // NOTE: ChatBedrockConverse does NOT support 'jsonMode' - it only supports tool-based structured output
462
463
  let method;
463
464
  if (mode === 'tool') {
464
465
  method = 'functionCalling';
465
466
  }
466
467
  else if (mode === 'provider') {
467
- // Use native JSON mode - best for Anthropic/Bedrock
468
- method = 'jsonMode';
469
- }
470
- else {
471
- // Auto mode: choose based on provider
472
- // Bedrock and Anthropic work better with JSON mode
473
- // OpenAI, Azure work better with function calling
474
- if (provider === _enum.Providers.BEDROCK || provider === _enum.Providers.ANTHROPIC) {
475
- method = 'jsonMode';
468
+ // Use native JSON mode - but NOT for Bedrock which doesn't support it
469
+ if (provider === _enum.Providers.BEDROCK) {
470
+ // Bedrock only supports function calling for structured output
471
+ method = 'functionCalling';
476
472
  }
477
- else if (provider === _enum.Providers.GOOGLE || provider === _enum.Providers.VERTEXAI) {
478
- // Gemini supports native JSON mode
473
+ else {
479
474
  method = 'jsonMode';
480
475
  }
481
- // For OpenAI/Azure, leave undefined to use default (function calling)
476
+ }
477
+ else {
478
+ // Auto mode: use function calling for all providers
479
+ // This is the most compatible approach
480
+ // Bedrock: only supports functionCalling
481
+ // Anthropic direct: supports both but functionCalling is more reliable
482
+ // OpenAI/Azure: supports both, functionCalling is default
483
+ // Google/Vertex: supports jsonMode but functionCalling works too
484
+ method = undefined; // Let LangChain choose the default
482
485
  }
483
486
  // Use withStructuredOutput to bind the schema
484
487
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -754,22 +757,27 @@ class StandardGraph extends Graph {
754
757
  // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled
755
758
  const structuredClientOptions = { ...agentContext.clientOptions };
756
759
  // Remove thinking configuration for Bedrock
760
+ // Bedrock uses additionalModelRequestFields.thinking for extended thinking
757
761
  if (agentContext.provider === _enum.Providers.BEDROCK) {
758
762
  const bedrockOpts = structuredClientOptions;
759
- if (bedrockOpts.additionalModelRequestFields?.['thinking']) {
763
+ if (bedrockOpts.additionalModelRequestFields) {
760
764
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
761
765
  const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields);
766
+ // Remove thinking configuration
762
767
  delete additionalFields.thinking;
768
+ // Remove budget tokens which is also related to thinking
769
+ delete additionalFields.budgetTokens;
763
770
  bedrockOpts.additionalModelRequestFields = additionalFields;
764
771
  }
765
772
  }
766
- // Remove thinking configuration for Anthropic
773
+ // Remove thinking configuration for Anthropic direct API
767
774
  if (agentContext.provider === _enum.Providers.ANTHROPIC) {
768
775
  const anthropicOpts = structuredClientOptions;
769
776
  if (anthropicOpts.thinking) {
770
777
  delete anthropicOpts.thinking;
771
778
  }
772
779
  }
780
+ console.log('[Graph] Creating structured model for provider:', agentContext.provider, 'with options:', JSON.stringify(structuredClientOptions, null, 2));
773
781
  const structuredModel = this.getNewModel({
774
782
  provider: agentContext.provider,
775
783
  clientOptions: structuredClientOptions,
@@ -1 +1 @@
1
- {"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n HumanMessage,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n MessageTypes,\n Constants,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n extractToolDiscoveries,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n buildContextAnalytics,\n type ContextAnalytics,\n} from '@/utils/contextAnalytics';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /**\n * Estimates a human-friendly description of the conversation timeframe based on message count.\n * Uses rough heuristics to provide context about how much history is available.\n *\n * @param messageCount - Number of messages in the remaining context\n * @returns A friendly description like \"the last few minutes\", \"the past hour\", etc.\n */\n getContextTimeframeDescription(messageCount: number): string {\n // Rough heuristics based on typical conversation patterns:\n // - Very active chat: ~20-30 messages per hour\n // - Normal chat: ~10-15 messages per hour\n // - Slow/thoughtful chat: ~5-8 messages per hour\n // We use a middle estimate of ~12 messages per hour\n\n if (messageCount <= 5) {\n return 'just the last few exchanges';\n } else if (messageCount <= 15) {\n return 'the last several minutes';\n } else if (messageCount <= 30) {\n return 'roughly the past hour';\n } else if (messageCount <= 60) {\n return 'the past couple of hours';\n } else if (messageCount <= 150) {\n return 'the past few hours';\n } else if (messageCount <= 300) {\n return 'roughly a day\\'s worth';\n } else if (messageCount <= 700) {\n return 'the past few days';\n } else {\n return 'about a week or more';\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /**\n * Get the context breakdown from the primary agent for admin token tracking.\n * Returns detailed token counts for instructions, tools, etc.\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 } | null {\n const primaryContext = this.agentContexts.get(this.defaultAgentId);\n if (!primaryContext) {\n return null;\n }\n return primaryContext.getContextBreakdown();\n }\n\n /**\n * Get the latest context analytics from the graph.\n * Returns metrics like utilization %, TOON stats, message breakdown.\n */\n getContextAnalytics(): ContextAnalytics | null {\n return this.lastContextAnalytics ?? null;\n }\n\n /** Store the latest context analytics for retrieval after run */\n private lastContextAnalytics: ContextAnalytics | null = null;\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n (clientOptions as t.AnthropicClientOptions).promptCache === true\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: schemaTools as t.GenericTool[],\n toolMap: new Map(schemaTools.map((tool) => [tool.name, tool])),\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n eventDrivenMode: true,\n toolDefinitions: toolDefMap,\n agentId: agentContext?.agentId,\n });\n }\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n /**\n * Execute model invocation with structured output.\n * Uses withStructuredOutput to force the model to return JSON conforming to the schema.\n * Disables streaming and returns a validated JSON response.\n */\n private async attemptStructuredInvoke(\n {\n currentModel,\n finalMessages,\n schema,\n structuredOutputConfig,\n provider,\n }: {\n currentModel: t.ChatModelInstance;\n finalMessages: BaseMessage[];\n schema: Record<string, unknown>;\n structuredOutputConfig: t.StructuredOutputConfig;\n provider?: Providers;\n },\n config?: RunnableConfig\n ): Promise<{\n structuredResponse: Record<string, unknown>;\n rawMessage?: AIMessageChunk;\n }> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n // Check if model supports withStructuredOutput\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (model as any).withStructuredOutput !== 'function') {\n throw new Error(\n `The selected model does not support structured output. ` +\n `Please use a model that supports JSON schema output (e.g., OpenAI GPT-4, Anthropic Claude, Google Gemini) ` +\n `or disable structured output for this agent.`\n );\n }\n\n const {\n name = 'StructuredResponse',\n mode = 'auto',\n includeRaw = false,\n handleErrors = true,\n maxRetries = 2,\n } = structuredOutputConfig;\n\n // Determine the method based on mode and provider\n // - 'tool': Use tool calling (works well with OpenAI)\n // - 'json_mode': Use JSON mode (works well with Bedrock/Anthropic)\n // - 'auto': Auto-detect based on provider\n let method: 'functionCalling' | 'jsonMode' | 'jsonSchema' | undefined;\n \n if (mode === 'tool') {\n method = 'functionCalling';\n } else if (mode === 'provider') {\n // Use native JSON mode - best for Anthropic/Bedrock\n method = 'jsonMode';\n } else {\n // Auto mode: choose based on provider\n // Bedrock and Anthropic work better with JSON mode\n // OpenAI, Azure work better with function calling\n if (provider === Providers.BEDROCK || provider === Providers.ANTHROPIC) {\n method = 'jsonMode';\n } else if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI) {\n // Gemini supports native JSON mode\n method = 'jsonMode';\n }\n // For OpenAI/Azure, leave undefined to use default (function calling)\n }\n\n // Use withStructuredOutput to bind the schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const structuredModel = (model as any).withStructuredOutput(schema, {\n name,\n method,\n includeRaw,\n strict: structuredOutputConfig.strict !== false,\n });\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n while (attempts <= maxRetries) {\n try {\n const result = await structuredModel.invoke(finalMessages, config);\n\n // Handle includeRaw response format\n if (includeRaw && result.raw && result.parsed) {\n return {\n structuredResponse: result.parsed as Record<string, unknown>,\n rawMessage: result.raw as AIMessageChunk,\n };\n }\n\n // Direct response\n return {\n structuredResponse: result as Record<string, unknown>,\n };\n } catch (error) {\n lastError = error as Error;\n attempts++;\n\n // If error handling is disabled, throw immediately\n if (handleErrors === false) {\n throw error;\n }\n\n // If we've exhausted retries, throw\n if (attempts > maxRetries) {\n throw new Error(\n `Structured output failed after ${maxRetries + 1} attempts: ${lastError.message}`\n );\n }\n\n // Add error message to conversation for retry\n const errorMessage =\n typeof handleErrors === 'string'\n ? handleErrors\n : `The response did not match the expected schema. Error: ${lastError.message}. Please try again with a valid response.`;\n\n console.warn(\n `[Graph] Structured output attempt ${attempts} failed: ${lastError.message}. Retrying...`\n );\n\n // Add the error as a human message for context\n finalMessages = [\n ...finalMessages,\n new HumanMessage({\n content: `[VALIDATION ERROR]\\n${errorMessage}`,\n }),\n ];\n }\n }\n\n throw lastError ?? new Error('Structured output failed');\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n let { messages } = state;\n\n // CACHE OPTIMIZATION: Inject dynamicContext as a HumanMessage at the start of conversation\n // This keeps the system message static (cacheable) while providing dynamic context\n // (timestamps, user info, tool context) as conversation content instead.\n // Only inject on the first turn when messages don't already have the context marker.\n if (\n agentContext.dynamicContext &&\n messages.length > 0 &&\n !messages.some(\n (m) =>\n m instanceof HumanMessage &&\n typeof m.content === 'string' &&\n m.content.startsWith('[SESSION_CONTEXT]')\n )\n ) {\n const dynamicContextMessage = new HumanMessage({\n content: `[SESSION_CONTEXT]\\n${agentContext.dynamicContext}`,\n });\n const ackMessage = new AIMessageChunk({\n content:\n 'Understood. I have noted the session context including the current date/time (CST) and will apply it appropriately.',\n });\n messages = [dynamicContextMessage, ackMessage, ...messages];\n }\n\n // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY?.getType() === MessageTypes.TOOL &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n // Use getType() instead of instanceof to avoid module mismatch issues\n const isLatestToolMessage = lastMessageY?.getType() === MessageTypes.TOOL;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n *\n * IMPORTANT: This MUST happen BEFORE cache control is applied.\n * If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,\n * the cachePoint is lost. By converting first, we ensure cache control is applied to the\n * final message structure that will be sent to the API.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n // Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost\n // when AI messages are converted to HumanMessages\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === true) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Both Claude and Nova models support cachePoint in system and messages\n // (Llama, Titan, and other models do NOT support cachePoint)\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n // Get model info for analytics\n const bedrockOpts = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId =\n bedrockOpts?.model ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.modelName;\n const thinkingConfig =\n bedrockOpts?.additionalModelRequestFields?.['thinking'] ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.thinking;\n\n // Build and emit context analytics for traces\n const contextAnalytics = buildContextAnalytics(finalMessages, {\n tokenCounter: agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n instructionTokens: agentContext.instructionTokens,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n\n // Store for retrieval via getContextAnalytics() after run completes\n this.lastContextAnalytics = contextAnalytics;\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_ANALYTICS,\n {\n provider: agentContext.provider,\n model: modelId,\n thinkingEnabled: thinkingConfig != null,\n cacheEnabled: bedrockOpts?.promptCache === true,\n analytics: contextAnalytics,\n },\n config\n );\n\n // Check if structured output mode is enabled\n if (\n agentContext.isStructuredOutputMode &&\n agentContext.structuredOutput\n ) {\n const schema = agentContext.getStructuredOutputSchema();\n if (!schema) {\n throw new Error('Structured output schema is not configured');\n }\n\n try {\n // Use structured output invocation (non-streaming)\n // Get a fresh model WITHOUT tools bound - bindTools() returns RunnableBinding which lacks withStructuredOutput\n // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled\n const structuredClientOptions = { ...agentContext.clientOptions } as t.ClientOptions;\n\n // Remove thinking configuration for Bedrock\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOpts = structuredClientOptions as t.BedrockAnthropicClientOptions;\n if (bedrockOpts.additionalModelRequestFields?.['thinking']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields) as any;\n delete additionalFields.thinking;\n bedrockOpts.additionalModelRequestFields = additionalFields;\n }\n }\n\n // Remove thinking configuration for Anthropic\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOpts = structuredClientOptions as t.AnthropicClientOptions;\n if (anthropicOpts.thinking) {\n delete anthropicOpts.thinking;\n }\n }\n\n const structuredModel = this.getNewModel({\n provider: agentContext.provider,\n clientOptions: structuredClientOptions,\n });\n\n const { structuredResponse, rawMessage } =\n await this.attemptStructuredInvoke(\n {\n currentModel: structuredModel,\n finalMessages,\n schema,\n structuredOutputConfig: agentContext.structuredOutput,\n provider: agentContext.provider,\n },\n config\n );\n\n // Emit structured output event\n await safeDispatchCustomEvent(\n GraphEvents.ON_STRUCTURED_OUTPUT,\n {\n structuredResponse,\n schema,\n raw: rawMessage,\n },\n config\n );\n\n agentContext.currentUsage = rawMessage\n ? this.getUsageMetadata(rawMessage)\n : undefined;\n this.cleanupSignalListener();\n\n // Return both the structured response and the raw message\n return {\n messages: rawMessage ? [rawMessage] : [],\n structuredResponse,\n };\n } catch (structuredError) {\n console.error('[Graph] Structured output failed:', structuredError);\n throw structuredError;\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n // Check if this is a \"input too long\" error from Bedrock/Anthropic\n const errorMessage =\n (primaryError as Error).message.toLowerCase() ?? '';\n const isInputTooLongError =\n errorMessage.includes('too long') ||\n errorMessage.includes('input is too long') ||\n errorMessage.includes('context length') ||\n errorMessage.includes('maximum context') ||\n errorMessage.includes('validationexception') ||\n errorMessage.includes('prompt is too long');\n\n // Log when we detect the error\n if (isInputTooLongError) {\n console.warn(\n '[Graph] Detected input too long error:',\n errorMessage.substring(0, 200)\n );\n console.warn('[Graph] Checking emergency pruning conditions:', {\n hasPruneMessages: !!agentContext.pruneMessages,\n hasTokenCounter: !!agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)\n .length,\n });\n }\n\n // If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning\n // Note: We can create emergency pruneMessages dynamically if we have tokenCounter and maxContextTokens\n const canPrune =\n agentContext.tokenCounter && agentContext.maxContextTokens;\n if (isInputTooLongError && canPrune) {\n // Progressive reduction: 50% -> 25% -> 10% of original context\n const reductionLevels = [0.5, 0.25, 0.1];\n\n for (const reductionFactor of reductionLevels) {\n if (result) break; // Exit if we got a result\n\n const reducedMaxTokens = Math.floor(\n agentContext.maxContextTokens! * reductionFactor\n );\n console.warn(\n `[Graph] Input too long. Retrying with ${reductionFactor * 100}% context (${reducedMaxTokens} tokens)...`\n );\n\n // Build fresh indexTokenCountMap if missing/incomplete\n // This is needed when messages were dynamically added without updating the token map\n let tokenMapForPruning = agentContext.indexTokenCountMap;\n if (Object.keys(tokenMapForPruning).length < messages.length) {\n console.warn(\n '[Graph] Building fresh token count map for emergency pruning...'\n );\n tokenMapForPruning = {};\n for (let i = 0; i < messages.length; i++) {\n tokenMapForPruning[i] = agentContext.tokenCounter!(messages[i]);\n }\n }\n\n const emergencyPrune = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter!,\n maxTokens: reducedMaxTokens,\n thinkingEnabled: false, // Disable thinking for emergency prune\n indexTokenCountMap: tokenMapForPruning,\n });\n\n const { context: reducedMessages } = emergencyPrune({\n messages,\n usageMetadata: agentContext.currentUsage,\n });\n\n // Skip if we can't fit any messages\n if (reducedMessages.length === 0) {\n console.warn(\n `[Graph] Cannot fit any messages at ${reductionFactor * 100}% reduction, trying next level...`\n );\n continue;\n }\n\n // Calculate how many messages were pruned and estimate context timeframe\n const prunedCount = finalMessages.length - reducedMessages.length;\n const remainingCount = reducedMessages.length;\n const estimatedContextDescription =\n this.getContextTimeframeDescription(remainingCount);\n\n // Inject a personalized context message to inform the agent about pruning\n const pruneNoticeMessage = new HumanMessage({\n content: `[CONTEXT NOTICE]\nOur conversation has grown quite long, so I've focused on ${estimatedContextDescription} of our chat (${remainingCount} recent messages). ${prunedCount} earlier messages are no longer in my immediate memory.\n\nIf I seem to be missing something we discussed earlier, just give me a quick reminder and I'll pick right back up! I'm still fully engaged and ready to help with whatever you need.`,\n });\n\n // Insert the notice after the system message (if any) but before conversation\n const hasSystemMessage = reducedMessages[0]?.getType() === 'system';\n const insertIndex = hasSystemMessage ? 1 : 0;\n\n // Create new array with the pruning notice\n const messagesWithNotice = [\n ...reducedMessages.slice(0, insertIndex),\n pruneNoticeMessage,\n ...reducedMessages.slice(insertIndex),\n ];\n\n let retryMessages = agentContext.useLegacyContent\n ? formatContentStrings(messagesWithNotice)\n : messagesWithNotice;\n\n // Apply thinking block handling first (before cache control)\n // This ensures AI+Tool sequences are converted to HumanMessages\n // before we add cache points that could be lost in the conversion\n if (isAnthropicWithThinking) {\n retryMessages = ensureThinkingBlockInMessages(\n retryMessages,\n agentContext.provider\n );\n }\n\n // Apply Bedrock cache control if needed (after thinking block handling)\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n retryMessages =\n addBedrockCacheControl<BaseMessage>(retryMessages);\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages: retryMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n // Success with reduced context\n console.info(\n `[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`\n );\n } catch (retryError) {\n const retryErrorMsg =\n (retryError as Error).message.toLowerCase() ?? '';\n const stillTooLong =\n retryErrorMsg.includes('too long') ||\n retryErrorMsg.includes('context length') ||\n retryErrorMsg.includes('validationexception');\n\n if (stillTooLong && reductionFactor > 0.1) {\n console.warn(\n `[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`\n );\n } else {\n console.error(\n `[Graph] Retry at ${reductionFactor * 100}% failed:`,\n (retryError as Error).message\n );\n }\n }\n }\n }\n\n // If we got a result from retry, skip fallbacks\n if (result) {\n // result already set from retry\n } else {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract agentId and parallelGroupId from metadata\n * Only set agentId for MultiAgentGraph (so frontend knows when to show agent labels)\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n // Only include agentId for MultiAgentGraph - enables frontend to show agent labels\n runStep.agentId = agentContext.agentId;\n // Set group ID if this agent is part of a parallel group\n // Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order\n const groupId = this.getParallelGroupIdForAgent(agentContext.agentId);\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n /**\n * Extract and store code execution session context from artifacts.\n * Each file is stamped with its source session_id to support multi-session file tracking.\n * When the same filename appears in a later execution, the newer version replaces the old.\n */\n const toolName = output.name;\n if (\n toolName === Constants.EXECUTE_CODE ||\n toolName === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const artifact = output.artifact as t.CodeExecutionArtifact | undefined;\n const newFiles = artifact?.files ?? [];\n const hasNewFiles = newFiles.length > 0;\n\n if (\n hasNewFiles &&\n artifact?.session_id != null &&\n artifact.session_id !== ''\n ) {\n /**\n * Stamp each new file with its source session_id.\n * This enables files from different executions (parallel or sequential)\n * to be tracked and passed to subsequent calls.\n */\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n /**\n * Merge files, preferring latest versions by name.\n * If a file with the same name exists, replace it with the new version.\n * This handles cases where files are edited/recreated in subsequent executions.\n */\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n /** Keep latest session_id for reference/fallback */\n session_id: artifact.session_id,\n /** Accumulated files with latest versions preferred */\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n }\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["GraphNodeKeys","AgentContext","resetIfNotEmpty","joinKeys","nanoid","ContentTypes","convertMessagesToContent","Providers","SystemMessage","RunnableLambda","createSchemaOnlyTools","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","manualToolStreamProviders","stream","safeDispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","HumanMessage","messages","AIMessageChunk","extractToolDiscoveries","createPruneMessages","formatContentStrings","MessageTypes","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","ensureThinkingBlockInMessages","addCacheControl","addBedrockCacheControl","sleep","contextAnalytics","buildContextAnalytics","toolsCondition","Annotation","messagesStateReducer","StateGraph","START","END","StepTypes","Constants"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAwEA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa;MAEhB,KAAK,CAAA;AA0DzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;AACf;;;;AAIG;AACH,IAAA,QAAQ,GAAqB,IAAI,GAAG,EAAE;AACvC;AAEK,MAAO,aAAc,SAAQ,KAAoC,CAAA;AACrE,IAAA,aAAa;;AAEb,IAAA,cAAc;IACd,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;IACL,UAAU,GAAW,CAAC;AACtB,IAAA,MAAM;;AAEN,IAAA,aAAa,GAA8B,IAAI,GAAG,EAAE;;AAEpD,IAAA,cAAc;IAEd,WAAY,CAAA;;IAEV,KAAK,EACL,MAAM,EACN,MAAM,EACN,YAAY,EACZ,kBAAkB,GACG,EAAA;AACrB,QAAA,KAAK,EAAE;AACP,QAAA,IAAI,CAAC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AAuB,CAC3BC,iBAAW,CAAC,gBAAgB,EAC5B,YAAY,EACZ,IAAI,CAAC,MAAM,CACZ;;AAGH,IAAA,sBAAsB,GAAG,OACvB,MAAc,EACd,KAAuB,KACN;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;AACD,QAAA,MAAMD,8BAAuB,CAC3BC,iBAAW,CAAC,kBAAkB,EAC9B,cAAc,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;;"}
1
+ {"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n HumanMessage,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n MessageTypes,\n Constants,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n extractToolDiscoveries,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n buildContextAnalytics,\n type ContextAnalytics,\n} from '@/utils/contextAnalytics';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /**\n * Estimates a human-friendly description of the conversation timeframe based on message count.\n * Uses rough heuristics to provide context about how much history is available.\n *\n * @param messageCount - Number of messages in the remaining context\n * @returns A friendly description like \"the last few minutes\", \"the past hour\", etc.\n */\n getContextTimeframeDescription(messageCount: number): string {\n // Rough heuristics based on typical conversation patterns:\n // - Very active chat: ~20-30 messages per hour\n // - Normal chat: ~10-15 messages per hour\n // - Slow/thoughtful chat: ~5-8 messages per hour\n // We use a middle estimate of ~12 messages per hour\n\n if (messageCount <= 5) {\n return 'just the last few exchanges';\n } else if (messageCount <= 15) {\n return 'the last several minutes';\n } else if (messageCount <= 30) {\n return 'roughly the past hour';\n } else if (messageCount <= 60) {\n return 'the past couple of hours';\n } else if (messageCount <= 150) {\n return 'the past few hours';\n } else if (messageCount <= 300) {\n return 'roughly a day\\'s worth';\n } else if (messageCount <= 700) {\n return 'the past few days';\n } else {\n return 'about a week or more';\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /**\n * Get the context breakdown from the primary agent for admin token tracking.\n * Returns detailed token counts for instructions, tools, etc.\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 } | null {\n const primaryContext = this.agentContexts.get(this.defaultAgentId);\n if (!primaryContext) {\n return null;\n }\n return primaryContext.getContextBreakdown();\n }\n\n /**\n * Get the latest context analytics from the graph.\n * Returns metrics like utilization %, TOON stats, message breakdown.\n */\n getContextAnalytics(): ContextAnalytics | null {\n return this.lastContextAnalytics ?? null;\n }\n\n /** Store the latest context analytics for retrieval after run */\n private lastContextAnalytics: ContextAnalytics | null = null;\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n (clientOptions as t.AnthropicClientOptions).promptCache === true\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: schemaTools as t.GenericTool[],\n toolMap: new Map(schemaTools.map((tool) => [tool.name, tool])),\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n eventDrivenMode: true,\n toolDefinitions: toolDefMap,\n agentId: agentContext?.agentId,\n });\n }\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n /**\n * Execute model invocation with structured output.\n * Uses withStructuredOutput to force the model to return JSON conforming to the schema.\n * Disables streaming and returns a validated JSON response.\n */\n private async attemptStructuredInvoke(\n {\n currentModel,\n finalMessages,\n schema,\n structuredOutputConfig,\n provider,\n }: {\n currentModel: t.ChatModelInstance;\n finalMessages: BaseMessage[];\n schema: Record<string, unknown>;\n structuredOutputConfig: t.StructuredOutputConfig;\n provider?: Providers;\n },\n config?: RunnableConfig\n ): Promise<{\n structuredResponse: Record<string, unknown>;\n rawMessage?: AIMessageChunk;\n }> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n // Check if model supports withStructuredOutput\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (model as any).withStructuredOutput !== 'function') {\n throw new Error(\n `The selected model does not support structured output. ` +\n `Please use a model that supports JSON schema output (e.g., OpenAI GPT-4, Anthropic Claude, Google Gemini) ` +\n `or disable structured output for this agent.`\n );\n }\n\n const {\n name = 'StructuredResponse',\n mode = 'auto',\n includeRaw = false,\n handleErrors = true,\n maxRetries = 2,\n } = structuredOutputConfig;\n\n // Determine the method based on mode and provider\n // - 'tool' / 'functionCalling': Use tool calling (works with OpenAI, Bedrock)\n // - 'provider' / 'jsonMode': Use native JSON mode (OpenAI, Anthropic direct - NOT Bedrock)\n // - 'auto': Auto-detect based on provider\n // NOTE: ChatBedrockConverse does NOT support 'jsonMode' - it only supports tool-based structured output\n let method: 'functionCalling' | 'jsonMode' | 'jsonSchema' | undefined;\n \n if (mode === 'tool') {\n method = 'functionCalling';\n } else if (mode === 'provider') {\n // Use native JSON mode - but NOT for Bedrock which doesn't support it\n if (provider === Providers.BEDROCK) {\n // Bedrock only supports function calling for structured output\n method = 'functionCalling';\n } else {\n method = 'jsonMode';\n }\n } else {\n // Auto mode: use function calling for all providers\n // This is the most compatible approach\n // Bedrock: only supports functionCalling\n // Anthropic direct: supports both but functionCalling is more reliable\n // OpenAI/Azure: supports both, functionCalling is default\n // Google/Vertex: supports jsonMode but functionCalling works too\n method = undefined; // Let LangChain choose the default\n }\n\n // Use withStructuredOutput to bind the schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const structuredModel = (model as any).withStructuredOutput(schema, {\n name,\n method,\n includeRaw,\n strict: structuredOutputConfig.strict !== false,\n });\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n while (attempts <= maxRetries) {\n try {\n const result = await structuredModel.invoke(finalMessages, config);\n\n // Handle includeRaw response format\n if (includeRaw && result.raw && result.parsed) {\n return {\n structuredResponse: result.parsed as Record<string, unknown>,\n rawMessage: result.raw as AIMessageChunk,\n };\n }\n\n // Direct response\n return {\n structuredResponse: result as Record<string, unknown>,\n };\n } catch (error) {\n lastError = error as Error;\n attempts++;\n\n // If error handling is disabled, throw immediately\n if (handleErrors === false) {\n throw error;\n }\n\n // If we've exhausted retries, throw\n if (attempts > maxRetries) {\n throw new Error(\n `Structured output failed after ${maxRetries + 1} attempts: ${lastError.message}`\n );\n }\n\n // Add error message to conversation for retry\n const errorMessage =\n typeof handleErrors === 'string'\n ? handleErrors\n : `The response did not match the expected schema. Error: ${lastError.message}. Please try again with a valid response.`;\n\n console.warn(\n `[Graph] Structured output attempt ${attempts} failed: ${lastError.message}. Retrying...`\n );\n\n // Add the error as a human message for context\n finalMessages = [\n ...finalMessages,\n new HumanMessage({\n content: `[VALIDATION ERROR]\\n${errorMessage}`,\n }),\n ];\n }\n }\n\n throw lastError ?? new Error('Structured output failed');\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n let { messages } = state;\n\n // CACHE OPTIMIZATION: Inject dynamicContext as a HumanMessage at the start of conversation\n // This keeps the system message static (cacheable) while providing dynamic context\n // (timestamps, user info, tool context) as conversation content instead.\n // Only inject on the first turn when messages don't already have the context marker.\n if (\n agentContext.dynamicContext &&\n messages.length > 0 &&\n !messages.some(\n (m) =>\n m instanceof HumanMessage &&\n typeof m.content === 'string' &&\n m.content.startsWith('[SESSION_CONTEXT]')\n )\n ) {\n const dynamicContextMessage = new HumanMessage({\n content: `[SESSION_CONTEXT]\\n${agentContext.dynamicContext}`,\n });\n const ackMessage = new AIMessageChunk({\n content:\n 'Understood. I have noted the session context including the current date/time (CST) and will apply it appropriately.',\n });\n messages = [dynamicContextMessage, ackMessage, ...messages];\n }\n\n // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY?.getType() === MessageTypes.TOOL &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n // Use getType() instead of instanceof to avoid module mismatch issues\n const isLatestToolMessage = lastMessageY?.getType() === MessageTypes.TOOL;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n *\n * IMPORTANT: This MUST happen BEFORE cache control is applied.\n * If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,\n * the cachePoint is lost. By converting first, we ensure cache control is applied to the\n * final message structure that will be sent to the API.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n // Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost\n // when AI messages are converted to HumanMessages\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === true) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Both Claude and Nova models support cachePoint in system and messages\n // (Llama, Titan, and other models do NOT support cachePoint)\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n // Get model info for analytics\n const bedrockOpts = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId =\n bedrockOpts?.model ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.modelName;\n const thinkingConfig =\n bedrockOpts?.additionalModelRequestFields?.['thinking'] ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.thinking;\n\n // Build and emit context analytics for traces\n const contextAnalytics = buildContextAnalytics(finalMessages, {\n tokenCounter: agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n instructionTokens: agentContext.instructionTokens,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n\n // Store for retrieval via getContextAnalytics() after run completes\n this.lastContextAnalytics = contextAnalytics;\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_ANALYTICS,\n {\n provider: agentContext.provider,\n model: modelId,\n thinkingEnabled: thinkingConfig != null,\n cacheEnabled: bedrockOpts?.promptCache === true,\n analytics: contextAnalytics,\n },\n config\n );\n\n // Check if structured output mode is enabled\n if (\n agentContext.isStructuredOutputMode &&\n agentContext.structuredOutput\n ) {\n const schema = agentContext.getStructuredOutputSchema();\n if (!schema) {\n throw new Error('Structured output schema is not configured');\n }\n\n try {\n // Use structured output invocation (non-streaming)\n // Get a fresh model WITHOUT tools bound - bindTools() returns RunnableBinding which lacks withStructuredOutput\n // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled\n const structuredClientOptions = { ...agentContext.clientOptions } as t.ClientOptions;\n\n // Remove thinking configuration for Bedrock\n // Bedrock uses additionalModelRequestFields.thinking for extended thinking\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOpts = structuredClientOptions as t.BedrockAnthropicClientOptions;\n if (bedrockOpts.additionalModelRequestFields) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields) as any;\n // Remove thinking configuration\n delete additionalFields.thinking;\n // Remove budget tokens which is also related to thinking\n delete additionalFields.budgetTokens;\n bedrockOpts.additionalModelRequestFields = additionalFields;\n }\n }\n\n // Remove thinking configuration for Anthropic direct API\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOpts = structuredClientOptions as t.AnthropicClientOptions;\n if (anthropicOpts.thinking) {\n delete anthropicOpts.thinking;\n }\n }\n\n console.log('[Graph] Creating structured model for provider:', agentContext.provider, 'with options:', JSON.stringify(structuredClientOptions, null, 2));\n\n const structuredModel = this.getNewModel({\n provider: agentContext.provider,\n clientOptions: structuredClientOptions,\n });\n\n const { structuredResponse, rawMessage } =\n await this.attemptStructuredInvoke(\n {\n currentModel: structuredModel,\n finalMessages,\n schema,\n structuredOutputConfig: agentContext.structuredOutput,\n provider: agentContext.provider,\n },\n config\n );\n\n // Emit structured output event\n await safeDispatchCustomEvent(\n GraphEvents.ON_STRUCTURED_OUTPUT,\n {\n structuredResponse,\n schema,\n raw: rawMessage,\n },\n config\n );\n\n agentContext.currentUsage = rawMessage\n ? this.getUsageMetadata(rawMessage)\n : undefined;\n this.cleanupSignalListener();\n\n // Return both the structured response and the raw message\n return {\n messages: rawMessage ? [rawMessage] : [],\n structuredResponse,\n };\n } catch (structuredError) {\n console.error('[Graph] Structured output failed:', structuredError);\n throw structuredError;\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n // Check if this is a \"input too long\" error from Bedrock/Anthropic\n const errorMessage =\n (primaryError as Error).message.toLowerCase() ?? '';\n const isInputTooLongError =\n errorMessage.includes('too long') ||\n errorMessage.includes('input is too long') ||\n errorMessage.includes('context length') ||\n errorMessage.includes('maximum context') ||\n errorMessage.includes('validationexception') ||\n errorMessage.includes('prompt is too long');\n\n // Log when we detect the error\n if (isInputTooLongError) {\n console.warn(\n '[Graph] Detected input too long error:',\n errorMessage.substring(0, 200)\n );\n console.warn('[Graph] Checking emergency pruning conditions:', {\n hasPruneMessages: !!agentContext.pruneMessages,\n hasTokenCounter: !!agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)\n .length,\n });\n }\n\n // If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning\n // Note: We can create emergency pruneMessages dynamically if we have tokenCounter and maxContextTokens\n const canPrune =\n agentContext.tokenCounter && agentContext.maxContextTokens;\n if (isInputTooLongError && canPrune) {\n // Progressive reduction: 50% -> 25% -> 10% of original context\n const reductionLevels = [0.5, 0.25, 0.1];\n\n for (const reductionFactor of reductionLevels) {\n if (result) break; // Exit if we got a result\n\n const reducedMaxTokens = Math.floor(\n agentContext.maxContextTokens! * reductionFactor\n );\n console.warn(\n `[Graph] Input too long. Retrying with ${reductionFactor * 100}% context (${reducedMaxTokens} tokens)...`\n );\n\n // Build fresh indexTokenCountMap if missing/incomplete\n // This is needed when messages were dynamically added without updating the token map\n let tokenMapForPruning = agentContext.indexTokenCountMap;\n if (Object.keys(tokenMapForPruning).length < messages.length) {\n console.warn(\n '[Graph] Building fresh token count map for emergency pruning...'\n );\n tokenMapForPruning = {};\n for (let i = 0; i < messages.length; i++) {\n tokenMapForPruning[i] = agentContext.tokenCounter!(messages[i]);\n }\n }\n\n const emergencyPrune = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter!,\n maxTokens: reducedMaxTokens,\n thinkingEnabled: false, // Disable thinking for emergency prune\n indexTokenCountMap: tokenMapForPruning,\n });\n\n const { context: reducedMessages } = emergencyPrune({\n messages,\n usageMetadata: agentContext.currentUsage,\n });\n\n // Skip if we can't fit any messages\n if (reducedMessages.length === 0) {\n console.warn(\n `[Graph] Cannot fit any messages at ${reductionFactor * 100}% reduction, trying next level...`\n );\n continue;\n }\n\n // Calculate how many messages were pruned and estimate context timeframe\n const prunedCount = finalMessages.length - reducedMessages.length;\n const remainingCount = reducedMessages.length;\n const estimatedContextDescription =\n this.getContextTimeframeDescription(remainingCount);\n\n // Inject a personalized context message to inform the agent about pruning\n const pruneNoticeMessage = new HumanMessage({\n content: `[CONTEXT NOTICE]\nOur conversation has grown quite long, so I've focused on ${estimatedContextDescription} of our chat (${remainingCount} recent messages). ${prunedCount} earlier messages are no longer in my immediate memory.\n\nIf I seem to be missing something we discussed earlier, just give me a quick reminder and I'll pick right back up! I'm still fully engaged and ready to help with whatever you need.`,\n });\n\n // Insert the notice after the system message (if any) but before conversation\n const hasSystemMessage = reducedMessages[0]?.getType() === 'system';\n const insertIndex = hasSystemMessage ? 1 : 0;\n\n // Create new array with the pruning notice\n const messagesWithNotice = [\n ...reducedMessages.slice(0, insertIndex),\n pruneNoticeMessage,\n ...reducedMessages.slice(insertIndex),\n ];\n\n let retryMessages = agentContext.useLegacyContent\n ? formatContentStrings(messagesWithNotice)\n : messagesWithNotice;\n\n // Apply thinking block handling first (before cache control)\n // This ensures AI+Tool sequences are converted to HumanMessages\n // before we add cache points that could be lost in the conversion\n if (isAnthropicWithThinking) {\n retryMessages = ensureThinkingBlockInMessages(\n retryMessages,\n agentContext.provider\n );\n }\n\n // Apply Bedrock cache control if needed (after thinking block handling)\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n retryMessages =\n addBedrockCacheControl<BaseMessage>(retryMessages);\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages: retryMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n // Success with reduced context\n console.info(\n `[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`\n );\n } catch (retryError) {\n const retryErrorMsg =\n (retryError as Error).message.toLowerCase() ?? '';\n const stillTooLong =\n retryErrorMsg.includes('too long') ||\n retryErrorMsg.includes('context length') ||\n retryErrorMsg.includes('validationexception');\n\n if (stillTooLong && reductionFactor > 0.1) {\n console.warn(\n `[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`\n );\n } else {\n console.error(\n `[Graph] Retry at ${reductionFactor * 100}% failed:`,\n (retryError as Error).message\n );\n }\n }\n }\n }\n\n // If we got a result from retry, skip fallbacks\n if (result) {\n // result already set from retry\n } else {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract agentId and parallelGroupId from metadata\n * Only set agentId for MultiAgentGraph (so frontend knows when to show agent labels)\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n // Only include agentId for MultiAgentGraph - enables frontend to show agent labels\n runStep.agentId = agentContext.agentId;\n // Set group ID if this agent is part of a parallel group\n // Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order\n const groupId = this.getParallelGroupIdForAgent(agentContext.agentId);\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n /**\n * Extract and store code execution session context from artifacts.\n * Each file is stamped with its source session_id to support multi-session file tracking.\n * When the same filename appears in a later execution, the newer version replaces the old.\n */\n const toolName = output.name;\n if (\n toolName === Constants.EXECUTE_CODE ||\n toolName === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const artifact = output.artifact as t.CodeExecutionArtifact | undefined;\n const newFiles = artifact?.files ?? [];\n const hasNewFiles = newFiles.length > 0;\n\n if (\n hasNewFiles &&\n artifact?.session_id != null &&\n artifact.session_id !== ''\n ) {\n /**\n * Stamp each new file with its source session_id.\n * This enables files from different executions (parallel or sequential)\n * to be tracked and passed to subsequent calls.\n */\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n /**\n * Merge files, preferring latest versions by name.\n * If a file with the same name exists, replace it with the new version.\n * This handles cases where files are edited/recreated in subsequent executions.\n */\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n /** Keep latest session_id for reference/fallback */\n session_id: artifact.session_id,\n /** Accumulated files with latest versions preferred */\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n }\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["GraphNodeKeys","AgentContext","resetIfNotEmpty","joinKeys","nanoid","ContentTypes","convertMessagesToContent","Providers","SystemMessage","RunnableLambda","createSchemaOnlyTools","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","manualToolStreamProviders","stream","safeDispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","HumanMessage","messages","AIMessageChunk","extractToolDiscoveries","createPruneMessages","formatContentStrings","MessageTypes","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","ensureThinkingBlockInMessages","addCacheControl","addBedrockCacheControl","sleep","contextAnalytics","buildContextAnalytics","toolsCondition","Annotation","messagesStateReducer","StateGraph","START","END","StepTypes","Constants"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAA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AAE,EAAE,MAAM;YACV,KAAK;SACN;AACD,QAAA,MAAMD,8BAAuB,CAC3BC,iBAAW,CAAC,kBAAkB,EAC9B,cAAc,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;;"}
@@ -454,29 +454,32 @@ class StandardGraph extends Graph {
454
454
  }
455
455
  const { name = 'StructuredResponse', mode = 'auto', includeRaw = false, handleErrors = true, maxRetries = 2, } = structuredOutputConfig;
456
456
  // Determine the method based on mode and provider
457
- // - 'tool': Use tool calling (works well with OpenAI)
458
- // - 'json_mode': Use JSON mode (works well with Bedrock/Anthropic)
457
+ // - 'tool' / 'functionCalling': Use tool calling (works with OpenAI, Bedrock)
458
+ // - 'provider' / 'jsonMode': Use native JSON mode (OpenAI, Anthropic direct - NOT Bedrock)
459
459
  // - 'auto': Auto-detect based on provider
460
+ // NOTE: ChatBedrockConverse does NOT support 'jsonMode' - it only supports tool-based structured output
460
461
  let method;
461
462
  if (mode === 'tool') {
462
463
  method = 'functionCalling';
463
464
  }
464
465
  else if (mode === 'provider') {
465
- // Use native JSON mode - best for Anthropic/Bedrock
466
- method = 'jsonMode';
467
- }
468
- else {
469
- // Auto mode: choose based on provider
470
- // Bedrock and Anthropic work better with JSON mode
471
- // OpenAI, Azure work better with function calling
472
- if (provider === Providers.BEDROCK || provider === Providers.ANTHROPIC) {
473
- method = 'jsonMode';
466
+ // Use native JSON mode - but NOT for Bedrock which doesn't support it
467
+ if (provider === Providers.BEDROCK) {
468
+ // Bedrock only supports function calling for structured output
469
+ method = 'functionCalling';
474
470
  }
475
- else if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI) {
476
- // Gemini supports native JSON mode
471
+ else {
477
472
  method = 'jsonMode';
478
473
  }
479
- // For OpenAI/Azure, leave undefined to use default (function calling)
474
+ }
475
+ else {
476
+ // Auto mode: use function calling for all providers
477
+ // This is the most compatible approach
478
+ // Bedrock: only supports functionCalling
479
+ // Anthropic direct: supports both but functionCalling is more reliable
480
+ // OpenAI/Azure: supports both, functionCalling is default
481
+ // Google/Vertex: supports jsonMode but functionCalling works too
482
+ method = undefined; // Let LangChain choose the default
480
483
  }
481
484
  // Use withStructuredOutput to bind the schema
482
485
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -752,22 +755,27 @@ class StandardGraph extends Graph {
752
755
  // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled
753
756
  const structuredClientOptions = { ...agentContext.clientOptions };
754
757
  // Remove thinking configuration for Bedrock
758
+ // Bedrock uses additionalModelRequestFields.thinking for extended thinking
755
759
  if (agentContext.provider === Providers.BEDROCK) {
756
760
  const bedrockOpts = structuredClientOptions;
757
- if (bedrockOpts.additionalModelRequestFields?.['thinking']) {
761
+ if (bedrockOpts.additionalModelRequestFields) {
758
762
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
759
763
  const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields);
764
+ // Remove thinking configuration
760
765
  delete additionalFields.thinking;
766
+ // Remove budget tokens which is also related to thinking
767
+ delete additionalFields.budgetTokens;
761
768
  bedrockOpts.additionalModelRequestFields = additionalFields;
762
769
  }
763
770
  }
764
- // Remove thinking configuration for Anthropic
771
+ // Remove thinking configuration for Anthropic direct API
765
772
  if (agentContext.provider === Providers.ANTHROPIC) {
766
773
  const anthropicOpts = structuredClientOptions;
767
774
  if (anthropicOpts.thinking) {
768
775
  delete anthropicOpts.thinking;
769
776
  }
770
777
  }
778
+ console.log('[Graph] Creating structured model for provider:', agentContext.provider, 'with options:', JSON.stringify(structuredClientOptions, null, 2));
771
779
  const structuredModel = this.getNewModel({
772
780
  provider: agentContext.provider,
773
781
  clientOptions: structuredClientOptions,
@@ -1 +1 @@
1
- {"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n HumanMessage,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n MessageTypes,\n Constants,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n extractToolDiscoveries,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n buildContextAnalytics,\n type ContextAnalytics,\n} from '@/utils/contextAnalytics';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /**\n * Estimates a human-friendly description of the conversation timeframe based on message count.\n * Uses rough heuristics to provide context about how much history is available.\n *\n * @param messageCount - Number of messages in the remaining context\n * @returns A friendly description like \"the last few minutes\", \"the past hour\", etc.\n */\n getContextTimeframeDescription(messageCount: number): string {\n // Rough heuristics based on typical conversation patterns:\n // - Very active chat: ~20-30 messages per hour\n // - Normal chat: ~10-15 messages per hour\n // - Slow/thoughtful chat: ~5-8 messages per hour\n // We use a middle estimate of ~12 messages per hour\n\n if (messageCount <= 5) {\n return 'just the last few exchanges';\n } else if (messageCount <= 15) {\n return 'the last several minutes';\n } else if (messageCount <= 30) {\n return 'roughly the past hour';\n } else if (messageCount <= 60) {\n return 'the past couple of hours';\n } else if (messageCount <= 150) {\n return 'the past few hours';\n } else if (messageCount <= 300) {\n return 'roughly a day\\'s worth';\n } else if (messageCount <= 700) {\n return 'the past few days';\n } else {\n return 'about a week or more';\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /**\n * Get the context breakdown from the primary agent for admin token tracking.\n * Returns detailed token counts for instructions, tools, etc.\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 } | null {\n const primaryContext = this.agentContexts.get(this.defaultAgentId);\n if (!primaryContext) {\n return null;\n }\n return primaryContext.getContextBreakdown();\n }\n\n /**\n * Get the latest context analytics from the graph.\n * Returns metrics like utilization %, TOON stats, message breakdown.\n */\n getContextAnalytics(): ContextAnalytics | null {\n return this.lastContextAnalytics ?? null;\n }\n\n /** Store the latest context analytics for retrieval after run */\n private lastContextAnalytics: ContextAnalytics | null = null;\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n (clientOptions as t.AnthropicClientOptions).promptCache === true\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: schemaTools as t.GenericTool[],\n toolMap: new Map(schemaTools.map((tool) => [tool.name, tool])),\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n eventDrivenMode: true,\n toolDefinitions: toolDefMap,\n agentId: agentContext?.agentId,\n });\n }\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n /**\n * Execute model invocation with structured output.\n * Uses withStructuredOutput to force the model to return JSON conforming to the schema.\n * Disables streaming and returns a validated JSON response.\n */\n private async attemptStructuredInvoke(\n {\n currentModel,\n finalMessages,\n schema,\n structuredOutputConfig,\n provider,\n }: {\n currentModel: t.ChatModelInstance;\n finalMessages: BaseMessage[];\n schema: Record<string, unknown>;\n structuredOutputConfig: t.StructuredOutputConfig;\n provider?: Providers;\n },\n config?: RunnableConfig\n ): Promise<{\n structuredResponse: Record<string, unknown>;\n rawMessage?: AIMessageChunk;\n }> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n // Check if model supports withStructuredOutput\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (model as any).withStructuredOutput !== 'function') {\n throw new Error(\n `The selected model does not support structured output. ` +\n `Please use a model that supports JSON schema output (e.g., OpenAI GPT-4, Anthropic Claude, Google Gemini) ` +\n `or disable structured output for this agent.`\n );\n }\n\n const {\n name = 'StructuredResponse',\n mode = 'auto',\n includeRaw = false,\n handleErrors = true,\n maxRetries = 2,\n } = structuredOutputConfig;\n\n // Determine the method based on mode and provider\n // - 'tool': Use tool calling (works well with OpenAI)\n // - 'json_mode': Use JSON mode (works well with Bedrock/Anthropic)\n // - 'auto': Auto-detect based on provider\n let method: 'functionCalling' | 'jsonMode' | 'jsonSchema' | undefined;\n \n if (mode === 'tool') {\n method = 'functionCalling';\n } else if (mode === 'provider') {\n // Use native JSON mode - best for Anthropic/Bedrock\n method = 'jsonMode';\n } else {\n // Auto mode: choose based on provider\n // Bedrock and Anthropic work better with JSON mode\n // OpenAI, Azure work better with function calling\n if (provider === Providers.BEDROCK || provider === Providers.ANTHROPIC) {\n method = 'jsonMode';\n } else if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI) {\n // Gemini supports native JSON mode\n method = 'jsonMode';\n }\n // For OpenAI/Azure, leave undefined to use default (function calling)\n }\n\n // Use withStructuredOutput to bind the schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const structuredModel = (model as any).withStructuredOutput(schema, {\n name,\n method,\n includeRaw,\n strict: structuredOutputConfig.strict !== false,\n });\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n while (attempts <= maxRetries) {\n try {\n const result = await structuredModel.invoke(finalMessages, config);\n\n // Handle includeRaw response format\n if (includeRaw && result.raw && result.parsed) {\n return {\n structuredResponse: result.parsed as Record<string, unknown>,\n rawMessage: result.raw as AIMessageChunk,\n };\n }\n\n // Direct response\n return {\n structuredResponse: result as Record<string, unknown>,\n };\n } catch (error) {\n lastError = error as Error;\n attempts++;\n\n // If error handling is disabled, throw immediately\n if (handleErrors === false) {\n throw error;\n }\n\n // If we've exhausted retries, throw\n if (attempts > maxRetries) {\n throw new Error(\n `Structured output failed after ${maxRetries + 1} attempts: ${lastError.message}`\n );\n }\n\n // Add error message to conversation for retry\n const errorMessage =\n typeof handleErrors === 'string'\n ? handleErrors\n : `The response did not match the expected schema. Error: ${lastError.message}. Please try again with a valid response.`;\n\n console.warn(\n `[Graph] Structured output attempt ${attempts} failed: ${lastError.message}. Retrying...`\n );\n\n // Add the error as a human message for context\n finalMessages = [\n ...finalMessages,\n new HumanMessage({\n content: `[VALIDATION ERROR]\\n${errorMessage}`,\n }),\n ];\n }\n }\n\n throw lastError ?? new Error('Structured output failed');\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n let { messages } = state;\n\n // CACHE OPTIMIZATION: Inject dynamicContext as a HumanMessage at the start of conversation\n // This keeps the system message static (cacheable) while providing dynamic context\n // (timestamps, user info, tool context) as conversation content instead.\n // Only inject on the first turn when messages don't already have the context marker.\n if (\n agentContext.dynamicContext &&\n messages.length > 0 &&\n !messages.some(\n (m) =>\n m instanceof HumanMessage &&\n typeof m.content === 'string' &&\n m.content.startsWith('[SESSION_CONTEXT]')\n )\n ) {\n const dynamicContextMessage = new HumanMessage({\n content: `[SESSION_CONTEXT]\\n${agentContext.dynamicContext}`,\n });\n const ackMessage = new AIMessageChunk({\n content:\n 'Understood. I have noted the session context including the current date/time (CST) and will apply it appropriately.',\n });\n messages = [dynamicContextMessage, ackMessage, ...messages];\n }\n\n // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY?.getType() === MessageTypes.TOOL &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n // Use getType() instead of instanceof to avoid module mismatch issues\n const isLatestToolMessage = lastMessageY?.getType() === MessageTypes.TOOL;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n *\n * IMPORTANT: This MUST happen BEFORE cache control is applied.\n * If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,\n * the cachePoint is lost. By converting first, we ensure cache control is applied to the\n * final message structure that will be sent to the API.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n // Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost\n // when AI messages are converted to HumanMessages\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === true) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Both Claude and Nova models support cachePoint in system and messages\n // (Llama, Titan, and other models do NOT support cachePoint)\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n // Get model info for analytics\n const bedrockOpts = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId =\n bedrockOpts?.model ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.modelName;\n const thinkingConfig =\n bedrockOpts?.additionalModelRequestFields?.['thinking'] ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.thinking;\n\n // Build and emit context analytics for traces\n const contextAnalytics = buildContextAnalytics(finalMessages, {\n tokenCounter: agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n instructionTokens: agentContext.instructionTokens,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n\n // Store for retrieval via getContextAnalytics() after run completes\n this.lastContextAnalytics = contextAnalytics;\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_ANALYTICS,\n {\n provider: agentContext.provider,\n model: modelId,\n thinkingEnabled: thinkingConfig != null,\n cacheEnabled: bedrockOpts?.promptCache === true,\n analytics: contextAnalytics,\n },\n config\n );\n\n // Check if structured output mode is enabled\n if (\n agentContext.isStructuredOutputMode &&\n agentContext.structuredOutput\n ) {\n const schema = agentContext.getStructuredOutputSchema();\n if (!schema) {\n throw new Error('Structured output schema is not configured');\n }\n\n try {\n // Use structured output invocation (non-streaming)\n // Get a fresh model WITHOUT tools bound - bindTools() returns RunnableBinding which lacks withStructuredOutput\n // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled\n const structuredClientOptions = { ...agentContext.clientOptions } as t.ClientOptions;\n\n // Remove thinking configuration for Bedrock\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOpts = structuredClientOptions as t.BedrockAnthropicClientOptions;\n if (bedrockOpts.additionalModelRequestFields?.['thinking']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields) as any;\n delete additionalFields.thinking;\n bedrockOpts.additionalModelRequestFields = additionalFields;\n }\n }\n\n // Remove thinking configuration for Anthropic\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOpts = structuredClientOptions as t.AnthropicClientOptions;\n if (anthropicOpts.thinking) {\n delete anthropicOpts.thinking;\n }\n }\n\n const structuredModel = this.getNewModel({\n provider: agentContext.provider,\n clientOptions: structuredClientOptions,\n });\n\n const { structuredResponse, rawMessage } =\n await this.attemptStructuredInvoke(\n {\n currentModel: structuredModel,\n finalMessages,\n schema,\n structuredOutputConfig: agentContext.structuredOutput,\n provider: agentContext.provider,\n },\n config\n );\n\n // Emit structured output event\n await safeDispatchCustomEvent(\n GraphEvents.ON_STRUCTURED_OUTPUT,\n {\n structuredResponse,\n schema,\n raw: rawMessage,\n },\n config\n );\n\n agentContext.currentUsage = rawMessage\n ? this.getUsageMetadata(rawMessage)\n : undefined;\n this.cleanupSignalListener();\n\n // Return both the structured response and the raw message\n return {\n messages: rawMessage ? [rawMessage] : [],\n structuredResponse,\n };\n } catch (structuredError) {\n console.error('[Graph] Structured output failed:', structuredError);\n throw structuredError;\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n // Check if this is a \"input too long\" error from Bedrock/Anthropic\n const errorMessage =\n (primaryError as Error).message.toLowerCase() ?? '';\n const isInputTooLongError =\n errorMessage.includes('too long') ||\n errorMessage.includes('input is too long') ||\n errorMessage.includes('context length') ||\n errorMessage.includes('maximum context') ||\n errorMessage.includes('validationexception') ||\n errorMessage.includes('prompt is too long');\n\n // Log when we detect the error\n if (isInputTooLongError) {\n console.warn(\n '[Graph] Detected input too long error:',\n errorMessage.substring(0, 200)\n );\n console.warn('[Graph] Checking emergency pruning conditions:', {\n hasPruneMessages: !!agentContext.pruneMessages,\n hasTokenCounter: !!agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)\n .length,\n });\n }\n\n // If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning\n // Note: We can create emergency pruneMessages dynamically if we have tokenCounter and maxContextTokens\n const canPrune =\n agentContext.tokenCounter && agentContext.maxContextTokens;\n if (isInputTooLongError && canPrune) {\n // Progressive reduction: 50% -> 25% -> 10% of original context\n const reductionLevels = [0.5, 0.25, 0.1];\n\n for (const reductionFactor of reductionLevels) {\n if (result) break; // Exit if we got a result\n\n const reducedMaxTokens = Math.floor(\n agentContext.maxContextTokens! * reductionFactor\n );\n console.warn(\n `[Graph] Input too long. Retrying with ${reductionFactor * 100}% context (${reducedMaxTokens} tokens)...`\n );\n\n // Build fresh indexTokenCountMap if missing/incomplete\n // This is needed when messages were dynamically added without updating the token map\n let tokenMapForPruning = agentContext.indexTokenCountMap;\n if (Object.keys(tokenMapForPruning).length < messages.length) {\n console.warn(\n '[Graph] Building fresh token count map for emergency pruning...'\n );\n tokenMapForPruning = {};\n for (let i = 0; i < messages.length; i++) {\n tokenMapForPruning[i] = agentContext.tokenCounter!(messages[i]);\n }\n }\n\n const emergencyPrune = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter!,\n maxTokens: reducedMaxTokens,\n thinkingEnabled: false, // Disable thinking for emergency prune\n indexTokenCountMap: tokenMapForPruning,\n });\n\n const { context: reducedMessages } = emergencyPrune({\n messages,\n usageMetadata: agentContext.currentUsage,\n });\n\n // Skip if we can't fit any messages\n if (reducedMessages.length === 0) {\n console.warn(\n `[Graph] Cannot fit any messages at ${reductionFactor * 100}% reduction, trying next level...`\n );\n continue;\n }\n\n // Calculate how many messages were pruned and estimate context timeframe\n const prunedCount = finalMessages.length - reducedMessages.length;\n const remainingCount = reducedMessages.length;\n const estimatedContextDescription =\n this.getContextTimeframeDescription(remainingCount);\n\n // Inject a personalized context message to inform the agent about pruning\n const pruneNoticeMessage = new HumanMessage({\n content: `[CONTEXT NOTICE]\nOur conversation has grown quite long, so I've focused on ${estimatedContextDescription} of our chat (${remainingCount} recent messages). ${prunedCount} earlier messages are no longer in my immediate memory.\n\nIf I seem to be missing something we discussed earlier, just give me a quick reminder and I'll pick right back up! I'm still fully engaged and ready to help with whatever you need.`,\n });\n\n // Insert the notice after the system message (if any) but before conversation\n const hasSystemMessage = reducedMessages[0]?.getType() === 'system';\n const insertIndex = hasSystemMessage ? 1 : 0;\n\n // Create new array with the pruning notice\n const messagesWithNotice = [\n ...reducedMessages.slice(0, insertIndex),\n pruneNoticeMessage,\n ...reducedMessages.slice(insertIndex),\n ];\n\n let retryMessages = agentContext.useLegacyContent\n ? formatContentStrings(messagesWithNotice)\n : messagesWithNotice;\n\n // Apply thinking block handling first (before cache control)\n // This ensures AI+Tool sequences are converted to HumanMessages\n // before we add cache points that could be lost in the conversion\n if (isAnthropicWithThinking) {\n retryMessages = ensureThinkingBlockInMessages(\n retryMessages,\n agentContext.provider\n );\n }\n\n // Apply Bedrock cache control if needed (after thinking block handling)\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n retryMessages =\n addBedrockCacheControl<BaseMessage>(retryMessages);\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages: retryMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n // Success with reduced context\n console.info(\n `[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`\n );\n } catch (retryError) {\n const retryErrorMsg =\n (retryError as Error).message.toLowerCase() ?? '';\n const stillTooLong =\n retryErrorMsg.includes('too long') ||\n retryErrorMsg.includes('context length') ||\n retryErrorMsg.includes('validationexception');\n\n if (stillTooLong && reductionFactor > 0.1) {\n console.warn(\n `[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`\n );\n } else {\n console.error(\n `[Graph] Retry at ${reductionFactor * 100}% failed:`,\n (retryError as Error).message\n );\n }\n }\n }\n }\n\n // If we got a result from retry, skip fallbacks\n if (result) {\n // result already set from retry\n } else {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract agentId and parallelGroupId from metadata\n * Only set agentId for MultiAgentGraph (so frontend knows when to show agent labels)\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n // Only include agentId for MultiAgentGraph - enables frontend to show agent labels\n runStep.agentId = agentContext.agentId;\n // Set group ID if this agent is part of a parallel group\n // Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order\n const groupId = this.getParallelGroupIdForAgent(agentContext.agentId);\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n /**\n * Extract and store code execution session context from artifacts.\n * Each file is stamped with its source session_id to support multi-session file tracking.\n * When the same filename appears in a later execution, the newer version replaces the old.\n */\n const toolName = output.name;\n if (\n toolName === Constants.EXECUTE_CODE ||\n toolName === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const artifact = output.artifact as t.CodeExecutionArtifact | undefined;\n const newFiles = artifact?.files ?? [];\n const hasNewFiles = newFiles.length > 0;\n\n if (\n hasNewFiles &&\n artifact?.session_id != null &&\n artifact.session_id !== ''\n ) {\n /**\n * Stamp each new file with its source session_id.\n * This enables files from different executions (parallel or sequential)\n * to be tracked and passed to subsequent calls.\n */\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n /**\n * Merge files, preferring latest versions by name.\n * If a file with the same name exists, replace it with the new version.\n * This handles cases where files are edited/recreated in subsequent executions.\n */\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n /** Keep latest session_id for reference/fallback */\n session_id: artifact.session_id,\n /** Accumulated files with latest versions preferred */\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n }\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAwEA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAEhB,KAAK,CAAA;AA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;AAEtB,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;aAChC,IAAI,CAAC,EAAE,EAAE;AACd,YAAA,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC;;AAErC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,iBAAiB,EAC7B,YAAY,EACZ,IAAI,CAAC,MAAM,CACZ;;AAGH,IAAA,MAAM,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AAC1D,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,gBAAgB,EAC5B,YAAY,EACZ,IAAI,CAAC,MAAM,CACZ;;AAGH,IAAA,sBAAsB,GAAG,OACvB,MAAc,EACd,KAAuB,KACN;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,kBAAkB,EAC9B,cAAc,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;"}
1
+ {"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n HumanMessage,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n MessageTypes,\n Constants,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n extractToolDiscoveries,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n buildContextAnalytics,\n type ContextAnalytics,\n} from '@/utils/contextAnalytics';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /**\n * Estimates a human-friendly description of the conversation timeframe based on message count.\n * Uses rough heuristics to provide context about how much history is available.\n *\n * @param messageCount - Number of messages in the remaining context\n * @returns A friendly description like \"the last few minutes\", \"the past hour\", etc.\n */\n getContextTimeframeDescription(messageCount: number): string {\n // Rough heuristics based on typical conversation patterns:\n // - Very active chat: ~20-30 messages per hour\n // - Normal chat: ~10-15 messages per hour\n // - Slow/thoughtful chat: ~5-8 messages per hour\n // We use a middle estimate of ~12 messages per hour\n\n if (messageCount <= 5) {\n return 'just the last few exchanges';\n } else if (messageCount <= 15) {\n return 'the last several minutes';\n } else if (messageCount <= 30) {\n return 'roughly the past hour';\n } else if (messageCount <= 60) {\n return 'the past couple of hours';\n } else if (messageCount <= 150) {\n return 'the past few hours';\n } else if (messageCount <= 300) {\n return 'roughly a day\\'s worth';\n } else if (messageCount <= 700) {\n return 'the past few days';\n } else {\n return 'about a week or more';\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /**\n * Get the context breakdown from the primary agent for admin token tracking.\n * Returns detailed token counts for instructions, tools, etc.\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 } | null {\n const primaryContext = this.agentContexts.get(this.defaultAgentId);\n if (!primaryContext) {\n return null;\n }\n return primaryContext.getContextBreakdown();\n }\n\n /**\n * Get the latest context analytics from the graph.\n * Returns metrics like utilization %, TOON stats, message breakdown.\n */\n getContextAnalytics(): ContextAnalytics | null {\n return this.lastContextAnalytics ?? null;\n }\n\n /** Store the latest context analytics for retrieval after run */\n private lastContextAnalytics: ContextAnalytics | null = null;\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n (clientOptions as t.AnthropicClientOptions).promptCache === true\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: schemaTools as t.GenericTool[],\n toolMap: new Map(schemaTools.map((tool) => [tool.name, tool])),\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n eventDrivenMode: true,\n toolDefinitions: toolDefMap,\n agentId: agentContext?.agentId,\n });\n }\n\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n /**\n * Execute model invocation with structured output.\n * Uses withStructuredOutput to force the model to return JSON conforming to the schema.\n * Disables streaming and returns a validated JSON response.\n */\n private async attemptStructuredInvoke(\n {\n currentModel,\n finalMessages,\n schema,\n structuredOutputConfig,\n provider,\n }: {\n currentModel: t.ChatModelInstance;\n finalMessages: BaseMessage[];\n schema: Record<string, unknown>;\n structuredOutputConfig: t.StructuredOutputConfig;\n provider?: Providers;\n },\n config?: RunnableConfig\n ): Promise<{\n structuredResponse: Record<string, unknown>;\n rawMessage?: AIMessageChunk;\n }> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n // Check if model supports withStructuredOutput\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (model as any).withStructuredOutput !== 'function') {\n throw new Error(\n `The selected model does not support structured output. ` +\n `Please use a model that supports JSON schema output (e.g., OpenAI GPT-4, Anthropic Claude, Google Gemini) ` +\n `or disable structured output for this agent.`\n );\n }\n\n const {\n name = 'StructuredResponse',\n mode = 'auto',\n includeRaw = false,\n handleErrors = true,\n maxRetries = 2,\n } = structuredOutputConfig;\n\n // Determine the method based on mode and provider\n // - 'tool' / 'functionCalling': Use tool calling (works with OpenAI, Bedrock)\n // - 'provider' / 'jsonMode': Use native JSON mode (OpenAI, Anthropic direct - NOT Bedrock)\n // - 'auto': Auto-detect based on provider\n // NOTE: ChatBedrockConverse does NOT support 'jsonMode' - it only supports tool-based structured output\n let method: 'functionCalling' | 'jsonMode' | 'jsonSchema' | undefined;\n \n if (mode === 'tool') {\n method = 'functionCalling';\n } else if (mode === 'provider') {\n // Use native JSON mode - but NOT for Bedrock which doesn't support it\n if (provider === Providers.BEDROCK) {\n // Bedrock only supports function calling for structured output\n method = 'functionCalling';\n } else {\n method = 'jsonMode';\n }\n } else {\n // Auto mode: use function calling for all providers\n // This is the most compatible approach\n // Bedrock: only supports functionCalling\n // Anthropic direct: supports both but functionCalling is more reliable\n // OpenAI/Azure: supports both, functionCalling is default\n // Google/Vertex: supports jsonMode but functionCalling works too\n method = undefined; // Let LangChain choose the default\n }\n\n // Use withStructuredOutput to bind the schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const structuredModel = (model as any).withStructuredOutput(schema, {\n name,\n method,\n includeRaw,\n strict: structuredOutputConfig.strict !== false,\n });\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n while (attempts <= maxRetries) {\n try {\n const result = await structuredModel.invoke(finalMessages, config);\n\n // Handle includeRaw response format\n if (includeRaw && result.raw && result.parsed) {\n return {\n structuredResponse: result.parsed as Record<string, unknown>,\n rawMessage: result.raw as AIMessageChunk,\n };\n }\n\n // Direct response\n return {\n structuredResponse: result as Record<string, unknown>,\n };\n } catch (error) {\n lastError = error as Error;\n attempts++;\n\n // If error handling is disabled, throw immediately\n if (handleErrors === false) {\n throw error;\n }\n\n // If we've exhausted retries, throw\n if (attempts > maxRetries) {\n throw new Error(\n `Structured output failed after ${maxRetries + 1} attempts: ${lastError.message}`\n );\n }\n\n // Add error message to conversation for retry\n const errorMessage =\n typeof handleErrors === 'string'\n ? handleErrors\n : `The response did not match the expected schema. Error: ${lastError.message}. Please try again with a valid response.`;\n\n console.warn(\n `[Graph] Structured output attempt ${attempts} failed: ${lastError.message}. Retrying...`\n );\n\n // Add the error as a human message for context\n finalMessages = [\n ...finalMessages,\n new HumanMessage({\n content: `[VALIDATION ERROR]\\n${errorMessage}`,\n }),\n ];\n }\n }\n\n throw lastError ?? new Error('Structured output failed');\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n let { messages } = state;\n\n // CACHE OPTIMIZATION: Inject dynamicContext as a HumanMessage at the start of conversation\n // This keeps the system message static (cacheable) while providing dynamic context\n // (timestamps, user info, tool context) as conversation content instead.\n // Only inject on the first turn when messages don't already have the context marker.\n if (\n agentContext.dynamicContext &&\n messages.length > 0 &&\n !messages.some(\n (m) =>\n m instanceof HumanMessage &&\n typeof m.content === 'string' &&\n m.content.startsWith('[SESSION_CONTEXT]')\n )\n ) {\n const dynamicContextMessage = new HumanMessage({\n content: `[SESSION_CONTEXT]\\n${agentContext.dynamicContext}`,\n });\n const ackMessage = new AIMessageChunk({\n content:\n 'Understood. I have noted the session context including the current date/time (CST) and will apply it appropriately.',\n });\n messages = [dynamicContextMessage, ackMessage, ...messages];\n }\n\n // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY?.getType() === MessageTypes.TOOL &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n // Use getType() instead of instanceof to avoid module mismatch issues\n const isLatestToolMessage = lastMessageY?.getType() === MessageTypes.TOOL;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n *\n * IMPORTANT: This MUST happen BEFORE cache control is applied.\n * If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,\n * the cachePoint is lost. By converting first, we ensure cache control is applied to the\n * final message structure that will be sent to the API.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n // Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost\n // when AI messages are converted to HumanMessages\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === true) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Both Claude and Nova models support cachePoint in system and messages\n // (Llama, Titan, and other models do NOT support cachePoint)\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n // Get model info for analytics\n const bedrockOpts = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId =\n bedrockOpts?.model ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.modelName;\n const thinkingConfig =\n bedrockOpts?.additionalModelRequestFields?.['thinking'] ||\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.thinking;\n\n // Build and emit context analytics for traces\n const contextAnalytics = buildContextAnalytics(finalMessages, {\n tokenCounter: agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n instructionTokens: agentContext.instructionTokens,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n\n // Store for retrieval via getContextAnalytics() after run completes\n this.lastContextAnalytics = contextAnalytics;\n\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_ANALYTICS,\n {\n provider: agentContext.provider,\n model: modelId,\n thinkingEnabled: thinkingConfig != null,\n cacheEnabled: bedrockOpts?.promptCache === true,\n analytics: contextAnalytics,\n },\n config\n );\n\n // Check if structured output mode is enabled\n if (\n agentContext.isStructuredOutputMode &&\n agentContext.structuredOutput\n ) {\n const schema = agentContext.getStructuredOutputSchema();\n if (!schema) {\n throw new Error('Structured output schema is not configured');\n }\n\n try {\n // Use structured output invocation (non-streaming)\n // Get a fresh model WITHOUT tools bound - bindTools() returns RunnableBinding which lacks withStructuredOutput\n // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled\n const structuredClientOptions = { ...agentContext.clientOptions } as t.ClientOptions;\n\n // Remove thinking configuration for Bedrock\n // Bedrock uses additionalModelRequestFields.thinking for extended thinking\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOpts = structuredClientOptions as t.BedrockAnthropicClientOptions;\n if (bedrockOpts.additionalModelRequestFields) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields) as any;\n // Remove thinking configuration\n delete additionalFields.thinking;\n // Remove budget tokens which is also related to thinking\n delete additionalFields.budgetTokens;\n bedrockOpts.additionalModelRequestFields = additionalFields;\n }\n }\n\n // Remove thinking configuration for Anthropic direct API\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOpts = structuredClientOptions as t.AnthropicClientOptions;\n if (anthropicOpts.thinking) {\n delete anthropicOpts.thinking;\n }\n }\n\n console.log('[Graph] Creating structured model for provider:', agentContext.provider, 'with options:', JSON.stringify(structuredClientOptions, null, 2));\n\n const structuredModel = this.getNewModel({\n provider: agentContext.provider,\n clientOptions: structuredClientOptions,\n });\n\n const { structuredResponse, rawMessage } =\n await this.attemptStructuredInvoke(\n {\n currentModel: structuredModel,\n finalMessages,\n schema,\n structuredOutputConfig: agentContext.structuredOutput,\n provider: agentContext.provider,\n },\n config\n );\n\n // Emit structured output event\n await safeDispatchCustomEvent(\n GraphEvents.ON_STRUCTURED_OUTPUT,\n {\n structuredResponse,\n schema,\n raw: rawMessage,\n },\n config\n );\n\n agentContext.currentUsage = rawMessage\n ? this.getUsageMetadata(rawMessage)\n : undefined;\n this.cleanupSignalListener();\n\n // Return both the structured response and the raw message\n return {\n messages: rawMessage ? [rawMessage] : [],\n structuredResponse,\n };\n } catch (structuredError) {\n console.error('[Graph] Structured output failed:', structuredError);\n throw structuredError;\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n // Check if this is a \"input too long\" error from Bedrock/Anthropic\n const errorMessage =\n (primaryError as Error).message.toLowerCase() ?? '';\n const isInputTooLongError =\n errorMessage.includes('too long') ||\n errorMessage.includes('input is too long') ||\n errorMessage.includes('context length') ||\n errorMessage.includes('maximum context') ||\n errorMessage.includes('validationexception') ||\n errorMessage.includes('prompt is too long');\n\n // Log when we detect the error\n if (isInputTooLongError) {\n console.warn(\n '[Graph] Detected input too long error:',\n errorMessage.substring(0, 200)\n );\n console.warn('[Graph] Checking emergency pruning conditions:', {\n hasPruneMessages: !!agentContext.pruneMessages,\n hasTokenCounter: !!agentContext.tokenCounter,\n maxContextTokens: agentContext.maxContextTokens,\n indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)\n .length,\n });\n }\n\n // If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning\n // Note: We can create emergency pruneMessages dynamically if we have tokenCounter and maxContextTokens\n const canPrune =\n agentContext.tokenCounter && agentContext.maxContextTokens;\n if (isInputTooLongError && canPrune) {\n // Progressive reduction: 50% -> 25% -> 10% of original context\n const reductionLevels = [0.5, 0.25, 0.1];\n\n for (const reductionFactor of reductionLevels) {\n if (result) break; // Exit if we got a result\n\n const reducedMaxTokens = Math.floor(\n agentContext.maxContextTokens! * reductionFactor\n );\n console.warn(\n `[Graph] Input too long. Retrying with ${reductionFactor * 100}% context (${reducedMaxTokens} tokens)...`\n );\n\n // Build fresh indexTokenCountMap if missing/incomplete\n // This is needed when messages were dynamically added without updating the token map\n let tokenMapForPruning = agentContext.indexTokenCountMap;\n if (Object.keys(tokenMapForPruning).length < messages.length) {\n console.warn(\n '[Graph] Building fresh token count map for emergency pruning...'\n );\n tokenMapForPruning = {};\n for (let i = 0; i < messages.length; i++) {\n tokenMapForPruning[i] = agentContext.tokenCounter!(messages[i]);\n }\n }\n\n const emergencyPrune = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter!,\n maxTokens: reducedMaxTokens,\n thinkingEnabled: false, // Disable thinking for emergency prune\n indexTokenCountMap: tokenMapForPruning,\n });\n\n const { context: reducedMessages } = emergencyPrune({\n messages,\n usageMetadata: agentContext.currentUsage,\n });\n\n // Skip if we can't fit any messages\n if (reducedMessages.length === 0) {\n console.warn(\n `[Graph] Cannot fit any messages at ${reductionFactor * 100}% reduction, trying next level...`\n );\n continue;\n }\n\n // Calculate how many messages were pruned and estimate context timeframe\n const prunedCount = finalMessages.length - reducedMessages.length;\n const remainingCount = reducedMessages.length;\n const estimatedContextDescription =\n this.getContextTimeframeDescription(remainingCount);\n\n // Inject a personalized context message to inform the agent about pruning\n const pruneNoticeMessage = new HumanMessage({\n content: `[CONTEXT NOTICE]\nOur conversation has grown quite long, so I've focused on ${estimatedContextDescription} of our chat (${remainingCount} recent messages). ${prunedCount} earlier messages are no longer in my immediate memory.\n\nIf I seem to be missing something we discussed earlier, just give me a quick reminder and I'll pick right back up! I'm still fully engaged and ready to help with whatever you need.`,\n });\n\n // Insert the notice after the system message (if any) but before conversation\n const hasSystemMessage = reducedMessages[0]?.getType() === 'system';\n const insertIndex = hasSystemMessage ? 1 : 0;\n\n // Create new array with the pruning notice\n const messagesWithNotice = [\n ...reducedMessages.slice(0, insertIndex),\n pruneNoticeMessage,\n ...reducedMessages.slice(insertIndex),\n ];\n\n let retryMessages = agentContext.useLegacyContent\n ? formatContentStrings(messagesWithNotice)\n : messagesWithNotice;\n\n // Apply thinking block handling first (before cache control)\n // This ensures AI+Tool sequences are converted to HumanMessages\n // before we add cache points that could be lost in the conversion\n if (isAnthropicWithThinking) {\n retryMessages = ensureThinkingBlockInMessages(\n retryMessages,\n agentContext.provider\n );\n }\n\n // Apply Bedrock cache control if needed (after thinking block handling)\n if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n retryMessages =\n addBedrockCacheControl<BaseMessage>(retryMessages);\n }\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages: retryMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n // Success with reduced context\n console.info(\n `[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`\n );\n } catch (retryError) {\n const retryErrorMsg =\n (retryError as Error).message.toLowerCase() ?? '';\n const stillTooLong =\n retryErrorMsg.includes('too long') ||\n retryErrorMsg.includes('context length') ||\n retryErrorMsg.includes('validationexception');\n\n if (stillTooLong && reductionFactor > 0.1) {\n console.warn(\n `[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`\n );\n } else {\n console.error(\n `[Graph] Retry at ${reductionFactor * 100}% failed:`,\n (retryError as Error).message\n );\n }\n }\n }\n }\n\n // If we got a result from retry, skip fallbacks\n if (result) {\n // result already set from retry\n } else {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract agentId and parallelGroupId from metadata\n * Only set agentId for MultiAgentGraph (so frontend knows when to show agent labels)\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n // Only include agentId for MultiAgentGraph - enables frontend to show agent labels\n runStep.agentId = agentContext.agentId;\n // Set group ID if this agent is part of a parallel group\n // Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order\n const groupId = this.getParallelGroupIdForAgent(agentContext.agentId);\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n /**\n * Extract and store code execution session context from artifacts.\n * Each file is stamped with its source session_id to support multi-session file tracking.\n * When the same filename appears in a later execution, the newer version replaces the old.\n */\n const toolName = output.name;\n if (\n toolName === Constants.EXECUTE_CODE ||\n toolName === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const artifact = output.artifact as t.CodeExecutionArtifact | undefined;\n const newFiles = artifact?.files ?? [];\n const hasNewFiles = newFiles.length > 0;\n\n if (\n hasNewFiles &&\n artifact?.session_id != null &&\n artifact.session_id !== ''\n ) {\n /**\n * Stamp each new file with its source session_id.\n * This enables files from different executions (parallel or sequential)\n * to be tracked and passed to subsequent calls.\n */\n const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n ...file,\n session_id: artifact.session_id,\n }));\n\n const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n const existingFiles = existingSession?.files ?? [];\n\n /**\n * Merge files, preferring latest versions by name.\n * If a file with the same name exists, replace it with the new version.\n * This handles cases where files are edited/recreated in subsequent executions.\n */\n const newFileNames = new Set(filesWithSession.map((f) => f.name));\n const filteredExisting = existingFiles.filter(\n (f) => !newFileNames.has(f.name)\n );\n\n this.sessions.set(Constants.EXECUTE_CODE, {\n /** Keep latest session_id for reference/fallback */\n session_id: artifact.session_id,\n /** Accumulated files with latest versions preferred */\n files: [...filteredExisting, ...filesWithSession],\n lastUpdated: Date.now(),\n });\n }\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent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c,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "illuma-agents",
3
- "version": "1.0.51",
3
+ "version": "1.0.52",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -737,27 +737,30 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
737
737
  } = structuredOutputConfig;
738
738
 
739
739
  // Determine the method based on mode and provider
740
- // - 'tool': Use tool calling (works well with OpenAI)
741
- // - 'json_mode': Use JSON mode (works well with Bedrock/Anthropic)
740
+ // - 'tool' / 'functionCalling': Use tool calling (works with OpenAI, Bedrock)
741
+ // - 'provider' / 'jsonMode': Use native JSON mode (OpenAI, Anthropic direct - NOT Bedrock)
742
742
  // - 'auto': Auto-detect based on provider
743
+ // NOTE: ChatBedrockConverse does NOT support 'jsonMode' - it only supports tool-based structured output
743
744
  let method: 'functionCalling' | 'jsonMode' | 'jsonSchema' | undefined;
744
745
 
745
746
  if (mode === 'tool') {
746
747
  method = 'functionCalling';
747
748
  } else if (mode === 'provider') {
748
- // Use native JSON mode - best for Anthropic/Bedrock
749
- method = 'jsonMode';
750
- } else {
751
- // Auto mode: choose based on provider
752
- // Bedrock and Anthropic work better with JSON mode
753
- // OpenAI, Azure work better with function calling
754
- if (provider === Providers.BEDROCK || provider === Providers.ANTHROPIC) {
755
- method = 'jsonMode';
756
- } else if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI) {
757
- // Gemini supports native JSON mode
749
+ // Use native JSON mode - but NOT for Bedrock which doesn't support it
750
+ if (provider === Providers.BEDROCK) {
751
+ // Bedrock only supports function calling for structured output
752
+ method = 'functionCalling';
753
+ } else {
758
754
  method = 'jsonMode';
759
755
  }
760
- // For OpenAI/Azure, leave undefined to use default (function calling)
756
+ } else {
757
+ // Auto mode: use function calling for all providers
758
+ // This is the most compatible approach
759
+ // Bedrock: only supports functionCalling
760
+ // Anthropic direct: supports both but functionCalling is more reliable
761
+ // OpenAI/Azure: supports both, functionCalling is default
762
+ // Google/Vertex: supports jsonMode but functionCalling works too
763
+ method = undefined; // Let LangChain choose the default
761
764
  }
762
765
 
763
766
  // Use withStructuredOutput to bind the schema
@@ -1126,17 +1129,21 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1126
1129
  const structuredClientOptions = { ...agentContext.clientOptions } as t.ClientOptions;
1127
1130
 
1128
1131
  // Remove thinking configuration for Bedrock
1132
+ // Bedrock uses additionalModelRequestFields.thinking for extended thinking
1129
1133
  if (agentContext.provider === Providers.BEDROCK) {
1130
1134
  const bedrockOpts = structuredClientOptions as t.BedrockAnthropicClientOptions;
1131
- if (bedrockOpts.additionalModelRequestFields?.['thinking']) {
1135
+ if (bedrockOpts.additionalModelRequestFields) {
1132
1136
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1133
1137
  const additionalFields = Object.assign({}, bedrockOpts.additionalModelRequestFields) as any;
1138
+ // Remove thinking configuration
1134
1139
  delete additionalFields.thinking;
1140
+ // Remove budget tokens which is also related to thinking
1141
+ delete additionalFields.budgetTokens;
1135
1142
  bedrockOpts.additionalModelRequestFields = additionalFields;
1136
1143
  }
1137
1144
  }
1138
1145
 
1139
- // Remove thinking configuration for Anthropic
1146
+ // Remove thinking configuration for Anthropic direct API
1140
1147
  if (agentContext.provider === Providers.ANTHROPIC) {
1141
1148
  const anthropicOpts = structuredClientOptions as t.AnthropicClientOptions;
1142
1149
  if (anthropicOpts.thinking) {
@@ -1144,6 +1151,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1144
1151
  }
1145
1152
  }
1146
1153
 
1154
+ console.log('[Graph] Creating structured model for provider:', agentContext.provider, 'with options:', JSON.stringify(structuredClientOptions, null, 2));
1155
+
1147
1156
  const structuredModel = this.getNewModel({
1148
1157
  provider: agentContext.provider,
1149
1158
  clientOptions: structuredClientOptions,