import { getLogger as getLogger$1 } from "../../../logger.js";
import runDbClient_default from "../../../data/db/runDbClient.js";
import { ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS } from "../constants/execution-limits/index.js";
import { toolSessionManager } from "../agents/ToolSessionManager.js";
import { setSpanWithError as setSpanWithError$1, tracer } from "../utils/tracer.js";
import { getFormattedConversationHistory } from "../data/conversations.js";
import { defaultStatusSchemas } from "../utils/default-status-schemas.js";
import { getStreamHelper } from "../utils/stream-registry.js";
import { ArtifactService } from "./ArtifactService.js";
import { ArtifactParser } from "./ArtifactParser.js";
import { z } from "@hono/zod-openapi";
import { CONVERSATION_HISTORY_DEFAULT_LIMIT, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, ModelFactory, getLedgerArtifacts } from "@inkeep/agents-core";
import { Output, generateText } from "ai";
import { SpanStatusCode } from "@opentelemetry/api";

//#region src/domains/run/services/AgentSession.ts
const logger = getLogger$1("AgentSession");
/**
* Tracks all agent operations and interactions for a single message
* Now includes intelligent status update functionality
*/
var AgentSession = class {
	events = [];
	statusUpdateState;
	statusUpdateTimer;
	previousSummaries = [];
	isEnded = false;
	isTextStreaming = false;
	isGeneratingUpdate = false;
	pendingArtifacts = /* @__PURE__ */ new Set();
	artifactProcessingErrors = /* @__PURE__ */ new Map();
	MAX_ARTIFACT_RETRIES = ARTIFACT_GENERATION_MAX_RETRIES;
	MAX_PENDING_ARTIFACTS = ARTIFACT_SESSION_MAX_PENDING;
	scheduledTimeouts;
	artifactCache = /* @__PURE__ */ new Map();
	artifactService;
	artifactParser;
	isEmitOperations = false;
	constructor(sessionId, messageId, executionContext, contextId) {
		this.sessionId = sessionId;
		this.messageId = messageId;
		this.executionContext = executionContext;
		this.contextId = contextId;
		logger.debug({
			sessionId,
			messageId,
			agentId: executionContext.agentId
		}, "AgentSession created");
		if (executionContext.tenantId && executionContext.projectId) {
			toolSessionManager.createSessionWithId(sessionId, executionContext.tenantId, executionContext.projectId, contextId || "default", `task_${contextId}-${messageId}`);
			this.artifactService = new ArtifactService({
				executionContext,
				sessionId,
				contextId,
				taskId: `task_${contextId}-${messageId}`,
				streamRequestId: sessionId
			});
			this.artifactParser = new ArtifactParser(executionContext, {
				sessionId,
				contextId,
				taskId: `task_${contextId}-${messageId}`,
				streamRequestId: sessionId,
				artifactService: this.artifactService
			});
		}
		this.executionContext = executionContext;
	}
	/**
	* Enable emit operations to send data operations
	*/
	enableEmitOperations() {
		this.isEmitOperations = true;
		logger.info({ sessionId: this.sessionId }, "🔍 DEBUG: Emit operations enabled for AgentSession");
	}
	/**
	* Send data operation to stream when emit operations is enabled
	*/
	async sendDataOperation(event) {
		try {
			const streamHelper = getStreamHelper(this.sessionId);
			if (streamHelper) {
				const formattedOperation = {
					type: event.eventType,
					label: this.generateEventLabel(event),
					details: {
						timestamp: event.timestamp,
						subAgentId: event.subAgentId,
						data: event.data
					}
				};
				await streamHelper.writeOperation(formattedOperation);
			}
		} catch (error) {
			logger.error({
				sessionId: this.sessionId,
				eventType: event.eventType,
				error: error instanceof Error ? error.message : error
			}, "❌ DEBUG: Failed to send data operation");
		}
	}
	/**
	* Generate human-readable labels for events
	*/
	generateEventLabel(event) {
		switch (event.eventType) {
			case "agent_generate": return `Agent ${event.subAgentId} generating response`;
			case "agent_reasoning": return `Agent ${event.subAgentId} reasoning through request`;
			case "tool_call": return `Tool call: ${event.data.toolName || "unknown"}`;
			case "tool_result": {
				const status = event.data.error ? "failed" : "completed";
				return `Tool result: ${event.data.toolName || "unknown"} (${status})`;
			}
			case "error": return `Error: ${event.data.message}`;
			case "transfer": return `Agent transfer: ${event.data.fromSubAgent} → ${event.data.targetSubAgent}`;
			case "delegation_sent": return `Task delegated: ${event.data.fromSubAgent} → ${event.data.targetSubAgent}`;
			case "delegation_returned": return `Task completed: ${event.data.targetSubAgent} → ${event.data.fromSubAgent}`;
			case "artifact_saved": return `Artifact saved: ${event.data.artifactType || "unknown type"}`;
			case "compression": return `Compressed ${event.data.messageCount} messages and ${event.data.artifactCount} artifacts (${event.data.reason})`;
			default: return `${event.eventType} event`;
		}
	}
	/**
	* Initialize status updates for this session
	*/
	initializeStatusUpdates(config, summarizerModel, baseModel) {
		const now = Date.now();
		this.statusUpdateState = {
			lastUpdateTime: now,
			lastEventCount: 0,
			startTime: now,
			summarizerModel,
			baseModel,
			config: {
				numEvents: config.numEvents || STATUS_UPDATE_DEFAULT_NUM_EVENTS,
				timeInSeconds: config.timeInSeconds || STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS,
				...config
			}
		};
		if (this.statusUpdateState.config.timeInSeconds) {
			this.statusUpdateTimer = setInterval(async () => {
				if (!this.statusUpdateState || this.isEnded) {
					logger.debug({ sessionId: this.sessionId }, "Timer triggered but session already cleaned up or ended");
					if (this.statusUpdateTimer) {
						clearInterval(this.statusUpdateTimer);
						this.statusUpdateTimer = void 0;
					}
					return;
				}
				await this.checkAndSendTimeBasedUpdate();
			}, this.statusUpdateState.config.timeInSeconds * 1e3);
			logger.info({
				sessionId: this.sessionId,
				intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
			}, "Time-based status update timer started");
		}
	}
	/**
	* Record an event in the session and trigger status updates if configured
	* Generic type parameter T ensures eventType and data are correctly paired
	*/
	recordEvent(eventType, subAgentId, data) {
		if (this.isEmitOperations) {
			const dataOpEvent = {
				timestamp: Date.now(),
				eventType,
				subAgentId,
				data
			};
			this.sendDataOperation(dataOpEvent);
		}
		if (this.isEnded) {
			logger.debug({
				sessionId: this.sessionId,
				eventType,
				subAgentId
			}, "Event received after session ended - ignoring");
			return;
		}
		const event = {
			timestamp: Date.now(),
			eventType,
			subAgentId,
			data
		};
		this.events.push(event);
		if (eventType === "artifact_saved") {
			const artifactData = data;
			if (artifactData.pendingGeneration) {
				const artifactId = artifactData.artifactId;
				if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
					logger.warn({
						sessionId: this.sessionId,
						artifactId,
						pendingCount: this.pendingArtifacts.size,
						maxAllowed: this.MAX_PENDING_ARTIFACTS
					}, "Too many pending artifacts, skipping processing");
					return;
				}
				this.pendingArtifacts.add(artifactId);
				setImmediate(() => {
					const artifactDataWithAgent = {
						...artifactData,
						subAgentId
					};
					this.processArtifact(artifactDataWithAgent).then(() => {
						this.pendingArtifacts.delete(artifactId);
						this.artifactProcessingErrors.delete(artifactId);
					}).catch((error) => {
						const errorCount = (this.artifactProcessingErrors.get(artifactId) || 0) + 1;
						this.artifactProcessingErrors.set(artifactId, errorCount);
						if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
							this.pendingArtifacts.delete(artifactId);
							logger.error({
								sessionId: this.sessionId,
								artifactId,
								errorCount,
								maxRetries: this.MAX_ARTIFACT_RETRIES,
								error: error instanceof Error ? error.message : "Unknown error",
								stack: error instanceof Error ? error.stack : void 0
							}, "Artifact processing failed after max retries, giving up");
						} else logger.warn({
							sessionId: this.sessionId,
							artifactId,
							errorCount,
							error: error instanceof Error ? error.message : "Unknown error"
						}, "Artifact processing failed, may retry");
					});
				});
			}
		}
		if (!this.isEnded) this.checkStatusUpdates();
	}
	/**
	* Check and send status updates if configured (async, non-blocking)
	*/
	checkStatusUpdates() {
		if (this.isEnded) {
			logger.debug({ sessionId: this.sessionId }, "Session has ended - skipping status update check");
			return;
		}
		if (!this.statusUpdateState) {
			logger.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
			return;
		}
		const statusUpdateState = this.statusUpdateState;
		this.scheduleStatusUpdateCheck(statusUpdateState);
	}
	/**
	* Check and send time-based status updates
	*/
	async checkAndSendTimeBasedUpdate() {
		if (this.isEnded) {
			logger.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
			return;
		}
		if (!this.statusUpdateState) {
			logger.debug({ sessionId: this.sessionId }, "No status updates configured for time-based check");
			return;
		}
		if (this.events.length - this.statusUpdateState.lastEventCount === 0) return;
		try {
			await this.generateAndSendUpdate();
		} catch (error) {
			logger.error({
				sessionId: this.sessionId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to send time-based status update");
		}
	}
	/**
	* Get all events in chronological order
	*/
	getEvents() {
		return [...this.events];
	}
	/**
	* Get events filtered by type
	*/
	getEventsByType(eventType) {
		return this.events.filter((event) => event.eventType === eventType);
	}
	/**
	* Get events filtered by agent
	*/
	getEventsByAgent(subAgentId) {
		return this.events.filter((event) => event.subAgentId === subAgentId);
	}
	/**
	* Get summary of session activity
	*/
	getSummary() {
		const eventCounts = this.events.reduce((counts, event) => {
			counts[event.eventType] = (counts[event.eventType] || 0) + 1;
			return counts;
		}, {});
		const agentCounts = this.events.reduce((counts, event) => {
			counts[event.subAgentId] = (counts[event.subAgentId] || 0) + 1;
			return counts;
		}, {});
		return {
			sessionId: this.sessionId,
			messageId: this.messageId,
			agentId: this.executionContext.agentId,
			totalEvents: this.events.length,
			eventCounts,
			agentCounts,
			startTime: this.events[0]?.timestamp,
			endTime: this.events[this.events.length - 1]?.timestamp,
			duration: this.events.length > 0 ? this.events[this.events.length - 1].timestamp - this.events[0].timestamp : 0
		};
	}
	/**
	* Mark that text streaming has started (to suppress status updates)
	*/
	setTextStreaming(isStreaming) {
		this.isTextStreaming = isStreaming;
	}
	/**
	* Check if text is currently being streamed
	*/
	isCurrentlyStreaming() {
		return this.isTextStreaming;
	}
	/**
	* Clean up status update resources when session ends
	*/
	async cleanup() {
		this.isEnded = true;
		if (this.statusUpdateTimer) {
			clearInterval(this.statusUpdateTimer);
			this.statusUpdateTimer = void 0;
		}
		this.statusUpdateState = void 0;
		if (this.pendingArtifacts.size > 0) {
			const maxWaitTime = 1e4;
			const startTime = Date.now();
			while (this.pendingArtifacts.size > 0 && Date.now() - startTime < maxWaitTime) await new Promise((resolve) => setTimeout(resolve, 100));
			if (this.pendingArtifacts.size > 0) logger.warn({
				sessionId: this.sessionId,
				pendingCount: this.pendingArtifacts.size,
				pendingIds: Array.from(this.pendingArtifacts)
			}, "Cleanup proceeding with pending artifacts still processing");
		}
		this.pendingArtifacts.clear();
		this.artifactProcessingErrors.clear();
		this.artifactCache.clear();
		if (this.sessionId) toolSessionManager.endSession(this.sessionId);
		if (this.sessionId) try {
			const { SandboxExecutorFactory } = await import("../tools/SandboxExecutorFactory.js");
			await SandboxExecutorFactory.cleanupSession(this.sessionId);
		} catch (error) {
			logger.warn({
				sessionId: this.sessionId,
				error
			}, "Failed to cleanup session-scoped sandbox executors");
		}
		if (this.scheduledTimeouts) {
			for (const timeoutId of this.scheduledTimeouts) clearTimeout(timeoutId);
			this.scheduledTimeouts.clear();
		}
		if (this.artifactService) {
			this.artifactService.constructor.clearCaches();
			this.artifactService = void 0;
		} else ArtifactService.clearCaches();
	}
	/**
	* Generate and send a status update using agent-level summarizer
	*/
	async generateAndSendUpdate() {
		if (this.isEnded) {
			logger.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
			return;
		}
		if (this.isTextStreaming) {
			logger.debug({ sessionId: this.sessionId }, "Text is currently streaming - skipping status update");
			return;
		}
		if (this.isGeneratingUpdate) {
			logger.debug({ sessionId: this.sessionId }, "Update already in progress - skipping duplicate generation");
			return;
		}
		if (!this.statusUpdateState) {
			logger.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
			return;
		}
		if (!this.executionContext.agentId) {
			logger.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
			return;
		}
		if (this.events.length - this.statusUpdateState.lastEventCount === 0) return;
		this.isGeneratingUpdate = true;
		const statusUpdateState = this.statusUpdateState;
		try {
			const streamHelper = getStreamHelper(this.sessionId);
			if (!streamHelper) {
				logger.warn({ sessionId: this.sessionId }, "No stream helper found - cannot send status update");
				this.isGeneratingUpdate = false;
				return;
			}
			const now = Date.now();
			const elapsedTime = now - statusUpdateState.startTime;
			const statusComponents = statusUpdateState.config.statusComponents && statusUpdateState.config.statusComponents.length > 0 ? statusUpdateState.config.statusComponents : defaultStatusSchemas;
			const result = await this.generateStructuredStatusUpdate(this.events.slice(statusUpdateState.lastEventCount), elapsedTime, statusComponents, statusUpdateState.summarizerModel, this.previousSummaries);
			if (result.summaries && result.summaries.length > 0) {
				for (const summary of result.summaries) {
					if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
						logger.warn({
							sessionId: this.sessionId,
							summary
						}, "Skipping empty or invalid structured operation");
						continue;
					}
					const summaryToSend = {
						type: summary.data.type || summary.type,
						label: summary.data.label,
						details: Object.fromEntries(Object.entries(summary.data).filter(([key]) => !["label", "type"].includes(key)))
					};
					await streamHelper.writeSummary(summaryToSend);
				}
				const summaryTexts = result.summaries.map((summary) => JSON.stringify({
					type: summary.type,
					data: summary.data
				}));
				this.previousSummaries.push(...summaryTexts);
				if (this.statusUpdateState) {
					this.statusUpdateState.lastUpdateTime = now;
					this.statusUpdateState.lastEventCount = this.events.length;
				}
				return;
			}
			if (this.previousSummaries.length > ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES) this.previousSummaries.shift();
			if (this.statusUpdateState) {
				this.statusUpdateState.lastUpdateTime = now;
				this.statusUpdateState.lastEventCount = this.events.length;
			}
		} catch (error) {
			logger.error({
				sessionId: this.sessionId,
				error: error instanceof Error ? error.message : "Unknown error",
				stack: error instanceof Error ? error.stack : void 0
			}, "❌ Failed to generate status update");
		} finally {
			this.isGeneratingUpdate = false;
		}
	}
	/**
	* Schedule status update check without setImmediate race conditions
	*/
	scheduleStatusUpdateCheck(statusUpdateState) {
		const timeoutId = setTimeout(async () => {
			try {
				if (this.isEnded || !this.statusUpdateState) return;
				if (!this.acquireUpdateLock()) return;
				try {
					if (this.isEnded || !statusUpdateState || this.isTextStreaming) return;
					const currentEventCount = this.events.length;
					const numEventsThreshold = statusUpdateState.config.numEvents;
					if (numEventsThreshold && currentEventCount >= statusUpdateState.lastEventCount + numEventsThreshold) await this.generateAndSendUpdate();
				} finally {
					this.releaseUpdateLock();
				}
			} catch (error) {
				logger.error({
					sessionId: this.sessionId,
					error: error instanceof Error ? error.message : "Unknown error"
				}, "Failed to check status updates during event recording");
				this.releaseUpdateLock();
			}
		}, 0);
		if (!this.scheduledTimeouts) this.scheduledTimeouts = /* @__PURE__ */ new Set();
		this.scheduledTimeouts.add(timeoutId);
		setTimeout(() => {
			if (this.scheduledTimeouts) this.scheduledTimeouts.delete(timeoutId);
		}, 1e3);
	}
	/**
	* Acquire update lock with atomic check
	*/
	acquireUpdateLock() {
		if (this.statusUpdateState?.updateLock) return false;
		if (this.statusUpdateState) this.statusUpdateState.updateLock = true;
		return true;
	}
	/**
	* Release update lock
	*/
	releaseUpdateLock() {
		if (this.statusUpdateState) this.statusUpdateState.updateLock = false;
	}
	/**
	* Generate structured status update using configured data components
	*/
	async generateStructuredStatusUpdate(newEvents, elapsedTime, statusComponents, summarizerModel, previousSummaries = []) {
		const { tenantId, projectId } = this.executionContext;
		return tracer.startActiveSpan("agent_session.generate_structured_update", { attributes: {
			"agent_session.id": this.sessionId,
			"events.count": newEvents.length,
			"elapsed_time.seconds": Math.round(elapsedTime / 1e3),
			"llm.model": summarizerModel?.model,
			"status_components.count": statusComponents.length,
			"previous_summaries.count": previousSummaries.length
		} }, async (span) => {
			try {
				const userVisibleActivities = this.extractUserVisibleActivities(newEvents);
				let conversationContext = "";
				if (tenantId && projectId) try {
					const conversationHistory = await getFormattedConversationHistory({
						tenantId,
						projectId,
						conversationId: this.contextId || "default",
						options: {
							limit: CONVERSATION_HISTORY_DEFAULT_LIMIT,
							maxOutputTokens: CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT,
							includeInternal: true,
							messageTypes: ["chat", "tool-result"]
						},
						filters: {}
					});
					conversationContext = conversationHistory.trim() ? `\nUser's Question/Context:\n${conversationHistory}\n` : "";
				} catch (error) {
					logger.warn({
						sessionId: this.sessionId,
						error
					}, "Failed to fetch conversation history for structured status update");
				}
				const previousSummaryContext = previousSummaries.length > 0 ? `\nPrevious updates sent to user:\n${previousSummaries.map((s, i) => `${i + 1}. ${s}`).join("\n")}\n` : "";
				const selectionSchema = z.object({ updates: z.array(z.union([z.object({
					type: z.literal("no_relevant_updates"),
					data: z.object({ no_updates: z.boolean() }).describe("Use when nothing substantially new to report. Should only use on its own.")
				}), ...statusComponents.map((component) => z.object({
					type: z.literal(component.type),
					data: this.getComponentSchema(component).describe(component.description || component.type)
				}))])) });
				const prompt = `Generate status updates for relevant components based on what the user has asked for.${conversationContext}${previousSummaries.length > 0 ? `\n${previousSummaryContext}` : ""}

Activities:\n${userVisibleActivities.join("\n") || "No New Activities"}

Available component types: no_relevant_updates, ${statusComponents.map((c) => c.type).join(", ")}

Rules:
- Return an array of updates for relevant components
- Use 'no_relevant_updates' type if nothing substantially new to report. DO NOT INCLUDE OTHER COMPONENT TYPES IF YOU USE THIS ONE.
- Never repeat previous values, make every update EXTREMELY unique. If you cannot do that the update is not worth mentioning.
- Labels MUST be short 3-7 word phrases with ACTUAL information discovered. NEVER MAKE UP SOMETHING WITHOUT BACKING IT UP WITH ACTUAL INFORMATION.
- Use sentence case: only capitalize the first word and proper nouns (e.g., "Admin permissions required", not "Admin Permissions Required"). ALWAYS capitalize the first word of the label.
- DO NOT use action words like "Searching", "Processing", "Analyzing" - state what was FOUND
- Include specific details, numbers, requirements, or insights discovered
- Examples: "Admin permissions required", "Three OAuth steps found", "Token expires daily"

CRITICAL - HIDE ALL INTERNAL SYSTEM OPERATIONS:
- You are ONE unified AI system presenting results to the user
- ABSOLUTELY FORBIDDEN WORDS/PHRASES: "transfer", "transferring", "delegation", "delegating", "delegate", "agent", "routing", "route", "artifact", "saving artifact", "stored artifact", "artifact saved", "continuing", "passing to", "handing off", "switching to"
- NEVER reveal internal architecture: No mentions of different agents, components, systems, or modules working together
- NEVER mention artifact operations: Users don't need to know about data being saved, stored, or organized internally
- NEVER describe transfers or transitions: Present everything as one seamless operation
- If you see "transfer", "delegation_sent", "delegation_returned", or "artifact_saved" events - IGNORE THEM or translate to user-facing information only
- Focus ONLY on actual discoveries, findings, and results that matter to the user

- Bad examples: 
  * "Transferring to search agent"
  * "Delegating research task" 
  * "Routing to QA specialist"
  * "Artifact saved successfully"
  * "Storing results for later"
  * "Passing request to tool handler"
  * "Continuing with analysis"
  * "Handing off to processor"
- Good examples:
  * "Slack bot needs admin privileges"
  * "Found 3-step OAuth flow required"  
  * "Channel limit is 500 per workspace"
  * Use no_relevant_updates if nothing new to report

CRITICAL ANTI-HALLUCINATION RULES:
- NEVER MAKE UP SOMETHING WITHOUT BACKING IT UP WITH ACTUAL INFORMATION. EVERY SINGLE UPDATE MUST BE BACKED UP WITH ACTUAL INFORMATION.
- DO NOT MAKE UP PEOPLE, NAMES, PLACES, THINGS, ORGANIZATIONS, OR INFORMATION. IT IS OBVIOUS WHEN A PERSON/ENTITY DOES NOT EXIST.
- Only report facts that are EXPLICITLY mentioned in the activities or tool results
- If you don't have concrete information about something, DO NOT mention it
- Never invent names like "John Doe", "Alice", "Bob", or any other placeholder names
- Never create fictional companies, products, or services
- If a tool returned no results or an error, DO NOT pretend it found something
- Every detail in your status update must be traceable back to the actual activities provided

REMEMBER YOU CAN ONLY USE 'no_relevant_updates' ALONE! IT CANNOT BE CONCATENATED WITH OTHER STATUS UPDATES!

${this.statusUpdateState?.config.prompt?.trim() || ""}`;
				let modelToUse = summarizerModel;
				if (!summarizerModel?.model?.trim()) {
					if (!this.statusUpdateState?.baseModel?.model?.trim()) throw new Error("Either summarizer or base model is required for status update generation. Please configure models at the project level.");
					modelToUse = this.statusUpdateState.baseModel;
				}
				if (!modelToUse) throw new Error("No model configuration available");
				const { output: object } = await generateText({
					model: ModelFactory.createModel(modelToUse),
					prompt,
					output: Output.object({ schema: selectionSchema }),
					experimental_telemetry: {
						isEnabled: true,
						functionId: `structured_update_${this.sessionId}`,
						recordInputs: true,
						recordOutputs: true,
						metadata: {
							operation: "structured_status_update_generation",
							sessionId: this.sessionId
						}
					}
				});
				const result = object;
				logger.info({ result: JSON.stringify(result) }, "DEBUG: Result");
				const summaries = [];
				const updates = result.updates || [];
				for (const update of updates) {
					logger.info({ update: JSON.stringify(update) }, "DEBUG: Update data");
					if (update.type === "no_relevant_updates") continue;
					if (update.data && typeof update.data === "object" && Object.keys(update.data).length > 0) summaries.push({
						type: update.type,
						data: update.data
					});
				}
				span.setAttributes({
					"summaries.count": summaries.length,
					"user_activities.count": userVisibleActivities.length,
					"updates.count": updates.length
				});
				span.setStatus({ code: SpanStatusCode.OK });
				return { summaries };
			} catch (error) {
				setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
				logger.error({ error }, "Failed to generate structured update, using fallback");
				return { summaries: [] };
			} finally {
				span.end();
			}
		});
	}
	/**
	* Build Zod schema from JSON schema configuration or use pre-defined schemas
	*/
	getComponentSchema(component) {
		if (component.detailsSchema && "properties" in component.detailsSchema) return this.buildZodSchemaFromJson(component.detailsSchema);
		return z.object({ label: z.string().describe("A short 3-5 word phrase, that is a descriptive label for the update component. This Label must be EXTREMELY unique to represent the UNIQUE update we are providing. The ACTUAL finding or result, not the action. What specific information was discovered? (e.g., \"Slack requires OAuth 2.0 setup\", \"Found 5 integration methods\", \"API rate limit is 100/minute\"). Include the actual detail or insight, not just that you searched or processed. CRITICAL: Only use facts explicitly found in the activities - NEVER invent names, people, organizations, or details that are not present in the actual tool results.") });
	}
	/**
	* Build Zod schema from JSON schema with improved type handling
	*/
	buildZodSchemaFromJson(jsonSchema) {
		const properties = {};
		properties.label = z.string().describe("A short 3-5 word phrase, that is a descriptive label for the update component. This Label must be EXTREMELY unique to represent the UNIQUE update we are providing. The SPECIFIC finding, result, or insight discovered (e.g., \"Slack bot needs workspace admin role\", \"Found ingestion requires 3 steps\", \"Channel history limited to 10k messages\"). State the ACTUAL information found, not that you searched. What did you LEARN or DISCOVER? What specific detail is now known? CRITICAL: Only use facts explicitly found in the activities - NEVER invent names, people, organizations, or details that are not present in the actual tool results.");
		for (const [key, value] of Object.entries(jsonSchema.properties)) {
			let zodType;
			if (value.enum && Array.isArray(value.enum)) if (value.enum.length === 1) zodType = z.literal(value.enum[0]);
			else {
				const [first, ...rest] = value.enum;
				zodType = z.enum([first, ...rest]);
			}
			else if (value.type === "string") {
				zodType = z.string();
				if (value.minLength) zodType = zodType.min(value.minLength);
				if (value.maxLength) zodType = zodType.max(value.maxLength);
				if (value.format === "email") zodType = zodType.email();
				if (value.format === "url" || value.format === "uri") zodType = zodType.url();
			} else if (value.type === "number" || value.type === "integer") {
				zodType = value.type === "integer" ? z.number().int() : z.number();
				if (value.minimum !== void 0) zodType = zodType.min(value.minimum);
				if (value.maximum !== void 0) zodType = zodType.max(value.maximum);
			} else if (value.type === "boolean") zodType = z.boolean();
			else if (value.type === "array") {
				if (value.items) if (value.items.enum && Array.isArray(value.items.enum)) {
					const [first, ...rest] = value.items.enum;
					zodType = z.array(z.enum([first, ...rest]));
				} else if (value.items.type === "string") zodType = z.array(z.string());
				else if (value.items.type === "number") zodType = z.array(z.number());
				else if (value.items.type === "boolean") zodType = z.array(z.boolean());
				else if (value.items.type === "object") zodType = z.array(z.record(z.string(), z.any()));
				else zodType = z.array(z.any());
				else zodType = z.array(z.any());
				if (value.minItems) zodType = zodType.min(value.minItems);
				if (value.maxItems) zodType = zodType.max(value.maxItems);
			} else if (value.type === "object") zodType = z.record(z.string(), z.any());
			else zodType = z.any();
			if (value.description) zodType = zodType.describe(value.description);
			if (!jsonSchema.required?.includes(key) || value.optional === true) zodType = zodType.optional();
			properties[key] = zodType;
		}
		return z.object(properties);
	}
	/**
	* Extract user-visible activities with rich formatting and complete information
	*/
	extractUserVisibleActivities(events) {
		const activities = [];
		for (const event of events) switch (event.eventType) {
			case "tool_call":
				activities.push(`🔧 **${event.data.toolName}** (called)\n   📥 Input: ${JSON.stringify(event.data.input)}`);
				break;
			case "tool_result": {
				const resultStr = event.data.error ? `❌ Error: ${event.data.error}` : JSON.stringify(event.data.output);
				activities.push(`🔧 **${event.data.toolName}** ${event.data.duration ? `(${event.data.duration}ms)` : ""}\n   📤 Output: ${resultStr}`);
				break;
			}
			case "error":
				activities.push(`❌ **Error**: ${event.data.message}\n   🔍 Code: ${event.data.code || "unknown"}\n   📊 Severity: ${event.data.severity || "error"}`);
				break;
			case "transfer":
			case "delegation_sent":
			case "delegation_returned":
			case "artifact_saved": break;
			case "agent_reasoning":
				activities.push(`⚙️ **Analyzing request**\n   Details: ${JSON.stringify(event.data.parts, null, 2)}`);
				break;
			case "agent_generate":
				activities.push(`⚙️ **Preparing response**\n   Details: ${JSON.stringify(event.data.parts, null, 2)}`);
				break;
			default: {
				const safeEvent = event;
				activities.push(`📋 **${safeEvent.eventType}**: ${JSON.stringify(safeEvent.data, null, 2)}`);
				break;
			}
		}
		return activities;
	}
	/**
	* Process a single artifact to generate name and description using conversation context
	*/
	async processArtifact(artifactData) {
		return tracer.startActiveSpan("agent_session.process_artifact", { attributes: {
			"agent_session.id": this.sessionId,
			"artifact.id": artifactData.artifactId,
			"artifact.type": artifactData.artifactType || "unknown",
			"subAgent.id": artifactData.subAgentId || "unknown",
			"subAgent.name": artifactData.subAgentName || "unknown",
			"artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
			"artifact.data": JSON.stringify(artifactData.data, null, 2),
			"tenant.id": artifactData.tenantId || "unknown",
			"project.id": artifactData.projectId || "unknown",
			"context.id": artifactData.contextId || "unknown",
			has_tenant_id: !!artifactData.tenantId,
			has_project_id: !!artifactData.projectId,
			has_context_id: !!artifactData.contextId,
			has_metadata: !!artifactData.metadata,
			tool_call_id: artifactData.metadata?.toolCallId || "missing",
			pending_generation: !!artifactData.pendingGeneration,
			"schema_validation.schema_found": artifactData.schemaValidation?.schemaFound || false,
			"schema_validation.summary.has_expected_fields": artifactData.schemaValidation?.summary?.hasExpectedFields || true,
			"schema_validation.summary.missing_fields_count": artifactData.schemaValidation?.summary?.missingFields?.length || 0,
			"schema_validation.summary.extra_fields_count": artifactData.schemaValidation?.summary?.extraFields?.length || 0,
			"schema_validation.summary.expected_fields": JSON.stringify(artifactData.schemaValidation?.summary?.expectedFields || []),
			"schema_validation.summary.actual_fields": JSON.stringify(artifactData.schemaValidation?.summary?.actualFields || []),
			"schema_validation.summary.missing_fields": JSON.stringify(artifactData.schemaValidation?.summary?.missingFields || []),
			"schema_validation.summary.extra_fields": JSON.stringify(artifactData.schemaValidation?.summary?.extraFields || []),
			"schema_validation.summary.has_required_fields": artifactData.schemaValidation?.summary?.hasRequiredFields || true,
			"schema_validation.summary.missing_required_count": artifactData.schemaValidation?.summary?.missingRequired?.length || 0,
			"schema_validation.summary.missing_required": JSON.stringify(artifactData.schemaValidation?.summary?.missingRequired || []),
			"schema_validation.full.has_expected_fields": artifactData.schemaValidation?.full?.hasExpectedFields || true,
			"schema_validation.full.missing_fields_count": artifactData.schemaValidation?.full?.missingFields?.length || 0,
			"schema_validation.full.extra_fields_count": artifactData.schemaValidation?.full?.extraFields?.length || 0,
			"schema_validation.full.expected_fields": JSON.stringify(artifactData.schemaValidation?.full?.expectedFields || []),
			"schema_validation.full.actual_fields": JSON.stringify(artifactData.schemaValidation?.full?.actualFields || []),
			"schema_validation.full.missing_fields": JSON.stringify(artifactData.schemaValidation?.full?.missingFields || []),
			"schema_validation.full.extra_fields": JSON.stringify(artifactData.schemaValidation?.full?.extraFields || []),
			"schema_validation.full.has_required_fields": artifactData.schemaValidation?.full?.hasRequiredFields || true,
			"schema_validation.full.missing_required_count": artifactData.schemaValidation?.full?.missingRequired?.length || 0,
			"schema_validation.full.missing_required": JSON.stringify(artifactData.schemaValidation?.full?.missingRequired || [])
		} }, async (span) => {
			try {
				if (!artifactData.tenantId || !artifactData.projectId || !artifactData.contextId) {
					span.setAttributes({
						"validation.failed": true,
						missing_tenant_id: !artifactData.tenantId,
						missing_project_id: !artifactData.projectId,
						missing_context_id: !artifactData.contextId
					});
					throw new Error("Missing required session info (tenantId, projectId, or contextId) for artifact processing");
				}
				span.setAttributes({ "validation.passed": true });
				let mainSaveSucceeded = false;
				const conversationHistory = await getFormattedConversationHistory({
					tenantId: artifactData.tenantId,
					projectId: artifactData.projectId,
					conversationId: artifactData.contextId,
					options: {
						limit: 10,
						includeInternal: false,
						messageTypes: ["chat"]
					}
				});
				const toolCallEvent = this.events.find((event) => event.eventType === "tool_result" && event.data && "toolCallId" in event.data && event.data.toolCallId === artifactData.metadata?.toolCallId);
				const toolContext = toolCallEvent ? {
					toolName: toolCallEvent.data.toolName,
					args: toolCallEvent.data.args
				} : null;
				let existingNames = [];
				try {
					if (artifactData.tenantId && artifactData.projectId && artifactData.taskId) existingNames = (await getLedgerArtifacts(runDbClient_default)({
						scopes: {
							tenantId: artifactData.tenantId,
							projectId: artifactData.projectId
						},
						taskId: artifactData.taskId
					})).map((a) => a.name).filter(Boolean);
				} catch (error) {
					logger.warn({
						sessionId: this.sessionId,
						artifactId: artifactData.artifactId,
						error: error instanceof Error ? error.message : "Unknown error"
					}, "Failed to fetch existing artifact names for context");
				}
				const toolName = artifactData.metadata?.toolName || "unknown";
				const toolCallId = artifactData.metadata?.toolCallId || "unknown";
				const prompt = `Create a unique name and description for this tool result artifact.

CRITICAL: Your name must be different from these existing artifacts: ${existingNames.length > 0 ? existingNames.join(", ") : "None yet"}

Tool Context: ${toolContext ? JSON.stringify(toolContext.args, null, 2) : "No args"}
Context: ${conversationHistory?.slice(-200) || "No context"}
Type: ${artifactData.artifactType || "data"}
Data: ${JSON.stringify(artifactData.data || artifactData.summaryData || {}, null, 2)}

Requirements:
- Name: Max 50 chars, be extremely specific to THIS EXACT tool execution
- Description: Max 150 chars, describe what THIS SPECIFIC tool call returned  
- Focus on the unique aspects of this particular tool execution result
- Be descriptive about the actual content returned, not just the tool type

BAD Examples (too generic):
- "Search Results"
- "Tool Results" 
- "${toolName} Results"
- "Data from ${toolName}"
- "Tool Output"
- "Search Data"

GOOD Examples:
- "GitHub API Rate Limits & Auth Methods"
- "React Component Props Documentation"
- "Database Schema for User Tables"
- "Pricing Tiers with Enterprise Features"

Make the name extremely specific to what this tool call actually returned, not generic.`;
				let modelToUse = this.statusUpdateState?.summarizerModel;
				if (!modelToUse?.model?.trim()) if (!this.statusUpdateState?.baseModel?.model?.trim()) {
					if (artifactData.subAgentId && artifactData.tenantId && artifactData.projectId) try {
						const subAgentId = artifactData.subAgentId;
						const agentData = this.executionContext.project.agents[this.executionContext.agentId].subAgents?.[subAgentId];
						if (agentData && "models" in agentData && agentData.models?.base?.model) {
							modelToUse = agentData.models.base;
							logger.info({
								sessionId: this.sessionId,
								artifactId: artifactData.artifactId,
								subAgentId: artifactData.subAgentId,
								model: modelToUse.model
							}, "Using agent model configuration for artifact name generation");
						}
					} catch (error) {
						logger.warn({
							sessionId: this.sessionId,
							artifactId: artifactData.artifactId,
							subAgentId: artifactData.subAgentId,
							error: error instanceof Error ? error.message : "Unknown error"
						}, "Failed to get agent model configuration");
					}
					if (!modelToUse?.model?.trim()) {
						logger.warn({
							sessionId: this.sessionId,
							artifactId: artifactData.artifactId
						}, "No model configuration available for artifact name generation, will use fallback names");
						modelToUse = void 0;
					}
				} else modelToUse = this.statusUpdateState.baseModel;
				let result;
				if (!modelToUse) {
					const toolCallSuffix = artifactData.metadata?.toolCallId?.slice(-8) || Date.now().toString().slice(-8);
					result = {
						name: `${artifactData.artifactType || "Artifact"} ${toolCallSuffix}`,
						description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool"} (${artifactData.metadata?.toolCallId || "tool results"})`
					};
				} else {
					const model = ModelFactory.createModel(modelToUse);
					const schema = z.object({
						name: z.string().describe("Concise, descriptive name for the artifact"),
						description: z.string().describe("Brief description of the artifact's relevance to the user's question")
					});
					const { output: object } = await tracer.startActiveSpan("agent_session.generate_artifact_metadata", { attributes: {
						"llm.model": this.statusUpdateState?.summarizerModel?.model,
						"llm.operation": "generate_object",
						"artifact.id": artifactData.artifactId,
						"artifact.type": artifactData.artifactType,
						"artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
						"artifact.full": JSON.stringify(artifactData.data || artifactData.summaryData, null, 2),
						"prompt.length": prompt.length
					} }, async (generationSpan) => {
						const maxRetries = 3;
						let lastError = null;
						for (let attempt = 1; attempt <= maxRetries; attempt++) try {
							const result$1 = await generateText({
								model,
								prompt,
								output: Output.object({ schema }),
								experimental_telemetry: {
									isEnabled: true,
									functionId: `artifact_processing_${artifactData.artifactId}`,
									recordInputs: true,
									recordOutputs: true,
									metadata: {
										operation: "artifact_name_description_generation",
										sessionId: this.sessionId,
										attempt
									}
								}
							});
							generationSpan.setAttributes({
								"artifact.id": artifactData.artifactId,
								"artifact.type": artifactData.artifactType,
								"artifact.name": result$1.output.name,
								"artifact.description": result$1.output.description,
								"artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
								"artifact.full": JSON.stringify(artifactData.data || artifactData.summaryData, null, 2),
								"generation.name_length": result$1.output.name.length,
								"generation.description_length": result$1.output.description.length,
								"generation.attempts": attempt
							});
							generationSpan.setStatus({ code: SpanStatusCode.OK });
							return result$1;
						} catch (error) {
							lastError = error instanceof Error ? error : new Error(String(error));
							logger.warn({
								sessionId: this.sessionId,
								artifactId: artifactData.artifactId,
								attempt,
								maxRetries,
								error: lastError.message
							}, `Artifact name/description generation failed, attempt ${attempt}/${maxRetries}`);
							if (attempt < maxRetries) {
								const backoffMs = Math.min(ARTIFACT_GENERATION_BACKOFF_INITIAL_MS * 2 ** (attempt - 1), ARTIFACT_GENERATION_BACKOFF_MAX_MS);
								await new Promise((resolve) => setTimeout(resolve, backoffMs));
							}
						}
						setSpanWithError$1(generationSpan, lastError instanceof Error ? lastError : new Error(String(lastError)));
						throw new Error(`Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`);
					});
					result = object;
				}
				if (existingNames.includes(result.name)) {
					const toolCallSuffix = toolCallId.slice(-8);
					const originalName = result.name;
					result.name = result.name.length + toolCallSuffix.length + 1 <= 50 ? `${result.name} ${toolCallSuffix}` : `${result.name.substring(0, 50 - toolCallSuffix.length - 1)} ${toolCallSuffix}`;
					logger.info({
						sessionId: this.sessionId,
						artifactId: artifactData.artifactId,
						originalName,
						uniqueName: result.name,
						reason: "Name conflict resolved with toolCallId suffix"
					}, "Updated artifact name for uniqueness");
				}
				try {
					if (!this.artifactService) throw new Error("ArtifactService is not initialized");
					await this.artifactService.saveArtifact({
						artifactId: artifactData.artifactId,
						name: result.name,
						description: result.description,
						type: artifactData.artifactType || "source",
						data: artifactData.data || {},
						summaryData: artifactData.summaryData,
						metadata: artifactData.metadata || {},
						toolCallId: artifactData.toolCallId
					});
					mainSaveSucceeded = true;
					span.setAttributes({
						"artifact.name": result.name,
						"artifact.description": result.description,
						"processing.success": true
					});
					span.setStatus({ code: SpanStatusCode.OK });
				} catch (saveError) {
					logger.error({
						sessionId: this.sessionId,
						artifactId: artifactData.artifactId,
						error: saveError instanceof Error ? saveError.message : "Unknown error",
						errorName: saveError instanceof Error ? saveError.name : void 0,
						errorCause: saveError instanceof Error ? saveError.cause : void 0,
						errorCode: saveError?.code || saveError?.errno || void 0,
						artifactType: artifactData.artifactType,
						dataKeys: artifactData.data ? Object.keys(artifactData.data) : [],
						metadataKeys: artifactData.metadata ? Object.keys(artifactData.metadata) : []
					}, "Main artifact save failed, will attempt fallback");
				}
				if (!mainSaveSucceeded) try {
					if (artifactData.tenantId && artifactData.projectId) {
						await new ArtifactService({
							executionContext: this.executionContext,
							contextId: artifactData.contextId || "unknown",
							taskId: artifactData.taskId,
							sessionId: this.sessionId
						}).saveArtifact({
							artifactId: artifactData.artifactId,
							name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
							description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
							type: artifactData.artifactType || "source",
							data: artifactData.data || {},
							summaryData: artifactData.summaryData,
							metadata: artifactData.metadata || {},
							toolCallId: artifactData.toolCallId
						});
						logger.info({
							sessionId: this.sessionId,
							artifactId: artifactData.artifactId
						}, "Saved artifact with fallback name/description after main save failed");
					}
				} catch (fallbackError) {
					if (fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"))) {} else logger.error({
						sessionId: this.sessionId,
						artifactId: artifactData.artifactId,
						error: fallbackError instanceof Error ? fallbackError.message : "Unknown error",
						errorName: fallbackError instanceof Error ? fallbackError.name : void 0,
						errorCause: fallbackError instanceof Error ? fallbackError.cause : void 0,
						errorCode: fallbackError?.code || fallbackError?.errno || void 0,
						artifactType: artifactData.artifactType,
						dataKeys: artifactData.data ? Object.keys(artifactData.data) : [],
						metadataKeys: artifactData.metadata ? Object.keys(artifactData.metadata) : []
					}, "Failed to save artifact even with fallback");
				}
			} catch (error) {
				setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
				logger.error({
					sessionId: this.sessionId,
					artifactId: artifactData.artifactId,
					error: error instanceof Error ? error.message : "Unknown error"
				}, "Failed to process artifact (name/description generation failed)");
			} finally {
				span.end();
			}
		});
	}
	/**
	* Cache an artifact in this session for immediate access
	*/
	setArtifactCache(key, artifact) {
		this.artifactCache.set(key, artifact);
		logger.debug({
			sessionId: this.sessionId,
			key
		}, "Artifact cached in session");
	}
	/**
	* Get session-scoped ArtifactService instance
	*/
	getArtifactService() {
		return this.artifactService || null;
	}
	/**
	* Get session-scoped ArtifactParser instance
	*/
	getArtifactParser() {
		return this.artifactParser || null;
	}
	/**
	* Get an artifact from this session cache
	*/
	getArtifactCache(key) {
		const artifact = this.artifactCache.get(key);
		logger.debug({
			sessionId: this.sessionId,
			key,
			found: !!artifact
		}, "Artifact cache lookup");
		return artifact || null;
	}
	/**
	* Update artifact components in the shared ArtifactService
	*/
	updateArtifactComponents(artifactComponents) {
		if (this.artifactService) this.artifactService.updateArtifactComponents(artifactComponents);
	}
};
/**
* Manages AgentSession instances for message-level tracking
*/
var AgentSessionManager = class {
	sessions = /* @__PURE__ */ new Map();
	/**
	* Create a new session for a message
	*/
	createSession(messageId, executionContext, contextId) {
		const sessionId = messageId;
		const session = new AgentSession(sessionId, messageId, executionContext, contextId);
		this.sessions.set(sessionId, session);
		logger.info({
			sessionId,
			messageId,
			agentId: executionContext.agentId,
			tenantId: executionContext.tenantId,
			projectId: executionContext.projectId,
			contextId
		}, "AgentSession created");
		return sessionId;
	}
	/**
	* Initialize status updates for a session
	*/
	initializeStatusUpdates(sessionId, config, summarizerModel, baseModel) {
		const session = this.sessions.get(sessionId);
		if (session) session.initializeStatusUpdates(config, summarizerModel, baseModel);
		else logger.error({
			sessionId,
			availableSessions: Array.from(this.sessions.keys())
		}, "Session not found for status updates initialization");
	}
	/**
	* Enable emit operations for a session to send data operations
	*/
	enableEmitOperations(sessionId) {
		const session = this.sessions.get(sessionId);
		if (session) session.enableEmitOperations();
		else logger.error({
			sessionId,
			availableSessions: Array.from(this.sessions.keys())
		}, "Session not found for emit operations enablement");
	}
	/**
	* Get an existing session
	*/
	getSession(sessionId) {
		return this.sessions.get(sessionId) || null;
	}
	/**
	* Record an event in a session
	* Generic type parameter T ensures eventType and data are correctly paired
	*/
	recordEvent(sessionId, eventType, subAgentId, data) {
		const session = this.sessions.get(sessionId);
		if (!session) {
			logger.warn({
				sessionId,
				eventType,
				subAgentId
			}, "Attempted to record event in non-existent session (likely session already ended)");
			return;
		}
		session.recordEvent(eventType, subAgentId, data);
	}
	/**
	* End a session and return the final event data
	*/
	async endSession(sessionId) {
		const session = this.sessions.get(sessionId);
		if (!session) {
			logger.warn({ sessionId }, "Attempted to end non-existent session");
			return [];
		}
		const events = session.getEvents();
		const summary = session.getSummary();
		logger.info({
			sessionId,
			summary
		}, "AgentSession ended");
		await session.cleanup();
		this.sessions.delete(sessionId);
		return events;
	}
	/**
	* Set text streaming state for a session
	*/
	setTextStreaming(sessionId, isStreaming) {
		const session = this.sessions.get(sessionId);
		if (session) session.setTextStreaming(isStreaming);
	}
	/**
	* Get summary of all active sessions
	*/
	getActiveSessions() {
		return Array.from(this.sessions.values()).map((session) => ({
			sessionId: session.sessionId,
			messageId: session.messageId,
			eventCount: session.getEvents().length
		}));
	}
	/**
	* Cache an artifact in the specified session
	*/
	async setArtifactCache(sessionId, key, artifact) {
		const session = this.sessions.get(sessionId);
		if (session) session.setArtifactCache(key, artifact);
	}
	/**
	* Get an artifact from the specified session cache
	*/
	async getArtifactCache(sessionId, key) {
		const session = this.sessions.get(sessionId);
		return session ? session.getArtifactCache(key) : null;
	}
	/**
	* Get session-scoped ArtifactService instance
	*/
	getArtifactService(sessionId) {
		const session = this.sessions.get(sessionId);
		return session ? session.getArtifactService() : null;
	}
	/**
	* Get session-scoped ArtifactParser instance
	*/
	getArtifactParser(sessionId) {
		const session = this.sessions.get(sessionId);
		return session ? session.getArtifactParser() : null;
	}
	/**
	* Update artifact components for a session
	*/
	updateArtifactComponents(sessionId, artifactComponents) {
		const session = this.sessions.get(sessionId);
		if (session) session.updateArtifactComponents(artifactComponents);
	}
};
const agentSessionManager = new AgentSessionManager();

//#endregion
export { AgentSession, AgentSessionManager, agentSessionManager };