@memberjunction/ng-conversations 5.44.0 → 5.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/lib/components/artifact/artifact-share-modal.component.d.ts +3 -1
  2. package/dist/lib/components/artifact/artifact-share-modal.component.d.ts.map +1 -1
  3. package/dist/lib/components/artifact/artifact-share-modal.component.js +16 -12
  4. package/dist/lib/components/artifact/artifact-share-modal.component.js.map +1 -1
  5. package/dist/lib/components/collection/collection-share-modal.component.d.ts +3 -1
  6. package/dist/lib/components/collection/collection-share-modal.component.d.ts.map +1 -1
  7. package/dist/lib/components/collection/collection-share-modal.component.js +16 -12
  8. package/dist/lib/components/collection/collection-share-modal.component.js.map +1 -1
  9. package/dist/lib/components/collection/collection-tree.component.d.ts +3 -1
  10. package/dist/lib/components/collection/collection-tree.component.d.ts.map +1 -1
  11. package/dist/lib/components/collection/collection-tree.component.js +10 -7
  12. package/dist/lib/components/collection/collection-tree.component.js.map +1 -1
  13. package/dist/lib/components/collection/collection-view.component.d.ts +3 -1
  14. package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
  15. package/dist/lib/components/collection/collection-view.component.js +10 -8
  16. package/dist/lib/components/collection/collection-view.component.js.map +1 -1
  17. package/dist/lib/components/composer/ai-composer.component.d.ts +103 -0
  18. package/dist/lib/components/composer/ai-composer.component.d.ts.map +1 -0
  19. package/dist/lib/components/composer/ai-composer.component.js +263 -0
  20. package/dist/lib/components/composer/ai-composer.component.js.map +1 -0
  21. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +3 -4
  22. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
  23. package/dist/lib/components/conversation/conversation-chat-area.component.js +36 -36
  24. package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
  25. package/dist/lib/components/conversation/conversation-empty-state.component.d.ts +1 -1
  26. package/dist/lib/components/conversation/conversation-empty-state.component.d.ts.map +1 -1
  27. package/dist/lib/components/conversation/conversation-empty-state.component.js.map +1 -1
  28. package/dist/lib/components/message/message-input.component.d.ts +5 -6
  29. package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
  30. package/dist/lib/components/message/message-input.component.js +19 -19
  31. package/dist/lib/components/message/message-input.component.js.map +1 -1
  32. package/dist/lib/components/message/message-item.component.d.ts +2 -3
  33. package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
  34. package/dist/lib/components/message/message-item.component.js +17 -17
  35. package/dist/lib/components/message/message-item.component.js.map +1 -1
  36. package/dist/lib/components/overlay/chat-overlay.component.d.ts +1 -1
  37. package/dist/lib/components/overlay/chat-overlay.component.d.ts.map +1 -1
  38. package/dist/lib/components/overlay/chat-overlay.component.js.map +1 -1
  39. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts +11 -3
  40. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts.map +1 -1
  41. package/dist/lib/components/sidebar/conversation-sidebar.component.js +34 -10
  42. package/dist/lib/components/sidebar/conversation-sidebar.component.js.map +1 -1
  43. package/dist/lib/components/sidebar/routines-section.component.d.ts +73 -0
  44. package/dist/lib/components/sidebar/routines-section.component.d.ts.map +1 -0
  45. package/dist/lib/components/sidebar/routines-section.component.js +211 -0
  46. package/dist/lib/components/sidebar/routines-section.component.js.map +1 -0
  47. package/dist/lib/components/tasks/tasks-dropdown.component.d.ts +12 -0
  48. package/dist/lib/components/tasks/tasks-dropdown.component.d.ts.map +1 -1
  49. package/dist/lib/components/tasks/tasks-dropdown.component.js +37 -1
  50. package/dist/lib/components/tasks/tasks-dropdown.component.js.map +1 -1
  51. package/dist/lib/components/workspace/conversation-workspace.component.d.ts +11 -5
  52. package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
  53. package/dist/lib/components/workspace/conversation-workspace.component.js +35 -26
  54. package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
  55. package/dist/lib/composer-plugins/agent-mention.provider.d.ts +16 -0
  56. package/dist/lib/composer-plugins/agent-mention.provider.d.ts.map +1 -0
  57. package/dist/lib/composer-plugins/agent-mention.provider.js +28 -0
  58. package/dist/lib/composer-plugins/agent-mention.provider.js.map +1 -0
  59. package/dist/lib/composer-plugins/base-conversation-mention.provider.d.ts +20 -0
  60. package/dist/lib/composer-plugins/base-conversation-mention.provider.d.ts.map +1 -0
  61. package/dist/lib/composer-plugins/base-conversation-mention.provider.js +32 -0
  62. package/dist/lib/composer-plugins/base-conversation-mention.provider.js.map +1 -0
  63. package/dist/lib/composer-plugins/load-composer-plugins.d.ts +9 -0
  64. package/dist/lib/composer-plugins/load-composer-plugins.d.ts.map +1 -0
  65. package/dist/lib/composer-plugins/load-composer-plugins.js +17 -0
  66. package/dist/lib/composer-plugins/load-composer-plugins.js.map +1 -0
  67. package/dist/lib/composer-plugins/record-mention.provider.d.ts +14 -0
  68. package/dist/lib/composer-plugins/record-mention.provider.d.ts.map +1 -0
  69. package/dist/lib/composer-plugins/record-mention.provider.js +26 -0
  70. package/dist/lib/composer-plugins/record-mention.provider.js.map +1 -0
  71. package/dist/lib/composer-plugins/skill-command.provider.d.ts +15 -0
  72. package/dist/lib/composer-plugins/skill-command.provider.d.ts.map +1 -0
  73. package/dist/lib/composer-plugins/skill-command.provider.js +27 -0
  74. package/dist/lib/composer-plugins/skill-command.provider.js.map +1 -0
  75. package/dist/lib/conversations.module.d.ts +74 -73
  76. package/dist/lib/conversations.module.d.ts.map +1 -1
  77. package/dist/lib/conversations.module.js +33 -13
  78. package/dist/lib/conversations.module.js.map +1 -1
  79. package/dist/lib/services/conversation-agent.service.d.ts +7 -0
  80. package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
  81. package/dist/lib/services/conversation-agent.service.js +20 -0
  82. package/dist/lib/services/conversation-agent.service.js.map +1 -1
  83. package/dist/lib/services/conversation-attachment.service.d.ts +1 -1
  84. package/dist/lib/services/conversation-attachment.service.d.ts.map +1 -1
  85. package/dist/lib/services/conversation-attachment.service.js.map +1 -1
  86. package/dist/lib/services/mention-autocomplete.service.d.ts +27 -20
  87. package/dist/lib/services/mention-autocomplete.service.d.ts.map +1 -1
  88. package/dist/lib/services/mention-autocomplete.service.js +55 -16
  89. package/dist/lib/services/mention-autocomplete.service.js.map +1 -1
  90. package/dist/public-api.d.ts +23 -3
  91. package/dist/public-api.d.ts.map +1 -1
  92. package/dist/public-api.js +38 -3
  93. package/dist/public-api.js.map +1 -1
  94. package/package.json +29 -27
  95. package/dist/lib/components/mention/mention-dropdown.component.d.ts +0 -53
  96. package/dist/lib/components/mention/mention-dropdown.component.d.ts.map +0 -1
  97. package/dist/lib/components/mention/mention-dropdown.component.js +0 -297
  98. package/dist/lib/components/mention/mention-dropdown.component.js.map +0 -1
  99. package/dist/lib/components/mention/mention-editor.component.d.ts +0 -256
  100. package/dist/lib/components/mention/mention-editor.component.d.ts.map +0 -1
  101. package/dist/lib/components/mention/mention-editor.component.js +0 -1247
  102. package/dist/lib/components/mention/mention-editor.component.js.map +0 -1
  103. package/dist/lib/components/message/message-input-box.component.d.ts +0 -132
  104. package/dist/lib/components/message/message-input-box.component.d.ts.map +0 -1
  105. package/dist/lib/components/message/message-input-box.component.js +0 -327
  106. package/dist/lib/components/message/message-input-box.component.js.map +0 -1
