import { getLogger as getLogger$1 } from "../../../logger.js";
import { env } from "../../../env.js";
import manageDbPool_default from "../../../data/db/manageDbPool.js";
import runDbClient_default from "../../../data/db/runDbClient.js";
import { AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS } from "../constants/execution-limits/index.js";
import { toolSessionManager } from "./ToolSessionManager.js";
import { getCompressionConfigForModel } from "../utils/model-context-utils.js";
import { setSpanWithError as setSpanWithError$1, tracer } from "../utils/tracer.js";
import { getModelAwareCompressionConfig } from "../services/BaseCompressor.js";
import { createDefaultConversationHistoryConfig, getConversationHistoryWithCompression } from "../data/conversations.js";
import { getStreamHelper } from "../utils/stream-registry.js";
import { agentSessionManager } from "../services/AgentSession.js";
import { ContextResolver } from "../context/ContextResolver.js";
import "../context/index.js";
import { IncrementalStreamParser } from "../services/IncrementalStreamParser.js";
import { MidGenerationCompressor } from "../services/MidGenerationCompressor.js";
import { pendingToolApprovalManager } from "../services/PendingToolApprovalManager.js";
import { ResponseFormatter } from "../services/ResponseFormatter.js";
import { toolApprovalUiBus } from "../services/ToolApprovalUiBus.js";
import { generateToolId } from "../utils/agent-operations.js";
import { jsonSchemaToZod } from "../utils/data-component-schema.js";
import { ArtifactCreateSchema, ArtifactReferenceSchema } from "../utils/artifact-component-schema.js";
import { withJsonPostProcessing } from "../utils/json-postprocessor.js";
import { calculateBreakdownTotal, estimateTokens } from "../utils/token-estimator.js";
import { createDelegateToAgentTool, createTransferToAgentTool } from "./relationTools.js";
import { SystemPromptBuilder } from "./SystemPromptBuilder.js";
import { Phase1Config, V1_BREAKDOWN_SCHEMA } from "./versions/v1/Phase1Config.js";
import { Phase2Config } from "./versions/v1/Phase2Config.js";
import { z } from "@hono/zod-openapi";
import { CredentialStuffer, JsonTransformer, MCPServerType, MCPTransportType, McpClient, ModelFactory, TemplateEngine, buildComposioMCPUrl, createMessage, generateId, getFunctionToolsForSubAgent, getLedgerArtifacts, isGithubWorkAppTool, listTaskIdsByContextId, parseEmbeddedJson, withRef } from "@inkeep/agents-core";
import { Output, generateText, streamText, tool } from "ai";
import { SpanStatusCode, trace } from "@opentelemetry/api";

