@memberjunction/ng-conversations 6.2.0-edge.1 → 6.2.0-edge.2
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/README.md +9 -1
- package/dist/lib/components/conversation/conversation-agent-picker.component.js +1 -1
- package/dist/lib/components/conversation/conversation-agent-picker.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +102 -2
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.js +457 -119
- package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
- package/dist/lib/components/conversation/pinned-messages-panel.component.d.ts +3 -1
- package/dist/lib/components/conversation/pinned-messages-panel.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/pinned-messages-panel.component.js +22 -8
- package/dist/lib/components/conversation/pinned-messages-panel.component.js.map +1 -1
- package/dist/lib/components/message/actionable-commands.component.d.ts +12 -0
- package/dist/lib/components/message/actionable-commands.component.d.ts.map +1 -1
- package/dist/lib/components/message/actionable-commands.component.js +60 -12
- package/dist/lib/components/message/actionable-commands.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.d.ts +68 -4
- package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-input.component.js +161 -22
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/message/message-item.component.d.ts +80 -1
- package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-item.component.js +193 -23
- package/dist/lib/components/message/message-item.component.js.map +1 -1
- package/dist/lib/components/message/message-list.component.d.ts +10 -1
- package/dist/lib/components/message/message-list.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-list.component.js +38 -1
- package/dist/lib/components/message/message-list.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +4 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/models/agent-turn.model.d.ts +12 -2
- package/dist/lib/models/agent-turn.model.d.ts.map +1 -1
- package/dist/lib/models/agent-turn.model.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +21 -0
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +28 -2
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-liveness-dom.service.d.ts +42 -0
- package/dist/lib/services/conversation-liveness-dom.service.d.ts.map +1 -0
- package/dist/lib/services/conversation-liveness-dom.service.js +74 -0
- package/dist/lib/services/conversation-liveness-dom.service.js.map +1 -0
- package/dist/lib/services/ui-command-handler.service.d.ts +40 -3
- package/dist/lib/services/ui-command-handler.service.d.ts.map +1 -1
- package/dist/lib/services/ui-command-handler.service.js +78 -9
- package/dist/lib/services/ui-command-handler.service.js.map +1 -1
- package/dist/lib/utils/agent-turn-routing.d.ts +7 -6
- package/dist/lib/utils/agent-turn-routing.d.ts.map +1 -1
- package/dist/lib/utils/agent-turn-routing.js +4 -16
- package/dist/lib/utils/agent-turn-routing.js.map +1 -1
- package/dist/lib/utils/decision-routing.d.ts +68 -0
- package/dist/lib/utils/decision-routing.d.ts.map +1 -0
- package/dist/lib/utils/decision-routing.js +101 -0
- package/dist/lib/utils/decision-routing.js.map +1 -0
- package/dist/public-api.d.ts +2 -0
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +5 -0
- package/dist/public-api.js.map +1 -1
- package/package.json +32 -32
|
@@ -24,13 +24,15 @@ export type AgentReplyMode = 'Always' | 'MentionOnly';
|
|
|
24
24
|
* - `Mention`: the message tags the agent.
|
|
25
25
|
* - `Continuity`: the last agent that answered in the conversation, other than the
|
|
26
26
|
* conversation manager.
|
|
27
|
+
* - `DecisionRouted`: another agent in the conversation, which a confident routing decision chose
|
|
28
|
+
* in continuity's place. Only with the chat's `EnableDecisionRouting` on.
|
|
27
29
|
* - `ConversationDefault`: the agent pinned on the conversation (`Conversation.DefaultAgentID`).
|
|
28
30
|
* - `HostDefault`: the host's `DefaultAgentId` input.
|
|
29
31
|
* - `ConversationManager`: MJ's conversation manager agent (Sage unless configured otherwise),
|
|
30
32
|
* which may delegate to another agent.
|
|
31
33
|
* - `Redirect`: a `BeforeAgentTurn` listener sent the turn to a different agent.
|
|
32
34
|
*/
|
|
33
|
-
export type AgentTurnRoute = 'Mention' | 'Continuity' | 'ConversationDefault' | 'HostDefault' | 'ConversationManager' | 'Redirect';
|
|
35
|
+
export type AgentTurnRoute = 'Mention' | 'Continuity' | 'DecisionRouted' | 'ConversationDefault' | 'HostDefault' | 'ConversationManager' | 'Redirect';
|
|
34
36
|
/** The agent a turn resolved to, and the route that chose it. */
|
|
35
37
|
export interface AgentTurnTarget {
|
|
36
38
|
/** The agent that takes the turn. */
|
|
@@ -77,6 +79,12 @@ export interface AgentTurnRequest {
|
|
|
77
79
|
RequestedSkillIDs: string[];
|
|
78
80
|
/** Whether Plan Mode is on for the conversation. */
|
|
79
81
|
PlanMode: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* The artifact version (`MJ: Artifact Versions.ID`) the message modifies, when the chat's
|
|
84
|
+
* routing decision (`EnableDecisionRouting`) confidently named one this agent produced. MJ's
|
|
85
|
+
* own path continues from that version instead of the agent's latest output. Null otherwise.
|
|
86
|
+
*/
|
|
87
|
+
TargetArtifactVersionId: string | null;
|
|
80
88
|
}
|
|
81
89
|
/** What an {@link AgentTurnHandler} reports back to the chat area. */
|
|
82
90
|
export interface AgentTurnResult {
|
|
@@ -87,7 +95,9 @@ export interface AgentTurnResult {
|
|
|
87
95
|
/**
|
|
88
96
|
* The rows the host wrote for the turn, oldest first: the agent's reply and any status rows.
|
|
89
97
|
* The chat area loads and shows them. A row still `In-Progress` is followed like any other
|
|
90
|
-
* in-progress reply.
|
|
98
|
+
* in-progress reply. The host reports that row's live status through `AgentRunStatusPublisher`
|
|
99
|
+
* (`@memberjunction/server`) on the caller's session: significant-step progress, streamed text,
|
|
100
|
+
* the partial result, and the completion. The completion's `conversationDetailId` is the reply row.
|
|
91
101
|
*/
|
|
92
102
|
ReplyDetailIds?: string[];
|
|
93
103
|
/** The agent run, when the host has one. Carried on `AfterAgentTurn`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-turn.model.d.ts","sourceRoot":"","sources":["../../../src/lib/models/agent-turn.model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEtD
|
|
1
|
+
{"version":3,"file":"agent-turn.model.d.ts","sourceRoot":"","sources":["../../../src/lib/models/agent-turn.model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEtD;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,cAAc,GACpB,SAAS,GACT,YAAY,GACZ,gBAAgB,GAChB,qBAAqB,GACrB,aAAa,GACb,qBAAqB,GACrB,UAAU,CAAC;AAEjB,iEAAiE;AACjE,MAAM,WAAW,eAAe;IAC5B,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,gCAAgC;IAChC,KAAK,EAAE,cAAc,CAAC;CACzB;AAED,8EAA8E;AAC9E,MAAM,WAAW,aAAc,SAAQ,eAAe;IAClD,0CAA0C;IAC1C,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,wDAAwD;IACxD,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC7B,kDAAkD;IAClD,cAAc,EAAE,MAAM,CAAC;IACvB,4EAA4E;IAC5E,aAAa,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,WAAW,EAAE,MAAM,CAAC;IACpB,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAC;IAChB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,gCAAgC;IAChC,KAAK,EAAE,cAAc,CAAC;IACtB,6CAA6C;IAC7C,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,0CAA0C;IAC1C,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC3C,wGAAwG;IACxG,gBAAgB,EAAE,IAAI,GAAG,IAAI,CAAC;IAC9B;;;OAGG;IACH,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,iEAAiE;IACjE,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,oDAAoD;IACpD,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,uBAAuB,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1C;AAED,sEAAsE;AACtE,MAAM,WAAW,eAAe;IAC5B,+FAA+F;IAC/F,OAAO,EAAE,OAAO,CAAC;IACjB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,yEAAyE;IACzE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gGAAgG;IAChG,MAAM,CAAC,EAAE,kBAAkB,CAAC;CAC/B;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-turn.model.js","sourceRoot":"","sources":["../../../src/lib/models/agent-turn.model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * @fileoverview The host-facing contract for an agent turn in `mj-conversation-chat-area`.\n *\n * An agent turn is what may follow a person's saved message. The chat area picks one agent by a\n * fixed order of routes, announces the turn with `BeforeAgentTurn` (which a host can cancel or\n * redirect), and then runs it: on MJ's own path, or on the host's server through an\n * {@link AgentTurnHandler}. These types are what a host reads and writes along the way.\n *\n * @module @memberjunction/ng-conversations\n */\n\nimport type { ExecuteAgentResult } from '@memberjunction/ai-core-plus';\n\n/**\n * When a message starts an agent turn.\n *\n * - `Always` (the default): every message does, as it always has.\n * - `MentionOnly`: only a message that tags an agent does. Any other message is posted with no\n * turn at all: no reply row, no placeholder and no turn events.\n */\nexport type AgentReplyMode = 'Always' | 'MentionOnly';\n\n/**\n * How the turn's agent was chosen. MJ tries the routes in this order and takes the first that\n * applies; under `MentionOnly`, only `Mention` applies.\n *\n * - `Mention`: the message tags the agent.\n * - `Continuity`: the last agent that answered in the conversation, other than the\n * conversation manager.\n * - `ConversationDefault`: the agent pinned on the conversation (`Conversation.DefaultAgentID`).\n * - `HostDefault`: the host's `DefaultAgentId` input.\n * - `ConversationManager`: MJ's conversation manager agent (Sage unless configured otherwise),\n * which may delegate to another agent.\n * - `Redirect`: a `BeforeAgentTurn` listener sent the turn to a different agent.\n */\nexport type AgentTurnRoute =\n | 'Mention'\n | 'Continuity'\n | 'ConversationDefault'\n | 'HostDefault'\n | 'ConversationManager'\n | 'Redirect';\n\n/** The agent a turn resolved to, and the route that chose it. */\nexport interface AgentTurnTarget {\n /** The agent that takes the turn. */\n AgentId: string;\n /** How the agent was chosen. */\n Route: AgentTurnRoute;\n}\n\n/** What `BeforeAgentTurn` tells its listeners about the turn it announces. */\nexport interface AgentTurnInfo extends AgentTurnTarget {\n /** The agent's name, when MJ knows it. */\n AgentName: string | null;\n /** The person's saved message that the turn answers. */\n UserMessageId: string | null;\n}\n\n/**\n * Everything the chat area knows about a turn it hands to an {@link AgentTurnHandler}.\n * No reply row exists yet when the handler is called.\n */\nexport interface AgentTurnRequest {\n /** The conversation the message was posted in. */\n ConversationId: string;\n /** The person's saved message (`MJ: Conversation Details`, Role `User`). */\n UserMessageId: string;\n /** The message text, with mentions in their stored JSON form. */\n MessageText: string;\n /** The agent the turn resolved to, after any redirect. */\n AgentId: string;\n /** The agent's name, when MJ knows it. */\n AgentName: string | null;\n /** How the agent was chosen. */\n Route: AgentTurnRoute;\n /** The chat area's `ApplicationId` input. */\n ApplicationId: string | null;\n /** The chat area's `AppContext` input. */\n AppContext: Record<string, unknown> | null;\n /** The chat area's `AgentHistoryFrom` input: the first moment of the conversation the turn may read. */\n AgentHistoryFrom: Date | null;\n /**\n * The agent configuration preset (`MJ: AI Agent Configurations.ID`) the person chose: the one\n * on the mention for a `Mention` turn, otherwise the header mode picker's selection.\n */\n ConfigurationPresetId: string | null;\n /** Skills the person asked for with `/skill` in this message. */\n RequestedSkillIDs: string[];\n /** Whether Plan Mode is on for the conversation. */\n PlanMode: boolean;\n}\n\n/** What an {@link AgentTurnHandler} reports back to the chat area. */\nexport interface AgentTurnResult {\n /** False when the turn failed. The chat area shows {@link ErrorMessage} and writes nothing. */\n Success: boolean;\n /** Why the turn failed, shown to the person. */\n ErrorMessage?: string;\n /**\n * The rows the host wrote for the turn, oldest first: the agent's reply and any status rows.\n * The chat area loads and shows them. A row still `In-Progress` is followed like any other\n * in-progress reply.\n */\n ReplyDetailIds?: string[];\n /** The agent run, when the host has one. Carried on `AfterAgentTurn`. */\n AgentRunId?: string;\n /** The agent's result, when the host has one. `AfterAgentTurn` fires only when it's present. */\n Result?: ExecuteAgentResult;\n}\n\n/**\n * Runs an agent turn on the host's server instead of MJ's own path. The chat area calls it once\n * per turn, after `BeforeAgentTurn` and before any reply row exists, and shows the rows it reports.\n */\nexport type AgentTurnHandler = (request: AgentTurnRequest) => Promise<AgentTurnResult>;\n"]}
|
|
1
|
+
{"version":3,"file":"agent-turn.model.js","sourceRoot":"","sources":["../../../src/lib/models/agent-turn.model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * @fileoverview The host-facing contract for an agent turn in `mj-conversation-chat-area`.\n *\n * An agent turn is what may follow a person's saved message. The chat area picks one agent by a\n * fixed order of routes, announces the turn with `BeforeAgentTurn` (which a host can cancel or\n * redirect), and then runs it: on MJ's own path, or on the host's server through an\n * {@link AgentTurnHandler}. These types are what a host reads and writes along the way.\n *\n * @module @memberjunction/ng-conversations\n */\n\nimport type { ExecuteAgentResult } from '@memberjunction/ai-core-plus';\n\n/**\n * When a message starts an agent turn.\n *\n * - `Always` (the default): every message does, as it always has.\n * - `MentionOnly`: only a message that tags an agent does. Any other message is posted with no\n * turn at all: no reply row, no placeholder and no turn events.\n */\nexport type AgentReplyMode = 'Always' | 'MentionOnly';\n\n/**\n * How the turn's agent was chosen. MJ tries the routes in this order and takes the first that\n * applies; under `MentionOnly`, only `Mention` applies.\n *\n * - `Mention`: the message tags the agent.\n * - `Continuity`: the last agent that answered in the conversation, other than the\n * conversation manager.\n * - `DecisionRouted`: another agent in the conversation, which a confident routing decision chose\n * in continuity's place. Only with the chat's `EnableDecisionRouting` on.\n * - `ConversationDefault`: the agent pinned on the conversation (`Conversation.DefaultAgentID`).\n * - `HostDefault`: the host's `DefaultAgentId` input.\n * - `ConversationManager`: MJ's conversation manager agent (Sage unless configured otherwise),\n * which may delegate to another agent.\n * - `Redirect`: a `BeforeAgentTurn` listener sent the turn to a different agent.\n */\nexport type AgentTurnRoute =\n | 'Mention'\n | 'Continuity'\n | 'DecisionRouted'\n | 'ConversationDefault'\n | 'HostDefault'\n | 'ConversationManager'\n | 'Redirect';\n\n/** The agent a turn resolved to, and the route that chose it. */\nexport interface AgentTurnTarget {\n /** The agent that takes the turn. */\n AgentId: string;\n /** How the agent was chosen. */\n Route: AgentTurnRoute;\n}\n\n/** What `BeforeAgentTurn` tells its listeners about the turn it announces. */\nexport interface AgentTurnInfo extends AgentTurnTarget {\n /** The agent's name, when MJ knows it. */\n AgentName: string | null;\n /** The person's saved message that the turn answers. */\n UserMessageId: string | null;\n}\n\n/**\n * Everything the chat area knows about a turn it hands to an {@link AgentTurnHandler}.\n * No reply row exists yet when the handler is called.\n */\nexport interface AgentTurnRequest {\n /** The conversation the message was posted in. */\n ConversationId: string;\n /** The person's saved message (`MJ: Conversation Details`, Role `User`). */\n UserMessageId: string;\n /** The message text, with mentions in their stored JSON form. */\n MessageText: string;\n /** The agent the turn resolved to, after any redirect. */\n AgentId: string;\n /** The agent's name, when MJ knows it. */\n AgentName: string | null;\n /** How the agent was chosen. */\n Route: AgentTurnRoute;\n /** The chat area's `ApplicationId` input. */\n ApplicationId: string | null;\n /** The chat area's `AppContext` input. */\n AppContext: Record<string, unknown> | null;\n /** The chat area's `AgentHistoryFrom` input: the first moment of the conversation the turn may read. */\n AgentHistoryFrom: Date | null;\n /**\n * The agent configuration preset (`MJ: AI Agent Configurations.ID`) the person chose: the one\n * on the mention for a `Mention` turn, otherwise the header mode picker's selection.\n */\n ConfigurationPresetId: string | null;\n /** Skills the person asked for with `/skill` in this message. */\n RequestedSkillIDs: string[];\n /** Whether Plan Mode is on for the conversation. */\n PlanMode: boolean;\n /**\n * The artifact version (`MJ: Artifact Versions.ID`) the message modifies, when the chat's\n * routing decision (`EnableDecisionRouting`) confidently named one this agent produced. MJ's\n * own path continues from that version instead of the agent's latest output. Null otherwise.\n */\n TargetArtifactVersionId: string | null;\n}\n\n/** What an {@link AgentTurnHandler} reports back to the chat area. */\nexport interface AgentTurnResult {\n /** False when the turn failed. The chat area shows {@link ErrorMessage} and writes nothing. */\n Success: boolean;\n /** Why the turn failed, shown to the person. */\n ErrorMessage?: string;\n /**\n * The rows the host wrote for the turn, oldest first: the agent's reply and any status rows.\n * The chat area loads and shows them. A row still `In-Progress` is followed like any other\n * in-progress reply. The host reports that row's live status through `AgentRunStatusPublisher`\n * (`@memberjunction/server`) on the caller's session: significant-step progress, streamed text,\n * the partial result, and the completion. The completion's `conversationDetailId` is the reply row.\n */\n ReplyDetailIds?: string[];\n /** The agent run, when the host has one. Carried on `AfterAgentTurn`. */\n AgentRunId?: string;\n /** The agent's result, when the host has one. `AfterAgentTurn` fires only when it's present. */\n Result?: ExecuteAgentResult;\n}\n\n/**\n * Runs an agent turn on the host's server instead of MJ's own path. The chat area calls it once\n * per turn, after `BeforeAgentTurn` and before any reply row exists, and shows the rows it reports.\n */\nexport type AgentTurnHandler = (request: AgentTurnRequest) => Promise<AgentTurnResult>;\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Observable } from 'rxjs';
|
|
2
2
|
import { IMetadataProvider } from '@memberjunction/core';
|
|
3
|
+
import { type RunDecisionParams, type RunDecisionResult } from '@memberjunction/graphql-dataprovider';
|
|
3
4
|
import { ExecuteAgentResult, AgentExecutionProgressCallback } from '@memberjunction/ai-core-plus';
|
|
4
5
|
import { MJConversationDetailEntity } from '@memberjunction/core-entities';
|
|
5
6
|
import { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended } from '@memberjunction/ai-core-plus';
|
|
@@ -7,6 +8,7 @@ import { AgentClientService } from '@memberjunction/ng-agent-client';
|
|
|
7
8
|
import { LazyArtifactInfo } from '../models/lazy-artifact-info';
|
|
8
9
|
import { MentionParserService } from './mention-parser.service';
|
|
9
10
|
import { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';
|
|
11
|
+
import { type AgentArtifactSummary } from '../utils/agent-artifact-summary';
|
|
10
12
|
import * as i0 from "@angular/core";
|
|
11
13
|
/**
|
|
12
14
|
* Context for artifact lookups — pre-loaded conversation data.
|
|
@@ -187,6 +189,23 @@ export declare class ConversationAgentService {
|
|
|
187
189
|
CheckAgentContinuityIntent(conversationId: string, agentId: string, latestMessage: string, conversationHistory: MJConversationDetailEntity[]): Promise<IntentCheckResult>;
|
|
188
190
|
/** @deprecated Use {@link CheckAgentContinuityIntent}. */
|
|
189
191
|
checkAgentContinuityIntent(conversationId: string, agentId: string, latestMessage: string, conversationHistory: MJConversationDetailEntity[]): Promise<IntentCheckResult>;
|
|
192
|
+
/**
|
|
193
|
+
* Runs a typed decision on the server in one round trip, through
|
|
194
|
+
* {@link GraphQLAIClient.RunDecision}. Decision routing (`EnableDecisionRouting`) asks its
|
|
195
|
+
* routing questions here.
|
|
196
|
+
*
|
|
197
|
+
* Never throws: without an AI client, or on any failure, it resolves with `Success: false` and
|
|
198
|
+
* no answers.
|
|
199
|
+
*/
|
|
200
|
+
RunDecision(params: RunDecisionParams): Promise<RunDecisionResult>;
|
|
201
|
+
/**
|
|
202
|
+
* Every artifact this agent produced in this conversation, newest version first, for decision
|
|
203
|
+
* routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.
|
|
204
|
+
*
|
|
205
|
+
* @param historyFrom The chat's history floor. When set, only artifacts on replies written at or
|
|
206
|
+
* after it count, as with {@link FindLatestAgentOutputVersion}.
|
|
207
|
+
*/
|
|
208
|
+
FindAgentArtifacts(conversationId: string, agentId: string, historyFrom?: Date | null): Promise<AgentArtifactSummary[]>;
|
|
190
209
|
/**
|
|
191
210
|
* Every artifact this agent produced in this conversation, newest version first — resolved
|
|
192
211
|
* by QUERY, not by scanning the display array.
|
|
@@ -205,6 +224,8 @@ export declare class ConversationAgentService {
|
|
|
205
224
|
*
|
|
206
225
|
* Two reads, not the four the old shape would have needed — see
|
|
207
226
|
* {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.
|
|
227
|
+
*
|
|
228
|
+
* @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).
|
|
208
229
|
*/
|
|
209
230
|
private findAllAgentArtifacts;
|
|
210
231
|
/** Names and types for the artifacts behind a set of versions. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-agent.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAY,iBAAiB,EAAW,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version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AAE,MAAM,EACf,aAAa,EAAE,MAAM,EACrB,mBAAmB,EAAE,0BAA0B,EAAE,GAChD,OAAO,CAAC,iBAAiB,CAAC;IA0G7B,0DAA0D;IACpD,0BAA0B,CAC9B,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,EACrB,mBAAmB,EAAE,0BAA0B,EAAE,GAChD,OAAO,CAAC,iBAAiB,CAAC;IAI7B;;;;;;;OAOG;IACU,WAAW,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAO/E;;;;;;OAMG;IACU,kBAAkB,CAC7B,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,IAAI,GAAG,IAAI,GACxB,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAIlC;;;;;;;;;;;;;;;;;;;;OAoBG;YACW,qBAAqB;IAgCnC,kEAAkE;YACpD,iBAAiB;IAoB/B;;;;;;;;;;;;;;;;OAgBG;IACU,4BAA4B,CACvC,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,IAAI,GAAG,IAAI,GACxB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAMrC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,wBAAwB;IAYhC;;;;;;OAMG;IACU,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAI3F;;;;;OAKG;YACW,qBAAqB;yCA7rBxB,wBAAwB;6CAAxB,wBAAwB;CA6tBpC"}
|
|
@@ -458,6 +458,30 @@ ${compactHistory}${artifactContext}
|
|
|
458
458
|
async checkAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory) {
|
|
459
459
|
return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory);
|
|
460
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* Runs a typed decision on the server in one round trip, through
|
|
463
|
+
* {@link GraphQLAIClient.RunDecision}. Decision routing (`EnableDecisionRouting`) asks its
|
|
464
|
+
* routing questions here.
|
|
465
|
+
*
|
|
466
|
+
* Never throws: without an AI client, or on any failure, it resolves with `Success: false` and
|
|
467
|
+
* no answers.
|
|
468
|
+
*/
|
|
469
|
+
async RunDecision(params) {
|
|
470
|
+
if (!this._aiClient) {
|
|
471
|
+
return { Success: false, ErrorMessage: 'AI Client not initialized', Answers: {} };
|
|
472
|
+
}
|
|
473
|
+
return this._aiClient.RunDecision(params);
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Every artifact this agent produced in this conversation, newest version first, for decision
|
|
477
|
+
* routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.
|
|
478
|
+
*
|
|
479
|
+
* @param historyFrom The chat's history floor. When set, only artifacts on replies written at or
|
|
480
|
+
* after it count, as with {@link FindLatestAgentOutputVersion}.
|
|
481
|
+
*/
|
|
482
|
+
async FindAgentArtifacts(conversationId, agentId, historyFrom) {
|
|
483
|
+
return this.findAllAgentArtifacts(conversationId, agentId, historyFrom);
|
|
484
|
+
}
|
|
461
485
|
/**
|
|
462
486
|
* Every artifact this agent produced in this conversation, newest version first — resolved
|
|
463
487
|
* by QUERY, not by scanning the display array.
|
|
@@ -476,12 +500,14 @@ ${compactHistory}${artifactContext}
|
|
|
476
500
|
*
|
|
477
501
|
* Two reads, not the four the old shape would have needed — see
|
|
478
502
|
* {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.
|
|
503
|
+
*
|
|
504
|
+
* @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).
|
|
479
505
|
*/
|
|
480
|
-
async findAllAgentArtifacts(conversationId, agentId) {
|
|
506
|
+
async findAllAgentArtifacts(conversationId, agentId, historyFrom) {
|
|
481
507
|
const rv = RunView.FromMetadataProvider(this.Provider);
|
|
482
508
|
const versionResult = await rv.RunView({
|
|
483
509
|
EntityName: 'MJ: Artifact Versions',
|
|
484
|
-
ExtraFilter: this.agentOutputVersionFilter(conversationId, agentId),
|
|
510
|
+
ExtraFilter: this.agentOutputVersionFilter(conversationId, agentId, historyFrom),
|
|
485
511
|
OrderBy: '__mj_CreatedAt DESC',
|
|
486
512
|
MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,
|
|
487
513
|
Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],
|
|
@@ -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;AAC9D,OAAO,EACL,kBAAkB,EAInB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAG7E,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGpD,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;IAmBzB;IACA;IAnBV,2GAA2G;IACnG,SAAS,GAA2B,IAAI,CAAC;IACjD,2EAA2E;IACnE,yBAAyB,GAAmC,IAAI,CAAC;IACjE,WAAW,GAAwB,IAAI,GAAG,EA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E,MAAM;aACnB;;AA+rBD;;;;;;;;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 ConversationEngine,\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 /** @deprecated Use {@link IsProcessing$}. */\n public get isProcessing$(): Observable<boolean> {\n return this.IsProcessing$;\n }\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 /** @deprecated Use {@link GetConversationManagerAgent}. */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n return this.GetConversationManagerAgent();\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 /** The agents the conversation manager may delegate to. Null or omitted allows every agent. */\n allowedAgentIDs?: readonly string[] | null,\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\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 ...(allowedAgentIDs != null ? { AllowedAgentIDs: allowedAgentIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n });\n }\n\n /** @deprecated Use {@link ProcessMessage}. */\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 allowedAgentIDs?: readonly string[] | null,\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.ProcessMessage(conversationId, message, conversationHistory, conversationDetailId, onProgress, appContext, planMode, requestedSkillIDs, allowedAgentIDs, agentHistoryFrom);\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 /** @deprecated Use {@link ClearSession}. */\n clearSession(conversationId: string): void {\n return this.ClearSession(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 /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\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 ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\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 /** @deprecated Use {@link InvokeSubAgent}. */\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 agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.InvokeSubAgent(agentName, conversationId, message, conversationHistory, reasoning, conversationDetailId, payload, onProgress, sourceArtifactId, sourceArtifactVersionId, agentConfigurationPresetId, appContext, planMode, requestedSkillIDs, agentHistoryFrom);\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 /** @deprecated Use {@link CheckAgentContinuityIntent}. */\n async checkAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\n ): Promise<IntentCheckResult> {\n return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory);\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 * @param historyFrom The chat's history floor. When set, only artifacts on replies written at\n * or after it count: a run that may not read earlier messages must not pick up their work\n * as its payload either.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(\n this.agentOutputVersionFilter(conversationId, agentId, historyFrom), '__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, historyFrom?: Date | null): string {\n const floor = historyFrom ? ` AND ${ConversationEngine.HistoryFromFilter(historyFrom)}` : '';\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'${floor}\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,EAAkD,MAAM,sCAAsC,CAAC;AAC5I,OAAO,EAAsD,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAClI,O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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, type RunDecisionParams, type RunDecisionResult } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport {\n ConversationEngine,\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 /** @deprecated Use {@link IsProcessing$}. */\n public get isProcessing$(): Observable<boolean> {\n return this.IsProcessing$;\n }\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 /** @deprecated Use {@link GetConversationManagerAgent}. */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n return this.GetConversationManagerAgent();\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 /** The agents the conversation manager may delegate to. Null or omitted allows every agent. */\n allowedAgentIDs?: readonly string[] | null,\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\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 ...(allowedAgentIDs != null ? { AllowedAgentIDs: allowedAgentIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n });\n }\n\n /** @deprecated Use {@link ProcessMessage}. */\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 allowedAgentIDs?: readonly string[] | null,\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.ProcessMessage(conversationId, message, conversationHistory, conversationDetailId, onProgress, appContext, planMode, requestedSkillIDs, allowedAgentIDs, agentHistoryFrom);\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 /** @deprecated Use {@link ClearSession}. */\n clearSession(conversationId: string): void {\n return this.ClearSession(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 /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\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 ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\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 /** @deprecated Use {@link InvokeSubAgent}. */\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 agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.InvokeSubAgent(agentName, conversationId, message, conversationHistory, reasoning, conversationDetailId, payload, onProgress, sourceArtifactId, sourceArtifactVersionId, agentConfigurationPresetId, appContext, planMode, requestedSkillIDs, agentHistoryFrom);\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 /** @deprecated Use {@link CheckAgentContinuityIntent}. */\n async checkAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\n ): Promise<IntentCheckResult> {\n return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory);\n }\n\n /**\n * Runs a typed decision on the server in one round trip, through\n * {@link GraphQLAIClient.RunDecision}. Decision routing (`EnableDecisionRouting`) asks its\n * routing questions here.\n *\n * Never throws: without an AI client, or on any failure, it resolves with `Success: false` and\n * no answers.\n */\n public async RunDecision(params: RunDecisionParams): Promise<RunDecisionResult> {\n if (!this._aiClient) {\n return { Success: false, ErrorMessage: 'AI Client not initialized', Answers: {} };\n }\n return this._aiClient.RunDecision(params);\n }\n\n /**\n * Every artifact this agent produced in this conversation, newest version first, for decision\n * routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.\n *\n * @param historyFrom The chat's history floor. When set, only artifacts on replies written at or\n * after it count, as with {@link FindLatestAgentOutputVersion}.\n */\n public async FindAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentArtifactSummary[]> {\n return this.findAllAgentArtifacts(conversationId, agentId, historyFrom);\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 * @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).\n */\n private async findAllAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\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, historyFrom),\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 * @param historyFrom The chat's history floor. When set, only artifacts on replies written at\n * or after it count: a run that may not read earlier messages must not pick up their work\n * as its payload either.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(\n this.agentOutputVersionFilter(conversationId, agentId, historyFrom), '__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, historyFrom?: Date | null): string {\n const floor = historyFrom ? ` AND ${ConversationEngine.HistoryFromFilter(historyFrom)}` : '';\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'${floor}\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"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { OnDestroy } from '@angular/core';
|
|
2
|
+
import * as i0 from "@angular/core";
|
|
3
|
+
/**
|
|
4
|
+
* Translates browser events into liveness signals for the framework-agnostic
|
|
5
|
+
* `ConversationLiveness` supervisor in `@memberjunction/conversations-runtime` (MJ #4222).
|
|
6
|
+
*
|
|
7
|
+
* WHY THE SPLIT. The supervisor lives at L0 because that package already depends on
|
|
8
|
+
* `@memberjunction/graphql-dataprovider` and has no Angular dependency — and because the
|
|
9
|
+
* obvious alternative is closed to us: Explorer's `ServerConnectivityService` does almost
|
|
10
|
+
* exactly this, but `@memberjunction/ng-conversations` declares `"mjUILayer": "widgets"`, and
|
|
11
|
+
* `packages/Standards/src/checks/ui-layers.ts` forbids that layer from importing any
|
|
12
|
+
* `ng-explorer*` package at severity `error`. L0 cannot own the DOM half either: the runtime is
|
|
13
|
+
* documented as Node-consumable, so `document` and `window` may not exist there. Hence this thin
|
|
14
|
+
* Angular-side adapter, which is the only piece that touches the DOM.
|
|
15
|
+
*
|
|
16
|
+
* WHAT THE SIGNALS MEAN. Neither event proves anything is reachable — `navigator.onLine` reads
|
|
17
|
+
* true behind a captive portal or a dead VPN, and a tab regaining focus says nothing about the
|
|
18
|
+
* server. They are prompts to re-check, and the supervisor coalesces them with the transport-level
|
|
19
|
+
* signals before anyone acts.
|
|
20
|
+
*
|
|
21
|
+
* Root-provided so one instance serves every chat area; several open conversations must not each
|
|
22
|
+
* raise their own reconciliation for the same lid-open.
|
|
23
|
+
*/
|
|
24
|
+
export declare class ConversationLivenessDomService implements OnDestroy {
|
|
25
|
+
/**
|
|
26
|
+
* Stored bound references — `removeEventListener` only detaches a listener when handed the
|
|
27
|
+
* same function object `addEventListener` received. Matches the pattern already used for the
|
|
28
|
+
* resize handlers in `conversation-chat-area.component.ts` and in
|
|
29
|
+
* `packages/Angular/Generic/shared/src/lib/theme.service.ts`.
|
|
30
|
+
*/
|
|
31
|
+
private boundVisibilityHandler;
|
|
32
|
+
private boundOnlineHandler;
|
|
33
|
+
private started;
|
|
34
|
+
/** Begin translating DOM events into liveness signals. Idempotent. */
|
|
35
|
+
Start(): void;
|
|
36
|
+
/** Detach both listeners. Safe to call when never started. */
|
|
37
|
+
Stop(): void;
|
|
38
|
+
ngOnDestroy(): void;
|
|
39
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<ConversationLivenessDomService, never>;
|
|
40
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<ConversationLivenessDomService>;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=conversation-liveness-dom.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-liveness-dom.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/conversation-liveness-dom.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAE,MAAM,eAAe,CAAC;;AAGtD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBACa,8BAA+B,YAAW,SAAS;IAC5D;;;;;OAKG;IACH,OAAO,CAAC,sBAAsB,CAA6B;IAC3D,OAAO,CAAC,kBAAkB,CAA6B;IACvD,OAAO,CAAC,OAAO,CAAS;IAExB,sEAAsE;IAC/D,KAAK,IAAI,IAAI;IAmBpB,8DAA8D;IACvD,IAAI,IAAI,IAAI;IAYZ,WAAW,IAAI,IAAI;yCA5CjB,8BAA8B;6CAA9B,8BAA8B;CA+C1C"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { Injectable } from '@angular/core';
|
|
2
|
+
import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
|
|
3
|
+
import * as i0 from "@angular/core";
|
|
4
|
+
/**
|
|
5
|
+
* Translates browser events into liveness signals for the framework-agnostic
|
|
6
|
+
* `ConversationLiveness` supervisor in `@memberjunction/conversations-runtime` (MJ #4222).
|
|
7
|
+
*
|
|
8
|
+
* WHY THE SPLIT. The supervisor lives at L0 because that package already depends on
|
|
9
|
+
* `@memberjunction/graphql-dataprovider` and has no Angular dependency — and because the
|
|
10
|
+
* obvious alternative is closed to us: Explorer's `ServerConnectivityService` does almost
|
|
11
|
+
* exactly this, but `@memberjunction/ng-conversations` declares `"mjUILayer": "widgets"`, and
|
|
12
|
+
* `packages/Standards/src/checks/ui-layers.ts` forbids that layer from importing any
|
|
13
|
+
* `ng-explorer*` package at severity `error`. L0 cannot own the DOM half either: the runtime is
|
|
14
|
+
* documented as Node-consumable, so `document` and `window` may not exist there. Hence this thin
|
|
15
|
+
* Angular-side adapter, which is the only piece that touches the DOM.
|
|
16
|
+
*
|
|
17
|
+
* WHAT THE SIGNALS MEAN. Neither event proves anything is reachable — `navigator.onLine` reads
|
|
18
|
+
* true behind a captive portal or a dead VPN, and a tab regaining focus says nothing about the
|
|
19
|
+
* server. They are prompts to re-check, and the supervisor coalesces them with the transport-level
|
|
20
|
+
* signals before anyone acts.
|
|
21
|
+
*
|
|
22
|
+
* Root-provided so one instance serves every chat area; several open conversations must not each
|
|
23
|
+
* raise their own reconciliation for the same lid-open.
|
|
24
|
+
*/
|
|
25
|
+
export class ConversationLivenessDomService {
|
|
26
|
+
/**
|
|
27
|
+
* Stored bound references — `removeEventListener` only detaches a listener when handed the
|
|
28
|
+
* same function object `addEventListener` received. Matches the pattern already used for the
|
|
29
|
+
* resize handlers in `conversation-chat-area.component.ts` and in
|
|
30
|
+
* `packages/Angular/Generic/shared/src/lib/theme.service.ts`.
|
|
31
|
+
*/
|
|
32
|
+
boundVisibilityHandler = null;
|
|
33
|
+
boundOnlineHandler = null;
|
|
34
|
+
started = false;
|
|
35
|
+
/** Begin translating DOM events into liveness signals. Idempotent. */
|
|
36
|
+
Start() {
|
|
37
|
+
if (this.started || typeof document === 'undefined' || typeof window === 'undefined') {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
this.boundVisibilityHandler = () => {
|
|
41
|
+
// Only the hidden → visible edge matters. A tab going away needs no reconciliation,
|
|
42
|
+
// and signalling on both edges would double every recovery.
|
|
43
|
+
if (!document.hidden) {
|
|
44
|
+
ConversationsRuntime.Instance.Liveness.NotifyTabVisible();
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
this.boundOnlineHandler = () => ConversationsRuntime.Instance.Liveness.NotifyBrowserOnline();
|
|
48
|
+
document.addEventListener('visibilitychange', this.boundVisibilityHandler);
|
|
49
|
+
window.addEventListener('online', this.boundOnlineHandler);
|
|
50
|
+
this.started = true;
|
|
51
|
+
}
|
|
52
|
+
/** Detach both listeners. Safe to call when never started. */
|
|
53
|
+
Stop() {
|
|
54
|
+
if (this.boundVisibilityHandler && typeof document !== 'undefined') {
|
|
55
|
+
document.removeEventListener('visibilitychange', this.boundVisibilityHandler);
|
|
56
|
+
this.boundVisibilityHandler = null;
|
|
57
|
+
}
|
|
58
|
+
if (this.boundOnlineHandler && typeof window !== 'undefined') {
|
|
59
|
+
window.removeEventListener('online', this.boundOnlineHandler);
|
|
60
|
+
this.boundOnlineHandler = null;
|
|
61
|
+
}
|
|
62
|
+
this.started = false;
|
|
63
|
+
}
|
|
64
|
+
ngOnDestroy() {
|
|
65
|
+
this.Stop();
|
|
66
|
+
}
|
|
67
|
+
static ɵfac = function ConversationLivenessDomService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ConversationLivenessDomService)(); };
|
|
68
|
+
static ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: ConversationLivenessDomService, factory: ConversationLivenessDomService.ɵfac, providedIn: 'root' });
|
|
69
|
+
}
|
|
70
|
+
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ConversationLivenessDomService, [{
|
|
71
|
+
type: Injectable,
|
|
72
|
+
args: [{ providedIn: 'root' }]
|
|
73
|
+
}], null, null); })();
|
|
74
|
+
//# sourceMappingURL=conversation-liveness-dom.service.js.map
|