@memberjunction/ng-conversations 5.44.0 → 5.45.1
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/artifact/artifact-share-modal.component.d.ts +3 -1
- package/dist/lib/components/artifact/artifact-share-modal.component.d.ts.map +1 -1
- package/dist/lib/components/artifact/artifact-share-modal.component.js +16 -12
- package/dist/lib/components/artifact/artifact-share-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-share-modal.component.d.ts +3 -1
- package/dist/lib/components/collection/collection-share-modal.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-share-modal.component.js +16 -12
- package/dist/lib/components/collection/collection-share-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts +3 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.js +10 -7
- package/dist/lib/components/collection/collection-tree.component.js.map +1 -1
- package/dist/lib/components/collection/collection-view.component.d.ts +3 -1
- package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-view.component.js +10 -8
- package/dist/lib/components/collection/collection-view.component.js.map +1 -1
- package/dist/lib/components/composer/ai-composer.component.d.ts +103 -0
- package/dist/lib/components/composer/ai-composer.component.d.ts.map +1 -0
- package/dist/lib/components/composer/ai-composer.component.js +263 -0
- package/dist/lib/components/composer/ai-composer.component.js.map +1 -0
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +3 -4
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.js +36 -36
- package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-empty-state.component.d.ts +1 -1
- package/dist/lib/components/conversation/conversation-empty-state.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-empty-state.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.d.ts +5 -6
- package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-input.component.js +35 -20
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/message/message-item.component.d.ts +2 -3
- package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-item.component.js +17 -17
- package/dist/lib/components/message/message-item.component.js.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.js.map +1 -1
- package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts +11 -3
- package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts.map +1 -1
- package/dist/lib/components/sidebar/conversation-sidebar.component.js +34 -10
- package/dist/lib/components/sidebar/conversation-sidebar.component.js.map +1 -1
- package/dist/lib/components/sidebar/routines-section.component.d.ts +73 -0
- package/dist/lib/components/sidebar/routines-section.component.d.ts.map +1 -0
- package/dist/lib/components/sidebar/routines-section.component.js +211 -0
- package/dist/lib/components/sidebar/routines-section.component.js.map +1 -0
- package/dist/lib/components/tasks/tasks-dropdown.component.d.ts +12 -0
- package/dist/lib/components/tasks/tasks-dropdown.component.d.ts.map +1 -1
- package/dist/lib/components/tasks/tasks-dropdown.component.js +37 -1
- package/dist/lib/components/tasks/tasks-dropdown.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts +11 -5
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +35 -26
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/composer-plugins/agent-mention.provider.d.ts +16 -0
- package/dist/lib/composer-plugins/agent-mention.provider.d.ts.map +1 -0
- package/dist/lib/composer-plugins/agent-mention.provider.js +28 -0
- package/dist/lib/composer-plugins/agent-mention.provider.js.map +1 -0
- package/dist/lib/composer-plugins/base-conversation-mention.provider.d.ts +20 -0
- package/dist/lib/composer-plugins/base-conversation-mention.provider.d.ts.map +1 -0
- package/dist/lib/composer-plugins/base-conversation-mention.provider.js +32 -0
- package/dist/lib/composer-plugins/base-conversation-mention.provider.js.map +1 -0
- package/dist/lib/composer-plugins/load-composer-plugins.d.ts +9 -0
- package/dist/lib/composer-plugins/load-composer-plugins.d.ts.map +1 -0
- package/dist/lib/composer-plugins/load-composer-plugins.js +17 -0
- package/dist/lib/composer-plugins/load-composer-plugins.js.map +1 -0
- package/dist/lib/composer-plugins/record-mention.provider.d.ts +14 -0
- package/dist/lib/composer-plugins/record-mention.provider.d.ts.map +1 -0
- package/dist/lib/composer-plugins/record-mention.provider.js +26 -0
- package/dist/lib/composer-plugins/record-mention.provider.js.map +1 -0
- package/dist/lib/composer-plugins/skill-command.provider.d.ts +15 -0
- package/dist/lib/composer-plugins/skill-command.provider.d.ts.map +1 -0
- package/dist/lib/composer-plugins/skill-command.provider.js +27 -0
- package/dist/lib/composer-plugins/skill-command.provider.js.map +1 -0
- package/dist/lib/conversations.module.d.ts +74 -73
- package/dist/lib/conversations.module.d.ts.map +1 -1
- package/dist/lib/conversations.module.js +33 -13
- package/dist/lib/conversations.module.js.map +1 -1
- package/dist/lib/services/active-tasks.service.d.ts.map +1 -1
- package/dist/lib/services/active-tasks.service.js +4 -1
- package/dist/lib/services/active-tasks.service.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +7 -0
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +20 -0
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-attachment.service.d.ts +1 -1
- package/dist/lib/services/conversation-attachment.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-attachment.service.js.map +1 -1
- package/dist/lib/services/mention-autocomplete.service.d.ts +27 -20
- package/dist/lib/services/mention-autocomplete.service.d.ts.map +1 -1
- package/dist/lib/services/mention-autocomplete.service.js +55 -16
- package/dist/lib/services/mention-autocomplete.service.js.map +1 -1
- package/dist/public-api.d.ts +23 -3
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +38 -3
- package/dist/public-api.js.map +1 -1
- package/package.json +29 -27
- package/dist/lib/components/mention/mention-dropdown.component.d.ts +0 -53
- package/dist/lib/components/mention/mention-dropdown.component.d.ts.map +0 -1
- package/dist/lib/components/mention/mention-dropdown.component.js +0 -297
- package/dist/lib/components/mention/mention-dropdown.component.js.map +0 -1
- package/dist/lib/components/mention/mention-editor.component.d.ts +0 -256
- package/dist/lib/components/mention/mention-editor.component.d.ts.map +0 -1
- package/dist/lib/components/mention/mention-editor.component.js +0 -1247
- package/dist/lib/components/mention/mention-editor.component.js.map +0 -1
- package/dist/lib/components/message/message-input-box.component.d.ts +0 -132
- package/dist/lib/components/message/message-input-box.component.d.ts.map +0 -1
- package/dist/lib/components/message/message-input-box.component.js +0 -327
- package/dist/lib/components/message/message-input-box.component.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"active-tasks.service.js","sourceRoot":"","sources":["../../../src/lib/services/active-tasks.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,OAAO,EAAY,QAAQ,EAAqB,MAAM,sBAAsB,CAAC;AAEtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;;AAkBnE;;;GAGG;AAIH,MAAM,OAAO,kBAAkB;IACrB,OAAO,GAAG,IAAI,eAAe,CAA0B,IAAI,GAAG,EAAE,CAAC,CAAC;IAClE,0BAA0B,GAAG,IAAI,eAAe,CAAc,IAAI,GAAG,EAAE,CAAC,CAAC;IACzE,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC;IACrC,SAAS,GAA6B,IAAI,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7B,IAAI,CAAC,yBAAyB,CAAC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,CAAC;oBAClE,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC;oBACP,SAAS,EAAE,QAAQ,CAAC,KAAK,IAAI,eAAe;oBAC5C,OAAO,EAAE,QAAQ,CAAC,OAAO;oBACzB,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE,iCAAiC;oBAC1D,MAAM,EAAE,iBAAiB;oBACzB,gBAAgB,EAAE,QAAQ,CAAC,oBAAoB,IAAI,QAAQ,CAAC,EAAE;oBAC9D,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB,IAAI,SAAS;oBAChE,cAAc,EAAE,QAAQ,CAAC,cAAc,IAAI,SAAS;oBACpD,gBAAgB,EAAE,QAAQ,CAAC,cAAc;wBACvC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,IAAI;wBACxD,CAAC,CAAC,IAAI;iBACT,CAAC,CAAC;gBACH,aAAa,EAAE,CAAC;YAClB,CAAC;YAED,IAAI,aAAa,GAAG,CAAC,EAAE,CAAC;gBACtB,OAAO,CAAC,GAAG,CAAC,cAAc,aAAa,+BAA+B,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;4GA5PU,kBAAkB;gEAAlB,kBAAkB,WAAlB,kBAAkB,mBAFjB,MAAM;;iFAEP,kBAAkB;cAH9B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { RunView, UserInfo, Metadata, IMetadataProvider } from '@memberjunction/core';\nimport { MJAIAgentRunEntity } from '@memberjunction/core-entities';\nimport { ConversationEngine } from '@memberjunction/core-entities';\n\n/**\n * Represents an active agent task that is currently running\n */\nexport interface ActiveTask {\n id: string;\n agentName: string;\n agentId?: string; // The agent ID for looking up icon/metadata\n agentRunId?: string; // The AIAgentRun ID for finding task on completion\n status: string;\n relatedMessageId: string;\n conversationDetailId?: string; // The ConversationDetail that tracks this task\n conversationId?: string; // The conversation this task belongs to\n conversationName?: string | null; // Display name of the conversation\n startTime: number;\n}\n\n/**\n * Service for tracking active agent tasks across the application.\n * Maintains a live list of running agents and their status.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ActiveTasksService {\n private _tasks$ = new BehaviorSubject<Map<string, ActiveTask>>(new Map());\n private _conversationIdsWithTasks$ = new BehaviorSubject<Set<string>>(new Set());\n private engine = ConversationEngine.Instance;\n private _provider: IMetadataProvider | null = null;\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 * Observable of all active tasks as an array\n */\n public readonly tasks$: Observable<ActiveTask[]> = this._tasks$.pipe(\n map(taskMap => Array.from(taskMap.values()))\n );\n\n /**\n * Observable of the count of active tasks\n */\n public readonly taskCount$: Observable<number> = this.tasks$.pipe(\n map(tasks => tasks.length)\n );\n\n /**\n * Observable of conversation IDs that have 1+ active tasks\n * Use this for quick lookups in conversation lists\n */\n public readonly conversationIdsWithTasks$: Observable<Set<string>> = this._conversationIdsWithTasks$.asObservable();\n\n /**\n * Observable of tasks grouped by conversation ID\n * Returns Map<conversationId, ActiveTask[]>\n */\n public readonly tasksByConversationId$: Observable<Map<string, ActiveTask[]>> = this.tasks$.pipe(\n map(tasks => {\n const grouped = new Map<string, ActiveTask[]>();\n for (const task of tasks) {\n if (task.conversationId) {\n const existing = grouped.get(task.conversationId) || [];\n existing.push(task);\n grouped.set(task.conversationId, existing);\n }\n }\n return grouped;\n })\n );\n\n /**\n * Add a new active task\n * @param task Task details (without id and startTime)\n * @returns The generated task ID\n */\n add(task: Omit<ActiveTask, 'id' | 'startTime'>): string {\n const id = `task-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const fullTask = {\n ...task,\n id,\n startTime: Date.now()\n };\n const current = this._tasks$.value;\n current.set(id, fullTask);\n this._tasks$.next(new Map(current));\n\n // Update conversation IDs set\n if (fullTask.conversationId) {\n this.updateConversationIdsSet();\n }\n\n console.log(`➕ Task added:`, {id, conversationId: fullTask.conversationId, agentName: fullTask.agentName});\n console.log(`📊 Total tasks:`, this._tasks$.value.size);\n console.log(`🗂️ Conversation IDs with tasks:`, Array.from(this._conversationIdsWithTasks$.value));\n\n return id;\n }\n\n /**\n * Remove an active task\n * @param id The task ID to remove\n */\n remove(id: string): void {\n const current = this._tasks$.value;\n const task = current.get(id);\n current.delete(id);\n this._tasks$.next(new Map(current));\n\n // Update conversation IDs set if this was the last task for a conversation\n if (task?.conversationId) {\n this.updateConversationIdsSet();\n }\n\n console.log(`➖ Task removed:`, {id, conversationId: task?.conversationId, agentName: task?.agentName});\n console.log(`📊 Total tasks remaining:`, this._tasks$.value.size);\n console.log(`🗂️ Conversation IDs with tasks:`, Array.from(this._conversationIdsWithTasks$.value));\n }\n\n /**\n * Update the set of conversation IDs with active tasks\n * @private\n */\n private updateConversationIdsSet(): void {\n const conversationIds = new Set<string>();\n for (const task of this._tasks$.value.values()) {\n if (task.conversationId) {\n conversationIds.add(task.conversationId);\n }\n }\n this._conversationIdsWithTasks$.next(conversationIds);\n }\n\n /**\n * Update the status of an active task\n * @param id The task ID\n * @param status The new status text\n */\n updateStatus(id: string, status: string): void {\n const current = this._tasks$.value;\n const task = current.get(id);\n if (task) {\n task.status = status;\n this._tasks$.next(new Map(current));\n }\n }\n\n /**\n * Get an active task by its conversation detail ID\n * @param conversationDetailId The conversation detail ID\n * @returns The task if found, undefined otherwise\n */\n getByConversationDetailId(conversationDetailId: string): ActiveTask | undefined {\n const tasks = Array.from(this._tasks$.value.values());\n return tasks.find(task => task.conversationDetailId === conversationDetailId);\n }\n\n /**\n * Update the status of a task by its conversation detail ID\n * @param conversationDetailId The conversation detail ID\n * @param status The new status text\n * @returns true if task was found and updated, false otherwise\n */\n updateStatusByConversationDetailId(conversationDetailId: string, status: string): boolean {\n const task = this.getByConversationDetailId(conversationDetailId);\n if (task) {\n this.updateStatus(task.id, status);\n return true;\n }\n return false;\n }\n\n /**\n * Get an active task by its agent run ID\n * @param agentRunId The AIAgentRun ID\n * @returns The task if found, undefined otherwise\n */\n getByAgentRunId(agentRunId: string): ActiveTask | undefined {\n const tasks = Array.from(this._tasks$.value.values());\n return tasks.find(task => task.agentRunId === agentRunId);\n }\n\n /**\n * Remove a task by its agent run ID\n * @param agentRunId The AIAgentRun ID\n * @returns true if task was found and removed, false otherwise\n */\n removeByAgentRunId(agentRunId: string): boolean {\n const task = this.getByAgentRunId(agentRunId);\n if (task) {\n this.remove(task.id);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all active tasks\n */\n clear(): void {\n this._tasks$.next(new Map());\n }\n\n /**\n * Restore active tasks from database by querying running agent runs.\n * Call this on app initialization to restore state after browser refresh.\n * @param currentUser The current user to filter agent runs by\n */\n async restoreFromDatabase(currentUser: UserInfo): Promise<void> {\n try {\n const rv = RunView.FromMetadataProvider(this.Provider);\n\n // Query for running agent runs owned by this user\n // Only restore parent agents (those with ConversationDetailID) - child agents don't have one\n // This matches normal behavior where we only track parent agents, not child agents\n const result = await rv.RunView<MJAIAgentRunEntity>({\n EntityName: 'MJ: AI Agent Runs',\n Fields: [\"ID\", \"ConversationID\", \"AgentID\", \"Agent\", \"ConversationDetailID\"], // narrow field scope to not pull back JSON blobs - much faster\n ExtraFilter: `Status='Running' AND UserID='${currentUser.ID}' AND ConversationDetailID IS NOT NULL`,\n ResultType: 'simple' // no need for entity-object here we aren't mutating\n }, currentUser);\n\n if (!result.Success || !result.Results || result.Results.length === 0) {\n // No running tasks or query failed - nothing to restore\n return;\n }\n\n // Get conversation names from cached ConversationEngine\n const conversationNames = new Map<string, string>();\n for (const agentRun of result.Results) {\n if (agentRun.ConversationID) {\n const conv = this.engine.GetConversation(agentRun.ConversationID);\n if (conv?.Name) {\n conversationNames.set(agentRun.ConversationID, conv.Name);\n }\n }\n }\n\n // Add each running agent to ActiveTasksService\n let restoredCount = 0;\n for (const agentRun of result.Results) {\n // Skip if already tracked (prevents duplicates)\n if (agentRun.ConversationDetailID &&\n this.getByConversationDetailId(agentRun.ConversationDetailID)) {\n continue;\n }\n\n this.add({\n agentName: agentRun.Agent || 'Unknown Agent',\n agentId: agentRun.AgentID,\n agentRunId: agentRun.ID, // For finding task on completion\n status: 'Reconnecting...',\n relatedMessageId: agentRun.ConversationDetailID || agentRun.ID,\n conversationDetailId: agentRun.ConversationDetailID || undefined,\n conversationId: agentRun.ConversationID || undefined,\n conversationName: agentRun.ConversationID\n ? conversationNames.get(agentRun.ConversationID) || null\n : null\n });\n restoredCount++;\n }\n\n if (restoredCount > 0) {\n console.log(`✅ Restored ${restoredCount} active task(s) from database`);\n }\n } catch (error) {\n console.error('Failed to restore active tasks from database:', error);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"active-tasks.service.js","sourceRoot":"","sources":["../../../src/lib/services/active-tasks.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,OAAO,EAAY,QAAQ,EAAqB,MAAM,sBAAsB,CAAC;AAEtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;;AAkBnE;;;GAGG;AAIH,MAAM,OAAO,kBAAkB;IACrB,OAAO,GAAG,IAAI,eAAe,CAA0B,IAAI,GAAG,EAAE,CAAC,CAAC;IAClE,0BAA0B,GAAG,IAAI,eAAe,CAAc,IAAI,GAA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import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { RunView, UserInfo, Metadata, IMetadataProvider } from '@memberjunction/core';\nimport { MJAIAgentRunEntity } from '@memberjunction/core-entities';\nimport { ConversationEngine } from '@memberjunction/core-entities';\n\n/**\n * Represents an active agent task that is currently running\n */\nexport interface ActiveTask {\n id: string;\n agentName: string;\n agentId?: string; // The agent ID for looking up icon/metadata\n agentRunId?: string; // The AIAgentRun ID for finding task on completion\n status: string;\n relatedMessageId: string;\n conversationDetailId?: string; // The ConversationDetail that tracks this task\n conversationId?: string; // The conversation this task belongs to\n conversationName?: string | null; // Display name of the conversation\n startTime: number;\n}\n\n/**\n * Service for tracking active agent tasks across the application.\n * Maintains a live list of running agents and their status.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ActiveTasksService {\n private _tasks$ = new BehaviorSubject<Map<string, ActiveTask>>(new Map());\n private _conversationIdsWithTasks$ = new BehaviorSubject<Set<string>>(new Set());\n private engine = ConversationEngine.Instance;\n private _provider: IMetadataProvider | null = null;\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 * Observable of all active tasks as an array\n */\n public readonly tasks$: Observable<ActiveTask[]> = this._tasks$.pipe(\n map(taskMap => Array.from(taskMap.values()))\n );\n\n /**\n * Observable of the count of active tasks\n */\n public readonly taskCount$: Observable<number> = this.tasks$.pipe(\n map(tasks => tasks.length)\n );\n\n /**\n * Observable of conversation IDs that have 1+ active tasks\n * Use this for quick lookups in conversation lists\n */\n public readonly conversationIdsWithTasks$: Observable<Set<string>> = this._conversationIdsWithTasks$.asObservable();\n\n /**\n * Observable of tasks grouped by conversation ID\n * Returns Map<conversationId, ActiveTask[]>\n */\n public readonly tasksByConversationId$: Observable<Map<string, ActiveTask[]>> = this.tasks$.pipe(\n map(tasks => {\n const grouped = new Map<string, ActiveTask[]>();\n for (const task of tasks) {\n if (task.conversationId) {\n const existing = grouped.get(task.conversationId) || [];\n existing.push(task);\n grouped.set(task.conversationId, existing);\n }\n }\n return grouped;\n })\n );\n\n /**\n * Add a new active task\n * @param task Task details (without id and startTime)\n * @returns The generated task ID\n */\n add(task: Omit<ActiveTask, 'id' | 'startTime'>): string {\n const id = `task-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const fullTask = {\n ...task,\n id,\n startTime: Date.now()\n };\n const current = this._tasks$.value;\n current.set(id, fullTask);\n this._tasks$.next(new Map(current));\n\n // Update conversation IDs set\n if (fullTask.conversationId) {\n this.updateConversationIdsSet();\n }\n\n console.log(`➕ Task added:`, {id, conversationId: fullTask.conversationId, agentName: fullTask.agentName});\n console.log(`📊 Total tasks:`, this._tasks$.value.size);\n console.log(`🗂️ Conversation IDs with tasks:`, Array.from(this._conversationIdsWithTasks$.value));\n\n return id;\n }\n\n /**\n * Remove an active task\n * @param id The task ID to remove\n */\n remove(id: string): void {\n const current = this._tasks$.value;\n const task = current.get(id);\n current.delete(id);\n this._tasks$.next(new Map(current));\n\n // Update conversation IDs set if this was the last task for a conversation\n if (task?.conversationId) {\n this.updateConversationIdsSet();\n }\n\n console.log(`➖ Task removed:`, {id, conversationId: task?.conversationId, agentName: task?.agentName});\n console.log(`📊 Total tasks remaining:`, this._tasks$.value.size);\n console.log(`🗂️ Conversation IDs with tasks:`, Array.from(this._conversationIdsWithTasks$.value));\n }\n\n /**\n * Update the set of conversation IDs with active tasks\n * @private\n */\n private updateConversationIdsSet(): void {\n const conversationIds = new Set<string>();\n for (const task of this._tasks$.value.values()) {\n if (task.conversationId) {\n conversationIds.add(task.conversationId);\n }\n }\n this._conversationIdsWithTasks$.next(conversationIds);\n }\n\n /**\n * Update the status of an active task\n * @param id The task ID\n * @param status The new status text\n */\n updateStatus(id: string, status: string): void {\n const current = this._tasks$.value;\n const task = current.get(id);\n // Same-value updates are no-ops so high-frequency callers (e.g. the streamed\n // final-response render path, which fires per content delta) don't re-emit\n // the whole task map to every subscriber on each token.\n if (task && task.status !== status) {\n task.status = status;\n this._tasks$.next(new Map(current));\n }\n }\n\n /**\n * Get an active task by its conversation detail ID\n * @param conversationDetailId The conversation detail ID\n * @returns The task if found, undefined otherwise\n */\n getByConversationDetailId(conversationDetailId: string): ActiveTask | undefined {\n const tasks = Array.from(this._tasks$.value.values());\n return tasks.find(task => task.conversationDetailId === conversationDetailId);\n }\n\n /**\n * Update the status of a task by its conversation detail ID\n * @param conversationDetailId The conversation detail ID\n * @param status The new status text\n * @returns true if task was found and updated, false otherwise\n */\n updateStatusByConversationDetailId(conversationDetailId: string, status: string): boolean {\n const task = this.getByConversationDetailId(conversationDetailId);\n if (task) {\n this.updateStatus(task.id, status);\n return true;\n }\n return false;\n }\n\n /**\n * Get an active task by its agent run ID\n * @param agentRunId The AIAgentRun ID\n * @returns The task if found, undefined otherwise\n */\n getByAgentRunId(agentRunId: string): ActiveTask | undefined {\n const tasks = Array.from(this._tasks$.value.values());\n return tasks.find(task => task.agentRunId === agentRunId);\n }\n\n /**\n * Remove a task by its agent run ID\n * @param agentRunId The AIAgentRun ID\n * @returns true if task was found and removed, false otherwise\n */\n removeByAgentRunId(agentRunId: string): boolean {\n const task = this.getByAgentRunId(agentRunId);\n if (task) {\n this.remove(task.id);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all active tasks\n */\n clear(): void {\n this._tasks$.next(new Map());\n }\n\n /**\n * Restore active tasks from database by querying running agent runs.\n * Call this on app initialization to restore state after browser refresh.\n * @param currentUser The current user to filter agent runs by\n */\n async restoreFromDatabase(currentUser: UserInfo): Promise<void> {\n try {\n const rv = RunView.FromMetadataProvider(this.Provider);\n\n // Query for running agent runs owned by this user\n // Only restore parent agents (those with ConversationDetailID) - child agents don't have one\n // This matches normal behavior where we only track parent agents, not child agents\n const result = await rv.RunView<MJAIAgentRunEntity>({\n EntityName: 'MJ: AI Agent Runs',\n Fields: [\"ID\", \"ConversationID\", \"AgentID\", \"Agent\", \"ConversationDetailID\"], // narrow field scope to not pull back JSON blobs - much faster\n ExtraFilter: `Status='Running' AND UserID='${currentUser.ID}' AND ConversationDetailID IS NOT NULL`,\n ResultType: 'simple' // no need for entity-object here we aren't mutating\n }, currentUser);\n\n if (!result.Success || !result.Results || result.Results.length === 0) {\n // No running tasks or query failed - nothing to restore\n return;\n }\n\n // Get conversation names from cached ConversationEngine\n const conversationNames = new Map<string, string>();\n for (const agentRun of result.Results) {\n if (agentRun.ConversationID) {\n const conv = this.engine.GetConversation(agentRun.ConversationID);\n if (conv?.Name) {\n conversationNames.set(agentRun.ConversationID, conv.Name);\n }\n }\n }\n\n // Add each running agent to ActiveTasksService\n let restoredCount = 0;\n for (const agentRun of result.Results) {\n // Skip if already tracked (prevents duplicates)\n if (agentRun.ConversationDetailID &&\n this.getByConversationDetailId(agentRun.ConversationDetailID)) {\n continue;\n }\n\n this.add({\n agentName: agentRun.Agent || 'Unknown Agent',\n agentId: agentRun.AgentID,\n agentRunId: agentRun.ID, // For finding task on completion\n status: 'Reconnecting...',\n relatedMessageId: agentRun.ConversationDetailID || agentRun.ID,\n conversationDetailId: agentRun.ConversationDetailID || undefined,\n conversationId: agentRun.ConversationID || undefined,\n conversationName: agentRun.ConversationID\n ? conversationNames.get(agentRun.ConversationID) || null\n : null\n });\n restoredCount++;\n }\n\n if (restoredCount > 0) {\n console.log(`✅ Restored ${restoredCount} active task(s) from database`);\n }\n } catch (error) {\n console.error('Failed to restore active tasks from database:', error);\n }\n }\n}\n"]}
|
|
@@ -119,6 +119,13 @@ export declare class ConversationAgentService {
|
|
|
119
119
|
* Clear the session for a conversation (useful when starting a new topic)
|
|
120
120
|
*/
|
|
121
121
|
clearSession(conversationId: string): void;
|
|
122
|
+
/**
|
|
123
|
+
* Surfaces a warning toast when the user requested skills (via /skill mentions) that the
|
|
124
|
+
* target agent cannot activate — the server drops such requests, and without this the
|
|
125
|
+
* refusal is invisible to the user. Client-side check uses the agent gate only (the server
|
|
126
|
+
* additionally intersects with the user's Run permission).
|
|
127
|
+
*/
|
|
128
|
+
private warnOnUnacceptedSkills;
|
|
122
129
|
/**
|
|
123
130
|
* Invoke a sub-agent based on Sage Agent's payload.
|
|
124
131
|
* This is called when Sage decides to delegate to a specialist agent.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-agent.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAY,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAElG,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAEnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAGrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAGhE,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;;AAE1F;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,0BAA0B,CAAC,CAAC;IAC7D,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,gBAAgB,EAAE,CAAC,CAAC;CACtD;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,KAAK,GAAG,IAAI,GAAG,QAAQ,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,uBAAuB,CAAC,EAAE,MAAM,CAAC;CAClC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAGa,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E,GAChD,MAAM,GAAG,SAAS;IA8BrB;;OAEG;IACH,YAAY,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IAI1C;;;;;;OAMG;IACG,cAAc,CAClB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,0BAA0B,EACnC,mBAAmB,EAAE,0BAA0B,EAAE,EACjD,SAAS,EAAE,MAAM,EACjB,oBAAoB,EAAE,MAAM,EAC5B,OAAO,CAAC,EAAE,OAAO,EACjB,UAAU,CAAC,EAAE,8BAA8B,EAC3C,gBAAgB,CAAC,EAAE,MAAM,EACzB,uBAAuB,CAAC,EAAE,MAAM,EAChC,0BAA0B,CAAC,EAAE,MAAM,EACnC,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,EAC3C,QAAQ,CAAC,EAAE,OAAO,EAClB,iBAAiB,CAAC,EAAE,MAAM,EAAE,GAC3B,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"conversation-agent.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAY,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAElG,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAEnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAGrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAGhE,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAA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AO,CAAC,iBAAiB,CAAC;IA2G7B;;;;;;OAMG;IACH,OAAO,CAAC,qBAAqB;yCA/blB,wBAAwB;6CAAxB,wBAAwB;CA4gBpC"}
|
|
@@ -191,6 +191,23 @@ export class ConversationAgentService {
|
|
|
191
191
|
clearSession(conversationId) {
|
|
192
192
|
this._sessionIds.delete(conversationId);
|
|
193
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* Surfaces a warning toast when the user requested skills (via /skill mentions) that the
|
|
196
|
+
* target agent cannot activate — the server drops such requests, and without this the
|
|
197
|
+
* refusal is invisible to the user. Client-side check uses the agent gate only (the server
|
|
198
|
+
* additionally intersects with the user's Run permission).
|
|
199
|
+
*/
|
|
200
|
+
warnOnUnacceptedSkills(agent, requestedSkillIDs) {
|
|
201
|
+
const allowed = AIEngineBase.Instance.GetSkillsForAgent(agent);
|
|
202
|
+
const dropped = requestedSkillIDs.filter(id => !allowed.some(s => UUIDsEqual(s.ID, id)));
|
|
203
|
+
if (dropped.length === 0)
|
|
204
|
+
return;
|
|
205
|
+
const names = dropped.map(id => AIEngineBase.Instance.Skills.find(s => UUIDsEqual(s.ID, id))?.Name ?? 'requested skill');
|
|
206
|
+
const reason = agent.AcceptsSkills === 'None'
|
|
207
|
+
? `${agent.Name} doesn't accept skills`
|
|
208
|
+
: `${agent.Name} can't activate ${names.length === 1 ? 'this skill' : 'these skills'}`;
|
|
209
|
+
MJNotificationService.Instance?.CreateSimpleNotification(`${reason} — ${names.join(', ')} won't be used for this run.`, 'warning', 6000);
|
|
210
|
+
}
|
|
194
211
|
/**
|
|
195
212
|
* Invoke a sub-agent based on Sage Agent's payload.
|
|
196
213
|
* This is called when Sage decides to delegate to a specialist agent.
|
|
@@ -210,6 +227,9 @@ export class ConversationAgentService {
|
|
|
210
227
|
MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);
|
|
211
228
|
return null;
|
|
212
229
|
}
|
|
230
|
+
if (requestedSkillIDs?.length) {
|
|
231
|
+
this.warnOnUnacceptedSkills(agent, requestedSkillIDs);
|
|
232
|
+
}
|
|
213
233
|
console.log(`Invoking sub-agent: ${agentName}`, { reasoning, hasPayload: !!payload, hasConfigPreset: !!agentConfigurationPresetId });
|
|
214
234
|
// Map AIAgentConfiguration preset ID to actual AIConfiguration ID
|
|
215
235
|
let aiConfigurationId = undefined;
|
|
@@ -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;AAE3C,OAAO,EAAE,QAAQ,EAAqB,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAuB,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAE5F,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAG7E,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;;;;;AAuBpD;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,MAAM,OAAO,wBAAwB;IAczB;IACA;IAdV,2GAA2G;IACnG,SAAS,GAA2B,IAAI,CAAC;IACjD,2EAA2E;IACnE,yBAAyB,GAAmC,IAAI,CAAC;IACjE,WAAW,GAAwB,IAAI,GAAG,EAAE,CAAC;IAErD,mHAAmH;IACnG,aAAa,CAAsB;IAE3C,SAAS,GAA6B,IAAI,CAAC;IAEnD,YACE,UAAyC,EACjC,aAAmC,EACnC,kBAAsC;QADtC,kBAAa,GAAb,aAAa,CAAsB;QACnC,uBAAkB,GAAlB,kBAAkB,CAAoB;QAE9C,qEAAqE;QACrE,uEAAuE;QACvE,IAAI,CAAC,aAAa,GAAG,oBAAoB,CAAC,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC;QAC7E,IAAI,CAAC,kBAAk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AW,EAAE,YAAY,CAAC,WAAW;oBACrC,kBAAkB,EAAE,YAAY,CAAC,kBAAkB;oBACnD,SAAS,EAAE,YAAY,CAAC,gBAAgB;iBACzC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YACpD,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;YACxD,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;YACxD,OAAO,OAAO,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;kHAhfU,wBAAwB;gEAAxB,wBAAwB,WAAxB,wBAAwB,mBAFvB,MAAM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { MJConversationDetailEntity } 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 { ConversationsRuntime } from '@memberjunction/conversations-runtime';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { UUIDsEqual } from '@memberjunction/global';\n\nimport { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';\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 * Angular DI service for conversation-level agent orchestration.\n *\n * After PR 2 of the conversations-runtime extraction, the core\n * `processMessage` flow and the conversation-manager-agent resolution are\n * delegated to `@memberjunction/conversations-runtime`. This service is\n * primarily a shim for those operations PLUS the holder of the helpers\n * that haven't been ported yet:\n *\n * - `invokeSubAgent(...)` — used by Sage's routing decisions in\n * `message-input.component`.\n * - `checkAgentContinuityIntent(...)` — fast intent classification when the\n * user replies to a previous-agent thread.\n * - `findConfigurationPresetFromHistory(...)` — locates an agent's preset\n * from prior @mentions in the conversation.\n * - `clearSession(...)` — per-conversation session-id bookkeeping.\n *\n * These can move to the runtime in a follow-up; they aren't strictly needed\n * to invoke an agent end-to-end and stay here so the shim has zero behavior\n * difference vs. the original.\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 /** Cached resolution of the conversation manager agent (default agent). */\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map();\n\n /** Observable indicating if the ambient agent is currently processing — delegated to the runtime's AgentRunner. */\n public readonly isProcessing$: Observable<boolean>;\n\n private _provider: IMetadataProvider | null = null;\n\n constructor(\n _bootstrap: ConversationsRuntimeBootstrap,\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n // Injecting `_bootstrap` forces the runtime's INotificationAdapter +\n // IActiveTaskTracker adapters to register before any shim method runs.\n this.isProcessing$ = ConversationsRuntime.Instance.AgentRunner.isProcessing$;\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 and forwards the provider to the runtime's runner.\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 ConversationsRuntime.Instance.AgentRunner.Provider = value;\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 ConversationsRuntime.AgentRunner.\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 * Resolve the conversation manager agent via the runtime's 4-step\n * DefaultAgentResolver chain (explicit input → app-scoped Application\n * Setting → global Application Setting → code-const Sage fallback). The\n * result is cached on this service for use by the synchronous\n * {@link ConversationManagerAgentName} getter.\n *\n * Existing callers expect a Promise<MJAIAgentEntityExtended | null> — we\n * preserve that shape (returning null on failure rather than throwing)\n * so the call sites don't need to change.\n */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n\n try {\n const provider = this.Provider;\n const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({\n contextUser: provider.CurrentUser ?? undefined,\n provider,\n });\n this._conversationManagerAgent = agent;\n return agent;\n } catch (error) {\n const errorMsg = 'Error resolving conversation manager agent: ' + (error instanceof Error ? error.message : String(error));\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /**\n * Synchronous read of the cached conversation-manager-agent name. Returns\n * `null` until {@link getConversationManagerAgent} has been called at least\n * once and resolved successfully. Used by `MessageItemComponent.isConversationManager`\n * to flag messages from the routing agent without hardcoding `'Sage'`.\n */\n public get ConversationManagerAgentName(): string | null {\n return this._conversationManagerAgent?.Name ?? null;\n }\n\n /**\n * Returns `true` if the supplied agent identifier (UUID or name) matches the\n * currently cached conversation manager agent. Robust to either input.\n */\n public IsConversationManagerAgent(agentIdOrName: string | null | undefined): boolean {\n if (!agentIdOrName || !this._conversationManagerAgent) return false;\n return (\n UUIDsEqual(this._conversationManagerAgent.ID, agentIdOrName) ||\n this._conversationManagerAgent.Name === agentIdOrName\n );\n }\n\n /**\n * Process a message through the conversation manager agent. Delegates to\n * `ConversationsRuntime.Instance.AgentRunner.processMessage(...)`.\n *\n * Signature is preserved verbatim from the original service so existing\n * call sites continue to compile. The unused `conversationHistory`\n * parameter is kept for backwards compatibility (it was already\n * documented as \"kept for backwards compatibility but not used\" in the\n * original).\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 planMode?: boolean,\n requestedSkillIDs?: string[]\n ): Promise<ExecuteAgentResult | null> {\n // Warm the cached default-agent name for any synchronous consumers\n // before the runtime resolves on its own.\n if (!this._conversationManagerAgent) {\n await this.getConversationManagerAgent();\n }\n return ConversationsRuntime.Instance.AgentRunner.processMessage({\n conversationId,\n message,\n conversationDetailId,\n appContext,\n onProgress,\n ...(planMode ? { planMode: true } : {}),\n ...(requestedSkillIDs?.length ? { requestedSkillIDs } : {}),\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 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 * 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 * 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 * Stays on the Angular shim because it directly uses AgentClientService.\n * Could move to the runtime in a follow-up if needed.\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 appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: 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 const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\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 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 ...(appContext ? { appContext } : {}),\n },\n ...(payload ? { Payload: payload as Record<string, unknown> } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n ...(planMode ? { PlanMode: true } : {}),\n ...(requestedSkillIDs?.length ? { RequestedSkillIDs: requestedSkillIDs } : {}),\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 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 * Stays on the Angular shim because it directly uses GraphQLAIClient.\n * Could move to the runtime in a follow-up.\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 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 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 const agentArtifacts = this.findAllAgentArtifacts(\n agentId,\n conversationHistory,\n context\n );\n\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 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 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 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 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 return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\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 for (let i = conversationDetails.length - 1; i >= 0; i--) {\n const detail = conversationDetails[i];\n\n if (detail.Role !== 'AI' || detail.Status === 'Error') continue;\n\n const agentRun = context.agentRunsByDetailId.get(detail.ID);\n if (!agentRun || !UUIDsEqual(agentRun.AgentID, agentId) || agentRun.Status !== 'Completed') {\n continue;\n }\n\n const artifacts = context.artifactsByDetailId.get(detail.ID);\n if (!artifacts || artifacts.length === 0) continue;\n\n for (const lazyArtifact of artifacts) {\n const mainArtifactId = lazyArtifact.artifactId;\n\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 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 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;AAE3C,OAAO,EAAE,QAAQ,EAAqB,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAuB,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAE5F,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAG7E,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;;;;;AAuBpD;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,MAAM,OAAO,wBAAwB;IAczB;IACA;IAdV,2GAA2G;IACnG,SAAS,GAA2B,IAAI,CAAC;IACjD,2EAA2E;IACnE,yBAAyB,GAAmC,IAAI,CAAC;IACjE,WAAW,GAAwB,IAAI,GAAG,EAAE,CAAC;IAErD,mHAAmH;IACnG,aAAa,CAAsB;IAE3C,SAAS,GAA6B,IAAI,CAAC;IAEnD,YACE,UAAyC,EACjC,aAAmC,EACnC,kBAAsC;QADtC,kBAAa,GAAb,aAAa,CAAsB;QACnC,uBAAkB,GAAlB,kBAAkB,CAAoB;QAE9C,qEAAqE;QACrE,uEAAuE;QACvE,IAAI,CAAC,aAAa,GAAG,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W,EAAE,YAAY,CAAC,WAAW;oBACrC,kBAAkB,EAAE,YAAY,CAAC,kBAAkB;oBACnD,SAAS,EAAE,YAAY,CAAC,gBAAgB;iBACzC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YACpD,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;YACxD,MAAM,OAAO,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;YACxD,OAAO,OAAO,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;kHA3gBU,wBAAwB;gEAAxB,wBAAwB,WAAxB,wBAAwB,mBAFvB,MAAM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport { MJConversationDetailEntity } 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 { ConversationsRuntime } from '@memberjunction/conversations-runtime';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { UUIDsEqual } from '@memberjunction/global';\n\nimport { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';\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 * Angular DI service for conversation-level agent orchestration.\n *\n * After PR 2 of the conversations-runtime extraction, the core\n * `processMessage` flow and the conversation-manager-agent resolution are\n * delegated to `@memberjunction/conversations-runtime`. This service is\n * primarily a shim for those operations PLUS the holder of the helpers\n * that haven't been ported yet:\n *\n * - `invokeSubAgent(...)` — used by Sage's routing decisions in\n * `message-input.component`.\n * - `checkAgentContinuityIntent(...)` — fast intent classification when the\n * user replies to a previous-agent thread.\n * - `findConfigurationPresetFromHistory(...)` — locates an agent's preset\n * from prior @mentions in the conversation.\n * - `clearSession(...)` — per-conversation session-id bookkeeping.\n *\n * These can move to the runtime in a follow-up; they aren't strictly needed\n * to invoke an agent end-to-end and stay here so the shim has zero behavior\n * difference vs. the original.\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 /** Cached resolution of the conversation manager agent (default agent). */\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map();\n\n /** Observable indicating if the ambient agent is currently processing — delegated to the runtime's AgentRunner. */\n public readonly isProcessing$: Observable<boolean>;\n\n private _provider: IMetadataProvider | null = null;\n\n constructor(\n _bootstrap: ConversationsRuntimeBootstrap,\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n // Injecting `_bootstrap` forces the runtime's INotificationAdapter +\n // IActiveTaskTracker adapters to register before any shim method runs.\n this.isProcessing$ = ConversationsRuntime.Instance.AgentRunner.isProcessing$;\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 and forwards the provider to the runtime's runner.\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 ConversationsRuntime.Instance.AgentRunner.Provider = value;\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 ConversationsRuntime.AgentRunner.\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 * Resolve the conversation manager agent via the runtime's 4-step\n * DefaultAgentResolver chain (explicit input → app-scoped Application\n * Setting → global Application Setting → code-const Sage fallback). The\n * result is cached on this service for use by the synchronous\n * {@link ConversationManagerAgentName} getter.\n *\n * Existing callers expect a Promise<MJAIAgentEntityExtended | null> — we\n * preserve that shape (returning null on failure rather than throwing)\n * so the call sites don't need to change.\n */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n\n try {\n const provider = this.Provider;\n const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({\n contextUser: provider.CurrentUser ?? undefined,\n provider,\n });\n this._conversationManagerAgent = agent;\n return agent;\n } catch (error) {\n const errorMsg = 'Error resolving conversation manager agent: ' + (error instanceof Error ? error.message : String(error));\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /**\n * Synchronous read of the cached conversation-manager-agent name. Returns\n * `null` until {@link getConversationManagerAgent} has been called at least\n * once and resolved successfully. Used by `MessageItemComponent.isConversationManager`\n * to flag messages from the routing agent without hardcoding `'Sage'`.\n */\n public get ConversationManagerAgentName(): string | null {\n return this._conversationManagerAgent?.Name ?? null;\n }\n\n /**\n * Returns `true` if the supplied agent identifier (UUID or name) matches the\n * currently cached conversation manager agent. Robust to either input.\n */\n public IsConversationManagerAgent(agentIdOrName: string | null | undefined): boolean {\n if (!agentIdOrName || !this._conversationManagerAgent) return false;\n return (\n UUIDsEqual(this._conversationManagerAgent.ID, agentIdOrName) ||\n this._conversationManagerAgent.Name === agentIdOrName\n );\n }\n\n /**\n * Process a message through the conversation manager agent. Delegates to\n * `ConversationsRuntime.Instance.AgentRunner.processMessage(...)`.\n *\n * Signature is preserved verbatim from the original service so existing\n * call sites continue to compile. The unused `conversationHistory`\n * parameter is kept for backwards compatibility (it was already\n * documented as \"kept for backwards compatibility but not used\" in the\n * original).\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 planMode?: boolean,\n requestedSkillIDs?: string[]\n ): Promise<ExecuteAgentResult | null> {\n // Warm the cached default-agent name for any synchronous consumers\n // before the runtime resolves on its own.\n if (!this._conversationManagerAgent) {\n await this.getConversationManagerAgent();\n }\n return ConversationsRuntime.Instance.AgentRunner.processMessage({\n conversationId,\n message,\n conversationDetailId,\n appContext,\n onProgress,\n ...(planMode ? { planMode: true } : {}),\n ...(requestedSkillIDs?.length ? { requestedSkillIDs } : {}),\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 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 * 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 * Surfaces a warning toast when the user requested skills (via /skill mentions) that the\n * target agent cannot activate — the server drops such requests, and without this the\n * refusal is invisible to the user. Client-side check uses the agent gate only (the server\n * additionally intersects with the user's Run permission).\n */\n private warnOnUnacceptedSkills(agent: MJAIAgentEntityExtended, requestedSkillIDs: string[]): void {\n const allowed = AIEngineBase.Instance.GetSkillsForAgent(agent);\n const dropped = requestedSkillIDs.filter(id => !allowed.some(s => UUIDsEqual(s.ID, id)));\n if (dropped.length === 0) return;\n const names = dropped.map(\n id => AIEngineBase.Instance.Skills.find(s => UUIDsEqual(s.ID, id))?.Name ?? 'requested skill'\n );\n const reason = agent.AcceptsSkills === 'None'\n ? `${agent.Name} doesn't accept skills`\n : `${agent.Name} can't activate ${names.length === 1 ? 'this skill' : 'these skills'}`;\n MJNotificationService.Instance?.CreateSimpleNotification(\n `${reason} — ${names.join(', ')} won't be used for this run.`,\n 'warning',\n 6000\n );\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 * Stays on the Angular shim because it directly uses AgentClientService.\n * Could move to the runtime in a follow-up if needed.\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 appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: 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 if (requestedSkillIDs?.length) {\n this.warnOnUnacceptedSkills(agent, requestedSkillIDs);\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 const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\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 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 ...(appContext ? { appContext } : {}),\n },\n ...(payload ? { Payload: payload as Record<string, unknown> } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n ...(planMode ? { PlanMode: true } : {}),\n ...(requestedSkillIDs?.length ? { RequestedSkillIDs: requestedSkillIDs } : {}),\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 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 * Stays on the Angular shim because it directly uses GraphQLAIClient.\n * Could move to the runtime in a follow-up.\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 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 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 const agentArtifacts = this.findAllAgentArtifacts(\n agentId,\n conversationHistory,\n context\n );\n\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 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 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 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 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 return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\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 for (let i = conversationDetails.length - 1; i >= 0; i--) {\n const detail = conversationDetails[i];\n\n if (detail.Role !== 'AI' || detail.Status === 'Error') continue;\n\n const agentRun = context.agentRunsByDetailId.get(detail.ID);\n if (!agentRun || !UUIDsEqual(agentRun.AgentID, agentId) || agentRun.Status !== 'Completed') {\n continue;\n }\n\n const artifacts = context.artifactsByDetailId.get(detail.ID);\n if (!artifacts || artifacts.length === 0) continue;\n\n for (const lazyArtifact of artifacts) {\n const mainArtifactId = lazyArtifact.artifactId;\n\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 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 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,7 +1,7 @@
|
|
|
1
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
|
-
import { PendingAttachment } from '
|
|
4
|
+
import { PendingAttachment } from '@memberjunction/ng-composer';
|
|
5
5
|
import * as i0 from "@angular/core";
|
|
6
6
|
/**
|
|
7
7
|
* Service for managing conversation attachments.
|
|
@@ -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,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,
|
|
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,6BAA6B,CAAC;;AAIhE;;;GAGG;AACH,qBAGa,6BAA6B;IACxC,OAAO,CAAC,SAAS,CAAkC;;IAInD;;OAEG;IACH,IAAW,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,EAElD;IAED,IAAW,QAAQ,IAAI,iBAAiB,CAEvC;IAED;;;OAGG;IACG,0BAA0B,CAC9B,qBAAqB,EAAE,MAAM,EAAE,EAC/B,WAAW,CAAC,EAAE,QAAQ,GACrB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAC;IA0F5C;;OAEG;IACG,yBAAyB,CAC7B,oBAAoB,EAAE,MAAM,EAC5B,WAAW,CAAC,EAAE,QAAQ,GACrB,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAK/B;;;;;;;OAOG;IACG,eAAe,CACnB,oBAAoB,EAAE,MAAM,EAC5B,kBAAkB,EAAE,iBAAiB,EAAE,EACvC,WAAW,CAAC,EAAE,QAAQ,GACrB,OAAO,CAAC,oCAAoC,EAAE,CAAC;IA8ElD;;;OAGG;IACH,0BAA0B,CAAC,WAAW,EAAE,oCAAoC,EAAE,GAAG,MAAM;IAoBvF;;OAEG;IACH,OAAO,CAAC,0BAA0B;IAiClC;;OAEG;IACH,OAAO,CAAC,6BAA6B;IAYrC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAyB5B;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAKhC;;;OAGG;IACG,eAAe,CACnB,IAAI,EAAE,IAAI,EACV,OAAO,GAAE,MAAY,GACpB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IA+CzB;;OAEG;IACG,kBAAkB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAqBvF;;;OAGG;IACG,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,iBAAiB,CAAC;IA+BzD;;OAEG;IACH,OAAO,CAAC,aAAa;IASrB;;OAEG;IACH,OAAO,CAAC,cAAc;yCA/cX,6BAA6B;6CAA7B,6BAA6B;CAkdzC"}
|
|
@@ -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;AAC3C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAA+B,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAML,sBAAsB,EACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,mBAAmB,EAGpB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,YAAY,EAAE,MAAM,gCA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,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;uHAjdU,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 // Load input artifacts (ConversationDetailArtifact with Direction='Input').\n // Since the backfill migration (V202605271400__Backfill_Attachment_Artifacts)\n // converted all legacy ConversationDetailAttachment rows to artifact pairs,\n // the artifact junction is the single source of truth — no separate attachment\n // query needed.\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 rejectionMessages: string[] = [];\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 const message = attachment.LatestResult?.CompleteMessage\n ?? `Attachment \"${pending.fileName}\" was rejected by the server.`;\n console.error('Failed to save attachment:', attachment.LatestResult);\n rejectionMessages.push(message);\n }\n } catch (error) {\n console.error('Error saving attachment:', error);\n rejectionMessages.push(\n `Attachment \"${pending.fileName}\" failed to upload: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n // Surface server-side rejections (e.g. unregistered MIME types) to the\n // caller — throwing here lets the message-input toast pipeline display\n // the actual server message rather than silently dropping the file.\n if (rejectionMessages.length > 0) {\n throw new Error(rejectionMessages.join('\\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":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAA+B,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAML,sBAAsB,EACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,mBAAmB,EAGpB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;;AAEpD;;;GAGG;AAIH,MAAM,OAAO,6BAA6B;IAChC,SAAS,GAA6B,IAAI,CAAC;IAEnD,gBAAe,CAAC;IAEhB;;OAEG;IACH,IAAW,QAAQ,CAAC,KAA+B;QAC/C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IAC3B,CAAC;IAED,IAAW,QAAQ;QACf,OAAO,IAAI,CAAC,SAAS,IAAI,QAAQ,CAAC,QAAQ,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,0BAA0B,CAC9B,qBAA+B,EAC/B,WAAsB;QAEtB,MAAM,MAAM,GAAG,IAAI,GAAG,EAA+B,CAAC;QAEtD,IAAI,CAAC,qBAAqB,IAAI,qBAAqB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjE,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,CAAC;YACH,MAAM,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACvD,MAAM,MAAM,GAAG,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,E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,UAAU,CAAC,MAAM,CAAC;YACrC,CAAC;YAED,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;YACnD,IAAI,SAAS,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;uHAjdU,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 '@memberjunction/ng-composer';\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 // Load input artifacts (ConversationDetailArtifact with Direction='Input').\n // Since the backfill migration (V202605271400__Backfill_Attachment_Artifacts)\n // converted all legacy ConversationDetailAttachment rows to artifact pairs,\n // the artifact junction is the single source of truth — no separate attachment\n // query needed.\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 rejectionMessages: string[] = [];\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 const message = attachment.LatestResult?.CompleteMessage\n ?? `Attachment \"${pending.fileName}\" was rejected by the server.`;\n console.error('Failed to save attachment:', attachment.LatestResult);\n rejectionMessages.push(message);\n }\n } catch (error) {\n console.error('Error saving attachment:', error);\n rejectionMessages.push(\n `Attachment \"${pending.fileName}\" failed to upload: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n // Surface server-side rejections (e.g. unregistered MIME types) to the\n // caller — throwing here lets the message-input toast pipeline display\n // the actual server message rather than silently dropping the file.\n if (rejectionMessages.length > 0) {\n throw new Error(rejectionMessages.join('\\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,24 +1,23 @@
|
|
|
1
1
|
import { MJAIAgentEntityExtended } from '@memberjunction/ai-core-plus';
|
|
2
2
|
import { UserInfo, EntityInfo, QueryInfo, IMetadataProvider } from '@memberjunction/core';
|
|
3
|
-
import
|
|
3
|
+
import { BaseSingleton } from '@memberjunction/global';
|
|
4
|
+
import { MentionSuggestion } from '@memberjunction/ng-composer';
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
+
* Shared engine behind the conversations composer plugins (the agent-mentions /
|
|
7
|
+
* record-mentions / skill-commands `ComposerTriggerProvider`s) and the mention-parsing
|
|
8
|
+
* consumers (message routing, saved-message badge rendering). Loads the
|
|
9
|
+
* permission-filtered agent / user / entity / query / skill caches once per session and
|
|
10
|
+
* serves ranked `MentionSuggestion` lists per trigger char.
|
|
11
|
+
*
|
|
12
|
+
* NOT an Angular DI service — it's a `BaseSingleton` engine so the
|
|
13
|
+
* ClassFactory-instantiated trigger providers (which live outside Angular DI) and the
|
|
14
|
+
* Angular components share ONE instance (one cache warm-up) via
|
|
15
|
+
* `MentionAutocompleteService.Instance`.
|
|
6
16
|
*/
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
displayName: string;
|
|
12
|
-
description?: string;
|
|
13
|
-
avatarUrl?: string;
|
|
14
|
-
imageUrl?: string;
|
|
15
|
-
icon?: string;
|
|
16
|
-
color?: string;
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Service for autocomplete suggestions when typing @mentions
|
|
20
|
-
*/
|
|
21
|
-
export declare class MentionAutocompleteService {
|
|
17
|
+
export declare class MentionAutocompleteService extends BaseSingleton<MentionAutocompleteService> {
|
|
18
|
+
protected constructor();
|
|
19
|
+
/** The process-wide shared instance (Global Object Store backed). */
|
|
20
|
+
static get Instance(): MentionAutocompleteService;
|
|
22
21
|
private agentsCache;
|
|
23
22
|
private usersCache;
|
|
24
23
|
private entitiesCache;
|
|
@@ -31,7 +30,8 @@ export declare class MentionAutocompleteService {
|
|
|
31
30
|
private queriesEntityIcon;
|
|
32
31
|
private isInitialized;
|
|
33
32
|
private initializationPromise;
|
|
34
|
-
|
|
33
|
+
/** True once the caches have loaded (agents/users/entities/queries/skills). */
|
|
34
|
+
get IsInitialized(): boolean;
|
|
35
35
|
/**
|
|
36
36
|
* Initialize the service by loading agents and users
|
|
37
37
|
* Prevents concurrent initialization with promise lock
|
|
@@ -89,6 +89,15 @@ export declare class MentionAutocompleteService {
|
|
|
89
89
|
* Higher score = better match
|
|
90
90
|
*/
|
|
91
91
|
private calculateMatchScore;
|
|
92
|
+
/**
|
|
93
|
+
* Map an agent's AI Agent Configuration presets into the composer's generic
|
|
94
|
+
* `MentionSuggestionPreset` shape so the chip's preset picker works without the
|
|
95
|
+
* composer knowing anything about agents.
|
|
96
|
+
*
|
|
97
|
+
* IMPORTANT: preset.ID is the AIAgentConfiguration.ID (preset ID), not
|
|
98
|
+
* AIConfigurationID — the backend mapping converts preset ID -> AIConfigurationID.
|
|
99
|
+
*/
|
|
100
|
+
private getAgentPresets;
|
|
92
101
|
/**
|
|
93
102
|
* Get icon for agent based on type/name
|
|
94
103
|
*/
|
|
@@ -118,7 +127,5 @@ export declare class MentionAutocompleteService {
|
|
|
118
127
|
* Resets initialization state and reloads agents
|
|
119
128
|
*/
|
|
120
129
|
refresh(currentUser: UserInfo): Promise<void>;
|
|
121
|
-
static ɵfac: i0.ɵɵFactoryDeclaration<MentionAutocompleteService, never>;
|
|
122
|
-
static ɵprov: i0.ɵɵInjectableDeclaration<MentionAutocompleteService>;
|
|
123
130
|
}
|
|
124
131
|
//# sourceMappingURL=mention-autocomplete.service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mention-autocomplete.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/mention-autocomplete.service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"mention-autocomplete.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/mention-autocomplete.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAEvE,OAAO,EAAE,QAAQ,EAAY,UAAU,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEpG,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAA2B,MAAM,6BAA6B,CAAC;AAEzF;;;;;;;;;;;GAWG;AACH,qBAAa,0BAA2B,SAAQ,aAAa,CAAC,0BAA0B,CAAC;IACvF,SAAS;IAIT,qEAAqE;IACrE,WAAkB,QAAQ,IAAI,0BAA0B,CAEvD;IAED,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,UAAU,CAAkB;IACpC,OAAO,CAAC,aAAa,CAAoB;IACzC,OAAO,CAAC,YAAY,CAAmB;IACvC,+EAA+E;IAC/E,OAAO,CAAC,WAAW,CAAyB;IAC5C,6DAA6D;IAC7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