//#region src/domains/run/agents/Agent.ts
/**
* Creates a stopWhen condition that stops when any tool call name starts with the given prefix
* @param prefix - The prefix to check for in tool call names
* @returns A function that can be used as a stopWhen condition
*/
function hasToolCallWithPrefix(prefix) {
	return ({ steps }) => {
		const last = steps.at(-1);
		if (last && "toolCalls" in last && last.toolCalls) return last.toolCalls.some((tc) => tc.toolName.startsWith(prefix));
		return false;
	};
}
const logger = getLogger$1("Agent");
function validateModel(modelString, modelType) {
	if (!modelString?.trim()) throw new Error(`${modelType} model is required. Please configure models at the project level.`);
	return modelString.trim();
}
function isValidTool(tool$1) {
	return tool$1 && typeof tool$1 === "object" && typeof tool$1.description === "string" && tool$1.inputSchema && typeof tool$1.execute === "function";
}
var Agent = class {
	config;
	systemPromptBuilder = new SystemPromptBuilder("v1", new Phase1Config());
	credentialStuffer;
	streamHelper;
	streamRequestId;
	conversationId;
	delegationId;
	artifactComponents = [];
	isDelegatedAgent = false;
	contextResolver;
	credentialStoreRegistry;
	mcpClientCache = /* @__PURE__ */ new Map();
	mcpConnectionLocks = /* @__PURE__ */ new Map();
	currentCompressor = null;
	executionContext;
	functionToolRelationshipIdByName = /* @__PURE__ */ new Map();
	constructor(config, executionContext, credentialStoreRegistry) {
		this.artifactComponents = config.artifactComponents || [];
		this.executionContext = executionContext;
		let processedDataComponents = config.dataComponents || [];
		if (processedDataComponents.length > 0) processedDataComponents.push({
			id: "text-content",
			name: "Text",
			description: "Natural conversational text for the user - write naturally without mentioning technical details. Avoid redundancy and repetition with data components.",
			props: {
				type: "object",
				properties: { text: {
					type: "string",
					description: "Natural conversational text - respond as if having a normal conversation, never mention JSON, components, schemas, or technical implementation. Avoid redundancy and repetition with data components."
				} },
				required: ["text"]
			}
		});
		if (this.artifactComponents.length > 0 && config.dataComponents && config.dataComponents.length > 0) processedDataComponents = [ArtifactReferenceSchema.getDataComponent(config.tenantId, config.projectId), ...processedDataComponents];
		this.config = {
			...config,
			dataComponents: processedDataComponents,
			conversationHistoryConfig: config.conversationHistoryConfig || createDefaultConversationHistoryConfig()
		};
		this.credentialStoreRegistry = credentialStoreRegistry;
		if (credentialStoreRegistry) {
			this.contextResolver = new ContextResolver(executionContext, credentialStoreRegistry);
			this.credentialStuffer = new CredentialStuffer(credentialStoreRegistry, this.contextResolver);
		}
	}
	/**
	* Get the maximum number of generation steps for this agent
	* Uses agent's stopWhen.stepCountIs config or defaults to AGENT_EXECUTION_MAX_GENERATION_STEPS
	*/
	getMaxGenerationSteps() {
		return this.config.stopWhen?.stepCountIs ?? AGENT_EXECUTION_MAX_GENERATION_STEPS;
	}
	/**
	* Sanitizes tool names at runtime for AI SDK compatibility.
	* The AI SDK requires tool names to match pattern ^[a-zA-Z0-9_-]{1,128}$
	*/
	sanitizeToolsForAISDK(tools) {
		const sanitizedTools = {};
		for (const [originalKey, toolDef] of Object.entries(tools)) {
			let sanitizedKey = originalKey.replace(/[^a-zA-Z0-9_-]/g, "_");
			sanitizedKey = sanitizedKey.replace(/_+/g, "_");
			sanitizedKey = sanitizedKey.replace(/^_+|_+$/g, "");
			if (!sanitizedKey || sanitizedKey.length === 0) sanitizedKey = "unnamed_tool";
			if (sanitizedKey.length > 100) sanitizedKey = sanitizedKey.substring(0, 100);
			let sanitizedId = (toolDef.id || originalKey).replace(/[^a-zA-Z0-9_.-]/g, "_");
			sanitizedId = sanitizedId.replace(/_+/g, "_");
			sanitizedId = sanitizedId.replace(/^_+|_+$/g, "");
			if (sanitizedId.length > 128) sanitizedId = sanitizedId.substring(0, 128);
			sanitizedTools[sanitizedKey] = {
				...toolDef,
				id: sanitizedId
			};
		}
		return sanitizedTools;
	}
	#createRelationToolName(prefix, targetId) {
		return `${prefix}_to_${targetId.toLowerCase().replace(/\s+/g, "_")}`;
	}
	#getRelationshipIdForTool(toolName, toolType) {
		if (toolType === "mcp") return (this.config.tools?.find((tool$1) => {
			if (tool$1.config?.type !== "mcp") return false;
			if (tool$1.availableTools?.some((available) => available.name === toolName)) return true;
			if (tool$1.config.mcp.activeTools?.includes(toolName)) return true;
			return tool$1.name === toolName;
		}))?.relationshipId;
		if (toolType === "tool") return this.functionToolRelationshipIdByName.get(toolName);
		if (toolType === "delegation") return this.config.delegateRelations.find((relation) => this.#createRelationToolName("delegate", relation.config.id) === toolName)?.config.relationId;
	}
	/**
	* Get the primary model settings for text generation and thinking
	* Requires model to be configured at project level
	*/
	getPrimaryModel() {
		if (!this.config.models?.base) throw new Error("Base model configuration is required. Please configure models at the project level.");
		return {
			model: validateModel(this.config.models.base.model, "Base"),
			providerOptions: this.config.models.base.providerOptions
		};
	}
	/**
	* Get the model settings for structured output generation
	* Falls back to base model if structured output not configured
	*/
	getStructuredOutputModel() {
		if (!this.config.models) throw new Error("Model configuration is required. Please configure models at the project level.");
		const structuredConfig = this.config.models.structuredOutput;
		const baseConfig = this.config.models.base;
		if (structuredConfig) return {
			model: validateModel(structuredConfig.model, "Structured output"),
			providerOptions: structuredConfig.providerOptions
		};
		if (!baseConfig) throw new Error("Base model configuration is required for structured output fallback. Please configure models at the project level.");
		return {
			model: validateModel(baseConfig.model, "Base (fallback for structured output)"),
			providerOptions: baseConfig.providerOptions
		};
	}
	/**
	* Get the model settings for summarization/distillation
	* Falls back to base model if summarizer not configured
	*/
	getSummarizerModel() {
		if (!this.config.models) throw new Error("Model configuration is required. Please configure models at the project level.");
		const summarizerConfig = this.config.models.summarizer;
		const baseConfig = this.config.models.base;
		if (summarizerConfig) return {
			model: validateModel(summarizerConfig.model, "Summarizer"),
			providerOptions: summarizerConfig.providerOptions
		};
		if (!baseConfig) throw new Error("Base model configuration is required for summarizer fallback. Please configure models at the project level.");
		return {
			model: validateModel(baseConfig.model, "Base (fallback for summarizer)"),
			providerOptions: baseConfig.providerOptions
		};
	}
	setConversationId(conversationId) {
		this.conversationId = conversationId;
	}
	/**
	* Simple compression fallback: drop oldest messages to fit under token limit
	*/
	/**
	* Set delegation status for this agent instance
	*/
	setDelegationStatus(isDelegated) {
		this.isDelegatedAgent = isDelegated;
	}
	/**
	* Set delegation ID for this agent instance
	*/
	setDelegationId(delegationId) {
		this.delegationId = delegationId;
	}
	/**
	* Get streaming helper if this agent should stream to user
	* Returns undefined for delegated agents to prevent streaming data operations to user
	*/
	getStreamingHelper() {
		return this.isDelegatedAgent ? void 0 : this.streamHelper;
	}
	/**
	* Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
	*/
	wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, options) {
		if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) return toolDefinition;
		const relationshipId = this.#getRelationshipIdForTool(toolName, toolType);
		const originalExecute = toolDefinition.execute;
		return {
			...toolDefinition,
			execute: async (args, context$1) => {
				const startTime = Date.now();
				const toolCallId = context$1?.toolCallId || generateToolId();
				const streamHelper = this.getStreamingHelper();
				const chunkString = (s, size = 16) => {
					const out = [];
					for (let i = 0; i < s.length; i += size) out.push(s.slice(i, i + size));
					return out;
				};
				const activeSpan = trace.getActiveSpan();
				if (activeSpan) {
					const attributes = {
						"conversation.id": this.conversationId,
						"tool.purpose": toolDefinition.description || "No description provided",
						"ai.toolType": toolType || "unknown",
						"subAgent.name": this.config.name || "unknown",
						"subAgent.id": this.config.id || "unknown",
						"agent.id": this.config.agentId || "unknown"
					};
					if (options?.mcpServerId) attributes["ai.toolCall.mcpServerId"] = options.mcpServerId;
					if (options?.mcpServerName) attributes["ai.toolCall.mcpServerName"] = options.mcpServerName;
					activeSpan.setAttributes(attributes);
				}
				const isInternalToolForUi = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_") || toolName.startsWith("delegate_to_");
				const needsApproval = options?.needsApproval || false;
				if (streamRequestId && streamHelper && !isInternalToolForUi) {
					const inputText = JSON.stringify(args ?? {});
					await streamHelper.writeToolInputStart({
						toolCallId,
						toolName
					});
					for (const part of chunkString(inputText, 16)) await streamHelper.writeToolInputDelta({
						toolCallId,
						inputTextDelta: part
					});
					await streamHelper.writeToolInputAvailable({
						toolCallId,
						toolName,
						input: args ?? {},
						providerMetadata: context$1?.providerMetadata
					});
				}
				if (streamRequestId && !isInternalToolForUi) {
					const toolCallData = {
						toolName,
						input: args,
						toolCallId,
						relationshipId,
						inDelegatedAgent: this.isDelegatedAgent
					};
					if (needsApproval) {
						toolCallData.needsApproval = true;
						toolCallData.conversationId = this.conversationId;
					}
					await agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, toolCallData);
				}
				try {
					const result = await originalExecute(args, context$1);
					const duration = Date.now() - startTime;
					const toolResultConversationId = this.getToolResultConversationId();
					if (streamRequestId && !isInternalToolForUi && toolResultConversationId) try {
						const messagePayload = {
							id: generateId(),
							tenantId: this.config.tenantId,
							projectId: this.config.projectId,
							conversationId: toolResultConversationId,
							role: "assistant",
							content: { text: this.formatToolResult(toolName, args, result, toolCallId) },
							visibility: "internal",
							messageType: "tool-result",
							fromSubAgentId: this.config.id,
							metadata: { a2a_metadata: {
								toolName,
								toolCallId,
								timestamp: Date.now(),
								delegationId: this.delegationId,
								isDelegated: this.isDelegatedAgent
							} }
						};
						await createMessage(runDbClient_default)(messagePayload);
					} catch (error) {
						logger.warn({
							error,
							toolName,
							toolCallId,
							conversationId: toolResultConversationId
						}, "Failed to store tool result in conversation history");
					}
					if (streamRequestId && !isInternalToolForUi) agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
						toolName,
						output: result,
						toolCallId,
						duration,
						relationshipId,
						needsApproval,
						inDelegatedAgent: this.isDelegatedAgent
					});
					const isDeniedResult = !!result && typeof result === "object" && "__inkeepToolDenied" in result && result.__inkeepToolDenied === true;
					if (streamRequestId && streamHelper && !isInternalToolForUi) if (isDeniedResult) await streamHelper.writeToolOutputDenied({ toolCallId });
					else await streamHelper.writeToolOutputAvailable({
						toolCallId,
						output: result
					});
					return result;
				} catch (error) {
					const duration = Date.now() - startTime;
					const errorMessage = error instanceof Error ? error.message : "Unknown error";
					if (streamRequestId && !isInternalToolForUi) agentSessionManager.recordEvent(streamRequestId, "tool_result", this.config.id, {
						toolName,
						output: null,
						toolCallId,
						duration,
						error: errorMessage,
						relationshipId,
						needsApproval,
						inDelegatedAgent: this.isDelegatedAgent
					});
					if (streamRequestId && streamHelper && !isInternalToolForUi) await streamHelper.writeToolOutputError({
						toolCallId,
						errorText: errorMessage
					});
					throw error;
				}
			}
		};
	}
	getRelationTools(runtimeContext, sessionId) {
		const { transferRelations = [], delegateRelations = [] } = this.config;
		return Object.fromEntries([...transferRelations.map((agentConfig) => {
			const toolName = this.#createRelationToolName("transfer", agentConfig.id);
			return [toolName, this.wrapToolWithStreaming(toolName, createTransferToAgentTool({
				transferConfig: agentConfig,
				callingAgentId: this.config.id,
				streamRequestId: runtimeContext?.metadata?.streamRequestId
			}), runtimeContext?.metadata?.streamRequestId, "transfer")];
		}), ...delegateRelations.map((relation) => {
			const toolName = this.#createRelationToolName("delegate", relation.config.id);
			return [toolName, this.wrapToolWithStreaming(toolName, createDelegateToAgentTool({
				delegateConfig: relation,
				callingAgentId: this.config.id,
				executionContext: this.executionContext,
				contextId: runtimeContext?.contextId || "default",
				metadata: runtimeContext?.metadata || {
					conversationId: runtimeContext?.contextId || "default",
					threadId: runtimeContext?.contextId || "default",
					streamRequestId: runtimeContext?.metadata?.streamRequestId,
					apiKey: runtimeContext?.metadata?.apiKey
				},
				sessionId,
				credentialStoreRegistry: this.credentialStoreRegistry
			}), runtimeContext?.metadata?.streamRequestId, "delegation")];
		})]);
	}
	async getMcpTools(sessionId, streamRequestId) {
		const mcpTools = this.config.tools?.filter((tool$1) => {
			return tool$1.config?.type === "mcp";
		}) || [];
		const tools = await Promise.all(mcpTools.map((tool$1) => this.getMcpTool(tool$1)) || []) || [];
		if (!sessionId) {
			const wrappedTools$1 = {};
			for (const toolSet of tools) for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
				const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
				const enhancedTool = {
					...toolDef || {},
					needsApproval
				};
				wrappedTools$1[toolName] = this.wrapToolWithStreaming(toolName, enhancedTool, streamRequestId, "mcp", {
					needsApproval,
					mcpServerId: toolSet.mcpServerId,
					mcpServerName: toolSet.mcpServerName
				});
			}
			return wrappedTools$1;
		}
		const wrappedTools = {};
		for (const toolResult of tools) for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
			if (!isValidTool(originalTool)) {
				logger.error({ toolName }, "Invalid MCP tool structure - missing required properties");
				continue;
			}
			const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
			logger.debug({
				toolName,
				toolPolicies: toolResult.toolPolicies,
				needsApproval,
				policyForThisTool: toolResult.toolPolicies?.[toolName]
			}, "Tool approval check");
			const sessionWrappedTool = tool({
				description: originalTool.description,
				inputSchema: originalTool.inputSchema,
				execute: async (args, { toolCallId, providerMetadata }) => {
					let processedArgs;
					try {
						processedArgs = parseEmbeddedJson(args);
						if (JSON.stringify(args) !== JSON.stringify(processedArgs)) logger.warn({
							toolName,
							toolCallId
						}, "Fixed stringified JSON parameters (indicates schema ambiguity)");
					} catch (error) {
						logger.warn({
							toolName,
							toolCallId,
							error: error.message
						}, "Failed to parse embedded JSON, using original args");
						processedArgs = args;
					}
					const finalArgs = processedArgs;
					if (needsApproval) {
						logger.info({
							toolName,
							toolCallId,
							args: finalArgs
						}, "Tool requires approval - waiting for user response");
						const currentSpan = trace.getActiveSpan();
						if (currentSpan) currentSpan.addEvent("tool.approval.requested", {
							"tool.name": toolName,
							"tool.callId": toolCallId,
							"subAgent.id": this.config.id
						});
						tracer.startActiveSpan("tool.approval_requested", { attributes: {
							"tool.name": toolName,
							"tool.callId": toolCallId,
							"subAgent.id": this.config.id,
							"subAgent.name": this.config.name
						} }, (requestSpan) => {
							requestSpan.setStatus({ code: SpanStatusCode.OK });
							requestSpan.end();
						});
						const streamHelper = this.getStreamingHelper();
						if (streamHelper) await streamHelper.writeToolApprovalRequest({
							approvalId: `aitxt-${toolCallId}`,
							toolCallId
						});
						else if (this.isDelegatedAgent) {
							const streamRequestId$1 = this.getStreamRequestId();
							if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
								type: "approval-needed",
								toolCallId,
								toolName,
								input: finalArgs,
								providerMetadata,
								approvalId: `aitxt-${toolCallId}`
							});
						}
						const approvalResult = await pendingToolApprovalManager.waitForApproval(toolCallId, toolName, args, this.conversationId || "unknown", this.config.id);
						if (!approvalResult.approved) {
							if (!streamHelper && this.isDelegatedAgent) {
								const streamRequestId$1 = this.getStreamRequestId();
								if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
									type: "approval-resolved",
									toolCallId,
									approved: false
								});
							}
							return tracer.startActiveSpan("tool.approval_denied", { attributes: {
								"tool.name": toolName,
								"tool.callId": toolCallId,
								"subAgent.id": this.config.id,
								"subAgent.name": this.config.name
							} }, (denialSpan) => {
								logger.info({
									toolName,
									toolCallId,
									reason: approvalResult.reason
								}, "Tool execution denied by user");
								denialSpan.setStatus({ code: SpanStatusCode.OK });
								denialSpan.end();
								return {
									__inkeepToolDenied: true,
									toolCallId,
									reason: approvalResult.reason
								};
							});
						}
						tracer.startActiveSpan("tool.approval_approved", { attributes: {
							"tool.name": toolName,
							"tool.callId": toolCallId,
							"subAgent.id": this.config.id,
							"subAgent.name": this.config.name
						} }, (approvedSpan) => {
							logger.info({
								toolName,
								toolCallId
							}, "Tool approved, continuing with execution");
							approvedSpan.setStatus({ code: SpanStatusCode.OK });
							approvedSpan.end();
						});
						if (!streamHelper && this.isDelegatedAgent) {
							const streamRequestId$1 = this.getStreamRequestId();
							if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
								type: "approval-resolved",
								toolCallId,
								approved: true
							});
						}
					}
					logger.debug({
						toolName,
						toolCallId
					}, "MCP Tool Called");
					try {
						const rawResult = await originalTool.execute(finalArgs, { toolCallId });
						if (rawResult && typeof rawResult === "object" && rawResult.isError) {
							const errorMessage = rawResult.content?.[0]?.text || "MCP tool returned an error";
							logger.error({
								toolName,
								toolCallId,
								errorMessage,
								rawResult
							}, "MCP tool returned error status");
							toolSessionManager.recordToolResult(sessionId, {
								toolCallId,
								toolName,
								args: finalArgs,
								result: {
									error: errorMessage,
									failed: true
								},
								timestamp: Date.now()
							});
							if (streamRequestId) {
								const relationshipId = this.#getRelationshipIdForTool(toolName, "mcp");
								agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
									message: `MCP tool "${toolName}" failed: ${errorMessage}`,
									code: "mcp_tool_error",
									severity: "error",
									context: {
										toolName,
										toolCallId,
										errorMessage,
										relationshipId
									},
									relationshipId
								});
							}
							const activeSpan = trace.getActiveSpan();
							if (activeSpan) {
								const error = /* @__PURE__ */ new Error(`Tool "${toolName}" failed: ${errorMessage}. This tool is currently unavailable. Please try a different approach or inform the user of the issue.`);
								activeSpan.recordException(error);
								activeSpan.setStatus({
									code: SpanStatusCode.ERROR,
									message: `MCP tool returned error: ${errorMessage}`
								});
							}
							throw new Error(`Tool "${toolName}" failed: ${errorMessage}. This tool is currently unavailable. Please try a different approach or inform the user of the issue.`);
						}
						const parsedResult = parseEmbeddedJson(rawResult);
						const enhancedResult = this.enhanceToolResultWithStructureHints(parsedResult);
						toolSessionManager.recordToolResult(sessionId, {
							toolCallId,
							toolName,
							args: finalArgs,
							result: enhancedResult,
							timestamp: Date.now()
						});
						return enhancedResult;
					} catch (error) {
						logger.error({
							toolName,
							toolCallId,
							error
						}, "MCP tool execution failed");
						throw error;
					}
				}
			});
			wrappedTools[toolName] = this.wrapToolWithStreaming(toolName, sessionWrappedTool, streamRequestId, "mcp", {
				needsApproval,
				mcpServerId: toolResult.mcpServerId,
				mcpServerName: toolResult.mcpServerName
			});
		}
		return wrappedTools;
	}
	/**
	* Convert database McpTool to builder MCPToolConfig format
	*/
	convertToMCPToolConfig(tool$1, agentToolRelationHeaders) {
		if (tool$1.config.type !== "mcp") throw new Error(`Cannot convert non-MCP tool to MCP config: ${tool$1.id}`);
		return {
			id: tool$1.id,
			name: tool$1.name,
			description: tool$1.name,
			serverUrl: tool$1.config.mcp.server.url,
			activeTools: tool$1.config.mcp.activeTools,
			mcpType: tool$1.config.mcp.server.url.includes("api.nango.dev") ? MCPServerType.nango : MCPServerType.generic,
			transport: tool$1.config.mcp.transport,
			headers: {
				...tool$1.headers,
				...agentToolRelationHeaders
			},
			toolOverrides: tool$1.config.mcp.toolOverrides
		};
	}
	async getMcpTool(tool$1) {
		const forwardedHeadersHash = this.config.forwardedHeaders ? Object.keys(this.config.forwardedHeaders).sort().join(",") : "no-fwd";
		const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool$1.id}-${tool$1.credentialReferenceId || "no-cred"}-${forwardedHeadersHash}`;
		const project = this.executionContext.project;
		const credentialReferenceId = tool$1.credentialReferenceId;
		const toolRelation = (project.agents[this.config.agentId]?.subAgents?.[this.config.id])?.canUse?.find((t) => t.toolId === tool$1.id);
		const agentToolRelationHeaders = toolRelation?.headers || void 0;
		const selectedTools = toolRelation?.toolSelection || void 0;
		const toolPolicies = toolRelation?.toolPolicies || {};
		let serverConfig;
		const isUserScoped = tool$1.credentialScope === "user";
		const userId = this.config.userId;
		if (isUserScoped && userId && this.credentialStuffer) {
			const userCredentialReference = project.credentialReferences ? Object.values(project.credentialReferences).find((c) => c.toolId === tool$1.id && c.userId === userId) : void 0;
			if (userCredentialReference) {
				const storeReference = {
					credentialStoreId: userCredentialReference.credentialStoreId,
					retrievalParams: userCredentialReference.retrievalParams || {}
				};
				serverConfig = await this.credentialStuffer.buildMcpServerConfig({
					tenantId: this.config.tenantId,
					projectId: this.config.projectId,
					contextConfigId: this.config.contextConfigId || void 0,
					conversationId: this.conversationId || void 0
				}, this.convertToMCPToolConfig(tool$1, agentToolRelationHeaders), storeReference, selectedTools);
			} else {
				logger.warn({
					toolId: tool$1.id,
					userId
				}, "User-scoped tool has no credential connected for this user");
				serverConfig = await this.credentialStuffer.buildMcpServerConfig({
					tenantId: this.config.tenantId,
					projectId: this.config.projectId,
					contextConfigId: this.config.contextConfigId || void 0,
					conversationId: this.conversationId || void 0
				}, this.convertToMCPToolConfig(tool$1, agentToolRelationHeaders), void 0, selectedTools);
			}
		} else if (credentialReferenceId && this.credentialStuffer) {
			const credentialReference = project.credentialReferences?.[credentialReferenceId];
			if (!credentialReference) throw new Error(`Credential reference not found: ${credentialReferenceId}`);
			const storeReference = {
				credentialStoreId: credentialReference.credentialStoreId,
				retrievalParams: credentialReference.retrievalParams || {}
			};
			serverConfig = await this.credentialStuffer.buildMcpServerConfig({
				tenantId: this.config.tenantId,
				projectId: this.config.projectId,
				contextConfigId: this.config.contextConfigId || void 0,
				conversationId: this.conversationId || void 0
			}, this.convertToMCPToolConfig(tool$1, agentToolRelationHeaders), storeReference, selectedTools);
		} else if (this.credentialStuffer) serverConfig = await this.credentialStuffer.buildMcpServerConfig({
			tenantId: this.config.tenantId,
			projectId: this.config.projectId,
			contextConfigId: this.config.contextConfigId || void 0,
			conversationId: this.conversationId || void 0
		}, this.convertToMCPToolConfig(tool$1, agentToolRelationHeaders), void 0, selectedTools);
		else {
			if (tool$1.config.type !== "mcp") throw new Error(`Cannot build server config for non-MCP tool: ${tool$1.id}`);
			serverConfig = {
				type: tool$1.config.mcp.transport?.type || MCPTransportType.streamableHttp,
				url: tool$1.config.mcp.server.url,
				activeTools: tool$1.config.mcp.activeTools,
				selectedTools,
				headers: agentToolRelationHeaders
			};
		}
		if (isGithubWorkAppTool(tool$1)) serverConfig.headers = {
			...serverConfig.headers,
			"x-inkeep-tool-id": tool$1.id,
			Authorization: `Bearer ${env.GITHUB_MCP_API_KEY}`
		};
		if (serverConfig.url) serverConfig.url = buildComposioMCPUrl(serverConfig.url.toString(), this.config.tenantId, this.config.projectId, isUserScoped ? "user" : "project", userId);
		if (this.config.forwardedHeaders && Object.keys(this.config.forwardedHeaders).length > 0) serverConfig.headers = {
			...serverConfig.headers,
			...this.config.forwardedHeaders
		};
		logger.info({
			toolName: tool$1.name,
			credentialReferenceId,
			transportType: serverConfig.type,
			headers: tool$1.headers,
			hasForwardedHeaders: !!this.config.forwardedHeaders
		}, "Built MCP server config with credentials");
		let client = this.mcpClientCache.get(cacheKey);
		if (client && !client.isConnected()) {
			this.mcpClientCache.delete(cacheKey);
			client = void 0;
		}
		if (!client) {
			let connectionPromise = this.mcpConnectionLocks.get(cacheKey);
			if (!connectionPromise) {
				connectionPromise = this.createMcpConnection(tool$1, serverConfig);
				this.mcpConnectionLocks.set(cacheKey, connectionPromise);
			}
			try {
				client = await connectionPromise;
				this.mcpClientCache.set(cacheKey, client);
			} catch (error) {
				this.mcpConnectionLocks.delete(cacheKey);
				logger.error({
					toolName: tool$1.name,
					subAgentId: this.config.id,
					cacheKey,
					error: error instanceof Error ? error.message : String(error)
				}, "MCP connection failed");
				throw error;
			}
		}
		const originalTools = await client.tools();
		const tools = await this.applyToolOverrides(originalTools, tool$1);
		if (!tools || Object.keys(tools).length === 0) {
			const streamRequestId = this.getStreamRequestId();
			if (streamRequestId) tracer.startActiveSpan("ai.toolCall", { attributes: {
				"ai.toolCall.name": tool$1.name,
				"ai.toolCall.args": JSON.stringify({ operation: "mcp_tool_discovery" }),
				"ai.toolCall.result": JSON.stringify({
					status: "no_tools_available",
					message: `MCP server has 0 effective tools. Double check the selected tools in your agent and the active tools in the MCP server configuration.`,
					serverUrl: tool$1.config.type === "mcp" ? tool$1.config.mcp.server.url : "unknown",
					originalToolName: tool$1.name
				}),
				"ai.toolType": "mcp",
				"subAgent.name": this.config.name || "unknown",
				"subAgent.id": this.config.id || "unknown",
				"conversation.id": this.conversationId || "unknown",
				"agent.id": this.config.agentId || "unknown",
				"tenant.id": this.config.tenantId || "unknown",
				"project.id": this.config.projectId || "unknown"
			} }, (span) => {
				setSpanWithError$1(span, /* @__PURE__ */ new Error(`0 effective tools available for ${tool$1.name}`));
				const relationshipId = this.#getRelationshipIdForTool(tool$1.name, "mcp");
				agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
					message: `MCP server has 0 effective tools. Double check the selected tools in your graph and the active tools in the MCP server configuration.`,
					code: "no_tools_available",
					severity: "error",
					context: {
						toolName: tool$1.name,
						serverUrl: tool$1.config.type === "mcp" ? tool$1.config.mcp.server.url : "unknown",
						operation: "mcp_tool_discovery"
					},
					relationshipId
				});
				span.end();
			});
		}
		return {
			tools,
			toolPolicies,
			mcpServerId: tool$1.id,
			mcpServerName: tool$1.name
		};
	}
	async createMcpConnection(tool$1, serverConfig) {
		const client = new McpClient({
			name: tool$1.name,
			server: serverConfig
		});
		try {
			await client.connect();
			return client;
		} catch (error) {
			logger.error({
				toolName: tool$1.name,
				subAgentId: this.config.id,
				error: error instanceof Error ? error.message : String(error)
			}, "Agent failed to connect to MCP server");
			if (error instanceof Error) {
				if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) throw new Error("Connection refused. Please check if the MCP server is running.");
				if (error.message.includes("404")) throw new Error("Error accessing endpoint (HTTP 404)");
				throw new Error(`MCP server connection failed: ${error.message}`);
			}
			throw error;
		}
	}
	async getFunctionTools(sessionId, streamRequestId) {
		const functionTools = {};
		const project = this.executionContext.project;
		try {
			const functionToolsData = (await withRef(manageDbPool_default, this.executionContext.resolvedRef, async (db) => {
				return await getFunctionToolsForSubAgent(db)({
					scopes: {
						tenantId: this.config.tenantId,
						projectId: this.config.projectId,
						agentId: this.config.agentId
					},
					subAgentId: this.config.id
				});
			})).data ?? [];
			if (functionToolsData.length === 0) return functionTools;
			this.functionToolRelationshipIdByName = new Map(functionToolsData.flatMap((t) => {
				return t.relationshipId ? [[t.name, t.relationshipId]] : [];
			}));
			const { SandboxExecutorFactory } = await import("../tools/SandboxExecutorFactory.js");
			const sandboxExecutor = sessionId ? SandboxExecutorFactory.getForSession(sessionId) : new SandboxExecutorFactory();
			for (const functionToolDef of functionToolsData) {
				const functionId = functionToolDef.functionId;
				if (!functionId) {
					logger.warn({ functionToolId: functionToolDef.id }, "Function tool missing functionId reference");
					continue;
				}
				const functionData = project.functions?.[functionId];
				if (!functionData) {
					logger.warn({
						functionId,
						functionToolId: functionToolDef.id
					}, "Function not found in functions table");
					continue;
				}
				const zodSchema = jsonSchemaToZod(functionData.inputSchema);
				const toolPolicies = functionToolDef.toolPolicies;
				const needsApproval = !!toolPolicies?.["*"]?.needsApproval || !!toolPolicies?.[functionToolDef.name]?.needsApproval;
				const aiTool = tool({
					description: functionToolDef.description || functionToolDef.name,
					inputSchema: zodSchema,
					execute: async (args, { toolCallId, providerMetadata }) => {
						let processedArgs;
						try {
							processedArgs = parseEmbeddedJson(args);
							if (JSON.stringify(args) !== JSON.stringify(processedArgs)) logger.warn({
								toolName: functionToolDef.name,
								toolCallId
							}, "Fixed stringified JSON parameters (indicates schema ambiguity)");
						} catch (error) {
							logger.warn({
								toolName: functionToolDef.name,
								toolCallId,
								error: error.message
							}, "Failed to parse embedded JSON, using original args");
							processedArgs = args;
						}
						const finalArgs = processedArgs;
						if (needsApproval) {
							logger.info({
								toolName: functionToolDef.name,
								toolCallId,
								args: finalArgs
							}, "Function tool requires approval - waiting for user response");
							const currentSpan = trace.getActiveSpan();
							if (currentSpan) currentSpan.addEvent("tool.approval.requested", {
								"tool.name": functionToolDef.name,
								"tool.callId": toolCallId,
								"subAgent.id": this.config.id
							});
							tracer.startActiveSpan("tool.approval_requested", { attributes: {
								"tool.name": functionToolDef.name,
								"tool.callId": toolCallId,
								"subAgent.id": this.config.id,
								"subAgent.name": this.config.name
							} }, (requestSpan) => {
								requestSpan.setStatus({ code: SpanStatusCode.OK });
								requestSpan.end();
							});
							const streamHelper = this.getStreamingHelper();
							if (streamHelper) await streamHelper.writeToolApprovalRequest({
								approvalId: `aitxt-${toolCallId}`,
								toolCallId
							});
							else if (this.isDelegatedAgent) {
								const streamRequestId$1 = this.getStreamRequestId();
								if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
									type: "approval-needed",
									toolCallId,
									toolName: functionToolDef.name,
									input: finalArgs,
									providerMetadata,
									approvalId: `aitxt-${toolCallId}`
								});
							}
							const approvalResult = await pendingToolApprovalManager.waitForApproval(toolCallId, functionToolDef.name, args, this.conversationId || "unknown", this.config.id);
							if (!approvalResult.approved) {
								if (!streamHelper && this.isDelegatedAgent) {
									const streamRequestId$1 = this.getStreamRequestId();
									if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
										type: "approval-resolved",
										toolCallId,
										approved: false
									});
								}
								return tracer.startActiveSpan("tool.approval_denied", { attributes: {
									"tool.name": functionToolDef.name,
									"tool.callId": toolCallId,
									"subAgent.id": this.config.id,
									"subAgent.name": this.config.name
								} }, (denialSpan) => {
									logger.info({
										toolName: functionToolDef.name,
										toolCallId,
										reason: approvalResult.reason
									}, "Function tool execution denied by user");
									denialSpan.setStatus({ code: SpanStatusCode.OK });
									denialSpan.end();
									return {
										__inkeepToolDenied: true,
										toolCallId,
										reason: approvalResult.reason
									};
								});
							}
							tracer.startActiveSpan("tool.approval_approved", { attributes: {
								"tool.name": functionToolDef.name,
								"tool.callId": toolCallId,
								"subAgent.id": this.config.id,
								"subAgent.name": this.config.name
							} }, (approvedSpan) => {
								logger.info({
									toolName: functionToolDef.name,
									toolCallId
								}, "Function tool approved, continuing with execution");
								approvedSpan.setStatus({ code: SpanStatusCode.OK });
								approvedSpan.end();
							});
							if (!streamHelper && this.isDelegatedAgent) {
								const streamRequestId$1 = this.getStreamRequestId();
								if (streamRequestId$1) await toolApprovalUiBus.publish(streamRequestId$1, {
									type: "approval-resolved",
									toolCallId,
									approved: true
								});
							}
						}
						logger.debug({
							toolName: functionToolDef.name,
							toolCallId,
							args: finalArgs
						}, "Function Tool Called");
						try {
							const defaultSandboxConfig = {
								provider: "native",
								runtime: "node22",
								timeout: FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT,
								vcpus: FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT
							};
							const result = await sandboxExecutor.executeFunctionTool(functionToolDef.id, finalArgs, {
								description: functionToolDef.description || functionToolDef.name,
								inputSchema: functionData.inputSchema || {},
								executeCode: functionData.executeCode,
								dependencies: functionData.dependencies || {},
								sandboxConfig: this.config.sandboxConfig || defaultSandboxConfig
							});
							toolSessionManager.recordToolResult(sessionId || "", {
								toolCallId,
								toolName: functionToolDef.name,
								args: finalArgs,
								result,
								timestamp: Date.now()
							});
							return result;
						} catch (error) {
							logger.error({
								toolName: functionToolDef.name,
								toolCallId,
								error: error instanceof Error ? error.message : String(error)
							}, "Function tool execution failed");
							throw error;
						}
					}
				});
				functionTools[functionToolDef.name] = this.wrapToolWithStreaming(functionToolDef.name, aiTool, streamRequestId || "", "tool", { needsApproval });
			}
		} catch (error) {
			logger.error({ error }, "Failed to load function tools from database");
		}
		return functionTools;
	}
	/**
	* Get resolved context using ContextResolver - will return cached data or fetch fresh data as needed
	*/
	async getResolvedContext(conversationId, headers$1) {
		try {
			const project = this.executionContext.project;
			if (!this.config.contextConfigId) {
				logger.debug({ agentId: this.config.agentId }, "No context config found for agent");
				return null;
			}
			const contextConfig = project.agents[this.config.agentId]?.contextConfig;
			if (!contextConfig) {
				logger.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
				return null;
			}
			const contextConfigWithScopes = {
				...contextConfig,
				tenantId: this.config.tenantId,
				projectId: this.config.projectId,
				agentId: this.config.agentId,
				createdAt: contextConfig.createdAt || "",
				updatedAt: contextConfig.updatedAt || ""
			};
			if (!contextConfig) {
				logger.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
				return null;
			}
			if (!this.contextResolver) throw new Error("Context resolver not found");
			const result = await this.contextResolver.resolve(contextConfigWithScopes, {
				triggerEvent: "invocation",
				conversationId,
				headers: headers$1 || {},
				tenantId: this.config.tenantId
			});
			const contextWithBuiltins = {
				...result.resolvedContext,
				$env: process.env
			};
			logger.debug({
				conversationId,
				contextConfigId: contextConfig.id,
				resolvedKeys: Object.keys(contextWithBuiltins),
				cacheHits: result.cacheHits.length,
				cacheMisses: result.cacheMisses.length,
				fetchedDefinitions: result.fetchedDefinitions.length,
				errors: result.errors.length
			}, "Context resolved for agent");
			return contextWithBuiltins;
		} catch (error) {
			logger.error({
				conversationId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to get resolved context");
			return null;
		}
	}
	/**
	* Get the agent prompt for this agent's agent
	*/
	async getPrompt() {
		const agentDefinition = this.executionContext.project.agents[this.config.agentId];
		try {
			return agentDefinition?.prompt || void 0;
		} catch (error) {
			logger.warn({
				agentId: this.config.agentId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to get agent prompt");
			return;
		}
	}
	/**
	* Check if any agent in the agent has artifact components configured
	*/
	async hasAgentArtifactComponents() {
		const project = this.executionContext.project;
		try {
			const agentDefinition = project.agents[this.config.agentId];
			if (!agentDefinition) return false;
			return Object.values(agentDefinition.subAgents).some((subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0);
		} catch (error) {
			logger.warn({
				agentId: this.config.agentId,
				tenantId: this.config.tenantId,
				projectId: this.config.projectId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to check agent artifact components, assuming none exist");
			return this.artifactComponents.length > 0;
		}
	}
	/**
	* Build adaptive system prompt for Phase 2 structured output generation
	* based on configured data components and artifact components across the agent
	*/
	getClientCurrentTime() {
		const clientTimezone = this.config.forwardedHeaders?.["x-inkeep-client-timezone"];
		const clientTimestamp = this.config.forwardedHeaders?.["x-inkeep-client-timestamp"];
		if (!clientTimezone || !clientTimestamp) return;
		try {
			return new Date(clientTimestamp).toLocaleString("en-US", {
				timeZone: clientTimezone,
				weekday: "long",
				year: "numeric",
				month: "long",
				day: "numeric",
				hour: "numeric",
				minute: "2-digit",
				timeZoneName: "short"
			});
		} catch (error) {
			logger.warn({
				clientTimezone,
				clientTimestamp,
				error
			}, "Failed to format time for client timezone");
			return;
		}
	}
	async buildPhase2SystemPrompt(runtimeContext) {
		const phase2Config = new Phase2Config();
		const compressionConfig = getModelAwareCompressionConfig();
		const hasAgentArtifactComponents = await this.hasAgentArtifactComponents() || compressionConfig.enabled;
		const conversationId = runtimeContext?.metadata?.conversationId || runtimeContext?.contextId;
		const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
		let processedPrompt = this.config.prompt || "";
		if (resolvedContext && this.config.prompt) try {
			processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
				strict: false,
				preserveUnresolved: false
			});
		} catch (error) {
			logger.error({
				conversationId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to process agent prompt with context for Phase 2, using original");
			processedPrompt = this.config.prompt;
		}
		const referenceTaskIds = await listTaskIdsByContextId(runDbClient_default)({ contextId: this.conversationId || "" });
		const referenceArtifacts = [];
		for (const taskId of referenceTaskIds) {
			const artifacts = await getLedgerArtifacts(runDbClient_default)({
				scopes: {
					tenantId: this.config.tenantId,
					projectId: this.config.projectId
				},
				taskId
			});
			referenceArtifacts.push(...artifacts);
		}
		const clientCurrentTime = this.getClientCurrentTime();
		return phase2Config.assemblePhase2Prompt({
			corePrompt: processedPrompt,
			dataComponents: this.config.dataComponents || [],
			artifactComponents: this.artifactComponents,
			hasArtifactComponents: this.artifactComponents && this.artifactComponents.length > 0,
			hasAgentArtifactComponents,
			artifacts: referenceArtifacts,
			clientCurrentTime
		});
	}
	async buildSystemPrompt(runtimeContext, excludeDataComponents = false) {
		const conversationId = runtimeContext?.metadata?.conversationId || runtimeContext?.contextId;
		if (conversationId) this.setConversationId(conversationId);
		const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
		let processedPrompt = this.config.prompt || "";
		if (resolvedContext && this.config.prompt) try {
			processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
				strict: false,
				preserveUnresolved: false
			});
		} catch (error) {
			logger.error({
				conversationId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to process agent prompt with context, using original");
			processedPrompt = this.config.prompt;
		}
		const streamRequestId = runtimeContext?.metadata?.streamRequestId;
		const mcpTools = await this.getMcpTools(void 0, streamRequestId);
		const functionTools = await this.getFunctionTools(streamRequestId || "");
		const relationTools = this.getRelationTools(runtimeContext);
		const allTools = {
			...mcpTools,
			...functionTools,
			...relationTools
		};
		logger.info({
			mcpTools: Object.keys(mcpTools),
			functionTools: Object.keys(functionTools),
			relationTools: Object.keys(relationTools),
			allTools: Object.keys(allTools),
			functionToolsDetails: Object.entries(functionTools).map(([name, tool$1]) => ({
				name,
				hasExecute: typeof tool$1.execute === "function",
				hasDescription: !!tool$1.description,
				hasInputSchema: !!tool$1.inputSchema
			}))
		}, "Tools loaded for agent");
		const toolDefinitions = Object.entries(allTools).map(([name, tool$1]) => ({
			name,
			description: tool$1.description || "",
			inputSchema: tool$1.inputSchema || tool$1.parameters || {},
			usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
		}));
		const { getConversationScopedArtifacts } = await import("../data/conversations.js");
		const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
		const referenceArtifacts = await getConversationScopedArtifacts({
			tenantId: this.config.tenantId,
			projectId: this.config.projectId,
			conversationId: runtimeContext?.contextId || "",
			historyConfig,
			ref: this.executionContext.resolvedRef
		});
		const componentDataComponents = excludeDataComponents ? [] : this.config.dataComponents || [];
		const isThinkingPreparation = this.config.dataComponents && this.config.dataComponents.length > 0 && excludeDataComponents;
		let prompt = await this.getPrompt();
		if (prompt && resolvedContext) try {
			prompt = TemplateEngine.render(prompt, resolvedContext, {
				strict: false,
				preserveUnresolved: false
			});
		} catch (error) {
			logger.error({
				conversationId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to process agent prompt with context, using original");
		}
		const shouldIncludeArtifactComponents = !excludeDataComponents;
		const compressionConfig = getModelAwareCompressionConfig();
		const hasAgentArtifactComponents = await this.hasAgentArtifactComponents() || compressionConfig.enabled;
		const clientCurrentTime = this.getClientCurrentTime();
		const config = {
			corePrompt: processedPrompt,
			prompt,
			tools: toolDefinitions,
			dataComponents: componentDataComponents,
			artifacts: referenceArtifacts,
			artifactComponents: shouldIncludeArtifactComponents ? this.artifactComponents : [],
			hasAgentArtifactComponents,
			isThinkingPreparation,
			hasTransferRelations: (this.config.transferRelations?.length ?? 0) > 0,
			hasDelegateRelations: (this.config.delegateRelations?.length ?? 0) > 0,
			clientCurrentTime
		};
		return await this.systemPromptBuilder.buildSystemPrompt(config);
	}
	getArtifactTools() {
		return tool({
			description: "Call this tool to retrieve EXISTING artifacts that were previously created and saved. This tool is for accessing artifacts that already exist, NOT for extracting tool results. Only use this when you need the complete artifact data and the summary shown in your context is insufficient.",
			inputSchema: z.object({
				artifactId: z.string().describe("The unique identifier of the artifact to get."),
				toolCallId: z.string().describe("The tool call ID associated with this artifact.")
			}),
			execute: async ({ artifactId, toolCallId }) => {
				logger.info({
					artifactId,
					toolCallId
				}, "get_artifact_full executed");
				const streamRequestId = this.getStreamRequestId();
				const artifactService = agentSessionManager.getArtifactService(streamRequestId);
				if (!artifactService) throw new Error(`ArtifactService not found for session ${streamRequestId}`);
				const artifactData = await artifactService.getArtifactFull(artifactId, toolCallId);
				if (!artifactData) throw new Error(`Artifact ${artifactId} with toolCallId ${toolCallId} not found`);
				return {
					artifactId: artifactData.artifactId,
					name: artifactData.name,
					description: artifactData.description,
					type: artifactData.type,
					data: artifactData.data
				};
			}
		});
	}
	createThinkingCompleteTool() {
		return tool({
			description: "🚨 CRITICAL: Call this tool IMMEDIATELY when you have gathered enough information to answer the user. This is MANDATORY - you CANNOT provide text responses in thinking mode, only tool calls. Call thinking_complete as soon as you have sufficient data to generate a structured response.",
			inputSchema: z.object({
				complete: z.boolean().describe("ALWAYS set to true - marks end of research phase"),
				summary: z.string().describe("Brief summary of what information was gathered and why it is sufficient to answer the user")
			}),
			execute: async (params) => params
		});
	}
	async getDefaultTools(streamRequestId) {
		const defaultTools = {};
		const compressionConfig = getModelAwareCompressionConfig();
		if (await this.agentHasArtifactComponents() || compressionConfig.enabled) defaultTools.get_reference_artifact = this.getArtifactTools();
		if (this.config.dataComponents && this.config.dataComponents.length > 0) {
			const thinkingCompleteTool = this.createThinkingCompleteTool();
			if (thinkingCompleteTool) defaultTools.thinking_complete = this.wrapToolWithStreaming("thinking_complete", thinkingCompleteTool, streamRequestId, "tool");
		}
		logger.info({
			agentId: this.config.id,
			streamRequestId
		}, "Adding compress_context tool to defaultTools");
		defaultTools.compress_context = tool({
			description: "Manually compress the current conversation context to save space. Use when shifting topics, completing major tasks, or when context feels cluttered.",
			inputSchema: z.object({ reason: z.string().describe("Why you are requesting compression (e.g., \"shifting from research to coding\", \"completed analysis phase\")") }),
			execute: async ({ reason }) => {
				logger.info({
					agentId: this.config.id,
					streamRequestId,
					reason
				}, "Manual compression requested by LLM");
				if (this.currentCompressor) this.currentCompressor.requestManualCompression(reason);
				return {
					status: "compression_requested",
					reason,
					message: "Context compression will be applied on the next generation step. Previous work has been summarized and saved as artifacts."
				};
			}
		});
		logger.info("getDefaultTools returning tools:", Object.keys(defaultTools).join(", "));
		return defaultTools;
	}
	getStreamRequestId() {
		return this.streamRequestId || "";
	}
	async applyToolOverrides(originalTools, mcpTool) {
		const toolOverrides = mcpTool.config.type === "mcp" ? mcpTool.config.mcp?.toolOverrides : void 0;
		if (!toolOverrides) {
			logger.debug({ mcpToolName: mcpTool.name }, "No tool overrides configured, using original tools");
			return originalTools;
		}
		if (!originalTools || typeof originalTools !== "object") {
			logger.warn({
				mcpToolName: mcpTool.name,
				originalToolsType: typeof originalTools
			}, "Invalid original tools structure, skipping overrides");
			return originalTools || {};
		}
		const processedTools = {};
		const availableToolNames = Object.keys(originalTools);
		const overrideNames = Object.keys(toolOverrides);
		const invalidOverrides = overrideNames.filter((name) => !availableToolNames.includes(name));
		if (invalidOverrides.length > 0) logger.warn({
			mcpToolName: mcpTool.name,
			invalidOverrides,
			availableTools: availableToolNames
		}, "Tool override configured for non-existent tools");
		logger.info({
			mcpToolName: mcpTool.name,
			totalTools: availableToolNames.length,
			toolsWithOverrides: overrideNames.length,
			availableTools: availableToolNames,
			overrideTools: overrideNames
		}, "Starting tool override application");
		for (const [toolName, toolDef] of Object.entries(originalTools)) {
			if (!toolDef || typeof toolDef !== "object") {
				logger.warn({
					mcpToolName: mcpTool.name,
					toolName,
					toolDefType: typeof toolDef
				}, "Invalid tool definition structure, skipping tool");
				continue;
			}
			const override = toolOverrides[toolName];
			if (override && (override.schema || override.description || override.displayName)) try {
				logger.debug({
					mcpToolName: mcpTool.name,
					toolName,
					override: {
						hasSchema: !!override.schema,
						hasDescription: !!override.description,
						hasDisplayName: !!override.displayName,
						hasTransformation: !!override.transformation,
						transformationType: typeof override.transformation
					}
				}, "Processing tool override");
				let inputSchema;
				try {
					inputSchema = override.schema ? jsonSchemaToZod(override.schema) : toolDef.inputSchema;
				} catch (schemaError) {
					logger.error({
						mcpToolName: mcpTool.name,
						toolName,
						schemaError: schemaError instanceof Error ? schemaError.message : String(schemaError),
						overrideSchema: override.schema
					}, "Failed to convert override schema, using original");
					inputSchema = toolDef.inputSchema;
				}
				const toolId = override.displayName || toolName;
				const simplifiedTool = tool({
					description: override.description || toolDef.description || `Tool ${toolId}`,
					inputSchema,
					execute: async (simpleArgs) => {
						let complexArgs = simpleArgs;
						if (override.transformation) try {
							const startTime = Date.now();
							if (typeof override.transformation === "string") complexArgs = await JsonTransformer.transform(simpleArgs, override.transformation, { timeout: 1e4 });
							else if (typeof override.transformation === "object" && override.transformation !== null) complexArgs = await JsonTransformer.transformWithConfig(simpleArgs, { objectTransformation: override.transformation }, { timeout: 1e4 });
							else logger.warn({
								mcpToolName: mcpTool.name,
								toolName,
								transformationType: typeof override.transformation
							}, "Invalid transformation type, skipping transformation");
							const duration = Date.now() - startTime;
							logger.debug({
								mcpToolName: mcpTool.name,
								toolName,
								transformationDuration: duration,
								hasSimpleArgs: !!simpleArgs,
								hasComplexArgs: !!complexArgs,
								transformation: typeof override.transformation === "string" ? `${override.transformation.substring(0, 100)}...` : "object-transformation"
							}, "Successfully transformed tool arguments");
						} catch (transformError) {
							const errorMessage = transformError instanceof Error ? transformError.message : String(transformError);
							logger.error({
								mcpToolName: mcpTool.name,
								toolName,
								transformError: errorMessage,
								transformation: override.transformation,
								simpleArgs
							}, "Failed to transform tool arguments, using original arguments");
							complexArgs = simpleArgs;
						}
						if (typeof toolDef.execute !== "function") throw new Error(`Original tool ${toolName} does not have a valid execute function`);
						try {
							logger.debug({
								mcpToolName: mcpTool.name,
								toolName,
								hasComplexArgs: !!complexArgs
							}, "Executing original tool with processed arguments");
							return await toolDef.execute(complexArgs);
						} catch (executeError) {
							const errorMessage = executeError instanceof Error ? executeError.message : String(executeError);
							logger.error({
								mcpToolName: mcpTool.name,
								toolName,
								executeError: errorMessage,
								complexArgs
							}, "Failed to execute original tool");
							throw new Error(`Tool execution failed for ${toolName}: ${errorMessage}`);
						}
					}
				});
				const finalToolName = override.displayName || toolName;
				processedTools[finalToolName] = simplifiedTool;
				logger.info({
					mcpToolName: mcpTool.name,
					originalToolName: toolName,
					finalToolName,
					displayName: override.displayName,
					hasSchemaOverride: !!override.schema,
					hasDescriptionOverride: !!override.description,
					hasTransformation: !!override.transformation
				}, "Successfully applied tool overrides");
			} catch (error) {
				const errorMessage = error instanceof Error ? error.message : String(error);
				logger.error({
					mcpToolName: mcpTool.name,
					toolName,
					error: errorMessage,
					override
				}, "Failed to apply tool overrides, using original tool");
				processedTools[toolName] = toolDef;
			}
			else {
				processedTools[toolName] = toolDef;
				logger.debug({
					mcpToolName: mcpTool.name,
					toolName
				}, "No overrides configured for tool, using original");
			}
		}
		const processedToolNames = Object.keys(processedTools);
		logger.info({
			mcpToolName: mcpTool.name,
			originalToolCount: availableToolNames.length,
			processedToolCount: processedToolNames.length,
			processedTools: processedToolNames
		}, "Completed tool override application");
		return processedTools;
	}
	/**
	* Format tool result for storage in conversation history
	*/
	formatToolResult(toolName, args, result, toolCallId) {
		const input = args ? JSON.stringify(args, null, 2) : "No input";
		let parsedResult = result;
		if (typeof result === "string") try {
			parsedResult = JSON.parse(result);
		} catch (_e) {}
		const cleanResult = parsedResult && typeof parsedResult === "object" && !Array.isArray(parsedResult) ? {
			...parsedResult,
			result: parsedResult.result && typeof parsedResult.result === "object" && !Array.isArray(parsedResult.result) ? Object.fromEntries(Object.entries(parsedResult.result).filter(([key]) => key !== "_structureHints")) : parsedResult.result
		} : parsedResult;
		return `## Tool: ${toolName}

