@memberjunction/ng-conversations 6.1.5 → 6.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/components/task/tasks-full-view.component.d.ts +6 -1
- package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.js +15 -6
- package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts +11 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +21 -26
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +14 -6
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +46 -17
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-tasks-filter.d.ts +15 -0
- package/dist/lib/services/conversation-tasks-filter.d.ts.map +1 -0
- package/dist/lib/services/conversation-tasks-filter.js +69 -0
- package/dist/lib/services/conversation-tasks-filter.js.map +1 -0
- package/dist/lib/services/realtime-audio-recorder.d.ts +21 -4
- package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
- package/dist/lib/services/realtime-audio-recorder.js +42 -8
- package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
- package/dist/lib/services/realtime-session.service.js +3 -3
- package/dist/lib/services/realtime-session.service.js.map +1 -1
- package/dist/lib/services/search.service.d.ts.map +1 -1
- package/dist/lib/services/search.service.js +3 -16
- package/dist/lib/services/search.service.js.map +1 -1
- package/package.json +31 -31
|
@@ -5,7 +5,7 @@ import { coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';
|
|
|
5
5
|
import { AIEngineBase } from '@memberjunction/ai-engine-base';
|
|
6
6
|
import { MJNotificationService } from '@memberjunction/ng-notifications';
|
|
7
7
|
import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
|
|
8
|
-
import { UUIDsEqual } from '@memberjunction/global';
|
|
8
|
+
import { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';
|
|
9
9
|
import { GroupVersionsByArtifact } from '../utils/agent-artifact-summary';
|
|
10
10
|
import * as i0 from "@angular/core";
|
|
11
11
|
import * as i1 from "./conversations-runtime-bootstrap.service";
|
|
@@ -440,14 +440,18 @@ ${compactHistory}${artifactContext}
|
|
|
440
440
|
* plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},
|
|
441
441
|
* closed the same way.
|
|
442
442
|
*
|
|
443
|
-
*
|
|
443
|
+
* Three reads: the agent's replies, their Output versions, and the artifacts' names. See
|
|
444
444
|
* {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.
|
|
445
445
|
*/
|
|
446
446
|
async findAllAgentArtifacts(conversationId, agentId) {
|
|
447
|
+
const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId);
|
|
448
|
+
if (!versionFilter) {
|
|
449
|
+
return []; // the classifier degrades to no artifact context
|
|
450
|
+
}
|
|
447
451
|
const rv = RunView.FromMetadataProvider(this.Provider);
|
|
448
452
|
const versionResult = await rv.RunView({
|
|
449
453
|
EntityName: 'MJ: Artifact Versions',
|
|
450
|
-
ExtraFilter:
|
|
454
|
+
ExtraFilter: versionFilter,
|
|
451
455
|
OrderBy: '__mj_CreatedAt DESC',
|
|
452
456
|
MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,
|
|
453
457
|
Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],
|
|
@@ -489,32 +493,57 @@ ${compactHistory}${artifactContext}
|
|
|
489
493
|
* again" exchanges where payload continuity matters most. A null payload is a LEGAL agent
|
|
490
494
|
* input, so the failure is silent: the agent regenerates from scratch instead of modifying.
|
|
491
495
|
*
|
|
492
|
-
*
|
|
496
|
+
* Two reads: the agent's replies, then their newest Output version. Versions carry
|
|
493
497
|
* `__mj_CreatedAt`, so "newest" is expressible without joining back for `Sequence`.
|
|
494
498
|
*/
|
|
495
499
|
async FindLatestAgentOutputVersion(conversationId, agentId) {
|
|
496
|
-
|
|
500
|
+
const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId);
|
|
501
|
+
return versionFilter ? this.runPayloadSourceQuery(versionFilter, '__mj_CreatedAt DESC') : null;
|
|
497
502
|
}
|
|
498
503
|
/**
|
|
499
504
|
* `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced in one
|
|
500
|
-
* conversation. Shared by
|
|
501
|
-
* {@link findAllAgentArtifacts} so the two can never
|
|
502
|
-
* artifacts" means.
|
|
505
|
+
* conversation, or null when the agent has no such reply there. Shared by
|
|
506
|
+
* {@link FindLatestAgentOutputVersion} and {@link findAllAgentArtifacts} so the two can never
|
|
507
|
+
* disagree about what "this agent's artifacts" means.
|
|
508
|
+
*
|
|
509
|
+
* The replies are read with their own RunView ({@link agentReplyIds}), so the row-level
|
|
510
|
+
* security on conversation messages applies. A subquery over their view would skip it, and the
|
|
511
|
+
* server refuses one for a user whose read of messages is row-filtered.
|
|
512
|
+
*/
|
|
513
|
+
async agentOutputVersionFilter(conversationId, agentId) {
|
|
514
|
+
const replyIds = await this.agentReplyIds(conversationId, agentId);
|
|
515
|
+
if (replyIds.length === 0) {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
const inReplies = replyIds.map(id => `'${EscapeSQLString(id)}'`).join(',');
|
|
519
|
+
return `ID IN (
|
|
520
|
+
SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]
|
|
521
|
+
WHERE Direction='Output' AND ConversationDetailID IN (${inReplies})
|
|
522
|
+
)`;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* IDs of the agent's replies in one conversation. Empty when the read fails.
|
|
503
526
|
*
|
|
504
527
|
* Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's
|
|
505
528
|
* `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the
|
|
506
529
|
* run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the
|
|
507
530
|
* detail already carries.
|
|
508
531
|
*/
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
532
|
+
async agentReplyIds(conversationId, agentId) {
|
|
533
|
+
const rv = RunView.FromMetadataProvider(this.Provider);
|
|
534
|
+
const result = await rv.RunView({
|
|
535
|
+
EntityName: 'MJ: Conversation Details',
|
|
536
|
+
ExtraFilter: `ConversationID='${EscapeSQLString(conversationId)}' AND AgentID='${EscapeSQLString(agentId)}'` +
|
|
537
|
+
` AND Role='AI' AND Status <> 'Error'`,
|
|
538
|
+
Fields: ['ID'],
|
|
539
|
+
ResultType: 'simple',
|
|
540
|
+
IgnoreMaxRows: true
|
|
541
|
+
}, this.Provider.CurrentUser ?? undefined);
|
|
542
|
+
if (!result.Success) {
|
|
543
|
+
console.error('Failed to load agent replies:', result.ErrorMessage);
|
|
544
|
+
return [];
|
|
545
|
+
}
|
|
546
|
+
return (result.Results || []).map(reply => reply.ID);
|
|
518
547
|
}
|
|
519
548
|
/**
|
|
520
549
|
* One artifact version by ID, as a payload source.
|
|
@@ -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,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAuB,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAsD,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAClI,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAO9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EA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AAI,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACvE,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,yFAAyF;AACzF,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider, RunView } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport {\n MJConversationDetailEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity\n} 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';\nimport {\n GroupVersionsByArtifact,\n type AgentArtifactSummary\n} from '../utils/agent-artifact-summary';\n\n/**\n * Rows the configuration-preset lookup parses before giving up. The SQL prefilter is a LIKE,\n * so a few candidates may not be real mention blobs; this bounds how many we inspect.\n */\nconst CONFIG_PRESET_CANDIDATE_ROWS = 5;\n\n/**\n * Cap on artifact versions listed for the intent classifier.\n *\n * The block is a hint, not a record: the prompt prints a name, a type, a version count and\n * the latest version per artifact. Newest-first ordering means the cap only ever trims the\n * oldest versions of the busiest artifacts, which are the least useful lines in it.\n */\nconst MAX_AGENT_ARTIFACT_VERSIONS = 40;\n\n/**\n * Context for artifact lookups — pre-loaded conversation data.\n *\n * NO LONGER CONSUMED by this service. Both readers were converted to queries when transcript\n * windowing made these maps a partial view: they are keyed to the loaded window, so any\n * lookup for an older row silently missed. Retained as an exported type for API\n * compatibility; new code should not build one.\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * An agent's prior OUTPUT artifact, resolved for payload continuity.\n *\n * `payload` is the parsed `ArtifactVersion.Content`, typed to match what actually consumes it\n * — `executeAgentContinuation` and `invokeSubAgent` both take `Record<string, unknown> | null`.\n * It is null when the version carried no content, the content did not parse, or the content\n * parsed to something that is not a JSON object; callers treat all three the same as \"no prior\n * artifact\", which is already a legal agent input.\n */\nexport interface AgentPayloadSource {\n artifactId: string;\n versionId: string;\n versionNumber: number;\n payload: Record<string, unknown> | null;\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 * - `FindConfigurationPresetForAgent(...)` — 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 * Configuration preset an agent was pinned to by a previous `@mention` in this conversation.\n *\n * Resolved by QUERY, not by scanning the display array. The pinning `@mention` is normally\n * the FIRST message of an exchange and everything after it is follow-up, so it is the\n * message most likely to fall below the loaded transcript window — and `undefined` is a\n * legal value for `configurationPresetId`, so the miss is silent. The visible consequence\n * is a run executed under the default configuration (a different model tier) instead of the\n * one the user explicitly chose, with a plausible-looking result and no error.\n *\n * There is no column to filter on: the preset lives inside the message body as a JSON\n * mention blob (`@{\"type\":\"agent\",\"id\":\"…\",\"configId\":\"…\"}`). So SQL narrows and the parser\n * decides — both `configId` and the agent id appear verbatim in that blob, which makes the\n * two LIKEs a tight prefilter, and `parseMentions` is what actually confirms a match.\n */\n public async FindConfigurationPresetForAgent(\n conversationId: string,\n agentId: string\n ): Promise<string | undefined> {\n type MentionRow = Pick<MJConversationDetailEntity, 'ID' | 'Message'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<MentionRow>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `ConversationID='${conversationId}' AND Role='User'`\n + ` AND Message LIKE '%\"configId\"%' AND Message LIKE '%${agentId}%'`,\n OrderBy: 'Sequence DESC',\n // >1 because LIKE cannot tell a mention blob from the same id appearing elsewhere in\n // the prose; the parse below is authoritative and picks the newest genuine match.\n MaxRows: CONFIG_PRESET_CANDIDATE_ROWS,\n Fields: ['ID', 'Message'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve configuration preset:', result.ErrorMessage);\n return undefined;\n }\n\n for (const row of result.Results || []) {\n const configurationId = this.readAgentConfigFromMention(row.Message, agentId);\n if (configurationId) {\n console.log(`\\u{1F3AF} Found configuration preset from @mention: ${configurationId}`);\n return configurationId;\n }\n }\n return undefined;\n }\n\n /** Returns the configId this message pins for `agentId`, or null when it pins none. */\n private readAgentConfigFromMention(message: string | null, agentId: string): string | null {\n if (!message) {\n return null;\n }\n const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.Agents, []);\n const mention = parsed.agentMention;\n return mention?.id === agentId && mention.configurationId ? mention.configurationId : null;\n }\n\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n clearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /**\n * 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?: Record<string, unknown> | null,\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 } : {}),\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 }\n\n const failed = coerceFailedExecuteAgentResult(\n runResult.Result as ExecuteAgentResult | null | undefined,\n runResult.ErrorMessage || `Sub-agent \"${agentName}\" failed`,\n );\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${failed.errorMessage}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return failed;\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 coerceFailedExecuteAgentResult<ExecuteAgentResult>(undefined, errorMsg);\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 conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\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 // Queried, not read off the caller's window-scoped maps — see findAllAgentArtifacts.\n // `conversationHistory` below is still the window on purpose: the `.slice(-10)` wants\n // the most recent exchange, which the loaded tail always contains.\n const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId);\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 * Every artifact this agent produced in this conversation, newest version first — resolved\n * by QUERY, not by scanning the display array.\n *\n * The scan this replaces walked `conversationDetails` and looked each row up in the\n * caller's `artifactsByDetailId` / `agentRunsByDetailId` maps. Both are scoped to the\n * LOADED WINDOW, so under transcript windowing it saw only the artifacts attached to the\n * page currently on screen.\n *\n * That matters because this list is the \"Prior Artifacts Created by This Agent\" block fed\n * to the Check Sage Intent prompt, which is what produces `targetArtifactVersionId`. A\n * truncated list does not make the classifier fail — it makes it reason over a partial\n * history and confidently name the wrong version, or miss continuity altogether. Silent,\n * plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},\n * closed the same way.\n *\n * Two reads, not the four the old shape would have needed — see\n * {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.\n */\n private async findAllAgentArtifacts(\n conversationId: string,\n agentId: string\n ): Promise<AgentArtifactSummary[]> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Name'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const versionResult = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: this.agentOutputVersionFilter(conversationId, agentId),\n OrderBy: '__mj_CreatedAt DESC',\n MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!versionResult.Success) {\n console.error('Failed to load agent artifact versions:', versionResult.ErrorMessage);\n return []; // the classifier degrades to no artifact context\n }\n const versions = versionResult.Results || [];\n if (versions.length === 0) {\n return [];\n }\n\n const artifactsById = await this.loadArtifactNames(\n [...new Set(versions.map(v => v.ArtifactID))]\n );\n return GroupVersionsByArtifact(versions, artifactsById);\n }\n\n /** Names and types for the artifacts behind a set of versions. */\n private async loadArtifactNames(\n artifactIds: string[]\n ): Promise<Map<string, Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>>> {\n type ArtifactRow = Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<ArtifactRow>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIds.map(id => `'${id}'`).join(',')})`,\n Fields: ['ID', 'Name', 'Type'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent artifacts:', result.ErrorMessage);\n return new Map<string, ArtifactRow>();\n }\n return new Map((result.Results || []).map(a => [a.ID, a]));\n }\n\n /**\n * Newest OUTPUT artifact version an agent produced in this conversation — resolved by\n * QUERY, not by scanning the display array.\n *\n * The array scan this replaces was correct only while `conversationHistory` held the whole\n * conversation. Under transcript windowing it holds one page, so the scan silently returns\n * null for any artifact below the window's oldest row — exactly the long \"modify this\n * again\" exchanges where payload continuity matters most. A null payload is a LEGAL agent\n * input, so the failure is silent: the agent regenerates from scratch instead of modifying.\n *\n * One round trip. The subquery walks details -> Output junctions, and versions carry\n * `__mj_CreatedAt`, so \"newest\" is expressible without joining back for `Sequence`.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string\n ): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(\n this.agentOutputVersionFilter(conversationId, agentId), '__mj_CreatedAt DESC'\n );\n }\n\n /**\n * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced in one\n * conversation. Shared by {@link FindLatestAgentOutputVersion} and\n * {@link findAllAgentArtifacts} so the two can never disagree about what \"this agent's\n * artifacts\" means.\n *\n * Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's\n * `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the\n * run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the\n * detail already carries.\n */\n private agentOutputVersionFilter(conversationId: string, agentId: string): string {\n return `ID IN (\n SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]\n WHERE Direction='Output' AND ConversationDetailID IN (\n SELECT ID FROM [__mj].[vwConversationDetails]\n WHERE ConversationID='${conversationId}' AND AgentID='${agentId}'\n AND Role='AI' AND Status <> 'Error'\n )\n )`;\n }\n\n /**\n * One artifact version by ID, as a payload source.\n *\n * Used by the continuity path after the intent check names a specific version: that ID may\n * belong to a message below the loaded window, so it cannot be resolved from the window's\n * artifact maps.\n */\n public async FindArtifactVersionById(versionId: string): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(`ID='${versionId}'`, undefined);\n }\n\n /**\n * Shared read behind {@link FindLatestAgentOutputVersion} and {@link FindArtifactVersionById}.\n *\n * `ResultType: 'simple'` with an explicit `Fields` list: nothing here is mutated, and under\n * `entity_object` the `Fields` narrowing would be silently discarded by `PreRunView`.\n */\n private async runPayloadSourceQuery(\n extraFilter: string,\n orderBy: string | undefined\n ): Promise<AgentPayloadSource | null> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Content'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: extraFilter,\n OrderBy: orderBy,\n MaxRows: 1,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Content'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve agent payload source:', result.ErrorMessage);\n return null;\n }\n const row = result.Results?.[0];\n if (!row) {\n return null;\n }\n return {\n artifactId: row.ArtifactID,\n versionId: row.ID,\n versionNumber: row.VersionNumber,\n payload: parseArtifactContent(row.Content)\n };\n }\n\n}\n\n/**\n * Parses an artifact version's `Content` into an agent payload. Returns null rather than\n * throwing — a malformed artifact must not take down the send path, and \"no payload\" is\n * already a legal agent input.\n *\n * A payload must be a JSON OBJECT. Valid JSON that parses to an array, string, or number is\n * rejected for the same reason a parse failure is: every consumer spreads it or reads named\n * keys off it, so a non-object would satisfy the type at the boundary and misbehave deeper in.\n */\nfunction parseArtifactContent(content: string | null | undefined): Record<string, unknown> | null {\n if (!content) {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(content);\n return isPayloadObject(parsed) ? parsed : null;\n } catch (error) {\n console.warn('Artifact version content did not parse as JSON:', error);\n return null;\n }\n}\n\n/** Narrows a parsed JSON value to a plain object — the only shape a payload may take. */\nfunction isPayloadObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\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,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAuB,eAAe,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAsD,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAClI,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAO9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAG7E,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGrE,OAAO,EACL,uBAAuB,EAExB,MAAM,iCAAiC,CAAC;;;;;AAEzC;;;GAGG;AACH,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAyCvC;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,MAAM,OAAO,wBAAwB;IAczB;IACA;IAdV,2GAA2G;IACnG,SAAS,GAA2B,IAAI,CAAC;IACjD,2EAA2E;IACnE,yBAAyB,GAAmC,IAAI,CAAC;IACjE,WAAW,GAAwB,IAAI,GAAG,EAAE,CAAC;IAErD,mHAAmH;IACnG,aAAa,CAAsB;IAE3C,SAAS,GAA6B,IAAI,CAAC;IAEnD,YACE,UAAyC,EACjC,aAAmC,EACnC,kBAAsC;QADtC,kBAAa,GAAb,aAAa,CAAsB;QACnC,uBAAkB,GAAlB,kBAAkB,CAAoB;QAE9C,qEAAqE;QACrE,uEAAuE;QACvE,IAAI,CAAC,aAAa,GAAG,oBAAoB,CAAC,QAAQ,CAAC,WAAW,CAAC,aAAa,CAAC;QAC7E,IAAI,CAAC,kBAAkB,EAA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;YACjB,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,OAAO,EAAE,oBAAoB,CAAC,GAAG,CAAC,OAAO,CAAC;SAC3C,CAAC;IACJ,CAAC;kHA1oBU,wBAAwB;gEAAxB,wBAAwB,WAAxB,wBAAwB,mBAFvB,MAAM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB;;AA+oBD;;;;;;;;GAQG;AACH,SAAS,oBAAoB,CAAC,OAAkC;IAC9D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5C,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACvE,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,yFAAyF;AACzF,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider, RunView } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport {\n MJConversationDetailEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity\n} 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 { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';\n\nimport { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';\nimport {\n GroupVersionsByArtifact,\n type AgentArtifactSummary\n} from '../utils/agent-artifact-summary';\n\n/**\n * Rows the configuration-preset lookup parses before giving up. The SQL prefilter is a LIKE,\n * so a few candidates may not be real mention blobs; this bounds how many we inspect.\n */\nconst CONFIG_PRESET_CANDIDATE_ROWS = 5;\n\n/**\n * Cap on artifact versions listed for the intent classifier.\n *\n * The block is a hint, not a record: the prompt prints a name, a type, a version count and\n * the latest version per artifact. Newest-first ordering means the cap only ever trims the\n * oldest versions of the busiest artifacts, which are the least useful lines in it.\n */\nconst MAX_AGENT_ARTIFACT_VERSIONS = 40;\n\n/**\n * Context for artifact lookups — pre-loaded conversation data.\n *\n * NO LONGER CONSUMED by this service. Both readers were converted to queries when transcript\n * windowing made these maps a partial view: they are keyed to the loaded window, so any\n * lookup for an older row silently missed. Retained as an exported type for API\n * compatibility; new code should not build one.\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * An agent's prior OUTPUT artifact, resolved for payload continuity.\n *\n * `payload` is the parsed `ArtifactVersion.Content`, typed to match what actually consumes it\n * — `executeAgentContinuation` and `invokeSubAgent` both take `Record<string, unknown> | null`.\n * It is null when the version carried no content, the content did not parse, or the content\n * parsed to something that is not a JSON object; callers treat all three the same as \"no prior\n * artifact\", which is already a legal agent input.\n */\nexport interface AgentPayloadSource {\n artifactId: string;\n versionId: string;\n versionNumber: number;\n payload: Record<string, unknown> | null;\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 * - `FindConfigurationPresetForAgent(...)` — 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 * Configuration preset an agent was pinned to by a previous `@mention` in this conversation.\n *\n * Resolved by QUERY, not by scanning the display array. The pinning `@mention` is normally\n * the FIRST message of an exchange and everything after it is follow-up, so it is the\n * message most likely to fall below the loaded transcript window — and `undefined` is a\n * legal value for `configurationPresetId`, so the miss is silent. The visible consequence\n * is a run executed under the default configuration (a different model tier) instead of the\n * one the user explicitly chose, with a plausible-looking result and no error.\n *\n * There is no column to filter on: the preset lives inside the message body as a JSON\n * mention blob (`@{\"type\":\"agent\",\"id\":\"…\",\"configId\":\"…\"}`). So SQL narrows and the parser\n * decides — both `configId` and the agent id appear verbatim in that blob, which makes the\n * two LIKEs a tight prefilter, and `parseMentions` is what actually confirms a match.\n */\n public async FindConfigurationPresetForAgent(\n conversationId: string,\n agentId: string\n ): Promise<string | undefined> {\n type MentionRow = Pick<MJConversationDetailEntity, 'ID' | 'Message'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<MentionRow>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `ConversationID='${conversationId}' AND Role='User'`\n + ` AND Message LIKE '%\"configId\"%' AND Message LIKE '%${agentId}%'`,\n OrderBy: 'Sequence DESC',\n // >1 because LIKE cannot tell a mention blob from the same id appearing elsewhere in\n // the prose; the parse below is authoritative and picks the newest genuine match.\n MaxRows: CONFIG_PRESET_CANDIDATE_ROWS,\n Fields: ['ID', 'Message'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve configuration preset:', result.ErrorMessage);\n return undefined;\n }\n\n for (const row of result.Results || []) {\n const configurationId = this.readAgentConfigFromMention(row.Message, agentId);\n if (configurationId) {\n console.log(`\\u{1F3AF} Found configuration preset from @mention: ${configurationId}`);\n return configurationId;\n }\n }\n return undefined;\n }\n\n /** Returns the configId this message pins for `agentId`, or null when it pins none. */\n private readAgentConfigFromMention(message: string | null, agentId: string): string | null {\n if (!message) {\n return null;\n }\n const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.Agents, []);\n const mention = parsed.agentMention;\n return mention?.id === agentId && mention.configurationId ? mention.configurationId : null;\n }\n\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n clearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /**\n * 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?: Record<string, unknown> | null,\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 } : {}),\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 }\n\n const failed = coerceFailedExecuteAgentResult(\n runResult.Result as ExecuteAgentResult | null | undefined,\n runResult.ErrorMessage || `Sub-agent \"${agentName}\" failed`,\n );\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${failed.errorMessage}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return failed;\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 coerceFailedExecuteAgentResult<ExecuteAgentResult>(undefined, errorMsg);\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 conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\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 // Queried, not read off the caller's window-scoped maps — see findAllAgentArtifacts.\n // `conversationHistory` below is still the window on purpose: the `.slice(-10)` wants\n // the most recent exchange, which the loaded tail always contains.\n const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId);\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 * Every artifact this agent produced in this conversation, newest version first — resolved\n * by QUERY, not by scanning the display array.\n *\n * The scan this replaces walked `conversationDetails` and looked each row up in the\n * caller's `artifactsByDetailId` / `agentRunsByDetailId` maps. Both are scoped to the\n * LOADED WINDOW, so under transcript windowing it saw only the artifacts attached to the\n * page currently on screen.\n *\n * That matters because this list is the \"Prior Artifacts Created by This Agent\" block fed\n * to the Check Sage Intent prompt, which is what produces `targetArtifactVersionId`. A\n * truncated list does not make the classifier fail — it makes it reason over a partial\n * history and confidently name the wrong version, or miss continuity altogether. Silent,\n * plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},\n * closed the same way.\n *\n * Three reads: the agent's replies, their Output versions, and the artifacts' names. See\n * {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.\n */\n private async findAllAgentArtifacts(\n conversationId: string,\n agentId: string\n ): Promise<AgentArtifactSummary[]> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Name'>;\n const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId);\n if (!versionFilter) {\n return []; // the classifier degrades to no artifact context\n }\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const versionResult = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: versionFilter,\n OrderBy: '__mj_CreatedAt DESC',\n MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!versionResult.Success) {\n console.error('Failed to load agent artifact versions:', versionResult.ErrorMessage);\n return []; // the classifier degrades to no artifact context\n }\n const versions = versionResult.Results || [];\n if (versions.length === 0) {\n return [];\n }\n\n const artifactsById = await this.loadArtifactNames(\n [...new Set(versions.map(v => v.ArtifactID))]\n );\n return GroupVersionsByArtifact(versions, artifactsById);\n }\n\n /** Names and types for the artifacts behind a set of versions. */\n private async loadArtifactNames(\n artifactIds: string[]\n ): Promise<Map<string, Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>>> {\n type ArtifactRow = Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<ArtifactRow>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIds.map(id => `'${id}'`).join(',')})`,\n Fields: ['ID', 'Name', 'Type'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent artifacts:', result.ErrorMessage);\n return new Map<string, ArtifactRow>();\n }\n return new Map((result.Results || []).map(a => [a.ID, a]));\n }\n\n /**\n * Newest OUTPUT artifact version an agent produced in this conversation — resolved by\n * QUERY, not by scanning the display array.\n *\n * The array scan this replaces was correct only while `conversationHistory` held the whole\n * conversation. Under transcript windowing it holds one page, so the scan silently returns\n * null for any artifact below the window's oldest row — exactly the long \"modify this\n * again\" exchanges where payload continuity matters most. A null payload is a LEGAL agent\n * input, so the failure is silent: the agent regenerates from scratch instead of modifying.\n *\n * Two reads: the agent's replies, then their newest Output version. Versions carry\n * `__mj_CreatedAt`, so \"newest\" is expressible without joining back for `Sequence`.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string\n ): Promise<AgentPayloadSource | null> {\n const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId);\n return versionFilter ? this.runPayloadSourceQuery(versionFilter, '__mj_CreatedAt DESC') : null;\n }\n\n /**\n * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced in one\n * conversation, or null when the agent has no such reply there. Shared by\n * {@link FindLatestAgentOutputVersion} and {@link findAllAgentArtifacts} so the two can never\n * disagree about what \"this agent's artifacts\" means.\n *\n * The replies are read with their own RunView ({@link agentReplyIds}), so the row-level\n * security on conversation messages applies. A subquery over their view would skip it, and the\n * server refuses one for a user whose read of messages is row-filtered.\n */\n private async agentOutputVersionFilter(conversationId: string, agentId: string): Promise<string | null> {\n const replyIds = await this.agentReplyIds(conversationId, agentId);\n if (replyIds.length === 0) {\n return null;\n }\n const inReplies = replyIds.map(id => `'${EscapeSQLString(id)}'`).join(',');\n return `ID IN (\n SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]\n WHERE Direction='Output' AND ConversationDetailID IN (${inReplies})\n )`;\n }\n\n /**\n * IDs of the agent's replies in one conversation. Empty when the read fails.\n *\n * Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's\n * `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the\n * run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the\n * detail already carries.\n */\n private async agentReplyIds(conversationId: string, agentId: string): Promise<string[]> {\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<Pick<MJConversationDetailEntity, 'ID'>>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `ConversationID='${EscapeSQLString(conversationId)}' AND AgentID='${EscapeSQLString(agentId)}'` +\n ` AND Role='AI' AND Status <> 'Error'`,\n Fields: ['ID'],\n ResultType: 'simple',\n IgnoreMaxRows: true\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent replies:', result.ErrorMessage);\n return [];\n }\n return (result.Results || []).map(reply => reply.ID);\n }\n\n /**\n * One artifact version by ID, as a payload source.\n *\n * Used by the continuity path after the intent check names a specific version: that ID may\n * belong to a message below the loaded window, so it cannot be resolved from the window's\n * artifact maps.\n */\n public async FindArtifactVersionById(versionId: string): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(`ID='${versionId}'`, undefined);\n }\n\n /**\n * Shared read behind {@link FindLatestAgentOutputVersion} and {@link FindArtifactVersionById}.\n *\n * `ResultType: 'simple'` with an explicit `Fields` list: nothing here is mutated, and under\n * `entity_object` the `Fields` narrowing would be silently discarded by `PreRunView`.\n */\n private async runPayloadSourceQuery(\n extraFilter: string,\n orderBy: string | undefined\n ): Promise<AgentPayloadSource | null> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Content'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: extraFilter,\n OrderBy: orderBy,\n MaxRows: 1,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Content'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve agent payload source:', result.ErrorMessage);\n return null;\n }\n const row = result.Results?.[0];\n if (!row) {\n return null;\n }\n return {\n artifactId: row.ArtifactID,\n versionId: row.ID,\n versionNumber: row.VersionNumber,\n payload: parseArtifactContent(row.Content)\n };\n }\n\n}\n\n/**\n * Parses an artifact version's `Content` into an agent payload. Returns null rather than\n * throwing — a malformed artifact must not take down the send path, and \"no payload\" is\n * already a legal agent input.\n *\n * A payload must be a JSON OBJECT. Valid JSON that parses to an array, string, or number is\n * rejected for the same reason a parse failure is: every consumer spreads it or reads named\n * keys off it, so a non-object would satisfy the type at the boundary and misbehave deeper in.\n */\nfunction parseArtifactContent(content: string | null | undefined): Record<string, unknown> | null {\n if (!content) {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(content);\n return isPayloadObject(parsed) ? parsed : null;\n } catch (error) {\n console.warn('Artifact version content did not parse as JSON:', error);\n return null;\n }\n}\n\n/** Narrows a parsed JSON value to a plain object — the only shape a payload may take. */\nfunction isPayloadObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type IMetadataProvider, type UserInfo } from '@memberjunction/core';
|
|
2
|
+
/** The ExtraFilter for the top-level tasks a user owns. */
|
|
3
|
+
export declare function OwnTasksFilter(user: UserInfo): string;
|
|
4
|
+
/**
|
|
5
|
+
* The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user
|
|
6
|
+
* owns, and the tasks linked to a message the user wrote or that is in a conversation the user
|
|
7
|
+
* owns.
|
|
8
|
+
*
|
|
9
|
+
* The conversation and message IDs are read with their own RunView, so the row-level security on
|
|
10
|
+
* those entities applies. A subquery over their views would skip it, and the server refuses one
|
|
11
|
+
* for a user whose read of them is row-filtered. When a read fails, the result is the user's own
|
|
12
|
+
* tasks.
|
|
13
|
+
*/
|
|
14
|
+
export declare function BuildConversationTasksFilter(provider: IMetadataProvider, user: UserInfo): Promise<string>;
|
|
15
|
+
//# sourceMappingURL=conversation-tasks-filter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-tasks-filter.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-tasks-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,iBAAiB,EAAsB,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAG3H,2DAA2D;AAC3D,wBAAgB,cAAc,CAAC,IAAI,EAAE,QAAQ,GAAG,MAAM,CAErD;AAED;;;;;;;;;GASG;AACH,wBAAsB,4BAA4B,CAAC,QAAQ,EAAE,iBAAiB,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAwB/G"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { RunView } from '@memberjunction/core';
|
|
2
|
+
import { EscapeSQLString } from '@memberjunction/global';
|
|
3
|
+
/** The ExtraFilter for the top-level tasks a user owns. */
|
|
4
|
+
export function OwnTasksFilter(user) {
|
|
5
|
+
return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}'`;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user
|
|
9
|
+
* owns, and the tasks linked to a message the user wrote or that is in a conversation the user
|
|
10
|
+
* owns.
|
|
11
|
+
*
|
|
12
|
+
* The conversation and message IDs are read with their own RunView, so the row-level security on
|
|
13
|
+
* those entities applies. A subquery over their views would skip it, and the server refuses one
|
|
14
|
+
* for a user whose read of them is row-filtered. When a read fails, the result is the user's own
|
|
15
|
+
* tasks.
|
|
16
|
+
*/
|
|
17
|
+
export async function BuildConversationTasksFilter(provider, user) {
|
|
18
|
+
const ownTasks = OwnTasksFilter(user);
|
|
19
|
+
const tasks = provider.EntityByName('MJ: Tasks');
|
|
20
|
+
if (!tasks) {
|
|
21
|
+
return ownTasks;
|
|
22
|
+
}
|
|
23
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
24
|
+
const conversationIds = await readIds(rv, user, {
|
|
25
|
+
EntityName: 'MJ: Conversations',
|
|
26
|
+
ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,
|
|
27
|
+
Fields: ['ID'],
|
|
28
|
+
});
|
|
29
|
+
if (conversationIds == null) {
|
|
30
|
+
return ownTasks;
|
|
31
|
+
}
|
|
32
|
+
const messageIds = await readIds(rv, user, {
|
|
33
|
+
EntityName: 'MJ: Conversation Details',
|
|
34
|
+
ExtraFilter: taskMessagesFilter(user, conversationIds, tasks),
|
|
35
|
+
Fields: ['ID'],
|
|
36
|
+
});
|
|
37
|
+
if (messageIds == null || messageIds.length === 0) {
|
|
38
|
+
return ownTasks;
|
|
39
|
+
}
|
|
40
|
+
return `ParentID IS NULL AND (UserID = '${EscapeSQLString(user.ID)}' OR ConversationDetailID IN (${sqlInList(messageIds)}))`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The messages that have a top-level task and that the user wrote or that are in one of the
|
|
44
|
+
* user's conversations. The task subquery reads Tasks, which has no row filter in a default
|
|
45
|
+
* install. Its identifiers are bracketed so the PostgreSQL provider quotes them.
|
|
46
|
+
*/
|
|
47
|
+
function taskMessagesFilter(user, conversationIds, tasks) {
|
|
48
|
+
const inConversations = conversationIds.length > 0 ? ` OR ConversationID IN (${sqlInList(conversationIds)})` : '';
|
|
49
|
+
const taskView = `[${tasks.SchemaName}].[${tasks.BaseView}]`;
|
|
50
|
+
return (`(UserID = '${EscapeSQLString(user.ID)}'${inConversations}) AND ID IN ` +
|
|
51
|
+
`(SELECT [ConversationDetailID] FROM ${taskView} WHERE [ParentID] IS NULL AND [ConversationDetailID] IS NOT NULL)`);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The IDs of the rows `read` selects, with no row cap; null when the read fails. Each caller names
|
|
55
|
+
* an MJ core entity in `read`, so its key column is `ID`.
|
|
56
|
+
*/
|
|
57
|
+
async function readIds(rv, user, read) {
|
|
58
|
+
const result = await rv.RunView({ ...read, ResultType: 'simple', IgnoreMaxRows: true }, user);
|
|
59
|
+
if (!result.Success) {
|
|
60
|
+
console.error(`Failed to read ${read.EntityName} for the tasks filter:`, result.ErrorMessage);
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return (result.Results ?? []).map(row => row.ID);
|
|
64
|
+
}
|
|
65
|
+
/** A quoted, comma-separated list of IDs for an IN clause. */
|
|
66
|
+
function sqlInList(ids) {
|
|
67
|
+
return ids.map(id => `'${EscapeSQLString(id)}'`).join(',');
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=conversation-tasks-filter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-tasks-filter.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-tasks-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA8E,MAAM,sBAAsB,CAAC;AAC3H,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,2DAA2D;AAC3D,MAAM,UAAU,cAAc,CAAC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AE,KAAiB;IAC/F,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,0BAA0B,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAClH,MAAM,QAAQ,GAAG,IAAI,KAAK,CAAC,UAAU,MAAM,KAAK,CAAC,QAAQ,GAAG,CAAC;IAC7D,OAAO,CACL,cAAc,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,eAAe,cAAc;QACvE,uCAAuC,QAAQ,mEAAmE,CACnH,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,OAAO,CAAC,EAAW,EAAE,IAAc,EAAE,IAAkE;IACpH,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,OAAO,CAAiB,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC;IAC9G,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,kBAAkB,IAAI,CAAC,UAAU,wBAAwB,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;QAC9F,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC;AAED,8DAA8D;AAC9D,SAAS,SAAS,CAAC,GAAsB;IACvC,OAAO,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { RunView, type EntityInfo, type IMetadataProvider, type RunViewParams, type UserInfo } from '@memberjunction/core';\nimport { EscapeSQLString } from '@memberjunction/global';\n\n/** The ExtraFilter for the top-level tasks a user owns. */\nexport function OwnTasksFilter(user: UserInfo): string {\n return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}'`;\n}\n\n/**\n * The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user\n * owns, and the tasks linked to a message the user wrote or that is in a conversation the user\n * owns.\n *\n * The conversation and message IDs are read with their own RunView, so the row-level security on\n * those entities applies. A subquery over their views would skip it, and the server refuses one\n * for a user whose read of them is row-filtered. When a read fails, the result is the user's own\n * tasks.\n */\nexport async function BuildConversationTasksFilter(provider: IMetadataProvider, user: UserInfo): Promise<string> {\n const ownTasks = OwnTasksFilter(user);\n const tasks = provider.EntityByName('MJ: Tasks');\n if (!tasks) {\n return ownTasks;\n }\n const rv = RunView.FromMetadataProvider(provider);\n const conversationIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversations',\n ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,\n Fields: ['ID'],\n });\n if (conversationIds == null) {\n return ownTasks;\n }\n const messageIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: taskMessagesFilter(user, conversationIds, tasks),\n Fields: ['ID'],\n });\n if (messageIds == null || messageIds.length === 0) {\n return ownTasks;\n }\n return `ParentID IS NULL AND (UserID = '${EscapeSQLString(user.ID)}' OR ConversationDetailID IN (${sqlInList(messageIds)}))`;\n}\n\n/**\n * The messages that have a top-level task and that the user wrote or that are in one of the\n * user's conversations. The task subquery reads Tasks, which has no row filter in a default\n * install. Its identifiers are bracketed so the PostgreSQL provider quotes them.\n */\nfunction taskMessagesFilter(user: UserInfo, conversationIds: readonly string[], tasks: EntityInfo): string {\n const inConversations = conversationIds.length > 0 ? ` OR ConversationID IN (${sqlInList(conversationIds)})` : '';\n const taskView = `[${tasks.SchemaName}].[${tasks.BaseView}]`;\n return (\n `(UserID = '${EscapeSQLString(user.ID)}'${inConversations}) AND ID IN ` +\n `(SELECT [ConversationDetailID] FROM ${taskView} WHERE [ParentID] IS NULL AND [ConversationDetailID] IS NOT NULL)`\n );\n}\n\n/**\n * The IDs of the rows `read` selects, with no row cap; null when the read fails. Each caller names\n * an MJ core entity in `read`, so its key column is `ID`.\n */\nasync function readIds(rv: RunView, user: UserInfo, read: Pick<RunViewParams, 'EntityName' | 'ExtraFilter' | 'Fields'>): Promise<string[] | null> {\n const result = await rv.RunView<{ ID: string }>({ ...read, ResultType: 'simple', IgnoreMaxRows: true }, user);\n if (!result.Success) {\n console.error(`Failed to read ${read.EntityName} for the tasks filter:`, result.ErrorMessage);\n return null;\n }\n return (result.Results ?? []).map(row => row.ID);\n}\n\n/** A quoted, comma-separated list of IDs for an IN clause. */\nfunction sqlInList(ids: readonly string[]): string {\n return ids.map(id => `'${EscapeSQLString(id)}'`).join(',');\n}\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Browser-side audio recorder for a CLIENT-DIRECT realtime voice session.
|
|
3
3
|
*
|
|
4
|
-
* Mixes the user's microphone stream with the agent's remote-audio stream (
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Mixes the user's microphone stream with the agent's remote-audio stream (every driver exposes
|
|
5
|
+
* one via `GetRemoteMediaStream()`: WebRTC drivers publish their remote track, PCM drivers —
|
|
6
|
+
* Gemini, ElevenLabs, AssemblyAI, xAI, HuggingFace — publish their playout engine's output) into a
|
|
7
|
+
* single mono **WAV** (16-bit PCM) blob via the Web Audio API. Rather than a `MediaRecorder` (which only emits webm/opus —
|
|
7
8
|
* header-less, no duration/cues, so HTTP-range seeking is unreliable), the mix is routed into an
|
|
8
9
|
* {@link AudioWorkletNode} (preferred) or a {@link ScriptProcessorNode} (fallback) that captures
|
|
9
10
|
* Float32 PCM frames. PCM is accumulated in memory and encoded as a seekable RIFF/WAVE file at
|
|
@@ -15,7 +16,10 @@
|
|
|
15
16
|
* - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself
|
|
16
17
|
* ({@link IsRecording} stays `false`, {@link Stop} resolves `null`); the voice call proceeds.
|
|
17
18
|
* - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.
|
|
18
|
-
* - No remote stream (
|
|
19
|
+
* - No remote stream yet (e.g. the WebRTC track hasn't landed) → records mic only until it does.
|
|
20
|
+
* - A remote stream that can't be connected (e.g. a browser that rejects cross-sample-rate
|
|
21
|
+
* `createMediaStreamSource` — the PCM playout context runs at 24 kHz, this one at the device
|
|
22
|
+
* rate) → warns and records mic only; the mic recording is never lost to the agent stream.
|
|
19
23
|
* - Any construction/start error is logged and disables the recorder rather than throwing into
|
|
20
24
|
* the session-start path.
|
|
21
25
|
*
|
|
@@ -55,6 +59,12 @@ export declare class RealtimeAudioRecorder {
|
|
|
55
59
|
private startedAtMs;
|
|
56
60
|
/** Sample rate of the capturing {@link AudioContext}; 0 before {@link Start}. Needed to wrap shards. */
|
|
57
61
|
private sampleRate;
|
|
62
|
+
/**
|
|
63
|
+
* Bumped by {@link cleanup}. The async setup snapshots it and, after each await, gives up if it moved:
|
|
64
|
+
* a {@link Stop} that lands mid-setup can only release what setup has already published, so setup
|
|
65
|
+
* must release the rest itself rather than build a live graph on a stopped recorder.
|
|
66
|
+
*/
|
|
67
|
+
private setupGeneration;
|
|
58
68
|
/** True while a recorder is actively capturing. */
|
|
59
69
|
get IsRecording(): boolean;
|
|
60
70
|
/** Wall-clock ms when recording started (0 before {@link Start}). */
|
|
@@ -111,6 +121,13 @@ export declare class RealtimeAudioRecorder {
|
|
|
111
121
|
Stop(): Promise<Blob | null>;
|
|
112
122
|
/** Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture. */
|
|
113
123
|
private startMixedRecording;
|
|
124
|
+
/**
|
|
125
|
+
* Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure
|
|
126
|
+
* rightly disables the recorder), the agent stream is best-effort: a browser may reject it
|
|
127
|
+
* (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.
|
|
128
|
+
* Returns whether it was connected, so the caller only marks it attached on success.
|
|
129
|
+
*/
|
|
130
|
+
private connectRemoteStream;
|
|
114
131
|
/**
|
|
115
132
|
* Creates the PCM capture node and inserts it into the graph: sources → captureNode → destination.
|
|
116
133
|
* Prefers an {@link AudioWorkletNode} (off-main-thread, no deprecation); falls back to a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"realtime-audio-recorder.d.ts","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"realtime-audio-recorder.d.ts","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,qBAAqB;IAC9B,2EAA2E;IAC3E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAe;IAClD,4EAA4E;IAC5E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAO;IAC1C,mGAAmG;IACnG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAAQ;IACzD,kGAAkG;IAClG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,CAY5C;IAEF,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,WAAW,CAAgD;IACnE,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,UAAU,CAAoC;IACtD,kGAAkG;IAClG,OAAO,CAAC,SAAS,CAAsB;IACvC,+FAA+F;IAC/F,OAAO,CAAC,YAAY,CAAK;IACzB,oFAAoF;IACpF,OAAO,CAAC,KAAK,CAA0D;IACvE,gGAAgG;IAChG,OAAO,CAAC,UAAU,CAAgB;IAClC,OAAO,CAAC,SAAS,CAAS;IAE1B,gGAAgG;IAChG,OAAO,CAAC,cAAc,CAAS;IAC/B,qGAAqG;IACrG,OAAO,CAAC,mBAAmB,CAA4B;IAEvD,qGAAqG;IACrG,OAAO,CAAC,k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