import { n as loadEnvironmentFiles, t as env } from "./env.js";
import { n as getLogger } from "./logger.js";
import { r as MCPTransportType, t as CredentialStoreType } from "./utility.js";
import { z } from "@hono/zod-openapi";
import { customAlphabet } from "nanoid";
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import { HTTPException } from "hono/http-exception";
import destr from "destr";
import traverse from "traverse";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { DEFAULT_REQUEST_TIMEOUT_MSEC } from "@modelcontextprotocol/sdk/shared/protocol.js";
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { tool } from "ai";
import { asyncExitHook, gracefulExit } from "exit-hook";
import { match } from "ts-pattern";
import { anthropic, createAnthropic } from "@ai-sdk/anthropic";
import { createGateway, gateway } from "@ai-sdk/gateway";
import { createGoogleGenerativeAI, google } from "@ai-sdk/google";
import { createOpenAI, openai } from "@ai-sdk/openai";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { createOpenRouter, openrouter } from "@openrouter/ai-sdk-provider";
import * as jose from "jose";
import { SignJWT, jwtVerify } from "jose";
import { Composio } from "@composio/core";
import { SpanStatusCode, trace } from "@opentelemetry/api";

//#region src/constants/execution-limits-shared/defaults.ts
/**
* Shared execution limit default constants used for runtime behavior across services.
* These define limits and defaults for runtime execution, not schema validation.
*/
const executionLimitsSharedDefaults = {
	MCP_TOOL_CONNECTION_TIMEOUT_MS: 3e3,
	MCP_TOOL_MAX_RETRIES: 3,
	MCP_TOOL_MAX_RECONNECTION_DELAY_MS: 3e4,
	MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS: 1e3,
	MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR: 1.5,
	CONVERSATION_HISTORY_DEFAULT_LIMIT: 50,
	CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT: 8e3
};

//#endregion
//#region src/constants/execution-limits-shared/index.ts
loadEnvironmentFiles();
const constantsSchema = z.object(Object.fromEntries(Object.keys(executionLimitsSharedDefaults).map((key) => [`AGENTS_${key}`, z.coerce.number().optional()])));
const parseConstants = () => {
	const envOverrides = constantsSchema.parse(process.env);
	return Object.fromEntries(Object.entries(executionLimitsSharedDefaults).map(([key, defaultValue]) => [key, envOverrides[`AGENTS_${key}`] ?? defaultValue]));
};
const constants = parseConstants();
const { MCP_TOOL_CONNECTION_TIMEOUT_MS, MCP_TOOL_MAX_RETRIES, MCP_TOOL_MAX_RECONNECTION_DELAY_MS, MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS, MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR, CONVERSATION_HISTORY_DEFAULT_LIMIT, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT } = constants;

//#endregion
//#region src/utils/credential-store-utils.ts
/**
* Get a lookup key for a credential store from retrieval params
* @param retrievalParams - The retrieval params for the credential store
* @param credentialStoreType - The type of credential store
* @returns A lookup key for the credential store, used to call <CredentialStore>.get()
*/
function getCredentialStoreLookupKeyFromRetrievalParams({ retrievalParams, credentialStoreType }) {
	if (retrievalParams.key) return retrievalParams.key;
	if (credentialStoreType === CredentialStoreType.nango) return JSON.stringify({
		connectionId: retrievalParams.connectionId,
		providerConfigKey: retrievalParams.providerConfigKey
	});
	return null;
}

//#endregion
//#region src/utils/conversations.ts
const generateId = customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789", 21);
/**
* Generates a standardized conversation ID.
*
* The generated ID follows these rules:
* 1. Always lowercase
* 2. No leading hyphens
*
* @returns A unique conversation ID
*
* @example
* ```typescript
* const id = getConversationId(); // returns something like "v1stgxr8z5jdhi6bmyt"
* ```
*/
function getConversationId() {
	return generateId();
}

//#endregion
//#region src/utils/apiKeys.ts
const scryptAsync = promisify(scrypt);
const logger$5 = getLogger("api-key");
const API_KEY_LENGTH = 32;
const SALT_LENGTH = 32;
const KEY_LENGTH = 64;
const generatePublicId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-", 12);
/**
* Generate a new API key with secure random bytes
*/
async function generateApiKey() {
	const publicId = generatePublicId();
	const key = `sk_${publicId}.${randomBytes(API_KEY_LENGTH).toString("base64url")}`;
	const keyPrefix = key.substring(0, 12);
	const keyHash = await hashApiKey(key);
	return {
		id: generateId(),
		publicId,
		key,
		keyHash,
		keyPrefix
	};
}
/**
* Hash an API key using scrypt
*/
async function hashApiKey(key) {
	const salt = randomBytes(SALT_LENGTH);
	const hashedBuffer = await scryptAsync(key, salt, KEY_LENGTH);
	return Buffer.concat([salt, hashedBuffer]).toString("base64");
}
/**
* Validate an API key against its hash
*/
async function validateApiKey(key, storedHash) {
	try {
		const combined = Buffer.from(storedHash, "base64");
		const salt = combined.subarray(0, SALT_LENGTH);
		return timingSafeEqual(combined.subarray(SALT_LENGTH), await scryptAsync(key, salt, KEY_LENGTH));
	} catch (error) {
		logger$5.error({ error }, "Error validating API key");
		return false;
	}
}
/**
* Check if an API key has expired
*/
function isApiKeyExpired(expiresAt) {
	if (!expiresAt) return false;
	const expirationDate = new Date(expiresAt);
	return /* @__PURE__ */ new Date() > expirationDate;
}
/**
* Extract the publicId from an API key
*/
function extractPublicId(key) {
	try {
		const parts = key.split(".");
		if (parts.length !== 2) return null;
		const segments = parts[0].split("_");
		if (segments.length < 2) return null;
		const publicId = segments[segments.length - 1];
		if (publicId.length !== 12) return null;
		return publicId;
	} catch {
		return null;
	}
}
/**
* Mask an API key for display (show only prefix and last 4 chars)
*/
function maskApiKey(keyPrefix) {
	return `${keyPrefix}...`;
}