### 🔧 TOOL_CALL_ID: ${toolCallId}

### Input
${input}

### Output
${typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, null, 2)}`;
	}
	/**
	* Get the conversation ID for storing tool results
	* Always uses the real conversation ID - delegation filtering happens at query time
	*/
	getToolResultConversationId() {
		return this.conversationId;
	}
	/**
	* Analyze tool result structure and add helpful path hints for artifact creation
	* Only adds hints when artifact components are available
	*/
	enhanceToolResultWithStructureHints(result) {
		if (!result) return result;
		if (!this.artifactComponents || this.artifactComponents.length === 0) return result;
		let parsedForAnalysis = result;
		if (typeof result === "string") try {
			parsedForAnalysis = parseEmbeddedJson(result);
		} catch (_error) {
			parsedForAnalysis = result;
		}
		if (!parsedForAnalysis || typeof parsedForAnalysis !== "object") return result;
		const findAllPaths = (obj, prefix = "result", depth = 0) => {
			if (depth > 8) return [];
			const paths = [];
			if (Array.isArray(obj)) {
				if (obj.length > 0) {
					paths.push(`${prefix}[array-${obj.length}-items]`);
					if (obj[0] && typeof obj[0] === "object") {
						const sampleItem = obj[0];
						Object.keys(sampleItem).forEach((key) => {
							const value = sampleItem[key];
							if (typeof value === "string" && value.length < 50) paths.push(`${prefix}[?${key}=='${value}']`);
							else if (typeof value === "boolean") paths.push(`${prefix}[?${key}==${value}]`);
							else if (key === "id" || key === "name" || key === "type") paths.push(`${prefix}[?${key}=='value']`);
						});
					}
					paths.push(...findAllPaths(obj[0], `${prefix}[?field=='value']`, depth + 1));
				}
			} else if (obj && typeof obj === "object") Object.entries(obj).forEach(([key, value]) => {
				const currentPath = `${prefix}.${key}`;
				if (value && typeof value === "object") {
					if (Array.isArray(value)) paths.push(`${currentPath}[array]`);
					else paths.push(`${currentPath}[object]`);
					paths.push(...findAllPaths(value, currentPath, depth + 1));
				} else paths.push(`${currentPath}[${typeof value}]`);
			});
			return paths;
		};
		const findCommonFields = (obj, depth = 0) => {
			if (depth > 5) return /* @__PURE__ */ new Set();
			const fields = /* @__PURE__ */ new Set();
			if (Array.isArray(obj)) obj.slice(0, 3).forEach((item) => {
				if (item && typeof item === "object") Object.keys(item).forEach((key) => {
					fields.add(key);
				});
			});
			else if (obj && typeof obj === "object") {
				Object.keys(obj).forEach((key) => {
					fields.add(key);
				});
				Object.values(obj).forEach((value) => {
					findCommonFields(value, depth + 1).forEach((field) => {
						fields.add(field);
					});
				});
			}
			return fields;
		};
		const findUsefulSelectors = (obj, prefix = "result", depth = 0) => {
			if (depth > 5) return [];
			const selectors = [];
			if (Array.isArray(obj) && obj.length > 0) {
				const firstItem = obj[0];
				if (firstItem && typeof firstItem === "object") {
					if (firstItem.title) selectors.push(`${prefix}[?title=='${String(firstItem.title).replace(/'/g, "\\'")}'] | [0]`);
					if (firstItem.type) selectors.push(`${prefix}[?type=='${firstItem.type}'] | [0]`);
					if (firstItem.record_type) selectors.push(`${prefix}[?record_type=='${firstItem.record_type}'] | [0]`);
					if (firstItem.url) selectors.push(`${prefix}[?url!=null] | [0]`);
					if (firstItem.type && firstItem.title) selectors.push(`${prefix}[?type=='${firstItem.type}' && title=='${String(firstItem.title).replace(/'/g, "\\'")}'] | [0]`);
					selectors.push(`${prefix}[0]`);
				}
			} else if (obj && typeof obj === "object") Object.entries(obj).forEach(([key, value]) => {
				if (typeof value === "object" && value !== null) selectors.push(...findUsefulSelectors(value, `${prefix}.${key}`, depth + 1));
			});
			return selectors;
		};
		const findNestedContentPaths = (obj, prefix = "result", depth = 0) => {
			if (depth > 6) return [];
			const paths = [];
			if (obj && typeof obj === "object") Object.entries(obj).forEach(([key, value]) => {
				const currentPath = `${prefix}.${key}`;
				if (Array.isArray(value) && value.length > 0) {
					const firstItem = value[0];
					if (firstItem && typeof firstItem === "object") {
						if (firstItem.type === "document" || firstItem.type === "text") {
							paths.push(`${currentPath}[?type=='document'] | [0]`);
							paths.push(`${currentPath}[?type=='text'] | [0]`);
							if (firstItem.title) {
								const titleSample = String(firstItem.title).slice(0, 20);
								paths.push(`${currentPath}[?title && contains(title, '${titleSample.split(" ")[0]}')] | [0]`);
							}
							if (firstItem.record_type) paths.push(`${currentPath}[?record_type=='${firstItem.record_type}'] | [0]`);
						}
					}
					paths.push(...findNestedContentPaths(value, currentPath, depth + 1));
				} else if (value && typeof value === "object") paths.push(...findNestedContentPaths(value, currentPath, depth + 1));
			});
			return paths;
		};
		try {
			const allPaths = findAllPaths(parsedForAnalysis);
			const commonFields = Array.from(findCommonFields(parsedForAnalysis)).slice(0, 15);
			const usefulSelectors = findUsefulSelectors(parsedForAnalysis).slice(0, 10);
			const nestedContentPaths = findNestedContentPaths(parsedForAnalysis).slice(0, 8);
			const terminalPaths = allPaths.filter((p) => p.includes("[string]") || p.includes("[number]") || p.includes("[boolean]")).slice(0, 20);
			const arrayPaths = allPaths.filter((p) => p.includes("[array")).slice(0, 15);
			const objectPaths = allPaths.filter((p) => p.includes("[object]")).slice(0, 15);
			const allSelectors = [...usefulSelectors, ...nestedContentPaths];
			const uniqueSelectors = [...new Set(allSelectors)].slice(0, 15);
			return {
				...result,
				_structureHints: {
					terminalPaths,
					arrayPaths,
					objectPaths,
					commonFields,
					exampleSelectors: uniqueSelectors,
					deepStructureExamples: nestedContentPaths,
					maxDepthFound: Math.max(...allPaths.map((p) => (p.match(/\./g) || []).length)),
					totalPathsFound: allPaths.length,
					artifactGuidance: {
						creationFirst: "🚨 CRITICAL: Artifacts must be CREATED before they can be referenced. Use ArtifactCreate_[Type] components FIRST, then reference with Artifact components only if citing the SAME artifact again.",
						baseSelector: "🎯 CRITICAL: Use base_selector to navigate to ONE specific item. For deeply nested structures with repeated keys, use full paths with specific filtering (e.g., \"result.data.content.items[?type=='guide' && status=='active']\")",
						detailsSelector: "📝 Use relative selectors for specific fields (e.g., \"title\", \"metadata.category\", \"properties.status\", \"content.details\")",
						avoidLiterals: "❌ NEVER use literal values - always use field selectors to extract from data",
						avoidArrays: "✨ ALWAYS filter arrays to single items using [?condition] - NEVER use [*] notation which returns arrays",
						nestedKeys: "🔑 For structures with repeated keys (like result.content.data.content.items.content), use full paths with filtering at each level",
						filterTips: "💡 Use compound filters for precision: [?type=='document' && category=='api']",
						forbiddenSyntax: "🚫 FORBIDDEN JMESPATH PATTERNS:\n❌ NEVER: [?title~'.*text.*'] (regex patterns with ~ operator)\n❌ NEVER: [?field~'pattern.*'] (any ~ operator usage)\n❌ NEVER: [?title~'Slack.*Discord.*'] (regex wildcards)\n❌ NEVER: [?name~'https://.*'] (regex in URL matching)\n❌ NEVER: [?text ~ contains(@, 'word')] (~ with @ operator)\n❌ NEVER: contains(@, 'text') (@ operator usage)\n❌ NEVER: [?field==\"value\"] (double quotes in filters)\n❌ NEVER: result.items[?type=='doc'][?status=='active'] (chained filters)\n✅ USE INSTEAD:\n✅ [?contains(title, 'text')] (contains function)\n✅ [?title=='exact match'] (exact string matching)\n✅ [?contains(title, 'Slack') && contains(title, 'Discord')] (compound conditions)\n✅ [?starts_with(url, 'https://')] (starts_with function)\n✅ [?type=='doc' && status=='active'] (single filter with &&)",
						pathDepth: `📏 This structure goes ${Math.max(...allPaths.map((p) => (p.match(/\./g) || []).length))} levels deep - use full paths to avoid ambiguity`
					},
					note: `Comprehensive structure analysis: ${allPaths.length} paths found, ${Math.max(...allPaths.map((p) => (p.match(/\./g) || []).length))} levels deep. Use specific filtering for precise selection.`
				}
			};
		} catch (error) {
			logger.warn({ error }, "Failed to enhance tool result with structure hints");
			return result;
		}
	}
	async agentHasArtifactComponents() {
		try {
			const subAgents = this.executionContext.project.agents[this.config.agentId]?.subAgents;
			if (!subAgents) return false;
			return Object.values(subAgents).some((subAgent) => (subAgent.artifactComponents?.length ?? 0) > 0);
		} catch (error) {
			logger.error({
				error,
				agentId: this.config.agentId
			}, "Failed to check agent artifact components");
			return false;
		}
	}
	async generate(userMessage, runtimeContext) {
		const conversationIdForSpan = runtimeContext?.metadata?.conversationId;
		return tracer.startActiveSpan("agent.generate", { attributes: {
			"subAgent.id": this.config.id,
			"subAgent.name": this.config.name,
			"tenant.id": this.config.tenantId,
			"project.id": this.config.projectId,
			"agent.id": this.config.agentId,
			"agent.name": this.config.name,
			...conversationIdForSpan ? { "conversation.id": conversationIdForSpan } : {}
		} }, async (span) => {
			const { contextId, taskId, streamRequestId, sessionId } = this.setupGenerationContext(runtimeContext);
			try {
				const { systemPrompt, thinkingSystemPrompt, sanitizedTools, contextBreakdown: initialContextBreakdown } = await this.loadToolsAndPrompts(sessionId, streamRequestId, runtimeContext);
				if (streamRequestId && this.artifactComponents.length > 0) agentSessionManager.updateArtifactComponents(streamRequestId, this.artifactComponents);
				const conversationId = runtimeContext?.metadata?.conversationId;
				if (conversationId) this.setConversationId(conversationId);
				const { conversationHistory, contextBreakdown } = await this.buildConversationHistory(contextId, taskId, userMessage, streamRequestId, initialContextBreakdown);
				const breakdownAttributes = {};
				for (const componentDef of V1_BREAKDOWN_SCHEMA) breakdownAttributes[componentDef.spanAttribute] = contextBreakdown.components[componentDef.key] ?? 0;
				breakdownAttributes["context.breakdown.total_tokens"] = contextBreakdown.total;
				span.setAttributes(breakdownAttributes);
				const { primaryModelSettings, modelSettings, hasStructuredOutput, shouldStreamPhase1, timeoutMs } = this.configureModelSettings();
				let response;
				let textResponse;
				const messages = this.buildInitialMessages(systemPrompt, thinkingSystemPrompt, hasStructuredOutput, conversationHistory, userMessage);
				const { originalMessageCount, compressor } = this.setupCompression(messages, sessionId, contextId, primaryModelSettings);
				if (shouldStreamPhase1) {
					const streamConfig = {
						...modelSettings,
						toolChoice: "auto"
					};
					const streamResult = streamText(this.buildBaseGenerationConfig(streamConfig, messages, sanitizedTools, compressor, originalMessageCount, timeoutMs, "auto", void 0, false, contextBreakdown.total));
					const parser = this.setupStreamParser(sessionId, contextId);
					await this.processStreamEvents(streamResult, parser);
					response = await streamResult;
					response = this.formatStreamingResponse(response, parser);
				} else {
					const toolChoice = hasStructuredOutput ? "required" : "auto";
					response = await generateText(this.buildBaseGenerationConfig(modelSettings, messages, sanitizedTools, compressor, originalMessageCount, timeoutMs, toolChoice, "planning", true, contextBreakdown.total));
				}
				if (response.steps) {
					const resolvedSteps = await response.steps;
					response = {
						...response,
						steps: resolvedSteps
					};
				}
				if (hasStructuredOutput && !hasToolCallWithPrefix("transfer_to_")(response)) if (response.steps?.flatMap((s) => s.toolCalls || [])?.find((tc) => tc.toolName === "thinking_complete")) {
					const reasoningFlow = this.buildReasoningFlow(response, sessionId);
					const dataComponentsSchema = this.buildDataComponentsSchema();
					const structuredModelSettings = ModelFactory.prepareGenerationConfig(this.getStructuredOutputModel());
					const phase2TimeoutMs = this.calculatePhase2Timeout(structuredModelSettings);
					if (this.getStreamingHelper()) {
						const phase2Messages = await this.buildPhase2Messages(runtimeContext, conversationHistory, userMessage, reasoningFlow);
						const result = await this.executeStreamingPhase2(structuredModelSettings, phase2Messages, dataComponentsSchema, phase2TimeoutMs, sessionId, contextId, response);
						response = result;
						textResponse = result.textResponse;
					} else {
						const phase2Messages = await this.buildPhase2Messages(runtimeContext, conversationHistory, userMessage, reasoningFlow);
						const result = await this.executeNonStreamingPhase2(structuredModelSettings, phase2Messages, dataComponentsSchema, phase2TimeoutMs, response);
						response = result;
						textResponse = result.textResponse;
					}
				} else textResponse = response.text || "";
				else textResponse = response.steps[response.steps.length - 1].text || "";
				span.setStatus({ code: SpanStatusCode.OK });
				span.end();
				const formattedResponse = await this.formatFinalResponse(response, textResponse, sessionId, contextId);
				if (streamRequestId) {
					const generationType = response.object ? "object_generation" : "text_generation";
					agentSessionManager.recordEvent(streamRequestId, "agent_generate", this.config.id, {
						parts: (formattedResponse.formattedContent?.parts || []).map((part) => ({
							type: part.kind === "text" ? "text" : part.kind === "data" ? "tool_result" : "text",
							content: part.text || JSON.stringify(part.data)
						})),
						generationType
					});
				}
				if (compressor) compressor.fullCleanup();
				this.currentCompressor = null;
				return formattedResponse;
			} catch (error) {
				this.handleGenerationError(error, span);
			}
		});
	}
	/**
	* Setup generation context and initialize streaming helper
	*/
	setupGenerationContext(runtimeContext) {
		const contextId = runtimeContext?.contextId || "default";
		const taskId = runtimeContext?.metadata?.taskId || "unknown";
		const streamRequestId = runtimeContext?.metadata?.streamRequestId;
		const sessionId = streamRequestId || "fallback-session";
		this.streamRequestId = streamRequestId;
		this.streamHelper = streamRequestId ? getStreamHelper(streamRequestId) : void 0;
		if (streamRequestId && this.artifactComponents.length > 0) agentSessionManager.updateArtifactComponents(streamRequestId, this.artifactComponents);
		const conversationId = runtimeContext?.metadata?.conversationId;
		if (conversationId) this.setConversationId(conversationId);
		return {
			contextId,
			taskId,
			streamRequestId,
			sessionId
		};
	}
	/**
	* Load all tools and system prompts in parallel, then combine and sanitize them
	*/
	async loadToolsAndPrompts(sessionId, streamRequestId, runtimeContext) {
		const [mcpTools, systemPromptResult, thinkingSystemPromptResult, functionTools, relationTools, defaultTools] = await tracer.startActiveSpan("agent.load_tools", { attributes: {
			"subAgent.name": this.config.name,
			"session.id": sessionId || "none"
		} }, async (childSpan) => {
			try {
				const result = await Promise.all([
					this.getMcpTools(sessionId, streamRequestId),
					this.buildSystemPrompt(runtimeContext, false),
					this.buildSystemPrompt(runtimeContext, true),
					this.getFunctionTools(sessionId, streamRequestId),
					Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
					this.getDefaultTools(streamRequestId)
				]);
				childSpan.setStatus({ code: SpanStatusCode.OK });
				return result;
			} catch (err) {
				setSpanWithError$1(childSpan, err instanceof Error ? err : new Error(String(err)));
				throw err;
			} finally {
				childSpan.end();
			}
		});
		const systemPrompt = systemPromptResult.prompt;
		const thinkingSystemPrompt = thinkingSystemPromptResult.prompt;
		const contextBreakdown = systemPromptResult.breakdown;
		const allTools = {
			...mcpTools,
			...functionTools,
			...relationTools,
			...defaultTools
		};
		return {
			systemPrompt,
			thinkingSystemPrompt,
			sanitizedTools: this.sanitizeToolsForAISDK(allTools),
			contextBreakdown
		};
	}
	/**
	* Build conversation history based on configuration mode and filters
	*/
	async buildConversationHistory(contextId, taskId, userMessage, streamRequestId, initialContextBreakdown) {
		let conversationHistory = "";
		const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
		if (historyConfig && historyConfig.mode !== "none") {
			if (historyConfig.mode === "full") {
				const filters = {
					delegationId: this.delegationId,
					isDelegated: this.isDelegatedAgent
				};
				conversationHistory = await getConversationHistoryWithCompression({
					tenantId: this.config.tenantId,
					projectId: this.config.projectId,
					conversationId: contextId,
					currentMessage: userMessage,
					options: historyConfig,
					filters,
					summarizerModel: this.getSummarizerModel(),
					streamRequestId,
					fullContextSize: initialContextBreakdown.total
				});
			} else if (historyConfig.mode === "scoped") conversationHistory = await getConversationHistoryWithCompression({
				tenantId: this.config.tenantId,
				projectId: this.config.projectId,
				conversationId: contextId,
				currentMessage: userMessage,
				options: historyConfig,
				filters: {
					subAgentId: this.config.id,
					taskId,
					delegationId: this.delegationId,
					isDelegated: this.isDelegatedAgent
				},
				summarizerModel: this.getSummarizerModel(),
				streamRequestId,
				fullContextSize: initialContextBreakdown.total
			});
		}
		const conversationHistoryTokens = estimateTokens(conversationHistory);
		const updatedContextBreakdown = {
			components: {
				...initialContextBreakdown.components,
				conversationHistory: conversationHistoryTokens
			},
			total: initialContextBreakdown.total
		};
		calculateBreakdownTotal(updatedContextBreakdown);
		return {
			conversationHistory,
			contextBreakdown: updatedContextBreakdown
		};
	}
	/**
	* Configure model settings, timeouts, and streaming behavior
	*/
	configureModelSettings() {
		const primaryModelSettings = this.getPrimaryModel();
		const modelSettings = ModelFactory.prepareGenerationConfig(primaryModelSettings);
		const hasStructuredOutput = Boolean(this.config.dataComponents && this.config.dataComponents.length > 0);
		const shouldStreamPhase1 = this.getStreamingHelper() && !hasStructuredOutput;
		const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING : LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING;
		const timeoutMs = Math.min(configuredTimeout, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS);
		if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) logger.warn({
			requestedTimeout: modelSettings.maxDuration * 1e3,
			appliedTimeout: timeoutMs,
			maxAllowed: LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
		}, "Requested timeout exceeded maximum allowed, capping to 10 minutes");
		return {
			primaryModelSettings,
			modelSettings: {
				...modelSettings,
				maxDuration: timeoutMs / 1e3
			},
			hasStructuredOutput,
			shouldStreamPhase1,
			timeoutMs
		};
	}
	/**
	* Build initial messages array with system prompt and user content
	*/
	buildInitialMessages(systemPrompt, thinkingSystemPrompt, hasStructuredOutput, conversationHistory, userMessage) {
		const phase1SystemPrompt = hasStructuredOutput ? thinkingSystemPrompt : systemPrompt;
		const messages = [];
		messages.push({
			role: "system",
			content: phase1SystemPrompt
		});
		if (conversationHistory.trim() !== "") messages.push({
			role: "user",
			content: conversationHistory
		});
		messages.push({
			role: "user",
			content: userMessage
		});
		return messages;
	}
	/**
	* Setup compression for the current generation
	*/
	setupCompression(messages, sessionId, contextId, primaryModelSettings) {
		const originalMessageCount = messages.length;
		const compressionConfigResult = getCompressionConfigForModel(primaryModelSettings);
		const compressionConfig = {
			hardLimit: compressionConfigResult.hardLimit,
			safetyBuffer: compressionConfigResult.safetyBuffer,
			enabled: compressionConfigResult.enabled
		};
		const compressor = compressionConfig.enabled ? new MidGenerationCompressor(sessionId, contextId, this.config.tenantId, this.config.projectId, compressionConfig, this.getSummarizerModel(), primaryModelSettings) : null;
		this.currentCompressor = compressor;
		return {
			originalMessageCount,
			compressor
		};
	}
	/**
	* Prepare step function for streaming with compression logic
	*/
	async handlePrepareStepCompression(stepMessages, compressor, originalMessageCount, fullContextSize) {
		if (!compressor) return {};
		if (compressor.isCompressionNeeded(stepMessages)) {
			logger.info({ compressorState: compressor.getState() }, "Triggering layered mid-generation compression");
			const originalMessages = stepMessages.slice(0, originalMessageCount);
			const generatedMessages = stepMessages.slice(originalMessageCount);
			if (generatedMessages.length > 0) {
				const compressionResult = await compressor.safeCompress(generatedMessages, fullContextSize);
				if (Array.isArray(compressionResult.summary)) {
					const compressedMessages = compressionResult.summary;
					logger.info({
						originalTotal: stepMessages.length,
						compressed: originalMessages.length + compressedMessages.length,
						originalKept: originalMessages.length,
						generatedCompressed: compressedMessages.length
					}, "Simple compression fallback applied");
					return { messages: [...originalMessages, ...compressedMessages] };
				}
				const finalMessages = [...originalMessages];
				if (compressionResult.summary.text_messages && compressionResult.summary.text_messages.length > 0) finalMessages.push(...compressionResult.summary.text_messages);
				const summaryData = {
					high_level: compressionResult.summary?.high_level,
					user_intent: compressionResult.summary?.user_intent,
					decisions: compressionResult.summary?.decisions,
					open_questions: compressionResult.summary?.open_questions,
					next_steps: compressionResult.summary?.next_steps,
					related_artifacts: compressionResult.summary?.related_artifacts
				};
				if (summaryData.related_artifacts && summaryData.related_artifacts.length > 0) summaryData.related_artifacts = summaryData.related_artifacts.map((artifact) => ({
					...artifact,
					artifact_reference: `<artifact:ref id="${artifact.id}" tool="${artifact.tool_call_id}" />`
				}));
				const summaryMessage = JSON.stringify(summaryData);
				finalMessages.push({
					role: "user",
					content: `Based on your research, here's what you've discovered: ${summaryMessage}

**IMPORTANT**: If you have enough information from this compressed research to answer my original question, please provide your answer now. Only continue with additional tool calls if you need critical missing information that wasn't captured in the research above. When referencing any artifacts from the compressed research, you MUST use <artifact:ref id="artifact_id" tool="tool_call_id" /> tags with the exact IDs from the related_artifacts above.`
				});
				logger.info({
					originalTotal: stepMessages.length,
					compressed: finalMessages.length,
					originalKept: originalMessages.length,
					generatedCompressed: generatedMessages.length
				}, "AI compression completed successfully");
				return { messages: finalMessages };
			}
			return {};
		}
		return {};
	}
	async handleStopWhenConditions(steps, includeThinkingComplete = false) {
		const last = steps.at(-1);
		if (last && "text" in last && last.text) try {
			await agentSessionManager.recordEvent(this.getStreamRequestId(), "agent_reasoning", this.config.id, { parts: [{
				type: "text",
				content: last.text
			}] });
		} catch (error) {
			logger.debug({ error }, "Failed to track agent reasoning");
		}
		if (!includeThinkingComplete && last && last.content && last.content.length > 0) {
			const lastContent = last.content[last.content.length - 1];
			if (lastContent.type === "tool-error") {
				const error = lastContent.error;
				if (error && typeof error === "object" && "name" in error && error.name === "connection_refused") return true;
			}
		}
		if (steps.length >= 1) {
			const currentStep = steps[steps.length - 1];
			if (currentStep && "toolCalls" in currentStep && currentStep.toolCalls) {
				const hasTransferTool = currentStep.toolCalls.some((tc) => tc.toolName.startsWith("transfer_to_"));
				const hasThinkingComplete = currentStep.toolCalls.some((tc) => tc.toolName === "thinking_complete");
				if (hasTransferTool) return true;
				if (includeThinkingComplete && hasThinkingComplete && "toolResults" in currentStep && currentStep.toolResults) return true;
			}
		}
		const maxSteps = this.getMaxGenerationSteps();
		if (steps.length >= maxSteps) {
			logger.warn({
				subAgentId: this.config.id,
				agentId: this.config.agentId,
				stepsCompleted: steps.length,
				maxSteps,
				conversationId: this.conversationId
			}, "Sub-agent reached maximum generation steps limit");
			tracer.startActiveSpan("agent.max_steps_reached", { attributes: {
				"agent.max_steps_reached": true,
				"agent.steps_completed": steps.length,
				"agent.max_steps": maxSteps,
				"agent.id": this.config.agentId,
				"subAgent.id": this.config.id
			} }, (span) => {
				span.addEvent("max_generation_steps_reached", { message: `Sub-agent "${this.config.id}" reached maximum generation steps (${steps.length}/${maxSteps})` });
				span.end();
			});
			return true;
		}
		return false;
	}
	setupStreamParser(sessionId, contextId) {
		const streamHelper = this.getStreamingHelper();
		if (!streamHelper) throw new Error("Stream helper is unexpectedly undefined in streaming context");
		const session = toolSessionManager.getSession(sessionId);
		const artifactParserOptions = {
			sessionId,
			taskId: session?.taskId,
			projectId: session?.projectId,
			artifactComponents: this.artifactComponents,
			streamRequestId: this.getStreamRequestId(),
			subAgentId: this.config.id
		};
		return new IncrementalStreamParser(streamHelper, this.executionContext, contextId, artifactParserOptions);
	}
	buildTelemetryConfig(phase) {
		return {
			isEnabled: true,
			functionId: this.config.id,
			recordInputs: true,
			recordOutputs: true,
			metadata: {
				...phase && { phase },
				subAgentId: this.config.id,
				subAgentName: this.config.name
			}
		};
	}
	buildBaseGenerationConfig(modelSettings, messages, sanitizedTools, compressor, originalMessageCount, timeoutMs, toolChoice = "auto", phase, includeThinkingComplete = false, fullContextSize) {
		return {
			...modelSettings,
			toolChoice,
			messages,
			tools: sanitizedTools,
			prepareStep: async ({ messages: stepMessages }) => {
				return await this.handlePrepareStepCompression(stepMessages, compressor, originalMessageCount, fullContextSize);
			},
			stopWhen: async ({ steps }) => {
				return await this.handleStopWhenConditions(steps, includeThinkingComplete);
			},
			experimental_telemetry: this.buildTelemetryConfig(phase),
			abortSignal: AbortSignal.timeout(timeoutMs)
		};
	}
	buildReasoningFlow(response, sessionId) {
		const reasoningFlow = [];
		const compressionSummary = this.currentCompressor?.getCompressionSummary();
		if (compressionSummary) {
			const summaryContent = JSON.stringify(compressionSummary, null, 2);
			reasoningFlow.push({
				role: "assistant",
				content: `## Research Summary (Compressed)\n\nBased on tool executions, here's the comprehensive summary:\n\n\`\`\`json\n${summaryContent}\n\`\`\`\n\nThis summary represents all tool execution results in compressed form. Full details are preserved in artifacts.`
			});
		} else if (response.steps) response.steps.forEach((step) => {
			if (step.toolCalls && step.toolResults) step.toolCalls.forEach((call, index) => {
				const result = step.toolResults[index];
				if (result) {
					const storedResult = toolSessionManager.getToolResult(sessionId, result.toolCallId);
					if ((storedResult?.toolName || call.toolName) === "thinking_complete") return;
					const actualResult = storedResult?.result || result.result || result;
					const actualArgs = storedResult?.args || call.args;
					const cleanResult = actualResult && typeof actualResult === "object" && !Array.isArray(actualResult) ? Object.fromEntries(Object.entries(actualResult).filter(([key]) => key !== "_structureHints")) : actualResult;
					const input = actualArgs ? JSON.stringify(actualArgs, null, 2) : "No input";
					const output = typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, null, 2);
					let structureHintsFormatted = "";
					if (actualResult?._structureHints && this.artifactComponents && this.artifactComponents.length > 0) {
						const hints = actualResult._structureHints;
						structureHintsFormatted = `
### 📊 Structure Hints for Artifact Creation

**Terminal Field Paths (${hints.terminalPaths?.length || 0} found):**
${hints.terminalPaths?.map((path) => `  • ${path}`).join("\n") || "  None detected"}

**Array Structures (${hints.arrayPaths?.length || 0} found):**
${hints.arrayPaths?.map((path) => `  • ${path}`).join("\n") || "  None detected"}

**Object Structures (${hints.objectPaths?.length || 0} found):**
${hints.objectPaths?.map((path) => `  • ${path}`).join("\n") || "  None detected"}

**Example Selectors:**
${hints.exampleSelectors?.map((sel) => `  • ${sel}`).join("\n") || "  None detected"}

**Common Fields:**
${hints.commonFields?.map((field) => `  • ${field}`).join("\n") || "  None detected"}

**Structure Stats:** ${hints.totalPathsFound || 0} total paths, ${hints.maxDepthFound || 0} levels deep

**Note:** ${hints.note || "Use these paths for artifact base selectors."}

**Forbidden Syntax:** ${hints.forbiddenSyntax || "Use these paths for artifact base selectors."}
`;
					}
					const formattedResult = `## Tool: ${call.toolName}

### 🔧 TOOL_CALL_ID: ${result.toolCallId}

### Input
${input}

### Output
${output}${structureHintsFormatted}`;
					reasoningFlow.push({
						role: "assistant",
						content: formattedResult
					});
				}
			});
		});
		return reasoningFlow;
	}
	buildDataComponentsSchema() {
		const componentSchemas = [];
		if (this.config.dataComponents && this.config.dataComponents.length > 0) this.config.dataComponents.forEach((dc) => {
			const propsSchema = jsonSchemaToZod(dc.props);
			componentSchemas.push(z.object({
				id: z.string(),
				name: z.literal(dc.name),
				props: propsSchema
			}));
		});
		if (this.artifactComponents.length > 0) {
			const artifactCreateSchemas = ArtifactCreateSchema.getSchemas(this.artifactComponents);
			componentSchemas.push(...artifactCreateSchemas);
			componentSchemas.push(ArtifactReferenceSchema.getSchema());
		}
		let dataComponentsSchema;
		if (componentSchemas.length === 1) {
			dataComponentsSchema = componentSchemas[0];
			logger.info({ agentId: this.config.id }, "Using single schema (no union needed)");
		} else {
			dataComponentsSchema = z.union(componentSchemas);
			logger.info({ agentId: this.config.id }, "Created union schema");
		}
		return dataComponentsSchema;
	}
	calculatePhase2Timeout(structuredModelSettings) {
		const configuredPhase2Timeout = structuredModelSettings.maxDuration ? Math.min(structuredModelSettings.maxDuration * 1e3, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) : LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS;
		const phase2TimeoutMs = Math.min(configuredPhase2Timeout, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS);
		if (structuredModelSettings.maxDuration && structuredModelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) logger.warn({
			requestedTimeout: structuredModelSettings.maxDuration * 1e3,
			appliedTimeout: phase2TimeoutMs,
			maxAllowed: LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS,
			phase: "structured_generation"
		}, "Phase 2 requested timeout exceeded maximum allowed, capping to 10 minutes");
		return phase2TimeoutMs;
	}
	async buildPhase2Messages(runtimeContext, conversationHistory, userMessage, reasoningFlow) {
		const phase2Messages = [{
			role: "system",
			content: await this.buildPhase2SystemPrompt(runtimeContext)
		}];
		if (conversationHistory.trim() !== "") phase2Messages.push({
			role: "user",
			content: conversationHistory
		});
		phase2Messages.push({
			role: "user",
			content: userMessage
		});
		phase2Messages.push(...reasoningFlow);
		if (reasoningFlow.length > 0 && reasoningFlow[reasoningFlow.length - 1]?.role === "assistant") phase2Messages.push({
			role: "user",
			content: "Continue with the structured response."
		});
		return phase2Messages;
	}
	async executeStreamingPhase2(structuredModelSettings, phase2Messages, dataComponentsSchema, phase2TimeoutMs, sessionId, contextId, response) {
		const streamResult = streamText({
			...structuredModelSettings,
			messages: phase2Messages,
			output: Output.object({ schema: z.object({ dataComponents: z.array(dataComponentsSchema) }) }),
			experimental_telemetry: this.buildTelemetryConfig("structured_generation"),
			abortSignal: AbortSignal.timeout(phase2TimeoutMs)
		});
		const parser = this.setupStreamParser(sessionId, contextId);
		for await (const delta of streamResult.partialOutputStream) if (delta) await parser.processObjectDelta(delta);
		await parser.finalize();
		const structuredResponse = await streamResult;
		const collectedParts = parser.getCollectedParts();
		if (collectedParts.length > 0) response.formattedContent = { parts: collectedParts.map((part) => ({
			kind: part.kind,
			...part.kind === "text" && { text: part.text },
			...part.kind === "data" && { data: part.data }
		})) };
		return {
			...response,
			object: structuredResponse.output,
			textResponse: JSON.stringify(structuredResponse.output, null, 2)
		};
	}
	async executeNonStreamingPhase2(structuredModelSettings, phase2Messages, dataComponentsSchema, phase2TimeoutMs, response) {
		const structuredResponse = await generateText(withJsonPostProcessing({
			...structuredModelSettings,
			messages: phase2Messages,
			output: Output.object({ schema: z.object({ dataComponents: z.array(dataComponentsSchema) }) }),
			experimental_telemetry: this.buildTelemetryConfig("structured_generation"),
			abortSignal: AbortSignal.timeout(phase2TimeoutMs)
		}));
		return {
			...response,
			object: structuredResponse.output,
			textResponse: JSON.stringify(structuredResponse.output, null, 2)
		};
	}
	async formatFinalResponse(response, textResponse, sessionId, contextId) {
		let formattedContent = response.formattedContent || null;
		if (!formattedContent) {
			const session = toolSessionManager.getSession(sessionId);
			const responseFormatter = new ResponseFormatter(this.executionContext, {
				sessionId,
				taskId: session?.taskId,
				projectId: session?.projectId,
				contextId,
				artifactComponents: this.artifactComponents,
				streamRequestId: this.getStreamRequestId(),
				subAgentId: this.config.id
			});
			if (response.object) formattedContent = await responseFormatter.formatObjectResponse(response.object, contextId);
			else if (textResponse) formattedContent = await responseFormatter.formatResponse(textResponse, contextId);
		}
		return {
			...response,
			formattedContent
		};
	}
	handleGenerationError(error, span) {
		if (this.currentCompressor) this.currentCompressor.fullCleanup();
		this.currentCompressor = null;
		const errorToThrow = error instanceof Error ? error : new Error(String(error));
		setSpanWithError$1(span, errorToThrow);
		span.end();
		throw errorToThrow;
	}
	/**
	* Public cleanup method for external lifecycle management (e.g., session cleanup)
	* Performs full cleanup of compression state when agent/session is ending
	*/
	cleanupCompression() {
		if (this.currentCompressor) {
			this.currentCompressor.fullCleanup();
			this.currentCompressor = null;
		}
	}
	async processStreamEvents(streamResult, parser) {
		for await (const event of streamResult.fullStream) switch (event.type) {
			case "text-delta":
				await parser.processTextChunk(event.text);
				break;
			case "tool-call":
				parser.markToolResult();
				break;
			case "tool-result":
				parser.markToolResult();
				break;
			case "finish":
				if (event.finishReason === "tool-calls") parser.markToolResult();
				break;
			case "error": {
				if (event.error instanceof Error) throw event.error;
				const errorMessage = event.error?.error?.message;
				throw new Error(errorMessage);
			}
		}
		await parser.finalize();
	}
	formatStreamingResponse(response, parser) {
		const collectedParts = parser.getCollectedParts();
		if (collectedParts.length > 0) response.formattedContent = { parts: collectedParts.map((part) => ({
			kind: part.kind,
			...part.kind === "text" && { text: part.text },
			...part.kind === "data" && { data: part.data }
		})) };
		const streamedContent = parser.getAllStreamedContent();
		if (streamedContent.length > 0) response.streamedContent = { parts: streamedContent.map((part) => ({
			kind: part.kind,
			...part.kind === "text" && { text: part.text },
			...part.kind === "data" && { data: part.data }
		})) };
		return response;
	}
};

//#endregion
export { Agent, hasToolCallWithPrefix };