@@ -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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E,YAAY,CAAC,YAAY;wBACvC,YAAY,EAAE,YAAY,CAAC,YAAY;wBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB,IAAI,IAAI;wBAC7D,QAAQ,EAAE,EAAE;qBACb,CAAC,CAAC;gBACL,CAAC;gBAED,MAAM,aAAa,GAAG,WAAW,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;gBACvD,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC;oBAC1B,KAAK,EAAE,QAAQ,CAAC,EAAE;oBAClB,SAAS,EAAE,YAAY,CAAC,iBAAiB;oBACzC,aAAa,EAAE,YAAY,CAAC,aAAa;oBACzC,WAAW,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,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CAAC,YAAY;wBACvC,YAAY,EAAE,YAAY,CAAC,YAAY;wBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB,IAAI,IAAI;wBAC7D,QAAQ,EAAE,EAAE;qBACb,CAAC,CAAC;gBACL,CAAC;gBAED,MAAM,aAAa,GAAG,WAAW,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;gBACvD,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC;oBAC1B,KAAK,EAAE,QAAQ,CAAC,EAAE;oBAClB,SAAS,EAAE,YAAY,CAAC,iBAAiB;oBACzC,aAAa,EAAE,YAAY,CAAC,aAAa;oBACzC,WAAW,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 '../components/mention/mention-editor.component';
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,gDAAgD,CAAC;;AAInF;;;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
+ {"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,6B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AAC;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,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,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G,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 '../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,IAA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AAC,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 * as i0 from "@angular/core";
3
+ import { BaseSingleton } from '@memberjunction/global';
4
+ import { MentionSuggestion } from '@memberjunction/ng-composer';
4
5
  /**
5
- * Item in the autocomplete dropdown
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 interface MentionSuggestion {
8
- type: 'agent' | 'user' | 'entity' | 'query' | 'skill';
9
- id: string;
10
- name: string;
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
- constructor();
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":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAEvE,OAAO,EAAE,QAAQ,EAAY,UAAU,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;;AAGpG;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,OAAO,CAAC;IACtD,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,qBAGa,0BAA0B;IACrC,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,UAAU,CAAkB;IACpC,OAAO,CAAC,aAAa,CAAoB;IACzC,OAAO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EAAE,YAAY,GAAE,OAAc,EAAE,OAAO,GAAE,MAAY,GAAG,iBAAiB,EAAE;IA6DvG;;;OAGG;IACH,OAAO,CAAC,4BAA4B;IA2CpC;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAwB3B;;;;;;;OAOG;IACH,OAAO,CAAC,eAAe;IAmBvB;;OAEG;IACH,OAAO,CAAC,YAAY;IAepB;;OAEG;IACH,kBAAkB,IAAI,uBAAuB,EAAE;IAI/C;;OAEG;IACH,iBAAiB,IAAI,QAAQ,EAAE;IAI/B;;OAEG;IACH,oBAAoB,IAAI,UAAU,EAAE;IAIpC;;OAEG;IACH,mBAAmB,IAAI,SAAS,EAAE;IAIlC;;OAEG;IACH,oBAAoB,IAAI,MAAM;IAI9B;;;OAGG;IACG,OAAO,CAAC,WAAW,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAKpD"}
@@ -1,11 +1,26 @@
1
- import { Injectable } from '@angular/core';
2
1
  import { Metadata } from '@memberjunction/core';
3
2
  import { AIEngineBase, AIAgentPermissionHelper, AISkillPermissionHelper } from '@memberjunction/ai-engine-base';
4
- import * as i0 from "@angular/core";
3
+ import { BaseSingleton } from '@memberjunction/global';
5
4
  /**
6
- * Service for autocomplete suggestions when typing @mentions
5
+ * Shared engine behind the conversations composer plugins (the agent-mentions /
6
+ * record-mentions / skill-commands `ComposerTriggerProvider`s) and the mention-parsing
7
+ * consumers (message routing, saved-message badge rendering). Loads the
8
+ * permission-filtered agent / user / entity / query / skill caches once per session and
9
+ * serves ranked `MentionSuggestion` lists per trigger char.
10
+ *
11
+ * NOT an Angular DI service — it's a `BaseSingleton` engine so the
12
+ * ClassFactory-instantiated trigger providers (which live outside Angular DI) and the
13
+ * Angular components share ONE instance (one cache warm-up) via
14
+ * `MentionAutocompleteService.Instance`.
7
15
  */
8
- export class MentionAutocompleteService {
16
+ export class MentionAutocompleteService extends BaseSingleton {
17
+ constructor() {
18
+ super();
19
+ }
20
+ /** The process-wide shared instance (Global Object Store backed). */
21
+ static get Instance() {
22
+ return super.getInstance();
23
+ }
9
24
  agentsCache = [];
10
25
  usersCache = [];
11
26
  entitiesCache = [];
@@ -18,7 +33,10 @@ export class MentionAutocompleteService {
18
33
  queriesEntityIcon = 'fa-solid fa-database';
19
34
  isInitialized = false;
20
35
  initializationPromise = null;
21
- constructor() { }
36
+ /** True once the caches have loaded (agents/users/entities/queries/skills). */
37
+ get IsInitialized() {
38
+ return this.isInitialized;
39
+ }
22
40
  /**
23
41
  * Initialize the service by loading agents and users
24
42
  * Prevents concurrent initialization with promise lock
@@ -191,7 +209,10 @@ export class MentionAutocompleteService {
191
209
  displayName: agent.Name || 'Unknown',
192
210
  description: agent.Description || undefined,
193
211
  imageUrl: agent.LogoURL || undefined, // Agent logo/avatar image
194
- icon: this.getAgentIcon(agent)
212
+ icon: this.getAgentIcon(agent),
213
+ // Configuration presets ride on the suggestion — the (AI-blind) composer
214
+ // renders a preset picker on the inserted chip when there are 2+.
215
+ presets: this.getAgentPresets(agent.ID)
195
216
  });
196
217
  }
197
218
  }
@@ -205,8 +226,7 @@ export class MentionAutocompleteService {
205
226
  id: user.ID,
206
227
  name: user.Name,
207
228
  displayName: user.Name,
208
- description: user.Email || undefined,
209
- avatarUrl: undefined // Future: load user avatars
229
+ description: user.Email || undefined
210
230
  });
211
231
  }
212
232
  }
@@ -320,6 +340,33 @@ export class MentionAutocompleteService {
320
340
  }
321
341
  return 0; // No match
322
342
  }
343
+ /**
344
+ * Map an agent's AI Agent Configuration presets into the composer's generic
345
+ * `MentionSuggestionPreset` shape so the chip's preset picker works without the
346
+ * composer knowing anything about agents.
347
+ *
348
+ * IMPORTANT: preset.ID is the AIAgentConfiguration.ID (preset ID), not
349
+ * AIConfigurationID — the backend mapping converts preset ID -> AIConfigurationID.
350
+ */
351
+ getAgentPresets(agentId) {
352
+ try {
353
+ const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agentId, true);
354
+ if (!presets || presets.length === 0) {
355
+ return undefined;
356
+ }
357
+ return presets.map(p => ({
358
+ ID: p.ID,
359
+ Name: p.Name,
360
+ DisplayName: p.DisplayName || undefined,
361
+ Description: p.Description || undefined,
362
+ IsDefault: p.IsDefault
363
+ }));
364
+ }
365
+ catch {
366
+ // Presets are a chip nicety — never let them break suggestion building
367
+ return undefined;
368
+ }
369
+ }
323
370
  /**
324
371
  * Get icon for agent based on type/name
325
372
  */
@@ -380,13 +427,5 @@ export class MentionAutocompleteService {
380
427
  this.initializationPromise = null;
381
428
  await this.initialize(currentUser);
382
429
  }
383
- static ɵfac = function MentionAutocompleteService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MentionAutocompleteService)(); };
384
- static ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: MentionAutocompleteService, factory: MentionAutocompleteService.ɵfac, providedIn: 'root' });
385
430
  }
386
- (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(MentionAutocompleteService, [{
387
- type: Injectable,
388
- args: [{
389
- providedIn: 'root'
390
- }]
391
- }], () => [], null); })();
392
431
  //# sourceMappingURL=mention-autocomplete.service.js.map