//#endregion
//#region src/utils/date.ts
/**
* Checks if a date string is in PostgreSQL timestamp format and normalizes it to ISO 8601
* PostgreSQL format: "2025-11-07 21:48:24.858" or "2025-11-07 21:48:24"
* ISO 8601 format: "2025-11-07T21:48:24.858Z"
*/
function normalizeDateString(dateString) {
	if (typeof dateString !== "string") return dateString;
	if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d{1,3})?$/.test(dateString)) return `${dateString.replace(" ", "T")}Z`;
	return dateString;
}
/**
* Converts a date value (string or Date) to an ISO 8601 date-time string
* Ensures consistent string output for API responses and database operations
*/
function toISODateString(dateValue) {
	if (typeof dateValue === "string") {
		const normalized = normalizeDateString(dateValue);
		return typeof normalized === "string" ? normalized : normalized.toISOString();
	}
	return dateValue.toISOString();
}

//#endregion
//#region src/utils/error.ts
const ErrorCode = z.enum([
	"bad_request",
	"unauthorized",
	"forbidden",
	"not_found",
	"conflict",
	"internal_server_error",
	"unprocessable_entity"
]);
const errorCodeToHttpStatus = {
	bad_request: 400,
	unauthorized: 401,
	forbidden: 403,
	not_found: 404,
	conflict: 409,
	unprocessable_entity: 422,
	internal_server_error: 500
};
const ERROR_DOCS_BASE_URL = "https://docs.inkeep.com/agents-api/errors";
const problemDetailsSchema = z.object({
	title: z.string().openapi({
		description: "A short, human-readable summary of the problem type.",
		example: "Resource Not Found"
	}),
	status: z.number().int().openapi({
		description: "The HTTP status code.",
		example: 404
	}),
	detail: z.string().openapi({
		description: "A human-readable explanation specific to this occurrence of the problem.",
		example: "The requested resource was not found."
	}),
	instance: z.string().optional().openapi({
		description: "A URI reference that identifies the specific occurrence of the problem.",
		example: "/conversations/123"
	}),
	requestId: z.string().optional().openapi({
		description: "A unique identifier for the request, useful for troubleshooting.",
		example: "req_1234567890"
	}),
	code: ErrorCode.openapi({
		description: "A short code indicating the error code returned.",
		example: "not_found"
	})
}).openapi("ProblemDetails");
const errorResponseSchema = z.object({ error: z.object({
	code: ErrorCode.openapi({
		description: "A short code indicating the error code returned.",
		example: "not_found"
	}),
	message: z.string().openapi({
		description: "A human readable error message.",
		example: "The requested resource was not found."
	})
}) }).openapi("ErrorResponse");
function createApiError({ code, message, instance, requestId, extensions }) {
	const status = errorCodeToHttpStatus[code];
	const title = getTitleFromCode(code);
	`${ERROR_DOCS_BASE_URL}${code}`;
	const problemDetails = {
		title,
		status,
		detail: message,
		code,
		...instance && { instance },
		...requestId && { requestId }
	};
	const errorMessage = message.length > 100 ? `${message.substring(0, 97)}...` : message;
	const responseBody = {
		...problemDetails,
		error: {
			code,
			message: errorMessage
		},
		...extensions && extensions
	};
	return new HTTPException(status, {
		message,
		res: new Response(JSON.stringify(responseBody), {
			status,
			headers: {
				"Content-Type": "application/problem+json",
				"X-Content-Type-Options": "nosniff",
				...requestId && { "X-Request-ID": requestId }
			}
		})
	});
}
async function handleApiError(error, requestId) {
	if (error instanceof HTTPException) {
		const responseText = await error.getResponse().text();
		let responseJson;
		try {
			responseJson = JSON.parse(responseText);
			if (requestId && !responseJson.requestId) responseJson.requestId = requestId;
		} catch (_e) {
			responseJson = {
				title: "Internal Server Error",
				status: error.status,
				detail: `Error processing request: ${responseText || "Unknown error"}`,
				code: "internal_server_error",
				...requestId && { requestId },
				error: {
					code: "internal_server_error",
					message: "An internal server error occurred"
				}
			};
		}
		if (error.status >= 500) getLogger("core").error({
			error,
			status: error.status,
			message: responseJson.detail || responseJson.error.message,
			requestId: responseJson.requestId || requestId || "unknown"
		}, "API server error occurred");
		else getLogger("core").info({
			error,
			status: error.status,
			code: responseJson.code,
			message: responseJson.detail || responseJson.error.message,
			requestId: responseJson.requestId || requestId || "unknown"
		}, "API client error occurred");
		return responseJson;
	}
	const errorMessage = error instanceof Error ? error.message : String(error);
	const errorStack = error instanceof Error ? error.stack : void 0;
	getLogger("core").error({
		error,
		message: errorMessage,
		stack: errorStack,
		status: 500,
		requestId: requestId || "unknown"
	}, "Unhandled API error occurred");
	return {
		title: "Internal Server Error",
		status: 500,
		detail: `Server error occurred: ${error instanceof Error ? error.message.replace(/\b(password|token|key|secret|auth)\b/gi, "[REDACTED]") : "Unknown error"}`,
		code: "internal_server_error",
		...requestId && { requestId },
		error: {
			code: "internal_server_error",
			message: "An internal server error occurred. Please try again later."
		}
	};
}
function getTitleFromCode(code) {
	switch (code) {
		case "bad_request": return "Bad Request";
		case "unauthorized": return "Unauthorized";
		case "forbidden": return "Forbidden";
		case "not_found": return "Not Found";
		case "conflict": return "Conflict";
		case "unprocessable_entity": return "Unprocessable Entity";
		case "internal_server_error": return "Internal Server Error";
		default: return "Error";
	}
}
const toTitleCase = (str) => str?.replace(/\w+/g, (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).replace(/\s+/g, "") ?? "";
const errorSchemaFactory = (code, description) => ({
	description,
	content: { "application/problem+json": { schema: problemDetailsSchema.extend({
		code: z.literal(code).openapi({
			description: "A short code indicating the error code returned.",
			example: code
		}),
		detail: z.string().openapi({
			description: "A detailed explanation specific to this occurrence of the problem, providing context and specifics about what went wrong.",
			example: description
		}),
		title: z.string().openapi({
			description: "A short, human-readable summary of the problem type.",
			example: getTitleFromCode(code)
		}),
		status: z.number().int().openapi({
			description: "The HTTP status code.",
			example: errorCodeToHttpStatus[code]
		}),
		error: z.object({
			code: z.literal(code).openapi({
				description: "A short code indicating the error code returned.",
				example: code
			}),
			message: z.string().openapi({
				description: "A concise error message suitable for display to end users. May be truncated if the full detail is long.",
				example: description.length > 100 ? `${description.substring(0, 97)}...` : description
			})
		}).openapi({ description: "Legacy error format for backward compatibility." })
	}).openapi(toTitleCase(description)) } }
});
const commonCreateErrorResponses = {
	400: errorSchemaFactory("bad_request", "Bad Request"),
	401: errorSchemaFactory("unauthorized", "Unauthorized"),
	403: errorSchemaFactory("forbidden", "Forbidden"),
	422: errorSchemaFactory("unprocessable_entity", "Unprocessable Entity"),
	500: errorSchemaFactory("internal_server_error", "Internal Server Error")
};
const commonUpdateErrorResponses = {
	400: errorSchemaFactory("bad_request", "Bad Request"),
	401: errorSchemaFactory("unauthorized", "Unauthorized"),
	403: errorSchemaFactory("forbidden", "Forbidden"),
	404: errorSchemaFactory("not_found", "Not Found"),
	422: errorSchemaFactory("unprocessable_entity", "Unprocessable Entity"),
	500: errorSchemaFactory("internal_server_error", "Internal Server Error")
};
const commonGetErrorResponses = {
	400: errorSchemaFactory("bad_request", "Bad Request"),
	401: errorSchemaFactory("unauthorized", "Unauthorized"),
	403: errorSchemaFactory("forbidden", "Forbidden"),
	404: errorSchemaFactory("not_found", "Not Found"),
	422: errorSchemaFactory("unprocessable_entity", "Unprocessable Entity"),
	500: errorSchemaFactory("internal_server_error", "Internal Server Error")
};
const commonDeleteErrorResponses = {
	400: errorSchemaFactory("bad_request", "Bad Request"),
	401: errorSchemaFactory("unauthorized", "Unauthorized"),
	403: errorSchemaFactory("forbidden", "Forbidden"),
	404: errorSchemaFactory("not_found", "Not Found"),
	422: errorSchemaFactory("unprocessable_entity", "Unprocessable Entity"),
	500: errorSchemaFactory("internal_server_error", "Internal Server Error")
};

//#endregion
//#region src/utils/execution.ts
/**
* Create execution context from middleware values
*/
function createExecutionContext(params) {
	return {
		apiKey: params.apiKey,
		tenantId: params.tenantId,
		projectId: params.projectId,
		agentId: params.agentId,
		baseUrl: params.baseUrl || process.env.API_URL || "http://localhost:3003",
		apiKeyId: params.apiKeyId
	};
}
/**
* Get execution context from API key authentication
*/
function getRequestExecutionContext(c) {
	const executionContext = c.get("executionContext");
	if (!executionContext) throw new Error("No execution context available. API key authentication is required.");
	return executionContext;
}

//#endregion
//#region src/utils/format-messages.ts
function formatMessagesForLLM(messages) {
	return messages.map((message) => {
		return {
			role: message.role === "user" ? "user" : message.role === "agent" ? "assistant" : "system",
			content: typeof message.content === "object" && message.content && "text" in message.content ? message.content.text : String(message.content || ""),
			timestamp: message.createdAt,
			fromSubAgentId: message.fromSubAgentId
		};
	});
}
function formatMessagesForLLMContext(messages) {
	return formatMessagesForLLM(messages).map((msg) => {
		return `${msg.role === "user" ? "User" : msg.role === "assistant" ? "Agent" : "System"}${msg.fromSubAgentId ? ` (${msg.fromSubAgentId})` : ""}: ${msg.content}`;
	}).join("\n\n");
}

//#endregion
//#region src/utils/json-parser.ts
/**
* Turn any string value that is valid JSON into an object/array (in place).
* Useful for parsing MCP tool results and other string data that may contain embedded JSON.
*/
function parseEmbeddedJson(data) {
	if (data === null || data === void 0 || typeof data !== "object") return data;
	return traverse(data).map(function(x) {
		if (typeof x === "string") {
			const v = destr(x);
			if (v !== x && (Array.isArray(v) || v && typeof v === "object")) this.update(v);
		}
	});
}

//#endregion
//#region src/utils/mcp-client.ts
var McpClient = class {
	name;
	client;
	timeout;
	transport;
	serverConfig;
	connected = false;
	constructor(opts) {
		this.name = opts.name;
		this.timeout = opts.timeout || DEFAULT_REQUEST_TIMEOUT_MSEC;
		this.serverConfig = opts.server;
		this.client = new Client({
			name: opts.name,
			version: opts.version || "1.0.0"
		}, { capabilities: opts.capabilities || {} });
	}
	isConnected() {
		return this.connected;
	}
	async connect() {
		if (this.connected) return;
		await match(this.serverConfig).with({ type: MCPTransportType.streamableHttp }, (config) => this.connectHttp(config)).with({ type: MCPTransportType.sse }, (config) => this.connectSSE(config)).exhaustive();
		this.connected = true;
		const close = this.client.onclose;
		this.client.onclose = () => {
			this.connected = false;
			if (typeof close === "function") close();
		};
		asyncExitHook(() => this.disconnect(), { wait: 5e3 });
		process.on("SIGTERM", () => gracefulExit());
	}
	async connectSSE(config) {
		const url = typeof config.url === "string" ? config.url : config.url.toString();
		this.transport = new SSEClientTransport(new URL(url), {
			eventSourceInit: config.eventSourceInit,
			requestInit: { headers: config.headers || {} }
		});
		await this.client.connect(this.transport, { timeout: config.timeout ?? this.timeout });
	}
	async connectHttp(config) {
		const { url, requestInit } = config;
		const mergedRequestInit = {
			...requestInit,
			headers: {
				...requestInit?.headers || {},
				...config.headers || {}
			}
		};
		const urlString = typeof url === "string" ? url : url.toString();
		this.transport = new StreamableHTTPClientTransport(new URL(urlString), {
			requestInit: mergedRequestInit,
			reconnectionOptions: {
				maxRetries: MCP_TOOL_MAX_RETRIES,
				maxReconnectionDelay: MCP_TOOL_MAX_RECONNECTION_DELAY_MS,
				initialReconnectionDelay: MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS,
				reconnectionDelayGrowFactor: MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR,
				...config.reconnectionOptions
			},
			sessionId: config.sessionId
		});
		await this.client.connect(this.transport, { timeout: MCP_TOOL_CONNECTION_TIMEOUT_MS });
	}
	async disconnect() {
		if (!this.transport) return;
		try {
			await this.transport.close();
		} catch (e) {
			console.error(e);
			throw e;
		} finally {
			this.transport = void 0;
			this.connected = false;
		}
	}
	validateSelectedTools(tools, activeTools) {
		if (!activeTools) return;
		for (const item of activeTools) {
			if (tools.includes(item)) continue;
			console.warn(`[Tools] Tool ${item} not found in tools`);
		}
	}
	async selectTools() {
		const { tools } = await this.client.listTools();
		const { selectedTools, activeTools } = this.serverConfig;
		let availableTools;
		if (activeTools === void 0) availableTools = tools;
		else if (activeTools.length === 0) return [];
		else availableTools = tools.filter((tool$1) => activeTools.includes(tool$1.name));
		if (selectedTools === void 0) return availableTools;
		if (selectedTools.length === 0) return [];
		const toolNames = availableTools.map((tool$1) => tool$1.name);
		this.validateSelectedTools(toolNames, selectedTools);
		return availableTools.filter((tool$1) => selectedTools.includes(tool$1.name));
	}
	async tools() {
		const tools = await this.selectTools();
		const results = {};
		for (const def of tools) try {
			const createZodSchema = (inputSchema) => {
				if (!inputSchema || !inputSchema.properties) return z.object({});
				const zodProperties = {};
				for (const [key, prop] of Object.entries(inputSchema.properties)) {
					const propDef = prop;
					let zodType;
					switch (propDef.type) {
						case "string":
							zodType = z.string();
							break;
						case "number":
							zodType = z.number();
							break;
						case "boolean":
							zodType = z.boolean();
							break;
						case "array":
							zodType = z.array(z.any());
							break;
						case "object":
							zodType = createZodSchema(propDef);
							break;
						default: zodType = z.any();
					}
					if (propDef.description) zodType = zodType.describe(propDef.description);
					if (!inputSchema.required?.includes(key)) zodType = zodType.optional();
					zodProperties[key] = zodType;
				}
				return z.object(zodProperties);
			};
			const schema = createZodSchema(def.inputSchema);
			const createdTool = tool({
				id: `${this.name}.${def.name}`,
				description: def.description || "",
				inputSchema: schema,
				execute: async (context) => {
					return await this.client.callTool({
						name: def.name,
						arguments: context
					}, CallToolResultSchema, { timeout: this.timeout });
				}
			});
			if (def.name) results[def.name] = createdTool;
		} catch (e) {
			console.error(`Error creating tool ${def.name}:`, e);
		}
		return results;
	}
};

//#endregion
//#region src/utils/model-factory.ts
const logger$4 = getLogger("ModelFactory");
const nimDefault = createOpenAICompatible({
	name: "nim",
	baseURL: "https://integrate.api.nvidia.com/v1",
	headers: { Authorization: `Bearer ${process.env.NIM_API_KEY}` }
});
/**
* Factory for creating AI SDK language models from configuration
* Supports multiple providers and AI Gateway integration
*/
var ModelFactory = class ModelFactory {
	/**
	* Create a provider instance with custom configuration
	* Returns a provider with at least languageModel method
	*/
	static createProvider(provider, config) {
		switch (provider) {
			case "anthropic": return createAnthropic(config);
			case "openai": return createOpenAI(config);
			case "google": return createGoogleGenerativeAI(config);
			case "openrouter": return createOpenRouter(config);
			case "gateway": return createGateway(config);
			case "nim": return createOpenAICompatible({
				name: "nim",
				baseURL: "https://integrate.api.nvidia.com/v1",
				headers: { Authorization: `Bearer ${process.env.NIM_API_KEY}` },
				...config
			});
			case "custom": {
				if (!config.baseURL && !config.baseUrl) throw new Error("Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl");
				const customConfig = {
					name: "custom",
					baseURL: config.baseURL || config.baseUrl,
					headers: {
						...process.env.CUSTOM_LLM_API_KEY && { Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}` },
						...config.headers || {}
					},
					...config
				};
				logger$4.info({ config: {
					baseURL: customConfig.baseURL,
					hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
					apiKeyPrefix: `${process.env.CUSTOM_LLM_API_KEY?.substring(0, 10)}...`,
					headers: Object.keys(customConfig.headers || {})
				} }, "Creating custom OpenAI-compatible provider");
				return createOpenAICompatible(customConfig);
			}
			default: throw new Error(`Unsupported provider: ${provider}`);
		}
	}
	/**
	* Extract provider configuration from providerOptions
	* Only includes settings that go to the provider constructor (baseURL, apiKey, etc.)
	*/
	static extractProviderConfig(providerOptions) {
		if (!providerOptions) return {};
		const providerConfig = {};
		if (providerOptions.baseUrl || providerOptions.baseURL) providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
		if (providerOptions.headers) providerConfig.headers = providerOptions.headers;
		if (providerOptions.gateway) Object.assign(providerConfig, providerOptions.gateway);
		if (providerOptions.nim) Object.assign(providerConfig, providerOptions.nim);
		if (providerOptions.custom) Object.assign(providerConfig, providerOptions.custom);
		return providerConfig;
	}
	/**
	* Create a language model instance from configuration
	* Throws error if no config provided - models must be configured at project level
	*/
	static createModel(config) {
		if (!config?.model?.trim()) throw new Error("Model configuration is required. Please configure models at the project level.");
		const modelSettings = config;
		if (!modelSettings.model) throw new Error("Model configuration is required");
		const modelString = modelSettings.model.trim();
		const { provider, modelName } = ModelFactory.parseModelString(modelString);
		logger$4.debug({
			provider,
			model: modelName,
			fullModelString: modelSettings.model,
			hasProviderOptions: !!modelSettings.providerOptions
		}, "Creating language model from config");
		const providerConfig = ModelFactory.extractProviderConfig(modelSettings.providerOptions);
		if (Object.keys(providerConfig).length > 0) {
			logger$4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
			return ModelFactory.createProvider(provider, providerConfig).languageModel(modelName);
		}
		switch (provider) {
			case "anthropic": return anthropic(modelName);
			case "openai": return openai(modelName);
			case "google": return google(modelName);
			case "openrouter": return openrouter(modelName);
			case "gateway": return gateway(modelName);
			case "nim": return nimDefault(modelName);
			case "custom": throw new Error("Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL");
			default: throw new Error(`Unsupported provider: ${provider}. Supported providers are: ${ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`);
		}
	}
	/**
	* Built-in providers that have special handling
	*/
	static BUILT_IN_PROVIDERS = [
		"anthropic",
		"openai",
		"google",
		"openrouter",
		"gateway",
		"nim",
		"custom"
	];
	/**
	* Parse model string to extract provider and model name
	* Examples: "anthropic/claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" }
	*          "openrouter/anthropic/claude-sonnet-4" -> { provider: "openrouter", modelName: "anthropic/claude-sonnet-4" }
	*          "claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" } (default to anthropic)
	*/
	static parseModelString(modelString) {
		if (modelString.includes("/")) {
			const [provider, ...modelParts] = modelString.split("/");
			const normalizedProvider = provider.toLowerCase();
			if (!ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) throw new Error(`Unsupported provider: ${normalizedProvider}. Supported providers are: ${ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`);
			return {
				provider: normalizedProvider,
				modelName: modelParts.join("/")
			};
		}
		throw new Error(`No provider specified in model string: ${modelString}`);
	}
	/**
	* Get generation parameters from provider options
	* These are parameters that get passed to generateText/streamText calls
	*/
	static getGenerationParams(providerOptions) {
		if (!providerOptions) return {};
		const excludedKeys = [
			"apiKey",
			"baseURL",
			"baseUrl",
			"maxDuration",
			"headers",
			"gateway",
			"nim",
			"custom"
		];
		const params = {};
		for (const [key, value] of Object.entries(providerOptions)) if (!excludedKeys.includes(key) && value !== void 0) params[key] = value;
		return params;
	}
	/**
	* Prepare complete generation configuration from model settings
	* Returns model instance and generation parameters ready to spread into generateText/streamText
	* Includes maxDuration if specified in provider options (in seconds, following Vercel standard)
	*/
	static prepareGenerationConfig(modelSettings) {
		const modelString = modelSettings?.model?.trim();
		const model = ModelFactory.createModel({
			model: modelString,
			providerOptions: modelSettings?.providerOptions
		});
		const generationParams = ModelFactory.getGenerationParams(modelSettings?.providerOptions);
		const maxDuration = modelSettings?.providerOptions?.maxDuration;
		return {
			model,
			...generationParams,
			...maxDuration !== void 0 && { maxDuration }
		};
	}
	/**
	* Validate model settingsuration
	* Basic validation only - let AI SDK handle parameter-specific validation
	*/
	static validateConfig(config) {
		const errors = [];
		if (!config.model) errors.push("Model name is required");
		if (config.providerOptions) {
			if (config.providerOptions.apiKey) errors.push("API keys should not be stored in provider options. Use environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY) or credential store instead.");
			if (config.providerOptions.maxDuration !== void 0) {
				const maxDuration = config.providerOptions.maxDuration;
				if (typeof maxDuration !== "number" || maxDuration <= 0) errors.push("maxDuration must be a positive number (in seconds)");
			}
		}
		return errors;
	}
};

//#endregion
//#region src/utils/service-token-auth.ts
const logger$3 = getLogger("service-token-auth");
/**
* Get the JWT secret from environment variables
* Falls back to a default secret in non-production environments (with warning)
*/
function getJwtSecret() {
	const secret = env.INKEEP_AGENTS_JWT_SIGNING_SECRET;
	const dev_secret = "insecure-dev-secret-change-in-production-min-32-chars";
	if (!secret) {
		if (env.ENVIRONMENT === "production") throw new Error("INKEEP_AGENTS_JWT_SIGNING_SECRET environment variable is required in production");
		logger$3.warn({}, "INKEEP_AGENTS_JWT_SIGNING_SECRET not set, using insecure default. DO NOT USE IN PRODUCTION!");
		return new TextEncoder().encode(dev_secret);
	}
	return new TextEncoder().encode(secret);
}
/**
* Generate a JWT token for team agent authentication
* Token expires in 5 minutes
*
* @param params - Token generation parameters
* @returns Signed JWT token string
*/
async function generateServiceToken(params) {
	const secret = getJwtSecret();
	try {
		const token = await new SignJWT({
			tenantId: params.tenantId,
			projectId: params.projectId
		}).setProtectedHeader({
			alg: "HS256",
			typ: "JWT"
		}).setIssuer("inkeep-agents").setSubject(params.originAgentId).setAudience(params.targetAgentId).setIssuedAt().setExpirationTime("5m").sign(secret);
		logger$3.debug({
			originAgentId: params.originAgentId,
			targetAgentId: params.targetAgentId,
			tenantId: params.tenantId
		}, "Generated team agent token");
		return token;
	} catch (error) {
		logger$3.error({ error }, "Failed to generate service token");
		throw new Error("Failed to generate service token");
	}
}
/**
* Verify and decode a service JWT token
*
* @param token - JWT token string to verify
* @returns Verification result with payload if valid
*/
async function verifyServiceToken(token) {
	const secret = getJwtSecret();
	try {
		const { payload } = await jwtVerify(token, secret, {
			issuer: "inkeep-agents",
			algorithms: ["HS256"]
		});
		if (typeof payload.sub !== "string" || typeof payload.aud !== "string" || typeof payload.tenantId !== "string" || typeof payload.projectId !== "string") {
			logger$3.warn({ payload }, "Invalid service token: missing required claims");
			return {
				valid: false,
				error: "Invalid token: missing required claims"
			};
		}
		const validPayload = {
			iss: payload.iss,
			aud: payload.aud,
			sub: payload.sub,
			tenantId: payload.tenantId,
			projectId: payload.projectId,
			iat: payload.iat,
			exp: payload.exp
		};
		logger$3.debug({
			originAgentId: validPayload.sub,
			targetAgentId: validPayload.aud,
			tenantId: validPayload.tenantId
		}, "Successfully verified team agent token");
		return {
			valid: true,
			payload: validPayload
		};
	} catch (error) {
		if (error instanceof Error) {
			logger$3.warn({ error: error.message }, "Team agent token verification failed");
			return {
				valid: false,
				error: error.message
			};
		}
		logger$3.warn({ error }, "Team agent token verification failed with unknown error");
		return {
			valid: false,
			error: "Token verification failed"
		};
	}
}
/**
* Validate that the token's tenant ID matches the expected tenant
* This prevents cross-tenant delegation attempts
*
* @param payload - Decoded token payload
* @param expectedTenantId - The tenant ID to validate against
* @returns true if tenant IDs match, false otherwise
*/
function validateTenantId(payload, expectedTenantId) {
	if (payload.tenantId !== expectedTenantId) {
		logger$3.warn({
			tokenTenantId: payload.tenantId,
			expectedTenantId,
			originAgentId: payload.sub,
			targetAgentId: payload.aud
		}, "Cross-tenant delegation attempt detected");
		return false;
	}
	return true;
}
/**
* Validate that the token's target agent ID matches the expected agent
*
* @param payload - Decoded token payload
* @param expectedTargetAgentId - The agent ID to validate against
* @returns true if agent IDs match, false otherwise
*/
function validateTargetAgent(payload, expectedTargetAgentId) {
	if (payload.aud !== expectedTargetAgentId) {
		logger$3.warn({
			tokenTargetAgentId: payload.aud,
			expectedTargetAgentId,
			originAgentId: payload.sub
		}, "Token target agent mismatch");
		return false;
	}
	return true;
}
/**
* Extract the Authorization header and verify the bearer token
*
* @param authHeader - The Authorization header value (e.g., "Bearer <token>")
* @returns Verification result with payload if valid
*/
async function verifyAuthorizationHeader(authHeader) {
	if (!authHeader) return {
		valid: false,
		error: "Missing Authorization header"
	};
	if (!authHeader.startsWith("Bearer ")) return {
		valid: false,
		error: "Invalid Authorization header format. Expected: Bearer <token>"
	};
	const token = authHeader.substring(7);
	if (!token) return {
		valid: false,
		error: "Empty token in Authorization header"
	};
	return verifyServiceToken(token);
}

//#endregion
//#region src/utils/temp-jwt.ts
async function signTempToken(privateKeyPem, payload, userId) {
	const privateKey = await jose.importPKCS8(privateKeyPem, "RS256");
	return {
		token: await new jose.SignJWT(payload).setProtectedHeader({
			alg: "RS256",
			typ: "JWT"
		}).setIssuedAt().setExpirationTime("1h").setIssuer("inkeep-manage-api").setAudience("inkeep-run-api").setSubject(userId).setJti(generateId()).sign(privateKey),
		expiresAt: new Date(Date.now() + 3600 * 1e3).toISOString()
	};
}
async function verifyTempToken(publicKeyPem, token) {
	const publicKey = await jose.importSPKI(publicKeyPem, "RS256");
	const { payload } = await jose.jwtVerify(token, publicKey, {
		issuer: "inkeep-manage-api",
		audience: "inkeep-run-api"
	});
	if (payload.type !== "temporary") throw new Error("Invalid token type");
	return payload;
}

//#endregion
//#region src/utils/third-party-mcp-servers/composio-client.ts
/**
* Composio MCP Server Client
* Handles all Composio-specific operations for MCP server integration
*/
const logger$2 = getLogger("composio-client");
const TOOLKIT_TO_CATEGORY = {
	github: "development",
	gitlab: "development",
	bitbucket: "development",
	jira: "project_management",
	asana: "project_management",
	linear: "project_management",
	trello: "project_management",
	monday: "project_management",
	slack: "communication",
	discord: "communication",
	teams: "communication",
	zoom: "communication",
	notion: "knowledge",
	confluence: "knowledge",
	docs: "knowledge",
	drive: "storage",
	dropbox: "storage",
	box: "storage",
	stripe: "payments",
	paypal: "payments",
	square: "payments",
	gmail: "communication",
	outlook: "communication",
	calendar: "productivity",
	sheets: "productivity",
	airtable: "database",
	salesforce: "crm",
	hubspot: "crm",
	zendesk: "communication",
	intercom: "communication"
};
let composio = null;
/**
* Get or create a Composio instance
* Returns null if COMPOSIO_API_KEY is not configured
*/
function getComposioInstance() {
	if (!process.env.COMPOSIO_API_KEY) return null;
	if (!composio) composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
	return composio;
}
/**
* Derive a Composio user ID from tenant and project IDs
* This creates a unique identifier for Composio connected accounts per tenant/project
*/
function deriveComposioUserId(tenantId, projectId) {
	return `${tenantId}||${projectId}`;
}
/**
* Get the Composio user ID based on credential scope
* - For project-scoped: uses derived tenant||project ID (shared team credentials)
* - For user-scoped: uses the actual user ID (per-user credentials)
*/
function getComposioUserId(tenantId, projectId, credentialScope, userId) {
	if (credentialScope === "user" && userId) return userId;
	return deriveComposioUserId(tenantId, projectId);
}
/**
* Extract server ID from a Composio MCP URL
* Example: https://backend.composio.dev/v3/mcp/1234-1234-1234?user_id=... -> 1234-1234-1234
*/
function extractComposioServerId(mcpUrl) {
	if (!mcpUrl.includes("composio.dev")) return null;
	try {
		const pathParts = new URL(mcpUrl).pathname.split("/");
		const mcpIndex = pathParts.indexOf("mcp");
		if (mcpIndex !== -1 && pathParts[mcpIndex + 1]) return pathParts[mcpIndex + 1];
		return null;
	} catch {
		return null;
	}
}
/**
* Delete a Composio connected account
* Returns true if successful, false if failed (non-blocking)
*/
async function deleteComposioConnectedAccount(accountId) {
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured, skipping account deletion");
		return false;
	}
	try {
		await composioInstance.connectedAccounts.delete(accountId);
		return true;
	} catch (error) {
		logger$2.warn({ error }, "Error deleting Composio connected account");
		return false;
	}
}
/**
* Fetch connected accounts from Composio for a given user
* Returns null if the API call fails or Composio is not configured
*/
async function fetchComposioConnectedAccounts(derivedUserId) {
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured, skipping connected accounts fetch");
		return null;
	}
	try {
		return await composioInstance.connectedAccounts.list({
			userIds: [derivedUserId],
			statuses: ["ACTIVE", "INITIATED"]
		});
	} catch (error) {
		logger$2.error({ error }, "Error fetching Composio connected accounts");
		return null;
	}
}
/**
* Check if a Composio MCP server is authenticated for the given tenant/project/user
* Returns true if authenticated, false otherwise
* @param credentialScope - 'project' for shared team credentials, 'user' for per-user credentials
* @param userId - The actual user ID (required if credentialScope is 'user')
*/
async function isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
	if (!process.env.COMPOSIO_API_KEY) {
		logger$2.info({}, "Composio API key not configured, skipping auth check");
		return false;
	}
	const serverId = extractComposioServerId(mcpServerUrl);
	if (!serverId) {
		logger$2.info({ mcpServerUrl }, "Could not extract Composio server ID from URL");
		return false;
	}
	const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured, skipping auth check");
		return false;
	}
	try {
		const composioMcpServer = await composioInstance.mcp.get(serverId);
		const firstAuthConfigId = composioMcpServer.authConfigIds.length > 0 ? composioMcpServer.authConfigIds[0] : null;
		if (!firstAuthConfigId) return false;
		const connectedAccounts = await fetchComposioConnectedAccounts(composioUserId);
		if (!connectedAccounts) return false;
		return !!connectedAccounts.items.find((account) => account.authConfig.id === firstAuthConfigId && account.status === "ACTIVE");
	} catch (error) {
		logger$2.error({
			error,
			mcpServerUrl
		}, "Error checking Composio authentication status");
		return false;
	}
}
/**
* Convert Composio server data to PrebuiltMCPServer format
*/
function transformComposioServerData(composioMcpServer, isAuthenticated, url, thirdPartyConnectAccountUrl) {
	const firstToolkit = composioMcpServer.toolkits[0];
	const category = firstToolkit ? TOOLKIT_TO_CATEGORY[firstToolkit] || "integration" : "integration";
	const imageUrl = composioMcpServer.toolkitIcons?.[firstToolkit];
	const description = composioMcpServer.toolkits.length > 0 ? `${composioMcpServer.toolkits.slice(0, 3).join(", ")} integration${composioMcpServer.toolkits.length > 1 ? "s" : ""} via Composio` : "Integration via Composio";
	return {
		id: composioMcpServer.id,
		name: composioMcpServer.name,
		url,
		transport: MCPTransportType.streamableHttp,
		imageUrl,
		category,
		description,
		isOpen: isAuthenticated,
		thirdPartyConnectAccountUrl
	};
}
/**
* Side effects: Ensure Composio account exists for the given server
* Handles account creation/deletion and returns the redirect URL
* Returns null if account creation fails
*/
async function ensureComposioAccount(composioMcpServer, derivedUserId, initiatedAccounts) {
	const firstAuthConfigId = composioMcpServer.authConfigIds[0];
	if (!firstAuthConfigId) {
		logger$2.error({ serverId: composioMcpServer.id }, "No auth config ID found for MCP server");
		return null;
	}
	const existingInitiatedAccount = initiatedAccounts.find((account) => account.authConfig.id === firstAuthConfigId);
	if (existingInitiatedAccount) await deleteComposioConnectedAccount(existingInitiatedAccount.id);
	try {
		const composioInstance = getComposioInstance();
		if (!composioInstance) {
			logger$2.error({ serverId: composioMcpServer.id }, "Composio not configured");
			return null;
		}
		return (await composioInstance.connectedAccounts.link(derivedUserId, firstAuthConfigId)).redirectUrl ?? null;
	} catch (error) {
		logger$2.error({
			serverId: composioMcpServer.id,
			error
		}, "Error creating connected account for MCP server");
		return null;
	}
}
/**
* Get the OAuth redirect URL for a Composio MCP server based on credential scope
* This should be called AFTER scope selection to get the correct URL
* @param credentialScope - 'project' for shared team credentials, 'user' for per-user credentials
* @param userId - The actual user ID (required if credentialScope is 'user')
*/
async function getComposioOAuthRedirectUrl(tenantId, projectId, mcpServerUrl, credentialScope, userId) {
	if (!process.env.COMPOSIO_API_KEY) {
		logger$2.info({}, "Composio API key not configured");
		return null;
	}
	const serverId = extractComposioServerId(mcpServerUrl);
	if (!serverId) {
		logger$2.info({ mcpServerUrl }, "Could not extract Composio server ID from URL");
		return null;
	}
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured");
		return null;
	}
	const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
	try {
		return await ensureComposioAccount(await composioInstance.mcp.get(serverId), composioUserId, (await fetchComposioConnectedAccounts(composioUserId))?.items.filter((account) => account.status === "INITIATED") ?? []);
	} catch (error) {
		logger$2.error({
			error,
			mcpServerUrl
		}, "Failed to get Composio OAuth redirect URL");
		return null;
	}
}
/**
* Orchestration: Transform Composio server to PrebuiltMCPServer format
* Coordinates authentication checks and account management
* Returns null if the server cannot be properly configured
*/
async function transformComposioServer(composioMcpServer, authenticatedAuthConfigIds, initiatedAccounts, derivedUserId) {
	const isAuthenticated = composioMcpServer.authConfigIds.some((authConfigId) => authenticatedAuthConfigIds.has(authConfigId));
	let thirdPartyConnectAccountUrl;
	if (!isAuthenticated) {
		const redirectUrl = await ensureComposioAccount(composioMcpServer, derivedUserId, initiatedAccounts);
		if (!redirectUrl) return null;
		thirdPartyConnectAccountUrl = redirectUrl;
	}
	return transformComposioServerData(composioMcpServer, isAuthenticated, composioMcpServer.MCPUrl, thirdPartyConnectAccountUrl);
}
/**
* Fetch Composio MCP servers for the catalog
*/
async function fetchComposioServers() {
	if (!process.env.COMPOSIO_API_KEY) {
		logger$2.info({}, "COMPOSIO_API_KEY not configured, skipping Composio servers");
		return [];
	}
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured, returning empty list");
		return [];
	}
	try {
		return (await composioInstance.mcp.list({
			limit: 100,
			toolkits: [],
			page: 1,
			authConfigs: []
		}))?.items.map((server) => transformComposioServerData(server, false, server.MCPUrl, void 0)) ?? [];
	} catch (error) {
		logger$2.error({ error }, "Failed to fetch Composio servers");
		return [];
	}
}
/**
* Fetch a single Composio MCP server by URL and return its details with auth status
* @param credentialScope - 'project' uses tenant||project, 'user' uses actual userId
* @param userId - The actual user ID (required if credentialScope is 'user')
*/
async function fetchSingleComposioServer(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
	if (!process.env.COMPOSIO_API_KEY) {
		logger$2.debug({}, "COMPOSIO_API_KEY not configured");
		return null;
	}
	const composioUserId = getComposioUserId(tenantId, projectId, credentialScope, userId);
	const composioInstance = getComposioInstance();
	if (!composioInstance) {
		logger$2.info({}, "Composio not configured, returning null");
		return null;
	}
	try {
		const serverId = extractComposioServerId(mcpServerUrl);
		if (!serverId) {
			logger$2.error({ mcpServerUrl }, "Could not extract Composio server ID from URL");
			return null;
		}
		const composioMcpServer = await composioInstance.mcp.get(serverId);
		const userConnectedAccounts = await composioInstance.connectedAccounts.list({
			userIds: [composioUserId],
			statuses: ["ACTIVE", "INITIATED"]
		});
		const activeAccounts = userConnectedAccounts?.items.filter((account) => account.status === "ACTIVE");
		const initiatedAccounts = userConnectedAccounts?.items.filter((account) => account.status === "INITIATED");
		return await transformComposioServer(composioMcpServer, new Set(activeAccounts?.map((account) => account.authConfig.id) ?? []), initiatedAccounts ?? [], composioUserId);
	} catch (error) {
		logger$2.error({
			error,
			mcpServerUrl
		}, "Failed to fetch single Composio server");
		return null;
	}
}

//#endregion
//#region src/utils/third-party-mcp-servers/third-party-check.ts
/**
* Third-Party MCP Server Authentication Check
* Generic interface for checking authentication status of third-party MCP servers
*/
const logger$1 = getLogger("third-party-check");
/**
* Check if a third-party MCP server is authenticated for the given tenant/project/user
* This is a generic function that routes to the appropriate provider-specific check
* Returns true if authenticated, false otherwise
* @param credentialScope - 'project' for shared team credentials, 'user' for per-user credentials
* @param userId - The actual user ID (required if credentialScope is 'user')
*/
async function isThirdPartyMCPServerAuthenticated(tenantId, projectId, mcpServerUrl, credentialScope = "project", userId) {
	if (extractComposioServerId(mcpServerUrl)) {
		logger$1.debug({ mcpServerUrl }, "Detected Composio MCP server, checking auth status");
		return isComposioMCPServerAuthenticated(tenantId, projectId, mcpServerUrl, credentialScope, userId);
	}
	logger$1.info({ mcpServerUrl }, "Unknown third-party MCP server provider");
	return false;
}

//#endregion
//#region src/utils/tracer-factory.ts
const logger = getLogger("tracer");
const createNoOpSpan = () => ({
	setAttributes: () => ({}),
	recordException: () => ({}),
	setStatus: () => ({}),
	addEvent: () => ({}),
	end: () => {},
	isRecording: () => false,
	setAttribute: () => ({}),
	updateName: () => ({}),
	spanContext: () => ({
		traceId: "00000000000000000000000000000000",
		spanId: "0000000000000000",
		traceFlags: 0
	}),
	addLink: () => ({}),
	addLinks: () => ({})
});
const noopTracer = {
	startActiveSpan(_name, arg1, arg2, arg3) {
		const fn = typeof arg1 === "function" ? arg1 : typeof arg2 === "function" ? arg2 : arg3;
		if (!fn) throw new Error("No callback function provided");
		return fn(createNoOpSpan());
	},
	startSpan(_name, _options) {
		return createNoOpSpan();
	}
};
/**
* Helper function to handle span errors consistently
* Records the exception, sets error status, and optionally logs
*/
function setSpanWithError(span, error, logger$6, logMessage) {
	span.recordException(error);
	span.setStatus({
		code: SpanStatusCode.ERROR,
		message: error.message
	});
	if (logger$6 && logMessage) logger$6.error({ error: error.message }, logMessage);
}
/**
* Get a tracer instance for the specified service
* Returns a no-op tracer if OpenTelemetry is not available
*/
function getTracer(serviceName, serviceVersion) {
	try {
		return trace.getTracer(serviceName, serviceVersion);
	} catch (_error) {
		logger.debug({}, "OpenTelemetry tracer not available, using no-op tracer");
		return noopTracer;
	}
}

//#endregion
export { executionLimitsSharedDefaults as $, createApiError as A, isApiKeyExpired as B, getRequestExecutionContext as C, commonDeleteErrorResponses as D, commonCreateErrorResponses as E, normalizeDateString as F, getCredentialStoreLookupKeyFromRetrievalParams as G, validateApiKey as H, toISODateString as I, MCP_TOOL_CONNECTION_TIMEOUT_MS as J, CONVERSATION_HISTORY_DEFAULT_LIMIT as K, extractPublicId as L, errorSchemaFactory as M, handleApiError as N, commonGetErrorResponses as O, problemDetailsSchema as P, MCP_TOOL_RECONNECTION_DELAY_GROWTH_FACTOR as Q, generateApiKey as R, createExecutionContext as S, ErrorCode as T, generateId as U, maskApiKey as V, getConversationId as W, MCP_TOOL_MAX_RECONNECTION_DELAY_MS as X, MCP_TOOL_INITIAL_RECONNECTION_DELAY_MS as Y, MCP_TOOL_MAX_RETRIES as Z, ModelFactory as _, fetchComposioServers as a, formatMessagesForLLM as b, getComposioUserId as c, verifyTempToken as d, generateServiceToken as f, verifyServiceToken as g, verifyAuthorizationHeader as h, extractComposioServerId as i, errorResponseSchema as j, commonUpdateErrorResponses as k, isComposioMCPServerAuthenticated as l, validateTenantId as m, setSpanWithError as n, fetchSingleComposioServer as o, validateTargetAgent as p, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT as q, isThirdPartyMCPServerAuthenticated as r, getComposioOAuthRedirectUrl as s, getTracer as t, signTempToken as u, McpClient as v, ERROR_DOCS_BASE_URL as w, formatMessagesForLLMContext as x, parseEmbeddedJson as y, hashApiKey as z };
//# sourceMappingURL=utils.js.map