@memberjunction/ng-conversations 5.30.0 → 5.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/components/collection/artifact-collection-picker-modal.component.d.ts +2 -1
- package/dist/lib/components/collection/artifact-collection-picker-modal.component.d.ts.map +1 -1
- package/dist/lib/components/collection/artifact-collection-picker-modal.component.js +9 -6
- package/dist/lib/components/collection/artifact-collection-picker-modal.component.js.map +1 -1
- package/dist/lib/components/collection/artifact-create-modal.component.d.ts +2 -1
- package/dist/lib/components/collection/artifact-create-modal.component.d.ts.map +1 -1
- package/dist/lib/components/collection/artifact-create-modal.component.js +9 -6
- package/dist/lib/components/collection/artifact-create-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-form-modal.component.d.ts +2 -1
- package/dist/lib/components/collection/collection-form-modal.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-form-modal.component.js +8 -5
- package/dist/lib/components/collection/collection-form-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts +2 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.js +9 -6
- package/dist/lib/components/collection/collection-tree.component.js.map +1 -1
- package/dist/lib/components/collection/collection-view.component.d.ts +2 -1
- package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-view.component.js +12 -10
- package/dist/lib/components/collection/collection-view.component.js.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.d.ts +2 -1
- package/dist/lib/components/collection/collections-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.js +18 -12
- package/dist/lib/components/collection/collections-full-view.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +2 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.js +22 -11
- package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
- package/dist/lib/components/library/library-full-view.component.d.ts +2 -1
- package/dist/lib/components/library/library-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/library/library-full-view.component.js +8 -5
- package/dist/lib/components/library/library-full-view.component.js.map +1 -1
- package/dist/lib/components/message/conversation-message-rating.component.d.ts +2 -1
- package/dist/lib/components/message/conversation-message-rating.component.d.ts.map +1 -1
- package/dist/lib/components/message/conversation-message-rating.component.js +9 -7
- package/dist/lib/components/message/conversation-message-rating.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.d.ts +2 -1
- package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-input.component.js +12 -5
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-item.component.js +6 -1
- package/dist/lib/components/message/message-item.component.js.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts +2 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.js +6 -6
- package/dist/lib/components/overlay/chat-overlay.component.js.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.d.ts +2 -1
- package/dist/lib/components/project/project-form-modal.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.js +6 -5
- package/dist/lib/components/project/project-form-modal.component.js.map +1 -1
- package/dist/lib/components/project/project-selector.component.d.ts +2 -1
- package/dist/lib/components/project/project-selector.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-selector.component.js +8 -6
- package/dist/lib/components/project/project-selector.component.js.map +1 -1
- package/dist/lib/components/share/share-modal.component.d.ts +2 -1
- package/dist/lib/components/share/share-modal.component.d.ts.map +1 -1
- package/dist/lib/components/share/share-modal.component.js +11 -9
- package/dist/lib/components/share/share-modal.component.js.map +1 -1
- package/dist/lib/components/shared/user-picker.component.d.ts +2 -1
- package/dist/lib/components/shared/user-picker.component.d.ts.map +1 -1
- package/dist/lib/components/shared/user-picker.component.js +6 -4
- package/dist/lib/components/shared/user-picker.component.js.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.d.ts +2 -1
- package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.js +9 -8
- package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
- package/dist/lib/components/tasks/tasks-dropdown.component.d.ts.map +1 -1
- package/dist/lib/components/tasks/tasks-dropdown.component.js +5 -0
- package/dist/lib/components/tasks/tasks-dropdown.component.js.map +1 -1
- package/dist/lib/components/thread/thread-panel.component.d.ts +2 -1
- package/dist/lib/components/thread/thread-panel.component.d.ts.map +1 -1
- package/dist/lib/components/thread/thread-panel.component.js +7 -4
- package/dist/lib/components/thread/thread-panel.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +8 -4
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/models/lazy-artifact-info.js +1 -1
- package/dist/lib/models/lazy-artifact-info.js.map +1 -1
- package/dist/lib/services/active-tasks.service.d.ts +7 -1
- package/dist/lib/services/active-tasks.service.d.ts.map +1 -1
- package/dist/lib/services/active-tasks.service.js +12 -2
- package/dist/lib/services/active-tasks.service.js.map +1 -1
- package/dist/lib/services/agent-state.service.d.ts +7 -1
- package/dist/lib/services/agent-state.service.d.ts.map +1 -1
- package/dist/lib/services/agent-state.service.js +12 -2
- package/dist/lib/services/agent-state.service.js.map +1 -1
- package/dist/lib/services/artifact-permission.service.d.ts +8 -1
- package/dist/lib/services/artifact-permission.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-permission.service.js +21 -7
- package/dist/lib/services/artifact-permission.service.js.map +1 -1
- package/dist/lib/services/artifact-state.service.d.ts +8 -1
- package/dist/lib/services/artifact-state.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-state.service.js +25 -11
- package/dist/lib/services/artifact-state.service.js.map +1 -1
- package/dist/lib/services/artifact-use-tracking.service.d.ts +7 -1
- package/dist/lib/services/artifact-use-tracking.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-use-tracking.service.js +12 -2
- package/dist/lib/services/artifact-use-tracking.service.js.map +1 -1
- package/dist/lib/services/collection-permission.service.d.ts +7 -1
- package/dist/lib/services/collection-permission.service.d.ts.map +1 -1
- package/dist/lib/services/collection-permission.service.js +19 -9
- package/dist/lib/services/collection-permission.service.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +8 -0
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +15 -3
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-attachment.service.d.ts +7 -1
- package/dist/lib/services/conversation-attachment.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-attachment.service.js +12 -2
- package/dist/lib/services/conversation-attachment.service.js.map +1 -1
- package/dist/lib/services/data-cache.service.d.ts +7 -1
- package/dist/lib/services/data-cache.service.d.ts.map +1 -1
- package/dist/lib/services/data-cache.service.js +16 -7
- package/dist/lib/services/data-cache.service.js.map +1 -1
- package/dist/lib/services/export.service.d.ts +7 -1
- package/dist/lib/services/export.service.d.ts.map +1 -1
- package/dist/lib/services/export.service.js +12 -2
- package/dist/lib/services/export.service.js.map +1 -1
- package/dist/lib/services/search.service.d.ts +7 -1
- package/dist/lib/services/search.service.d.ts.map +1 -1
- package/dist/lib/services/search.service.js +16 -6
- package/dist/lib/services/search.service.js.map +1 -1
- package/package.json +22 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-agent.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,QAAQ,EAA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C;IACL,CAAC;kHAt1BU,wBAAwB;gEAAxB,wBAAwB,WAAxB,wBAAwB,mBAFvB,MAAM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { Metadata, RunView } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, ConversationUtility, AttachmentData } from '@memberjunction/ai-core-plus';\nimport { ChatMessage, ChatMessageContent } from '@memberjunction/ai';\nimport { AIEngineBase, AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';\nimport { MJConversationDetailEntity, MJConversationDetailArtifactEntity, MJArtifactVersionEntity, MJConversationDetailAttachmentEntity } from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended } from \"@memberjunction/ai-core-plus\";\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RunAgentFromConversationDetailParams } from '@memberjunction/ai-agent-client';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { UUIDsEqual } from '@memberjunction/global';\n\n/**\n * Context for artifact lookups - provides pre-loaded data from conversation\n * to avoid redundant database queries\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * Result from intent check - indicates whether to continue with agent\n * and which artifact version to use as payload\n */\nexport interface IntentCheckResult {\n decision: 'YES' | 'NO' | 'UNSURE';\n reasoning: string;\n targetArtifactVersionId?: string;\n}\n\n/**\n * Service for managing agent interactions within conversations.\n * Handles communication with the ambient Sage Agent and other agents.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAgentService {\n /** GraphQL AI client - retained for RunAIPrompt (intent checking) which AgentClientService doesn't wrap */\n private _aiClient: GraphQLAIClient | null = null;\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map(); // conversationId -> sessionId\n private _isProcessing$ = new BehaviorSubject<boolean>(false);\n\n /**\n * Observable indicating if the ambient agent is currently processing\n */\n public readonly isProcessing$: Observable<boolean> = this._isProcessing$.asObservable();\n\n constructor(\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n this.initializeAIClient();\n }\n\n /**\n * Initialize the GraphQL AI Client.\n * Retained for RunAIPrompt calls (intent checking) which the AgentClientService doesn't wrap.\n * Agent execution (RunAIAgentFromConversationDetail) now goes through AgentClientService.\n */\n private initializeAIClient(): void {\n try {\n const provider = Metadata.Provider as GraphQLDataProvider;\n if (provider) {\n this._aiClient = new GraphQLAIClient(provider);\n } else {\n console.warn('GraphQLDataProvider not available, agent functionality will be limited');\n }\n } catch (error) {\n console.error('Failed to initialize GraphQL AI Client:', error);\n }\n }\n\n /**\n * Get or load the Sage Agent (formerly Conversation Manager Agent)\n */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the Sage Agent\n const agents = AIEngineBase.Instance.Agents;\n this._conversationManagerAgent = agents.find(\n (agent: MJAIAgentEntityExtended) => agent.Name === 'Sage'\n ) || null;\n\n if (!this._conversationManagerAgent) {\n const errorMsg = 'Sage Agent not found in AIEngineBase.Agents';\n console.warn(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n }\n\n return this._conversationManagerAgent;\n } catch (error) {\n const errorMsg = 'Error loading Sage Agent: ' + (error instanceof Error ? error.message : String(error));\n console.error('Error loading Sage Agent:', error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n\n /**\n * Process a message through the ambient Sage Agent.\n * This should be called for every message sent in a conversation.\n *\n * Uses the optimized RunAIAgentFromConversationDetail mutation which loads\n * conversation history (including attachments) server-side for better performance.\n *\n * @param conversationId The conversation ID\n * @param message The message that was just sent\n * @param conversationHistory Recent messages in the conversation for context (kept for backwards compatibility but not used)\n * @param conversationDetailId The ID of the conversation detail record to link to the agent run\n * @param onProgress Optional callback for receiving progress updates during execution\n * @returns The agent's response, or null if the agent chooses not to respond\n */\n async processMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null\n ): Promise<ExecuteAgentResult | null> {\n // Don't process if user is tagging someone else (future enhancement)\n // For now, we'll always send to the ambient agent\n\n const agent = await this.getConversationManagerAgent();\n if (!agent || !agent.ID) {\n const errorMsg = 'Sage Agent not available';\n console.warn(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'warning', 5000);\n return null;\n }\n\n try {\n // Indicate agent is processing\n this._isProcessing$.next(true);\n\n // Get current user for permission filtering\n const currentUser = Metadata.Provider.CurrentUser;\n if (!currentUser) {\n console.warn('⚠️ No current user available for permission filtering, using unfiltered agents');\n }\n\n // Filter agents by status and hierarchy first\n const candidateAgents = AIEngineBase.Instance.Agents.filter(\n a => !UUIDsEqual(a.ID, agent.ID) &&\n !a.ParentID &&\n a.Status === 'Active' &&\n a.InvocationMode !== 'Sub-Agent' // ensure that the agent is intended to run as top-level\n );\n\n // Filter by user permissions if user context available\n const availAgents = currentUser\n ? await this.filterAgentsByPermissions(candidateAgents, currentUser)\n : candidateAgents;\n\n console.log(`📋 Available agents for Sage: ${availAgents.length} (filtered from ${candidateAgents.length} candidates)`);\n\n // Use AgentClientService which wraps GraphQLAIClient.RunAIAgentFromConversationDetail\n // and automatically integrates with client tool request handling\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n ALL_AVAILABLE_AGENTS: availAgents.map(a => ({\n ID: a.ID,\n Name: a.Name,\n Description: a.Description\n })),\n conversationId: conversationId,\n latestMessageId: message.ID,\n ...(appContext ? { appContext } : {}),\n // Include all registered client tools so the LLM sees them in the prompt.\n // These are ephemeral tools registered by the client app (CopyToClipboard, etc.)\n // that supplement the metadata-defined tools from the junction table.\n clientTools: this.agentClientService.GetRegisteredTools().map(t => ({\n Name: t.Name,\n Description: t.Description,\n InputSchema: t.ParameterSchema\n }))\n },\n CreateArtifacts: true,\n CreateNotification: true,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n // Unwrap RunAgentResult to get the original ExecuteAgentResult\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n } else if (!runResult.Success) {\n const errorMsg = runResult.ErrorMessage || 'Agent execution failed';\n console.error('Agent execution failed:', errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n return null;\n } catch (error) {\n const errorMsg = 'Error processing message through agent: ' + (error instanceof Error ? error.message : String(error));\n console.error('Error processing message through agent:', error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n } finally {\n // Always clear processing state\n this._isProcessing$.next(false);\n }\n }\n\n /**\n * Find the configuration preset ID from a previous @mention of an agent in conversation history.\n * Searches backwards through User messages to find the most recent @mention of the specified agent\n * that includes a configId.\n *\n * @param agentId The agent ID to search for\n * @param conversationHistory The conversation history to search through\n * @returns The configuration preset ID if found, undefined otherwise\n */\n public findConfigurationPresetFromHistory(\n agentId: string,\n conversationHistory: MJConversationDetailEntity[]\n ): string | undefined {\n // Search backwards through history for User messages that @mention this agent with a configId\n const userMentionWithConfig = conversationHistory\n .slice()\n .reverse()\n .find(msg => {\n if (msg.Role !== 'User' || !msg.Message) return false;\n // Parse the message to check for an @mention of this agent with a configId\n const mentionResult = this.mentionParser.parseMentions(\n msg.Message,\n AIEngineBase.Instance.Agents,\n []\n );\n return mentionResult.agentMention?.id === agentId && mentionResult.agentMention?.configurationId;\n });\n\n if (userMentionWithConfig) {\n const mentionResult = this.mentionParser.parseMentions(\n userMentionWithConfig.Message,\n AIEngineBase.Instance.Agents,\n []\n );\n if (mentionResult.agentMention?.configurationId) {\n console.log(`🎯 Found configuration preset from @mention: ${mentionResult.agentMention.configurationId}`);\n return mentionResult.agentMention.configurationId;\n }\n }\n\n return undefined;\n }\n\n /**\n * Build the message array for the agent from conversation history.\n * Note: conversationHistory already includes the current message, so we don't add it separately.\n * IMPORTANT: This method loads artifacts and attachments for each message.\n *\n * @deprecated This method is no longer used by processMessage() which now uses the optimized\n * RunAIAgentFromConversationDetail mutation that loads history server-side. Kept for backwards\n * compatibility with other callers that may need client-side message building.\n */\n private async buildAgentMessages(\n history: MJConversationDetailEntity[]\n ): Promise<ChatMessage[]> {\n const messages: ChatMessage[] = [];\n\n // Add historical messages (limit to recent context, e.g., last 20 messages)\n // History already includes the current message from the caller\n const recentHistory = history.slice(-20);\n\n // Get IDs of all messages in history\n const messageIds = recentHistory.map(msg => msg.ID).filter(id => id); // Filter out any undefined IDs\n\n // Create lookup maps\n const artifactsByDetailId = new Map<string, string[]>(); // DetailID -> array of artifact JSON strings\n const attachmentsByDetailId = new Map<string, AttachmentData[]>(); // DetailID -> array of AttachmentData\n\n if (messageIds.length > 0) {\n const rv = new RunView();\n\n // Load artifacts and attachments in parallel\n const [artifactsLoaded, attachmentsLoaded] = await Promise.all([\n this.loadArtifactsForMessages(rv, messageIds, artifactsByDetailId),\n this.loadAttachmentsForMessages(rv, messageIds, attachmentsByDetailId)\n ]);\n\n if (artifactsLoaded) {\n console.log(`📦 Loaded ${artifactsByDetailId.size} artifact groups for ${messageIds.length} messages`);\n }\n if (attachmentsLoaded) {\n console.log(`🖼️ Loaded ${attachmentsByDetailId.size} attachment groups for ${messageIds.length} messages`);\n }\n }\n\n // Build messages with proper multimodal content\n for (const msg of recentHistory) {\n const messageText = msg.Message || '';\n const artifacts = artifactsByDetailId.get(msg.ID);\n const attachments = attachmentsByDetailId.get(msg.ID);\n\n // Build content - may be string or ChatMessageContentBlock[]\n let content: ChatMessageContent;\n\n if (attachments && attachments.length > 0) {\n // Use BuildChatMessageContent to create proper content blocks for multimodal\n content = await ConversationUtility.BuildChatMessageContent(messageText, attachments);\n\n // Append artifacts to text content if present\n if (artifacts && artifacts.length > 0) {\n const artifactText = artifacts.map(json => `\\n\\n# Artifact\\n${json}\\n`).join('');\n\n if (typeof content === 'string') {\n content = content + artifactText;\n } else if (Array.isArray(content)) {\n // Find or create text block and append artifacts\n const textBlock = content.find(b => b.type === 'text');\n if (textBlock && textBlock.content) {\n textBlock.content += artifactText;\n } else {\n content.push({ type: 'text', content: artifactText });\n }\n }\n }\n } else {\n // No attachments - use simple string content\n content = messageText;\n\n // Append artifacts\n if (artifacts && artifacts.length > 0) {\n for (const artifactJson of artifacts) {\n content += `\\n\\n# Artifact\\n${artifactJson}\\n`;\n }\n }\n }\n\n messages.push({\n role: this.mapRoleToAgentRole(msg.Role) as 'system' | 'user' | 'assistant',\n content: content\n });\n }\n\n return messages;\n }\n\n /**\n * Load artifacts for messages (OUTPUT direction only)\n */\n private async loadArtifactsForMessages(\n rv: RunView,\n messageIds: string[],\n artifactsByDetailId: Map<string, string[]>\n ): Promise<boolean> {\n try {\n const junctionResult = await rv.RunView<MJConversationDetailArtifactEntity>({\n EntityName: 'MJ: Conversation Detail Artifacts',\n ExtraFilter: `ConversationDetailID IN ('${messageIds.join(\"','\")}') AND Direction='Output'`,\n ResultType: 'entity_object'\n });\n\n if (junctionResult.Success && junctionResult.Results && junctionResult.Results.length > 0) {\n // Collect unique version IDs\n const versionIds = new Set<string>();\n for (const junction of junctionResult.Results) {\n versionIds.add(junction.ArtifactVersionID);\n }\n\n // Batch load all artifact versions\n const versionResult = await rv.RunView<MJArtifactVersionEntity>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: `ID IN ('${Array.from(versionIds).join(\"','\")}')`,\n ResultType: 'entity_object'\n });\n\n if (versionResult.Success && versionResult.Results) {\n const versionMap = new Map(versionResult.Results.map(v => [v.ID, v]));\n\n for (const junction of junctionResult.Results) {\n const version = versionMap.get(junction.ArtifactVersionID);\n if (version && version.Content) {\n const existing = artifactsByDetailId.get(junction.ConversationDetailID) || [];\n existing.push(version.Content);\n artifactsByDetailId.set(junction.ConversationDetailID, existing);\n }\n }\n return true;\n }\n }\n } catch (error) {\n console.error('Error loading artifacts for conversation context:', error);\n }\n return false;\n }\n\n /**\n * Load attachments for messages and convert to AttachmentData format\n */\n private async loadAttachmentsForMessages(\n rv: RunView,\n messageIds: string[],\n attachmentsByDetailId: Map<string, AttachmentData[]>\n ): Promise<boolean> {\n console.log('[AgentService] loadAttachmentsForMessages - querying for messageIds:', messageIds);\n try {\n const filter = `ConversationDetailID IN ('${messageIds.join(\"','\")}')`;\n console.log('[AgentService] loadAttachmentsForMessages - filter:', filter);\n\n const attachmentResult = await rv.RunView<MJConversationDetailAttachmentEntity>({\n EntityName: 'MJ: Conversation Detail Attachments',\n ExtraFilter: filter,\n OrderBy: 'DisplayOrder ASC, __mj_CreatedAt ASC',\n ResultType: 'entity_object'\n });\n\n console.log('[AgentService] loadAttachmentsForMessages - query result:', {\n success: attachmentResult.Success,\n count: attachmentResult.Results?.length || 0,\n error: attachmentResult.ErrorMessage\n });\n\n if (attachmentResult.Success && attachmentResult.Results && attachmentResult.Results.length > 0) {\n for (const att of attachmentResult.Results) {\n console.log('[AgentService] loadAttachmentsForMessages - processing attachment:', {\n id: att.ID,\n detailId: att.ConversationDetailID,\n mimeType: att.MimeType,\n hasInlineData: !!att.InlineData,\n hasFileID: !!att.FileID\n });\n // Convert to AttachmentData format\n const attachmentData = this.convertToAttachmentData(att);\n if (attachmentData) {\n const existing = attachmentsByDetailId.get(att.ConversationDetailID) || [];\n existing.push(attachmentData);\n attachmentsByDetailId.set(att.ConversationDetailID, existing);\n }\n }\n return true;\n }\n } catch (error) {\n console.error('Error loading attachments for conversation context:', error);\n }\n return false;\n }\n\n /**\n * Convert a MJConversationDetailAttachmentEntity to AttachmentData format\n */\n private convertToAttachmentData(att: MJConversationDetailAttachmentEntity): AttachmentData | null {\n // Get the content - either inline data or file URL\n let content: string | null = null;\n\n if (att.InlineData) {\n // Create data URL from inline base64 data\n content = `data:${att.MimeType};base64,${att.InlineData}`;\n } else if (att.FileID) {\n // TODO: Get pre-authenticated URL from MJStorage\n // For now, skip attachments stored in external storage\n console.warn(`Attachment ${att.ID} uses FileID storage - external URLs not yet supported`);\n return null;\n }\n\n if (!content) {\n return null;\n }\n\n // Determine attachment type from modality or MIME type\n const attachmentType = ConversationUtility.GetAttachmentTypeFromMime(att.MimeType);\n\n return {\n type: attachmentType,\n mimeType: att.MimeType,\n fileName: att.FileName ?? undefined,\n sizeBytes: att.FileSizeBytes ?? undefined,\n width: att.Width ?? undefined,\n height: att.Height ?? undefined,\n durationSeconds: att.DurationSeconds ?? undefined,\n content: content\n };\n }\n\n /**\n * Map ConversationDetail Role to agent message role\n */\n private mapRoleToAgentRole(role: string): string {\n const roleLower = (role || '').toLowerCase();\n if (roleLower === 'user') return 'user';\n if (roleLower === 'assistant' || roleLower === 'agent') return 'assistant';\n return 'user'; // Default to user\n }\n\n /**\n * Check if a message is tagging another user or agent.\n * Returns true if the message contains @mentions that are NOT the ambient agent.\n * Future enhancement: parse @mentions and determine if ambient agent should process.\n */\n private isTaggingOthers(message: string): boolean {\n // Future implementation: check for @mentions\n // For now, always return false (always process through ambient agent)\n return false;\n }\n\n /**\n * Invoke a sub-agent based on Sage Agent's payload.\n * This is called when Sage decides to delegate to a specialist agent.\n *\n * @param agentName Name of the agent to invoke\n * @param conversationId The conversation ID\n * @param message The user message that triggered this\n * @param conversationHistory Recent conversation history for context\n * @param reasoning Why this agent is being invoked\n * @param conversationDetailId The ID of the conversation detail record to link to the agent run\n * @param payload Optional payload to pass to the agent (e.g., previous OUTPUT artifact for continuity)\n * @param onProgress Optional callback for receiving progress updates during execution\n * @param sourceArtifactId Optional source artifact ID for versioning\n * @param sourceArtifactVersionId Optional source artifact version ID for versioning\n * @param agentConfigurationPresetId Optional ID of the AIAgentConfiguration preset (will be mapped to AIConfigurationID)\n * @returns The agent's execution result, or null if agent not found\n */\n async invokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: unknown,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string\n ): Promise<ExecuteAgentResult | null> {\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the agent by name\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n if (!agent || !agent.ID) {\n const errorMsg = `Sub-agent \"${agentName}\" not found`;\n console.warn(`${errorMsg}`);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n console.log(`Invoking sub-agent: ${agentName}`, { reasoning, hasPayload: !!payload, hasConfigPreset: !!agentConfigurationPresetId });\n\n // Map AIAgentConfiguration preset ID to actual AIConfiguration ID\n let aiConfigurationId: string | undefined = undefined;\n if (agentConfigurationPresetId) {\n // Get the preset from AIEngineBase to extract the AIConfigurationID\n const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\n // check by preset ID or AIConfigurationID - since sometimes we have the actual\n // configuration ID. Since both UUID no collisions should ever be possible.\n const preset = presets.find(p => UUIDsEqual(p.ID, agentConfigurationPresetId) || UUIDsEqual(p.AIConfigurationID, agentConfigurationPresetId));\n\n if (preset) {\n aiConfigurationId = preset.AIConfigurationID || undefined;\n console.log(`Mapped agent configuration preset \"${preset.Name}\" to AIConfigurationID: ${aiConfigurationId || 'default'}`);\n } else {\n console.warn(`Agent configuration preset ${agentConfigurationPresetId} not found for agent ${agent.ID}`);\n }\n }\n\n // Use AgentClientService which wraps GraphQLAIClient.RunAIAgentFromConversationDetail\n // and integrates with client tool request handling\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n conversationId: conversationId,\n latestMessageId: message.ID,\n invocationReason: reasoning\n },\n ...(payload ? { Payload: payload as Record<string, unknown> } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n CreateArtifacts: true,\n CreateNotification: true,\n SourceArtifactId: sourceArtifactId,\n SourceArtifactVersionId: sourceArtifactVersionId,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n // Unwrap RunAgentResult to get the original ExecuteAgentResult\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n } else if (!runResult.Success) {\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${runResult.ErrorMessage || 'unknown error'}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n return null;\n } catch (error) {\n const errorMsg = `Error invoking sub-agent \"${agentName}\": ` + (error instanceof Error ? error.message : String(error));\n console.error(`Error invoking sub-agent \"${agentName}\":`, error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /**\n * Check if user's latest message should continue with the previous agent or route through Sage.\n * Uses fast inference (<500ms) to determine intent and avoid unnecessary Sage overhead.\n *\n * @param agentId The ID of the previous agent\n * @param latestMessage The user's new message\n * @param conversationHistory Recent conversation history for context (last 10 messages)\n * @param context Pre-loaded artifact and agent run data to avoid database queries\n * @returns IntentCheckResult with decision, reasoning, and optional target artifact version\n */\n async checkAgentContinuityIntent(\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[],\n context: ArtifactLookupContext\n ): Promise<IntentCheckResult> {\n if (!this._aiClient) {\n console.warn('AI Client not initialized, defaulting to UNSURE for intent check');\n return { decision: 'UNSURE', reasoning: 'AI Client not initialized' };\n }\n\n try {\n // Load the Check Sage Intent prompt\n await AIEngineBase.Instance.Config(false);\n const prompt = AIEngineBase.Instance.Prompts.find(p => p.Name === 'Check Sage Intent');\n if (!prompt) {\n console.warn('⚠️ Check Sage Intent prompt not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Check Sage Intent prompt not found' };\n }\n\n // Get agent details\n const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Previous agent not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Previous agent not found' };\n }\n\n // Find all artifacts from this agent in this conversation\n const agentArtifacts = this.findAllAgentArtifacts(\n agentId,\n conversationHistory,\n context\n );\n\n // Build compact conversation history (last 10 messages)\n const recentHistory = conversationHistory.slice(-10);\n const compactHistory = recentHistory.map((msg, idx) => {\n const role = msg.Role === 'User' ? 'User' : agent.Name || 'Agent';\n const content = msg.Message || '';\n return `${idx + 1}. ${role}: ${content.substring(0, 150)}${content.length > 150 ? '...' : ''}`;\n }).join('\\n');\n\n // Build artifact context if available\n let artifactContext = '';\n if (agentArtifacts.length > 0) {\n artifactContext = '\\n\\n**Prior Artifacts Created by This Agent**:\\n';\n agentArtifacts.forEach((artifact, idx) => {\n artifactContext += `${idx + 1}. ${artifact.artifactName} (${artifact.artifactType})\\n`;\n artifactContext += ` - Versions: ${artifact.versions.length}\\n`;\n if (artifact.versions.length > 0) {\n artifactContext += ` - Latest: v${artifact.versions[0].versionNumber}`;\n if (artifact.versions[0].versionName) {\n artifactContext += ` - ${artifact.versions[0].versionName}`;\n }\n artifactContext += '\\n';\n }\n });\n }\n\n // Build user message with context\n const userMessage = `**Previous Agent**: ${agent.Name} - ${agent.Description || 'No description'}\n\n**Conversation History** (last ${recentHistory.length} messages):\n${compactHistory}${artifactContext}\n\n**Latest User Message**: \"${latestMessage}\"`;\n\n console.log('🔍 Checking agent continuity intent...', {\n agentName: agent.Name,\n messagePreview: latestMessage.substring(0, 50),\n artifactCount: agentArtifacts.length\n });\n\n // Run the prompt with artifact data included\n const result = await this._aiClient.RunAIPrompt({\n promptId: prompt.ID,\n messages: [{ role: 'user', content: userMessage }],\n data: {\n hasPriorArtifact: agentArtifacts.length > 0,\n priorArtifacts: agentArtifacts\n }\n });\n\n if (result && result.success && (result.parsedResult || result.output)) {\n const parsed = result.parsedResult ||\n (result.output ? JSON.parse(result.output) : null);\n\n if (parsed && parsed.continuesWith) {\n const decision = parsed.continuesWith.toUpperCase();\n const reasoning = parsed.reasoning || 'No reasoning provided';\n const targetArtifactVersionId = parsed.targetArtifactVersionId || undefined;\n\n console.log(`✅ Intent check result: ${decision}`, {\n reasoning,\n targetArtifactVersionId,\n latency: result.executionTimeMs || 'unknown'\n });\n\n // Validate the response\n if (decision === 'YES' || decision === 'NO' || decision === 'UNSURE') {\n return {\n decision: decision as 'YES' | 'NO' | 'UNSURE',\n reasoning,\n targetArtifactVersionId\n };\n }\n }\n }\n\n console.warn('⚠️ Intent check failed or returned invalid format, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Invalid format from intent check prompt' };\n } catch (error) {\n console.error('❌ Error checking agent continuity intent:', error);\n // On error, default to UNSURE (safer to let Sage evaluate)\n return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\n }\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n clearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /**\n * Filter agents based on user's 'run' permission.\n * Only returns agents that the user has permission to run.\n *\n * @param agents List of candidate agents to filter\n * @param user User to check permissions for\n * @returns Filtered list of agents the user can run\n */\n private async filterAgentsByPermissions(\n agents: MJAIAgentEntityExtended[],\n user: any\n ): Promise<MJAIAgentEntityExtended[]> {\n const permittedAgents: MJAIAgentEntityExtended[] = [];\n\n for (const agent of agents) {\n try {\n const hasPermission = await AIAgentPermissionHelper.HasPermission(\n agent.ID,\n user,\n 'run'\n );\n if (hasPermission) {\n permittedAgents.push(agent);\n }\n } catch (error) {\n console.error(`Error checking permission for agent ${agent.Name}:`, error);\n // On error, exclude agent (fail closed)\n }\n }\n\n return permittedAgents;\n }\n\n /**\n * Find all artifacts created by the specified agent in this conversation.\n * Returns artifacts grouped by artifact with versions, ordered most recent first.\n * Enables LLM to reason about which artifact/version user is referencing.\n *\n * Uses pre-loaded data from ArtifactLookupContext for performance (no database queries).\n */\n private findAllAgentArtifacts(\n agentId: string,\n conversationDetails: MJConversationDetailEntity[],\n context: ArtifactLookupContext\n ): Array<{\n artifactId: string;\n artifactName: string;\n artifactType: string;\n artifactDescription: string | null;\n versions: Array<{\n runId: string;\n versionId: string;\n versionNumber: number;\n versionName: string | null;\n versionDescription: string | null;\n createdAt: Date;\n }>;\n }> {\n const artifactMap = new Map<string, {\n artifactId: string;\n artifactName: string;\n artifactType: string;\n artifactDescription: string | null;\n versions: Array<{\n runId: string;\n versionId: string;\n versionNumber: number;\n versionName: string | null;\n versionDescription: string | null;\n createdAt: Date;\n }>;\n }>();\n\n // Iterate backwards through conversation details (most recent first)\n for (let i = conversationDetails.length - 1; i >= 0; i--) {\n const detail = conversationDetails[i];\n\n // Skip non-AI messages and errors\n if (detail.Role !== 'AI' || detail.Status === 'Error') continue;\n\n // O(1) lookup for agent run from pre-loaded data\n const agentRun = context.agentRunsByDetailId.get(detail.ID);\n if (!agentRun || !UUIDsEqual(agentRun.AgentID, agentId) || agentRun.Status !== 'Completed') {\n continue;\n }\n\n // O(1) lookup for artifacts from pre-loaded data\n const artifacts = context.artifactsByDetailId.get(detail.ID);\n if (!artifacts || artifacts.length === 0) continue;\n\n // Process each artifact\n for (const lazyArtifact of artifacts) {\n const mainArtifactId = lazyArtifact.artifactId;\n\n // Get or create artifact entry\n if (!artifactMap.has(mainArtifactId)) {\n artifactMap.set(mainArtifactId, {\n artifactId: mainArtifactId,\n artifactName: lazyArtifact.artifactName,\n artifactType: lazyArtifact.artifactType,\n artifactDescription: lazyArtifact.artifactDescription || null,\n versions: []\n });\n }\n\n // Add version to artifact\n const artifactEntry = artifactMap.get(mainArtifactId)!;\n artifactEntry.versions.push({\n runId: agentRun.ID,\n versionId: lazyArtifact.artifactVersionId,\n versionNumber: lazyArtifact.versionNumber,\n versionName: lazyArtifact.versionName,\n versionDescription: lazyArtifact.versionDescription,\n createdAt: lazyArtifact.versionCreatedAt\n });\n }\n }\n\n // Convert map to array (most recent artifacts first based on their latest version)\n return Array.from(artifactMap.values()).sort((a, b) => {\n const aLatest = a.versions[0]?.createdAt || new Date(0);\n const bLatest = b.versions[0]?.createdAt || new Date(0);\n return bLatest.getTime() - aLatest.getTime();\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"conversation-agent.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAqB,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAuB,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAsD,mBAAmB,EAAkB,MAAM,8BAA8B,CAAC;AAEvI,OAAO,EAAE,YAAY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AI,IAAI,CAAC,CAAC,CAAC,CAAC;YACxD,OAAO,OAAO,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;kHAp2BU,wBAAwB;gEAAxB,wBAAwB,WAAxB,wBAAwB,mBAFvB,MAAM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { Metadata, RunView, IMetadataProvider } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, ConversationUtility, AttachmentData } from '@memberjunction/ai-core-plus';\nimport { ChatMessage, ChatMessageContent } from '@memberjunction/ai';\nimport { AIEngineBase, AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';\nimport { MJConversationDetailEntity, MJConversationDetailArtifactEntity, MJArtifactVersionEntity, MJConversationDetailAttachmentEntity } from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended } from \"@memberjunction/ai-core-plus\";\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RunAgentFromConversationDetailParams } from '@memberjunction/ai-agent-client';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { UUIDsEqual } from '@memberjunction/global';\n\n/**\n * Context for artifact lookups - provides pre-loaded data from conversation\n * to avoid redundant database queries\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * Result from intent check - indicates whether to continue with agent\n * and which artifact version to use as payload\n */\nexport interface IntentCheckResult {\n decision: 'YES' | 'NO' | 'UNSURE';\n reasoning: string;\n targetArtifactVersionId?: string;\n}\n\n/**\n * Service for managing agent interactions within conversations.\n * Handles communication with the ambient Sage Agent and other agents.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAgentService {\n /** GraphQL AI client - retained for RunAIPrompt (intent checking) which AgentClientService doesn't wrap */\n private _aiClient: GraphQLAIClient | null = null;\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map(); // conversationId -> sessionId\n private _isProcessing$ = new BehaviorSubject<boolean>(false);\n\n /**\n * Observable indicating if the ambient agent is currently processing\n */\n public readonly isProcessing$: Observable<boolean> = this._isProcessing$.asObservable();\n\n private _provider: IMetadataProvider | null = null;\n\n constructor(\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n this.initializeAIClient();\n }\n\n /**\n * The metadata provider this service uses. When unset, falls back to Metadata.Provider.\n * Setting it re-initializes the AI client to bind to the supplied provider.\n */\n public get Provider(): IMetadataProvider {\n return this._provider ?? Metadata.Provider;\n }\n public set Provider(value: IMetadataProvider | null) {\n this._provider = value;\n this.initializeAIClient();\n }\n\n /**\n * Initialize the GraphQL AI Client.\n * Retained for RunAIPrompt calls (intent checking) which the AgentClientService doesn't wrap.\n * Agent execution (RunAIAgentFromConversationDetail) now goes through AgentClientService.\n */\n private initializeAIClient(): void {\n try {\n const provider = this.Provider as GraphQLDataProvider;\n if (provider) {\n this._aiClient = new GraphQLAIClient(provider);\n } else {\n console.warn('GraphQLDataProvider not available, agent functionality will be limited');\n }\n } catch (error) {\n console.error('Failed to initialize GraphQL AI Client:', error);\n }\n }\n\n /**\n * Get or load the Sage Agent (formerly Conversation Manager Agent)\n */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the Sage Agent\n const agents = AIEngineBase.Instance.Agents;\n this._conversationManagerAgent = agents.find(\n (agent: MJAIAgentEntityExtended) => agent.Name === 'Sage'\n ) || null;\n\n if (!this._conversationManagerAgent) {\n const errorMsg = 'Sage Agent not found in AIEngineBase.Agents';\n console.warn(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n }\n\n return this._conversationManagerAgent;\n } catch (error) {\n const errorMsg = 'Error loading Sage Agent: ' + (error instanceof Error ? error.message : String(error));\n console.error('Error loading Sage Agent:', error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n\n /**\n * Process a message through the ambient Sage Agent.\n * This should be called for every message sent in a conversation.\n *\n * Uses the optimized RunAIAgentFromConversationDetail mutation which loads\n * conversation history (including attachments) server-side for better performance.\n *\n * @param conversationId The conversation ID\n * @param message The message that was just sent\n * @param conversationHistory Recent messages in the conversation for context (kept for backwards compatibility but not used)\n * @param conversationDetailId The ID of the conversation detail record to link to the agent run\n * @param onProgress Optional callback for receiving progress updates during execution\n * @returns The agent's response, or null if the agent chooses not to respond\n */\n async processMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null\n ): Promise<ExecuteAgentResult | null> {\n // Don't process if user is tagging someone else (future enhancement)\n // For now, we'll always send to the ambient agent\n\n const agent = await this.getConversationManagerAgent();\n if (!agent || !agent.ID) {\n const errorMsg = 'Sage Agent not available';\n console.warn(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'warning', 5000);\n return null;\n }\n\n try {\n // Indicate agent is processing\n this._isProcessing$.next(true);\n\n // Get current user for permission filtering\n const currentUser = this.Provider.CurrentUser;\n if (!currentUser) {\n console.warn('⚠️ No current user available for permission filtering, using unfiltered agents');\n }\n\n // Filter agents by status and hierarchy first\n const candidateAgents = AIEngineBase.Instance.Agents.filter(\n a => !UUIDsEqual(a.ID, agent.ID) &&\n !a.ParentID &&\n a.Status === 'Active' &&\n a.InvocationMode !== 'Sub-Agent' // ensure that the agent is intended to run as top-level\n );\n\n // Filter by user permissions if user context available\n const availAgents = currentUser\n ? await this.filterAgentsByPermissions(candidateAgents, currentUser)\n : candidateAgents;\n\n console.log(`📋 Available agents for Sage: ${availAgents.length} (filtered from ${candidateAgents.length} candidates)`);\n\n // Use AgentClientService which wraps GraphQLAIClient.RunAIAgentFromConversationDetail\n // and automatically integrates with client tool request handling\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n ALL_AVAILABLE_AGENTS: availAgents.map(a => ({\n ID: a.ID,\n Name: a.Name,\n Description: a.Description\n })),\n conversationId: conversationId,\n latestMessageId: message.ID,\n ...(appContext ? { appContext } : {}),\n // Include all registered client tools so the LLM sees them in the prompt.\n // These are ephemeral tools registered by the client app (CopyToClipboard, etc.)\n // that supplement the metadata-defined tools from the junction table.\n clientTools: this.agentClientService.GetRegisteredTools().map(t => ({\n Name: t.Name,\n Description: t.Description,\n InputSchema: t.ParameterSchema\n }))\n },\n CreateArtifacts: true,\n CreateNotification: true,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n // Unwrap RunAgentResult to get the original ExecuteAgentResult\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n } else if (!runResult.Success) {\n const errorMsg = runResult.ErrorMessage || 'Agent execution failed';\n console.error('Agent execution failed:', errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n return null;\n } catch (error) {\n const errorMsg = 'Error processing message through agent: ' + (error instanceof Error ? error.message : String(error));\n console.error('Error processing message through agent:', error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n } finally {\n // Always clear processing state\n this._isProcessing$.next(false);\n }\n }\n\n /**\n * Find the configuration preset ID from a previous @mention of an agent in conversation history.\n * Searches backwards through User messages to find the most recent @mention of the specified agent\n * that includes a configId.\n *\n * @param agentId The agent ID to search for\n * @param conversationHistory The conversation history to search through\n * @returns The configuration preset ID if found, undefined otherwise\n */\n public findConfigurationPresetFromHistory(\n agentId: string,\n conversationHistory: MJConversationDetailEntity[]\n ): string | undefined {\n // Search backwards through history for User messages that @mention this agent with a configId\n const userMentionWithConfig = conversationHistory\n .slice()\n .reverse()\n .find(msg => {\n if (msg.Role !== 'User' || !msg.Message) return false;\n // Parse the message to check for an @mention of this agent with a configId\n const mentionResult = this.mentionParser.parseMentions(\n msg.Message,\n AIEngineBase.Instance.Agents,\n []\n );\n return mentionResult.agentMention?.id === agentId && mentionResult.agentMention?.configurationId;\n });\n\n if (userMentionWithConfig) {\n const mentionResult = this.mentionParser.parseMentions(\n userMentionWithConfig.Message,\n AIEngineBase.Instance.Agents,\n []\n );\n if (mentionResult.agentMention?.configurationId) {\n console.log(`🎯 Found configuration preset from @mention: ${mentionResult.agentMention.configurationId}`);\n return mentionResult.agentMention.configurationId;\n }\n }\n\n return undefined;\n }\n\n /**\n * Build the message array for the agent from conversation history.\n * Note: conversationHistory already includes the current message, so we don't add it separately.\n * IMPORTANT: This method loads artifacts and attachments for each message.\n *\n * @deprecated This method is no longer used by processMessage() which now uses the optimized\n * RunAIAgentFromConversationDetail mutation that loads history server-side. Kept for backwards\n * compatibility with other callers that may need client-side message building.\n */\n private async buildAgentMessages(\n history: MJConversationDetailEntity[]\n ): Promise<ChatMessage[]> {\n const messages: ChatMessage[] = [];\n\n // Add historical messages (limit to recent context, e.g., last 20 messages)\n // History already includes the current message from the caller\n const recentHistory = history.slice(-20);\n\n // Get IDs of all messages in history\n const messageIds = recentHistory.map(msg => msg.ID).filter(id => id); // Filter out any undefined IDs\n\n // Create lookup maps\n const artifactsByDetailId = new Map<string, string[]>(); // DetailID -> array of artifact JSON strings\n const attachmentsByDetailId = new Map<string, AttachmentData[]>(); // DetailID -> array of AttachmentData\n\n if (messageIds.length > 0) {\n const rv = RunView.FromMetadataProvider(this.Provider);\n\n // Load artifacts and attachments in parallel\n const [artifactsLoaded, attachmentsLoaded] = await Promise.all([\n this.loadArtifactsForMessages(rv, messageIds, artifactsByDetailId),\n this.loadAttachmentsForMessages(rv, messageIds, attachmentsByDetailId)\n ]);\n\n if (artifactsLoaded) {\n console.log(`📦 Loaded ${artifactsByDetailId.size} artifact groups for ${messageIds.length} messages`);\n }\n if (attachmentsLoaded) {\n console.log(`🖼️ Loaded ${attachmentsByDetailId.size} attachment groups for ${messageIds.length} messages`);\n }\n }\n\n // Build messages with proper multimodal content\n for (const msg of recentHistory) {\n const messageText = msg.Message || '';\n const artifacts = artifactsByDetailId.get(msg.ID);\n const attachments = attachmentsByDetailId.get(msg.ID);\n\n // Build content - may be string or ChatMessageContentBlock[]\n let content: ChatMessageContent;\n\n if (attachments && attachments.length > 0) {\n // Use BuildChatMessageContent to create proper content blocks for multimodal\n content = await ConversationUtility.BuildChatMessageContent(messageText, attachments);\n\n // Append artifacts to text content if present\n if (artifacts && artifacts.length > 0) {\n const artifactText = artifacts.map(json => `\\n\\n# Artifact\\n${json}\\n`).join('');\n\n if (typeof content === 'string') {\n content = content + artifactText;\n } else if (Array.isArray(content)) {\n // Find or create text block and append artifacts\n const textBlock = content.find(b => b.type === 'text');\n if (textBlock && textBlock.content) {\n textBlock.content += artifactText;\n } else {\n content.push({ type: 'text', content: artifactText });\n }\n }\n }\n } else {\n // No attachments - use simple string content\n content = messageText;\n\n // Append artifacts\n if (artifacts && artifacts.length > 0) {\n for (const artifactJson of artifacts) {\n content += `\\n\\n# Artifact\\n${artifactJson}\\n`;\n }\n }\n }\n\n messages.push({\n role: this.mapRoleToAgentRole(msg.Role) as 'system' | 'user' | 'assistant',\n content: content\n });\n }\n\n return messages;\n }\n\n /**\n * Load artifacts for messages (OUTPUT direction only)\n */\n private async loadArtifactsForMessages(\n rv: RunView,\n messageIds: string[],\n artifactsByDetailId: Map<string, string[]>\n ): Promise<boolean> {\n try {\n const junctionResult = await rv.RunView<MJConversationDetailArtifactEntity>({\n EntityName: 'MJ: Conversation Detail Artifacts',\n ExtraFilter: `ConversationDetailID IN ('${messageIds.join(\"','\")}') AND Direction='Output'`,\n ResultType: 'entity_object'\n });\n\n if (junctionResult.Success && junctionResult.Results && junctionResult.Results.length > 0) {\n // Collect unique version IDs\n const versionIds = new Set<string>();\n for (const junction of junctionResult.Results) {\n versionIds.add(junction.ArtifactVersionID);\n }\n\n // Batch load all artifact versions\n const versionResult = await rv.RunView<MJArtifactVersionEntity>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: `ID IN ('${Array.from(versionIds).join(\"','\")}')`,\n ResultType: 'entity_object'\n });\n\n if (versionResult.Success && versionResult.Results) {\n const versionMap = new Map(versionResult.Results.map(v => [v.ID, v]));\n\n for (const junction of junctionResult.Results) {\n const version = versionMap.get(junction.ArtifactVersionID);\n if (version && version.Content) {\n const existing = artifactsByDetailId.get(junction.ConversationDetailID) || [];\n existing.push(version.Content);\n artifactsByDetailId.set(junction.ConversationDetailID, existing);\n }\n }\n return true;\n }\n }\n } catch (error) {\n console.error('Error loading artifacts for conversation context:', error);\n }\n return false;\n }\n\n /**\n * Load attachments for messages and convert to AttachmentData format\n */\n private async loadAttachmentsForMessages(\n rv: RunView,\n messageIds: string[],\n attachmentsByDetailId: Map<string, AttachmentData[]>\n ): Promise<boolean> {\n console.log('[AgentService] loadAttachmentsForMessages - querying for messageIds:', messageIds);\n try {\n const filter = `ConversationDetailID IN ('${messageIds.join(\"','\")}')`;\n console.log('[AgentService] loadAttachmentsForMessages - filter:', filter);\n\n const attachmentResult = await rv.RunView<MJConversationDetailAttachmentEntity>({\n EntityName: 'MJ: Conversation Detail Attachments',\n ExtraFilter: filter,\n OrderBy: 'DisplayOrder ASC, __mj_CreatedAt ASC',\n ResultType: 'entity_object'\n });\n\n console.log('[AgentService] loadAttachmentsForMessages - query result:', {\n success: attachmentResult.Success,\n count: attachmentResult.Results?.length || 0,\n error: attachmentResult.ErrorMessage\n });\n\n if (attachmentResult.Success && attachmentResult.Results && attachmentResult.Results.length > 0) {\n for (const att of attachmentResult.Results) {\n console.log('[AgentService] loadAttachmentsForMessages - processing attachment:', {\n id: att.ID,\n detailId: att.ConversationDetailID,\n mimeType: att.MimeType,\n hasInlineData: !!att.InlineData,\n hasFileID: !!att.FileID\n });\n // Convert to AttachmentData format\n const attachmentData = this.convertToAttachmentData(att);\n if (attachmentData) {\n const existing = attachmentsByDetailId.get(att.ConversationDetailID) || [];\n existing.push(attachmentData);\n attachmentsByDetailId.set(att.ConversationDetailID, existing);\n }\n }\n return true;\n }\n } catch (error) {\n console.error('Error loading attachments for conversation context:', error);\n }\n return false;\n }\n\n /**\n * Convert a MJConversationDetailAttachmentEntity to AttachmentData format\n */\n private convertToAttachmentData(att: MJConversationDetailAttachmentEntity): AttachmentData | null {\n // Get the content - either inline data or file URL\n let content: string | null = null;\n\n if (att.InlineData) {\n // Create data URL from inline base64 data\n content = `data:${att.MimeType};base64,${att.InlineData}`;\n } else if (att.FileID) {\n // TODO: Get pre-authenticated URL from MJStorage\n // For now, skip attachments stored in external storage\n console.warn(`Attachment ${att.ID} uses FileID storage - external URLs not yet supported`);\n return null;\n }\n\n if (!content) {\n return null;\n }\n\n // Determine attachment type from modality or MIME type\n const attachmentType = ConversationUtility.GetAttachmentTypeFromMime(att.MimeType);\n\n return {\n type: attachmentType,\n mimeType: att.MimeType,\n fileName: att.FileName ?? undefined,\n sizeBytes: att.FileSizeBytes ?? undefined,\n width: att.Width ?? undefined,\n height: att.Height ?? undefined,\n durationSeconds: att.DurationSeconds ?? undefined,\n content: content\n };\n }\n\n /**\n * Map ConversationDetail Role to agent message role\n */\n private mapRoleToAgentRole(role: string): string {\n const roleLower = (role || '').toLowerCase();\n if (roleLower === 'user') return 'user';\n if (roleLower === 'assistant' || roleLower === 'agent') return 'assistant';\n return 'user'; // Default to user\n }\n\n /**\n * Check if a message is tagging another user or agent.\n * Returns true if the message contains @mentions that are NOT the ambient agent.\n * Future enhancement: parse @mentions and determine if ambient agent should process.\n */\n private isTaggingOthers(message: string): boolean {\n // Future implementation: check for @mentions\n // For now, always return false (always process through ambient agent)\n return false;\n }\n\n /**\n * Invoke a sub-agent based on Sage Agent's payload.\n * This is called when Sage decides to delegate to a specialist agent.\n *\n * @param agentName Name of the agent to invoke\n * @param conversationId The conversation ID\n * @param message The user message that triggered this\n * @param conversationHistory Recent conversation history for context\n * @param reasoning Why this agent is being invoked\n * @param conversationDetailId The ID of the conversation detail record to link to the agent run\n * @param payload Optional payload to pass to the agent (e.g., previous OUTPUT artifact for continuity)\n * @param onProgress Optional callback for receiving progress updates during execution\n * @param sourceArtifactId Optional source artifact ID for versioning\n * @param sourceArtifactVersionId Optional source artifact version ID for versioning\n * @param agentConfigurationPresetId Optional ID of the AIAgentConfiguration preset (will be mapped to AIConfigurationID)\n * @returns The agent's execution result, or null if agent not found\n */\n async invokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: unknown,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string\n ): Promise<ExecuteAgentResult | null> {\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the agent by name\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n if (!agent || !agent.ID) {\n const errorMsg = `Sub-agent \"${agentName}\" not found`;\n console.warn(`${errorMsg}`);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n console.log(`Invoking sub-agent: ${agentName}`, { reasoning, hasPayload: !!payload, hasConfigPreset: !!agentConfigurationPresetId });\n\n // Map AIAgentConfiguration preset ID to actual AIConfiguration ID\n let aiConfigurationId: string | undefined = undefined;\n if (agentConfigurationPresetId) {\n // Get the preset from AIEngineBase to extract the AIConfigurationID\n const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\n // check by preset ID or AIConfigurationID - since sometimes we have the actual\n // configuration ID. Since both UUID no collisions should ever be possible.\n const preset = presets.find(p => UUIDsEqual(p.ID, agentConfigurationPresetId) || UUIDsEqual(p.AIConfigurationID, agentConfigurationPresetId));\n\n if (preset) {\n aiConfigurationId = preset.AIConfigurationID || undefined;\n console.log(`Mapped agent configuration preset \"${preset.Name}\" to AIConfigurationID: ${aiConfigurationId || 'default'}`);\n } else {\n console.warn(`Agent configuration preset ${agentConfigurationPresetId} not found for agent ${agent.ID}`);\n }\n }\n\n // Use AgentClientService which wraps GraphQLAIClient.RunAIAgentFromConversationDetail\n // and integrates with client tool request handling\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n conversationId: conversationId,\n latestMessageId: message.ID,\n invocationReason: reasoning\n },\n ...(payload ? { Payload: payload as Record<string, unknown> } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n CreateArtifacts: true,\n CreateNotification: true,\n SourceArtifactId: sourceArtifactId,\n SourceArtifactVersionId: sourceArtifactVersionId,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n // Unwrap RunAgentResult to get the original ExecuteAgentResult\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n } else if (!runResult.Success) {\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${runResult.ErrorMessage || 'unknown error'}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n return null;\n } catch (error) {\n const errorMsg = `Error invoking sub-agent \"${agentName}\": ` + (error instanceof Error ? error.message : String(error));\n console.error(`Error invoking sub-agent \"${agentName}\":`, error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /**\n * Check if user's latest message should continue with the previous agent or route through Sage.\n * Uses fast inference (<500ms) to determine intent and avoid unnecessary Sage overhead.\n *\n * @param agentId The ID of the previous agent\n * @param latestMessage The user's new message\n * @param conversationHistory Recent conversation history for context (last 10 messages)\n * @param context Pre-loaded artifact and agent run data to avoid database queries\n * @returns IntentCheckResult with decision, reasoning, and optional target artifact version\n */\n async checkAgentContinuityIntent(\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[],\n context: ArtifactLookupContext\n ): Promise<IntentCheckResult> {\n if (!this._aiClient) {\n console.warn('AI Client not initialized, defaulting to UNSURE for intent check');\n return { decision: 'UNSURE', reasoning: 'AI Client not initialized' };\n }\n\n try {\n // Load the Check Sage Intent prompt\n await AIEngineBase.Instance.Config(false);\n const prompt = AIEngineBase.Instance.Prompts.find(p => p.Name === 'Check Sage Intent');\n if (!prompt) {\n console.warn('⚠️ Check Sage Intent prompt not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Check Sage Intent prompt not found' };\n }\n\n // Get agent details\n const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Previous agent not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Previous agent not found' };\n }\n\n // Find all artifacts from this agent in this conversation\n const agentArtifacts = this.findAllAgentArtifacts(\n agentId,\n conversationHistory,\n context\n );\n\n // Build compact conversation history (last 10 messages)\n const recentHistory = conversationHistory.slice(-10);\n const compactHistory = recentHistory.map((msg, idx) => {\n const role = msg.Role === 'User' ? 'User' : agent.Name || 'Agent';\n const content = msg.Message || '';\n return `${idx + 1}. ${role}: ${content.substring(0, 150)}${content.length > 150 ? '...' : ''}`;\n }).join('\\n');\n\n // Build artifact context if available\n let artifactContext = '';\n if (agentArtifacts.length > 0) {\n artifactContext = '\\n\\n**Prior Artifacts Created by This Agent**:\\n';\n agentArtifacts.forEach((artifact, idx) => {\n artifactContext += `${idx + 1}. ${artifact.artifactName} (${artifact.artifactType})\\n`;\n artifactContext += ` - Versions: ${artifact.versions.length}\\n`;\n if (artifact.versions.length > 0) {\n artifactContext += ` - Latest: v${artifact.versions[0].versionNumber}`;\n if (artifact.versions[0].versionName) {\n artifactContext += ` - ${artifact.versions[0].versionName}`;\n }\n artifactContext += '\\n';\n }\n });\n }\n\n // Build user message with context\n const userMessage = `**Previous Agent**: ${agent.Name} - ${agent.Description || 'No description'}\n\n**Conversation History** (last ${recentHistory.length} messages):\n${compactHistory}${artifactContext}\n\n**Latest User Message**: \"${latestMessage}\"`;\n\n console.log('🔍 Checking agent continuity intent...', {\n agentName: agent.Name,\n messagePreview: latestMessage.substring(0, 50),\n artifactCount: agentArtifacts.length\n });\n\n // Run the prompt with artifact data included\n const result = await this._aiClient.RunAIPrompt({\n promptId: prompt.ID,\n messages: [{ role: 'user', content: userMessage }],\n data: {\n hasPriorArtifact: agentArtifacts.length > 0,\n priorArtifacts: agentArtifacts\n }\n });\n\n if (result && result.success && (result.parsedResult || result.output)) {\n const parsed = result.parsedResult ||\n (result.output ? JSON.parse(result.output) : null);\n\n if (parsed && parsed.continuesWith) {\n const decision = parsed.continuesWith.toUpperCase();\n const reasoning = parsed.reasoning || 'No reasoning provided';\n const targetArtifactVersionId = parsed.targetArtifactVersionId || undefined;\n\n console.log(`✅ Intent check result: ${decision}`, {\n reasoning,\n targetArtifactVersionId,\n latency: result.executionTimeMs || 'unknown'\n });\n\n // Validate the response\n if (decision === 'YES' || decision === 'NO' || decision === 'UNSURE') {\n return {\n decision: decision as 'YES' | 'NO' | 'UNSURE',\n reasoning,\n targetArtifactVersionId\n };\n }\n }\n }\n\n console.warn('⚠️ Intent check failed or returned invalid format, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Invalid format from intent check prompt' };\n } catch (error) {\n console.error('❌ Error checking agent continuity intent:', error);\n // On error, default to UNSURE (safer to let Sage evaluate)\n return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\n }\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n clearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /**\n * Filter agents based on user's 'run' permission.\n * Only returns agents that the user has permission to run.\n *\n * @param agents List of candidate agents to filter\n * @param user User to check permissions for\n * @returns Filtered list of agents the user can run\n */\n private async filterAgentsByPermissions(\n agents: MJAIAgentEntityExtended[],\n user: any\n ): Promise<MJAIAgentEntityExtended[]> {\n const permittedAgents: MJAIAgentEntityExtended[] = [];\n\n for (const agent of agents) {\n try {\n const hasPermission = await AIAgentPermissionHelper.HasPermission(\n agent.ID,\n user,\n 'run'\n );\n if (hasPermission) {\n permittedAgents.push(agent);\n }\n } catch (error) {\n console.error(`Error checking permission for agent ${agent.Name}:`, error);\n // On error, exclude agent (fail closed)\n }\n }\n\n return permittedAgents;\n }\n\n /**\n * Find all artifacts created by the specified agent in this conversation.\n * Returns artifacts grouped by artifact with versions, ordered most recent first.\n * Enables LLM to reason about which artifact/version user is referencing.\n *\n * Uses pre-loaded data from ArtifactLookupContext for performance (no database queries).\n */\n private findAllAgentArtifacts(\n agentId: string,\n conversationDetails: MJConversationDetailEntity[],\n context: ArtifactLookupContext\n ): Array<{\n artifactId: string;\n artifactName: string;\n artifactType: string;\n artifactDescription: string | null;\n versions: Array<{\n runId: string;\n versionId: string;\n versionNumber: number;\n versionName: string | null;\n versionDescription: string | null;\n createdAt: Date;\n }>;\n }> {\n const artifactMap = new Map<string, {\n artifactId: string;\n artifactName: string;\n artifactType: string;\n artifactDescription: string | null;\n versions: Array<{\n runId: string;\n versionId: string;\n versionNumber: number;\n versionName: string | null;\n versionDescription: string | null;\n createdAt: Date;\n }>;\n }>();\n\n // Iterate backwards through conversation details (most recent first)\n for (let i = conversationDetails.length - 1; i >= 0; i--) {\n const detail = conversationDetails[i];\n\n // Skip non-AI messages and errors\n if (detail.Role !== 'AI' || detail.Status === 'Error') continue;\n\n // O(1) lookup for agent run from pre-loaded data\n const agentRun = context.agentRunsByDetailId.get(detail.ID);\n if (!agentRun || !UUIDsEqual(agentRun.AgentID, agentId) || agentRun.Status !== 'Completed') {\n continue;\n }\n\n // O(1) lookup for artifacts from pre-loaded data\n const artifacts = context.artifactsByDetailId.get(detail.ID);\n if (!artifacts || artifacts.length === 0) continue;\n\n // Process each artifact\n for (const lazyArtifact of artifacts) {\n const mainArtifactId = lazyArtifact.artifactId;\n\n // Get or create artifact entry\n if (!artifactMap.has(mainArtifactId)) {\n artifactMap.set(mainArtifactId, {\n artifactId: mainArtifactId,\n artifactName: lazyArtifact.artifactName,\n artifactType: lazyArtifact.artifactType,\n artifactDescription: lazyArtifact.artifactDescription || null,\n versions: []\n });\n }\n\n // Add version to artifact\n const artifactEntry = artifactMap.get(mainArtifactId)!;\n artifactEntry.versions.push({\n runId: agentRun.ID,\n versionId: lazyArtifact.artifactVersionId,\n versionNumber: lazyArtifact.versionNumber,\n versionName: lazyArtifact.versionName,\n versionDescription: lazyArtifact.versionDescription,\n createdAt: lazyArtifact.versionCreatedAt\n });\n }\n }\n\n // Convert map to array (most recent artifacts first based on their latest version)\n return Array.from(artifactMap.values()).sort((a, b) => {\n const aLatest = a.versions[0]?.createdAt || new Date(0);\n const bLatest = b.versions[0]?.createdAt || new Date(0);\n return bLatest.getTime() - aLatest.getTime();\n });\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UserInfo } from '@memberjunction/core';
|
|
1
|
+
import { UserInfo, IMetadataProvider } from '@memberjunction/core';
|
|
2
2
|
import { MJConversationDetailAttachmentEntity } from '@memberjunction/core-entities';
|
|
3
3
|
import { MessageAttachment } from '../components/message/message-item.component';
|
|
4
4
|
import { PendingAttachment } from '../components/mention/mention-editor.component';
|
|
@@ -8,7 +8,13 @@ import * as i0 from "@angular/core";
|
|
|
8
8
|
* Handles loading, saving, and converting attachments between different formats.
|
|
9
9
|
*/
|
|
10
10
|
export declare class ConversationAttachmentService {
|
|
11
|
+
private _provider;
|
|
11
12
|
constructor();
|
|
13
|
+
/**
|
|
14
|
+
* Set the metadata provider this service should use. When unset, falls back to Metadata.Provider.
|
|
15
|
+
*/
|
|
16
|
+
set Provider(value: IMetadataProvider | null);
|
|
17
|
+
get Provider(): IMetadataProvider;
|
|
12
18
|
/**
|
|
13
19
|
* Load all attachments for a list of conversation detail IDs.
|
|
14
20
|
* Returns a map of ConversationDetailID -> MessageAttachment[]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-attachment.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-attachment.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"conversation-attachment.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-attachment.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,QAAQ,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EACL,oCAAoC,EAMrC,MAAM,+BAA+B,CAAC;AAMvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8CAA8C,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,gDAAgD,CAAC;;AAInF;;;GAGG;AACH,qBAGa,6BAA6B;IACxC,OAAO,CAAC,SAAS,CAAkC;;IAInD;;OAEG;IACH,IAAW,QAAQ,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C,cAAc;yCAjdX,6BAA6B;6CAA7B,6BAA6B;CAodzC"}
|
|
@@ -10,7 +10,17 @@ import * as i0 from "@angular/core";
|
|
|
10
10
|
* Handles loading, saving, and converting attachments between different formats.
|
|
11
11
|
*/
|
|
12
12
|
export class ConversationAttachmentService {
|
|
13
|
+
_provider = null;
|
|
13
14
|
constructor() { }
|
|
15
|
+
/**
|
|
16
|
+
* Set the metadata provider this service should use. When unset, falls back to Metadata.Provider.
|
|
17
|
+
*/
|
|
18
|
+
set Provider(value) {
|
|
19
|
+
this._provider = value;
|
|
20
|
+
}
|
|
21
|
+
get Provider() {
|
|
22
|
+
return this._provider ?? Metadata.Provider;
|
|
23
|
+
}
|
|
14
24
|
/**
|
|
15
25
|
* Load all attachments for a list of conversation detail IDs.
|
|
16
26
|
* Returns a map of ConversationDetailID -> MessageAttachment[]
|
|
@@ -21,7 +31,7 @@ export class ConversationAttachmentService {
|
|
|
21
31
|
return result;
|
|
22
32
|
}
|
|
23
33
|
try {
|
|
24
|
-
const rv =
|
|
34
|
+
const rv = RunView.FromMetadataProvider(this.Provider);
|
|
25
35
|
const idList = conversationDetailIds.map(id => `'${id}'`).join(',');
|
|
26
36
|
const attachmentResult = await rv.RunView({
|
|
27
37
|
EntityName: 'MJ: Conversation Detail Attachments',
|
|
@@ -126,7 +136,7 @@ export class ConversationAttachmentService {
|
|
|
126
136
|
*/
|
|
127
137
|
async saveAttachments(conversationDetailId, pendingAttachments, contextUser) {
|
|
128
138
|
const savedAttachments = [];
|
|
129
|
-
const md =
|
|
139
|
+
const md = this.Provider;
|
|
130
140
|
for (let i = 0; i < pendingAttachments.length; i++) {
|
|
131
141
|
const pending = pendingAttachments[i];
|
|
132
142
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-attachment.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-attachment.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3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,CAAC,MAAM,CAAC,MAAgB,CAAC,CAAC;YACvD,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC5C,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACK,cAAc;QACpB,OAAO,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;IACzE,CAAC;uHAtcU,6BAA6B;gEAA7B,6BAA6B,WAA7B,6BAA6B,mBAF5B,MAAM;;iFAEP,6BAA6B;cAHzC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { RunView, Metadata, UserInfo } from '@memberjunction/core';\nimport {\n MJConversationDetailAttachmentEntity,\n MJConversationDetailArtifactEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity,\n MJAIModalityEntity,\n ArtifactMetadataEngine\n} from '@memberjunction/core-entities';\nimport {\n ConversationUtility,\n AttachmentContent,\n AttachmentType\n} from '@memberjunction/ai-core-plus';\nimport { MessageAttachment } from '../components/message/message-item.component';\nimport { PendingAttachment } from '../components/mention/mention-editor.component';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { UUIDsEqual } from '@memberjunction/global';\n\n/**\n * Service for managing conversation attachments.\n * Handles loading, saving, and converting attachments between different formats.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAttachmentService {\n constructor() {}\n\n /**\n * Load all attachments for a list of conversation detail IDs.\n * Returns a map of ConversationDetailID -> MessageAttachment[]\n */\n async loadAttachmentsForMessages(\n conversationDetailIds: string[],\n contextUser?: UserInfo\n ): Promise<Map<string, MessageAttachment[]>> {\n const result = new Map<string, MessageAttachment[]>();\n\n if (!conversationDetailIds || conversationDetailIds.length === 0) {\n return result;\n }\n\n try {\n const rv = new RunView();\n const idList = conversationDetailIds.map(id => `'${id}'`).join(',');\n\n const attachmentResult = await rv.RunView<MJConversationDetailAttachmentEntity>({\n EntityName: 'MJ: Conversation Detail Attachments',\n ExtraFilter: `ConversationDetailID IN (${idList})`,\n OrderBy: 'DisplayOrder ASC, __mj_CreatedAt ASC',\n ResultType: 'entity_object'\n }, contextUser);\n\n if (attachmentResult.Success && attachmentResult.Results) {\n for (const attachment of attachmentResult.Results) {\n const detailId = attachment.ConversationDetailID;\n\n if (!result.has(detailId)) {\n result.set(detailId, []);\n }\n\n const messageAttachment = this.convertToMessageAttachment(attachment);\n result.get(detailId)!.push(messageAttachment);\n }\n }\n\n // Also load input artifacts (ConversationDetailArtifact with Direction='Input')\n const artifactLinksResult = await rv.RunView<MJConversationDetailArtifactEntity>({\n EntityName: 'MJ: Conversation Detail Artifacts',\n ExtraFilter: `ConversationDetailID IN (${idList}) AND Direction = 'Input'`,\n ResultType: 'entity_object'\n }, contextUser);\n\n if (artifactLinksResult.Success && artifactLinksResult.Results && artifactLinksResult.Results.length > 0) {\n // Load the referenced artifact versions AND their parent artifacts in parallel\n // so we can resolve the semantic artifact-type name for the tile badge.\n const versionIds = artifactLinksResult.Results.map(l => `'${l.ArtifactVersionID}'`).join(',');\n const versionsResult = await rv.RunView<MJArtifactVersionEntity>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: `ID IN (${versionIds})`,\n ResultType: 'entity_object'\n }, contextUser);\n\n if (versionsResult.Success && versionsResult.Results) {\n const versionMap = new Map<string, MJArtifactVersionEntity>();\n for (const v of versionsResult.Results) {\n versionMap.set(v.ID, v);\n }\n\n // Bulk-load parent artifacts to get TypeID, then resolve type names via cached engine.\n const artifactIds = Array.from(new Set(versionsResult.Results.map(v => v.ArtifactID).filter(Boolean)));\n const artifactMap = new Map<string, MJArtifactEntity>();\n if (artifactIds.length > 0) {\n const artifactIdList = artifactIds.map(id => `'${id}'`).join(',');\n const artifactsResult = await rv.RunView<MJArtifactEntity>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIdList})`,\n ResultType: 'entity_object'\n }, contextUser);\n if (artifactsResult.Success && artifactsResult.Results) {\n for (const a of artifactsResult.Results) {\n artifactMap.set(a.ID, a);\n }\n }\n // Ensure the artifact-type cache is populated so FindArtifactTypeByID resolves.\n await ArtifactMetadataEngine.Instance.Config(false, contextUser);\n }\n\n for (const link of artifactLinksResult.Results) {\n const version = versionMap.get(link.ArtifactVersionID);\n if (version) {\n const parentArtifact = artifactMap.get(version.ArtifactID);\n const artifactType = parentArtifact\n ? ArtifactMetadataEngine.Instance.FindArtifactTypeByID(parentArtifact.TypeID)\n : undefined;\n const detailId = link.ConversationDetailID;\n if (!result.has(detailId)) {\n result.set(detailId, []);\n }\n result.get(detailId)!.push({\n id: link.ID,\n type: version.ContentMode === 'File' ? this.getMimeAttachmentType(version.MimeType || '') : 'Document',\n mimeType: version.MimeType || 'text/plain',\n fileName: version.FileName || version.Name || 'Artifact',\n sizeBytes: version.ContentSizeBytes || 0,\n source: 'artifact',\n artifactId: version.ArtifactID || undefined,\n artifactVersionId: version.ID,\n artifactTypeName: artifactType?.Name || undefined\n } as MessageAttachment);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error loading attachments:', error);\n }\n\n return result;\n }\n\n /**\n * Load attachments for a single message\n */\n async loadAttachmentsForMessage(\n conversationDetailId: string,\n contextUser?: UserInfo\n ): Promise<MessageAttachment[]> {\n const map = await this.loadAttachmentsForMessages([conversationDetailId], contextUser);\n return map.get(conversationDetailId) || [];\n }\n\n /**\n * Save pending attachments to the database.\n * Returns the saved attachment entities.\n *\n * @param conversationDetailId - ID of the conversation detail to attach to\n * @param pendingAttachments - Array of pending attachments from the mention editor\n * @param contextUser - User context for the operation\n */\n async saveAttachments(\n conversationDetailId: string,\n pendingAttachments: PendingAttachment[],\n contextUser?: UserInfo\n ): Promise<MJConversationDetailAttachmentEntity[]> {\n const savedAttachments: MJConversationDetailAttachmentEntity[] = [];\n const md = new Metadata();\n\n for (let i = 0; i < pendingAttachments.length; i++) {\n const pending = pendingAttachments[i];\n\n try {\n const attachment = await md.GetEntityObject<MJConversationDetailAttachmentEntity>(\n 'MJ: Conversation Detail Attachments',\n contextUser\n );\n\n // Determine attachment type from MIME type\n const attachmentType = ConversationUtility.GetAttachmentTypeFromMime(pending.mimeType);\n\n attachment.ConversationDetailID = conversationDetailId;\n attachment.ModalityID = this.getModalityIdForType(attachmentType);\n attachment.MimeType = pending.mimeType;\n attachment.FileName = pending.fileName;\n attachment.FileSizeBytes = pending.sizeBytes;\n attachment.Width = pending.width ?? null;\n attachment.Height = pending.height ?? null;\n attachment.DurationSeconds = null; // PendingAttachment doesn't have duration\n attachment.DisplayOrder = i;\n attachment.ThumbnailBase64 = pending.thumbnailUrl ?? null;\n\n // For artifact references, create a ConversationDetailArtifact with Direction='Input'\n // instead of a ConversationDetailAttachment\n if (pending.source === 'artifact' && pending.artifactVersionId) {\n const artifactLink = await md.GetEntityObject<MJConversationDetailArtifactEntity>(\n 'MJ: Conversation Detail Artifacts',\n contextUser\n );\n artifactLink.ConversationDetailID = conversationDetailId;\n artifactLink.ArtifactVersionID = pending.artifactVersionId;\n artifactLink.Direction = 'Input';\n const artifactSaved = await artifactLink.Save();\n if (!artifactSaved) {\n console.error('Failed to save artifact input link:', artifactLink.LatestResult);\n }\n continue; // Skip creating a ConversationDetailAttachment for artifacts\n }\n\n // Store inline data for uploaded files\n if (pending.dataUrl) {\n const base64Data = this.extractBase64FromDataUrl(pending.dataUrl);\n attachment.InlineData = base64Data;\n }\n\n const saved = await attachment.Save();\n if (saved) {\n savedAttachments.push(attachment);\n } else {\n console.error('Failed to save attachment:', attachment.LatestResult);\n }\n } catch (error) {\n console.error('Error saving attachment:', error);\n }\n }\n\n return savedAttachments;\n }\n\n /**\n * Create attachment reference tokens for message text.\n * These tokens are stored in the Message field to reference attachments.\n */\n createAttachmentReferences(attachments: MJConversationDetailAttachmentEntity[]): string {\n return attachments\n .map(att => {\n const content: AttachmentContent = {\n _mode: 'attachment',\n id: att.ID,\n type: this.getAttachmentTypeFromModality(att.ModalityID),\n mimeType: att.MimeType,\n fileName: att.FileName ?? undefined,\n sizeBytes: att.FileSizeBytes,\n width: att.Width ?? undefined,\n height: att.Height ?? undefined,\n durationSeconds: att.DurationSeconds ?? undefined,\n thumbnailBase64: att.ThumbnailBase64 ?? undefined\n };\n return ConversationUtility.CreateAttachmentReference(content);\n })\n .join(' ');\n }\n\n /**\n * Convert a database entity to a MessageAttachment for display\n */\n private convertToMessageAttachment(entity: MJConversationDetailAttachmentEntity): MessageAttachment {\n // Determine content URL\n let contentUrl: string | undefined;\n let thumbnailUrl: string | undefined;\n\n if (entity.InlineData) {\n // Create data URL from inline data\n contentUrl = `data:${entity.MimeType};base64,${entity.InlineData}`;\n } else if (entity.FileID) {\n // TODO: Integrate with MJStorage to get pre-authenticated URL\n contentUrl = undefined; // Will need to be loaded separately\n }\n\n // Use thumbnail if available\n if (entity.ThumbnailBase64) {\n thumbnailUrl = entity.ThumbnailBase64.startsWith('data:')\n ? entity.ThumbnailBase64\n : `data:image/jpeg;base64,${entity.ThumbnailBase64}`;\n }\n\n return {\n id: entity.ID,\n type: this.getAttachmentTypeFromModality(entity.ModalityID),\n mimeType: entity.MimeType,\n fileName: entity.FileName,\n sizeBytes: entity.FileSizeBytes,\n width: entity.Width ?? undefined,\n height: entity.Height ?? undefined,\n thumbnailUrl: thumbnailUrl,\n contentUrl: contentUrl\n };\n }\n\n /**\n * Get the AttachmentType from a modality ID\n */\n private getAttachmentTypeFromModality(modalityId: string): AttachmentType {\n const modality = AIEngineBase.Instance.Modalities.find(m => UUIDsEqual(m.ID, modalityId))\n\n const name = modality?.Name?.toLowerCase() || '';\n\n if (name === 'image') return 'Image';\n if (name === 'video') return 'Video';\n if (name === 'audio') return 'Audio';\n\n return 'Document';\n }\n\n /**\n * Get the AttachmentType from a MIME type string\n */\n private getMimeAttachmentType(mimeType: string): 'Image' | 'Video' | 'Audio' | 'Document' {\n if (mimeType.startsWith('image/')) return 'Image';\n if (mimeType.startsWith('video/')) return 'Video';\n if (mimeType.startsWith('audio/')) return 'Audio';\n return 'Document';\n }\n\n /**\n * Get the modality ID for an attachment type\n */\n private getModalityIdForType(type: AttachmentType): string {\n // Map AttachmentType to modality name\n // AttachmentType is 'Image' | 'Video' | 'Audio' | 'Document'\n // Modality names are 'Image', 'Audio', 'Video', 'File'\n let modalityName = type.toLowerCase().trim();\n if (modalityName === 'document') {\n modalityName = 'file';\n }\n\n const modality = AIEngineBase.Instance.Modalities.find(m => m.Name?.trim().toLowerCase() === modalityName);\n if (modality) {\n return modality.ID;\n }\n\n // Fallback to 'file' modality if specific type not found\n // recursive call, so long as the current modality isn't file as that\n // would cause infinite recursion/stack overflow\n if (modalityName !== 'file') {\n return this.getModalityIdForType('Document');\n }\n else {\n return '';\n }\n }\n \n /**\n * Extract base64 data from a data URL\n */\n private extractBase64FromDataUrl(dataUrl: string): string {\n const matches = dataUrl.match(/^data:[^;]+;base64,(.+)$/);\n return matches ? matches[1] : dataUrl;\n }\n\n /**\n * Create a thumbnail from an image file.\n * Returns a base64 data URL of the thumbnail.\n */\n async createThumbnail(\n file: File,\n maxSize: number = 200\n ): Promise<string | null> {\n return new Promise((resolve) => {\n if (!file.type.startsWith('image/')) {\n resolve(null);\n return;\n }\n\n const reader = new FileReader();\n reader.onload = (e) => {\n const img = new Image();\n img.onload = () => {\n const canvas = document.createElement('canvas');\n let width = img.width;\n let height = img.height;\n\n // Scale down to maxSize\n if (width > height) {\n if (width > maxSize) {\n height = Math.round((height * maxSize) / width);\n width = maxSize;\n }\n } else {\n if (height > maxSize) {\n width = Math.round((width * maxSize) / height);\n height = maxSize;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(img, 0, 0, width, height);\n resolve(canvas.toDataURL('image/jpeg', 0.7));\n } else {\n resolve(null);\n }\n };\n img.onerror = () => resolve(null);\n img.src = e.target?.result as string;\n };\n reader.onerror = () => resolve(null);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Get image dimensions from a file\n */\n async getImageDimensions(file: File): Promise<{ width: number; height: number } | null> {\n return new Promise((resolve) => {\n if (!file.type.startsWith('image/')) {\n resolve(null);\n return;\n }\n\n const reader = new FileReader();\n reader.onload = (e) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = () => resolve(null);\n img.src = e.target?.result as string;\n };\n reader.onerror = () => resolve(null);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Process a file and create a PendingAttachment.\n * This creates the data structure needed for the mention editor component.\n */\n async processFile(file: File): Promise<PendingAttachment> {\n // Read file data URL\n const dataUrl = await this.fileToDataUrl(file);\n\n const pending: PendingAttachment = {\n id: this.generateTempId(),\n file: file,\n dataUrl: dataUrl,\n mimeType: file.type,\n fileName: file.name,\n sizeBytes: file.size\n };\n\n // Get image dimensions and create thumbnail\n const type = ConversationUtility.GetAttachmentTypeFromMime(file.type);\n if (type === 'Image') {\n const dimensions = await this.getImageDimensions(file);\n if (dimensions) {\n pending.width = dimensions.width;\n pending.height = dimensions.height;\n }\n\n const thumbnail = await this.createThumbnail(file);\n if (thumbnail) {\n pending.thumbnailUrl = thumbnail;\n }\n }\n\n return pending;\n }\n\n /**\n * Convert a file to a data URL\n */\n private fileToDataUrl(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Generate a temporary ID for pending attachments\n */\n private generateTempId(): string {\n return `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"conversation-attachment.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-attachment.service.ts"],"names":[],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AAS,EAAE,CAAC;gBACd,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC;YACnC,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;OAEG;IACK,aAAa,CAAC,IAAU;QAC9B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;YAChC,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAgB,CAAC,CAAC;YACvD,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC5C,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACK,cAAc;QACpB,OAAO,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;IACzE,CAAC;uHAndU,6BAA6B;gEAA7B,6BAA6B,WAA7B,6BAA6B,mBAF5B,MAAM;;iFAEP,6BAA6B;cAHzC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { RunView, Metadata, UserInfo, IMetadataProvider } from '@memberjunction/core';\nimport {\n MJConversationDetailAttachmentEntity,\n MJConversationDetailArtifactEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity,\n MJAIModalityEntity,\n ArtifactMetadataEngine\n} from '@memberjunction/core-entities';\nimport {\n ConversationUtility,\n AttachmentContent,\n AttachmentType\n} from '@memberjunction/ai-core-plus';\nimport { MessageAttachment } from '../components/message/message-item.component';\nimport { PendingAttachment } from '../components/mention/mention-editor.component';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { UUIDsEqual } from '@memberjunction/global';\n\n/**\n * Service for managing conversation attachments.\n * Handles loading, saving, and converting attachments between different formats.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAttachmentService {\n private _provider: IMetadataProvider | null = null;\n\n constructor() {}\n\n /**\n * Set the metadata provider this service should use. When unset, falls back to Metadata.Provider.\n */\n public set Provider(value: IMetadataProvider | null) {\n this._provider = value;\n }\n\n public get Provider(): IMetadataProvider {\n return this._provider ?? Metadata.Provider;\n }\n\n /**\n * Load all attachments for a list of conversation detail IDs.\n * Returns a map of ConversationDetailID -> MessageAttachment[]\n */\n async loadAttachmentsForMessages(\n conversationDetailIds: string[],\n contextUser?: UserInfo\n ): Promise<Map<string, MessageAttachment[]>> {\n const result = new Map<string, MessageAttachment[]>();\n\n if (!conversationDetailIds || conversationDetailIds.length === 0) {\n return result;\n }\n\n try {\n const rv = RunView.FromMetadataProvider(this.Provider);\n const idList = conversationDetailIds.map(id => `'${id}'`).join(',');\n\n const attachmentResult = await rv.RunView<MJConversationDetailAttachmentEntity>({\n EntityName: 'MJ: Conversation Detail Attachments',\n ExtraFilter: `ConversationDetailID IN (${idList})`,\n OrderBy: 'DisplayOrder ASC, __mj_CreatedAt ASC',\n ResultType: 'entity_object'\n }, contextUser);\n\n if (attachmentResult.Success && attachmentResult.Results) {\n for (const attachment of attachmentResult.Results) {\n const detailId = attachment.ConversationDetailID;\n\n if (!result.has(detailId)) {\n result.set(detailId, []);\n }\n\n const messageAttachment = this.convertToMessageAttachment(attachment);\n result.get(detailId)!.push(messageAttachment);\n }\n }\n\n // Also load input artifacts (ConversationDetailArtifact with Direction='Input')\n const artifactLinksResult = await rv.RunView<MJConversationDetailArtifactEntity>({\n EntityName: 'MJ: Conversation Detail Artifacts',\n ExtraFilter: `ConversationDetailID IN (${idList}) AND Direction = 'Input'`,\n ResultType: 'entity_object'\n }, contextUser);\n\n if (artifactLinksResult.Success && artifactLinksResult.Results && artifactLinksResult.Results.length > 0) {\n // Load the referenced artifact versions AND their parent artifacts in parallel\n // so we can resolve the semantic artifact-type name for the tile badge.\n const versionIds = artifactLinksResult.Results.map(l => `'${l.ArtifactVersionID}'`).join(',');\n const versionsResult = await rv.RunView<MJArtifactVersionEntity>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: `ID IN (${versionIds})`,\n ResultType: 'entity_object'\n }, contextUser);\n\n if (versionsResult.Success && versionsResult.Results) {\n const versionMap = new Map<string, MJArtifactVersionEntity>();\n for (const v of versionsResult.Results) {\n versionMap.set(v.ID, v);\n }\n\n // Bulk-load parent artifacts to get TypeID, then resolve type names via cached engine.\n const artifactIds = Array.from(new Set(versionsResult.Results.map(v => v.ArtifactID).filter(Boolean)));\n const artifactMap = new Map<string, MJArtifactEntity>();\n if (artifactIds.length > 0) {\n const artifactIdList = artifactIds.map(id => `'${id}'`).join(',');\n const artifactsResult = await rv.RunView<MJArtifactEntity>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIdList})`,\n ResultType: 'entity_object'\n }, contextUser);\n if (artifactsResult.Success && artifactsResult.Results) {\n for (const a of artifactsResult.Results) {\n artifactMap.set(a.ID, a);\n }\n }\n // Ensure the artifact-type cache is populated so FindArtifactTypeByID resolves.\n await ArtifactMetadataEngine.Instance.Config(false, contextUser);\n }\n\n for (const link of artifactLinksResult.Results) {\n const version = versionMap.get(link.ArtifactVersionID);\n if (version) {\n const parentArtifact = artifactMap.get(version.ArtifactID);\n const artifactType = parentArtifact\n ? ArtifactMetadataEngine.Instance.FindArtifactTypeByID(parentArtifact.TypeID)\n : undefined;\n const detailId = link.ConversationDetailID;\n if (!result.has(detailId)) {\n result.set(detailId, []);\n }\n result.get(detailId)!.push({\n id: link.ID,\n type: version.ContentMode === 'File' ? this.getMimeAttachmentType(version.MimeType || '') : 'Document',\n mimeType: version.MimeType || 'text/plain',\n fileName: version.FileName || version.Name || 'Artifact',\n sizeBytes: version.ContentSizeBytes || 0,\n source: 'artifact',\n artifactId: version.ArtifactID || undefined,\n artifactVersionId: version.ID,\n artifactTypeName: artifactType?.Name || undefined\n } as MessageAttachment);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error loading attachments:', error);\n }\n\n return result;\n }\n\n /**\n * Load attachments for a single message\n */\n async loadAttachmentsForMessage(\n conversationDetailId: string,\n contextUser?: UserInfo\n ): Promise<MessageAttachment[]> {\n const map = await this.loadAttachmentsForMessages([conversationDetailId], contextUser);\n return map.get(conversationDetailId) || [];\n }\n\n /**\n * Save pending attachments to the database.\n * Returns the saved attachment entities.\n *\n * @param conversationDetailId - ID of the conversation detail to attach to\n * @param pendingAttachments - Array of pending attachments from the mention editor\n * @param contextUser - User context for the operation\n */\n async saveAttachments(\n conversationDetailId: string,\n pendingAttachments: PendingAttachment[],\n contextUser?: UserInfo\n ): Promise<MJConversationDetailAttachmentEntity[]> {\n const savedAttachments: MJConversationDetailAttachmentEntity[] = [];\n const md = this.Provider;\n\n for (let i = 0; i < pendingAttachments.length; i++) {\n const pending = pendingAttachments[i];\n\n try {\n const attachment = await md.GetEntityObject<MJConversationDetailAttachmentEntity>(\n 'MJ: Conversation Detail Attachments',\n contextUser\n );\n\n // Determine attachment type from MIME type\n const attachmentType = ConversationUtility.GetAttachmentTypeFromMime(pending.mimeType);\n\n attachment.ConversationDetailID = conversationDetailId;\n attachment.ModalityID = this.getModalityIdForType(attachmentType);\n attachment.MimeType = pending.mimeType;\n attachment.FileName = pending.fileName;\n attachment.FileSizeBytes = pending.sizeBytes;\n attachment.Width = pending.width ?? null;\n attachment.Height = pending.height ?? null;\n attachment.DurationSeconds = null; // PendingAttachment doesn't have duration\n attachment.DisplayOrder = i;\n attachment.ThumbnailBase64 = pending.thumbnailUrl ?? null;\n\n // For artifact references, create a ConversationDetailArtifact with Direction='Input'\n // instead of a ConversationDetailAttachment\n if (pending.source === 'artifact' && pending.artifactVersionId) {\n const artifactLink = await md.GetEntityObject<MJConversationDetailArtifactEntity>(\n 'MJ: Conversation Detail Artifacts',\n contextUser\n );\n artifactLink.ConversationDetailID = conversationDetailId;\n artifactLink.ArtifactVersionID = pending.artifactVersionId;\n artifactLink.Direction = 'Input';\n const artifactSaved = await artifactLink.Save();\n if (!artifactSaved) {\n console.error('Failed to save artifact input link:', artifactLink.LatestResult);\n }\n continue; // Skip creating a ConversationDetailAttachment for artifacts\n }\n\n // Store inline data for uploaded files\n if (pending.dataUrl) {\n const base64Data = this.extractBase64FromDataUrl(pending.dataUrl);\n attachment.InlineData = base64Data;\n }\n\n const saved = await attachment.Save();\n if (saved) {\n savedAttachments.push(attachment);\n } else {\n console.error('Failed to save attachment:', attachment.LatestResult);\n }\n } catch (error) {\n console.error('Error saving attachment:', error);\n }\n }\n\n return savedAttachments;\n }\n\n /**\n * Create attachment reference tokens for message text.\n * These tokens are stored in the Message field to reference attachments.\n */\n createAttachmentReferences(attachments: MJConversationDetailAttachmentEntity[]): string {\n return attachments\n .map(att => {\n const content: AttachmentContent = {\n _mode: 'attachment',\n id: att.ID,\n type: this.getAttachmentTypeFromModality(att.ModalityID),\n mimeType: att.MimeType,\n fileName: att.FileName ?? undefined,\n sizeBytes: att.FileSizeBytes,\n width: att.Width ?? undefined,\n height: att.Height ?? undefined,\n durationSeconds: att.DurationSeconds ?? undefined,\n thumbnailBase64: att.ThumbnailBase64 ?? undefined\n };\n return ConversationUtility.CreateAttachmentReference(content);\n })\n .join(' ');\n }\n\n /**\n * Convert a database entity to a MessageAttachment for display\n */\n private convertToMessageAttachment(entity: MJConversationDetailAttachmentEntity): MessageAttachment {\n // Determine content URL\n let contentUrl: string | undefined;\n let thumbnailUrl: string | undefined;\n\n if (entity.InlineData) {\n // Create data URL from inline data\n contentUrl = `data:${entity.MimeType};base64,${entity.InlineData}`;\n } else if (entity.FileID) {\n // TODO: Integrate with MJStorage to get pre-authenticated URL\n contentUrl = undefined; // Will need to be loaded separately\n }\n\n // Use thumbnail if available\n if (entity.ThumbnailBase64) {\n thumbnailUrl = entity.ThumbnailBase64.startsWith('data:')\n ? entity.ThumbnailBase64\n : `data:image/jpeg;base64,${entity.ThumbnailBase64}`;\n }\n\n return {\n id: entity.ID,\n type: this.getAttachmentTypeFromModality(entity.ModalityID),\n mimeType: entity.MimeType,\n fileName: entity.FileName,\n sizeBytes: entity.FileSizeBytes,\n width: entity.Width ?? undefined,\n height: entity.Height ?? undefined,\n thumbnailUrl: thumbnailUrl,\n contentUrl: contentUrl\n };\n }\n\n /**\n * Get the AttachmentType from a modality ID\n */\n private getAttachmentTypeFromModality(modalityId: string): AttachmentType {\n const modality = AIEngineBase.Instance.Modalities.find(m => UUIDsEqual(m.ID, modalityId))\n\n const name = modality?.Name?.toLowerCase() || '';\n\n if (name === 'image') return 'Image';\n if (name === 'video') return 'Video';\n if (name === 'audio') return 'Audio';\n\n return 'Document';\n }\n\n /**\n * Get the AttachmentType from a MIME type string\n */\n private getMimeAttachmentType(mimeType: string): 'Image' | 'Video' | 'Audio' | 'Document' {\n if (mimeType.startsWith('image/')) return 'Image';\n if (mimeType.startsWith('video/')) return 'Video';\n if (mimeType.startsWith('audio/')) return 'Audio';\n return 'Document';\n }\n\n /**\n * Get the modality ID for an attachment type\n */\n private getModalityIdForType(type: AttachmentType): string {\n // Map AttachmentType to modality name\n // AttachmentType is 'Image' | 'Video' | 'Audio' | 'Document'\n // Modality names are 'Image', 'Audio', 'Video', 'File'\n let modalityName = type.toLowerCase().trim();\n if (modalityName === 'document') {\n modalityName = 'file';\n }\n\n const modality = AIEngineBase.Instance.Modalities.find(m => m.Name?.trim().toLowerCase() === modalityName);\n if (modality) {\n return modality.ID;\n }\n\n // Fallback to 'file' modality if specific type not found\n // recursive call, so long as the current modality isn't file as that\n // would cause infinite recursion/stack overflow\n if (modalityName !== 'file') {\n return this.getModalityIdForType('Document');\n }\n else {\n return '';\n }\n }\n \n /**\n * Extract base64 data from a data URL\n */\n private extractBase64FromDataUrl(dataUrl: string): string {\n const matches = dataUrl.match(/^data:[^;]+;base64,(.+)$/);\n return matches ? matches[1] : dataUrl;\n }\n\n /**\n * Create a thumbnail from an image file.\n * Returns a base64 data URL of the thumbnail.\n */\n async createThumbnail(\n file: File,\n maxSize: number = 200\n ): Promise<string | null> {\n return new Promise((resolve) => {\n if (!file.type.startsWith('image/')) {\n resolve(null);\n return;\n }\n\n const reader = new FileReader();\n reader.onload = (e) => {\n const img = new Image();\n img.onload = () => {\n const canvas = document.createElement('canvas');\n let width = img.width;\n let height = img.height;\n\n // Scale down to maxSize\n if (width > height) {\n if (width > maxSize) {\n height = Math.round((height * maxSize) / width);\n width = maxSize;\n }\n } else {\n if (height > maxSize) {\n width = Math.round((width * maxSize) / height);\n height = maxSize;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(img, 0, 0, width, height);\n resolve(canvas.toDataURL('image/jpeg', 0.7));\n } else {\n resolve(null);\n }\n };\n img.onerror = () => resolve(null);\n img.src = e.target?.result as string;\n };\n reader.onerror = () => resolve(null);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Get image dimensions from a file\n */\n async getImageDimensions(file: File): Promise<{ width: number; height: number } | null> {\n return new Promise((resolve) => {\n if (!file.type.startsWith('image/')) {\n resolve(null);\n return;\n }\n\n const reader = new FileReader();\n reader.onload = (e) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = () => resolve(null);\n img.src = e.target?.result as string;\n };\n reader.onerror = () => resolve(null);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Process a file and create a PendingAttachment.\n * This creates the data structure needed for the mention editor component.\n */\n async processFile(file: File): Promise<PendingAttachment> {\n // Read file data URL\n const dataUrl = await this.fileToDataUrl(file);\n\n const pending: PendingAttachment = {\n id: this.generateTempId(),\n file: file,\n dataUrl: dataUrl,\n mimeType: file.type,\n fileName: file.name,\n sizeBytes: file.size\n };\n\n // Get image dimensions and create thumbnail\n const type = ConversationUtility.GetAttachmentTypeFromMime(file.type);\n if (type === 'Image') {\n const dimensions = await this.getImageDimensions(file);\n if (dimensions) {\n pending.width = dimensions.width;\n pending.height = dimensions.height;\n }\n\n const thumbnail = await this.createThumbnail(file);\n if (thumbnail) {\n pending.thumbnailUrl = thumbnail;\n }\n }\n\n return pending;\n }\n\n /**\n * Convert a file to a data URL\n */\n private fileToDataUrl(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(file);\n });\n }\n\n /**\n * Generate a temporary ID for pending attachments\n */\n private generateTempId(): string {\n return `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MJConversationEntity, MJConversationDetailEntity } from '@memberjunction/core-entities';
|
|
2
|
-
import { UserInfo } from '@memberjunction/core';
|
|
2
|
+
import { UserInfo, IMetadataProvider } from '@memberjunction/core';
|
|
3
3
|
import * as i0 from "@angular/core";
|
|
4
4
|
/**
|
|
5
5
|
* Global singleton cache for conversation-related entities.
|
|
@@ -14,7 +14,13 @@ import * as i0 from "@angular/core";
|
|
|
14
14
|
export declare class DataCacheService {
|
|
15
15
|
private conversations;
|
|
16
16
|
private conversationDetails;
|
|
17
|
+
private _provider;
|
|
17
18
|
constructor();
|
|
19
|
+
/**
|
|
20
|
+
* Set the metadata provider this service should use. When unset, falls back to Metadata.Provider.
|
|
21
|
+
*/
|
|
22
|
+
set Provider(value: IMetadataProvider | null);
|
|
23
|
+
get Provider(): IMetadataProvider;
|
|
18
24
|
/**
|
|
19
25
|
* Get a MJConversationEntity by ID from cache, or load it if not cached
|
|
20
26
|
* @param id The conversation ID
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-cache.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/data-cache.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,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