@memberjunction/server 5.51.0 → 6.1.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +7 -0
  2. package/dist/agentSessions/SessionManager.d.ts +22 -1
  3. package/dist/agentSessions/SessionManager.d.ts.map +1 -1
  4. package/dist/agentSessions/SessionManager.js +13 -3
  5. package/dist/agentSessions/SessionManager.js.map +1 -1
  6. package/dist/auth/actingContextResolver.d.ts +44 -0
  7. package/dist/auth/actingContextResolver.d.ts.map +1 -0
  8. package/dist/auth/actingContextResolver.js +18 -0
  9. package/dist/auth/actingContextResolver.js.map +1 -0
  10. package/dist/auth/index.d.ts +1 -0
  11. package/dist/auth/index.d.ts.map +1 -1
  12. package/dist/auth/index.js +1 -0
  13. package/dist/auth/index.js.map +1 -1
  14. package/dist/auth/sessionUserClone.d.ts +32 -0
  15. package/dist/auth/sessionUserClone.d.ts.map +1 -0
  16. package/dist/auth/sessionUserClone.js +50 -0
  17. package/dist/auth/sessionUserClone.js.map +1 -0
  18. package/dist/context.d.ts +1 -1
  19. package/dist/context.d.ts.map +1 -1
  20. package/dist/context.js +43 -6
  21. package/dist/context.js.map +1 -1
  22. package/dist/generated/generated.d.ts +234 -642
  23. package/dist/generated/generated.d.ts.map +1 -1
  24. package/dist/generated/generated.js +1277 -3755
  25. package/dist/generated/generated.js.map +1 -1
  26. package/dist/generic/FireAndForgetHeartbeat.d.ts +5 -0
  27. package/dist/generic/FireAndForgetHeartbeat.d.ts.map +1 -1
  28. package/dist/generic/FireAndForgetHeartbeat.js +5 -4
  29. package/dist/generic/FireAndForgetHeartbeat.js.map +1 -1
  30. package/dist/generic/PushStatusResolver.d.ts +58 -0
  31. package/dist/generic/PushStatusResolver.d.ts.map +1 -1
  32. package/dist/generic/PushStatusResolver.js +42 -3
  33. package/dist/generic/PushStatusResolver.js.map +1 -1
  34. package/dist/generic/ResolverBase.d.ts +9 -0
  35. package/dist/generic/ResolverBase.d.ts.map +1 -1
  36. package/dist/generic/ResolverBase.js +31 -13
  37. package/dist/generic/ResolverBase.js.map +1 -1
  38. package/dist/index.d.ts +7 -2
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +20 -4
  41. package/dist/index.js.map +1 -1
  42. package/dist/multiTenancy/index.d.ts +19 -0
  43. package/dist/multiTenancy/index.d.ts.map +1 -1
  44. package/dist/multiTenancy/index.js +82 -5
  45. package/dist/multiTenancy/index.js.map +1 -1
  46. package/dist/resolvers/ActionResolver.d.ts.map +1 -1
  47. package/dist/resolvers/ActionResolver.js +12 -5
  48. package/dist/resolvers/ActionResolver.js.map +1 -1
  49. package/dist/resolvers/MCPResolver.d.ts.map +1 -1
  50. package/dist/resolvers/MCPResolver.js +13 -16
  51. package/dist/resolvers/MCPResolver.js.map +1 -1
  52. package/dist/resolvers/RealtimeClientSessionResolver.d.ts +1 -1
  53. package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -1
  54. package/dist/resolvers/RealtimeClientSessionResolver.js +15 -14
  55. package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -1
  56. package/dist/resolvers/RemoteBrowserActionResolver.d.ts.map +1 -1
  57. package/dist/resolvers/RemoteBrowserActionResolver.js +19 -26
  58. package/dist/resolvers/RemoteBrowserActionResolver.js.map +1 -1
  59. package/dist/resolvers/RunAIAgentResolver.d.ts.map +1 -1
  60. package/dist/resolvers/RunAIAgentResolver.js +30 -40
  61. package/dist/resolvers/RunAIAgentResolver.js.map +1 -1
  62. package/dist/resolvers/RunTestResolver.d.ts.map +1 -1
  63. package/dist/resolvers/RunTestResolver.js +90 -112
  64. package/dist/resolvers/RunTestResolver.js.map +1 -1
  65. package/dist/resolvers/SearchKnowledgeResolver.js +3 -3
  66. package/dist/resolvers/SearchKnowledgeResolver.js.map +1 -1
  67. package/dist/resolvers/SearchKnowledgeStreamResolver.js +2 -2
  68. package/dist/resolvers/SearchKnowledgeStreamResolver.js.map +1 -1
  69. package/dist/resolvers/TaskGraphFrameResolver.d.ts +85 -0
  70. package/dist/resolvers/TaskGraphFrameResolver.d.ts.map +1 -0
  71. package/dist/resolvers/TaskGraphFrameResolver.js +163 -0
  72. package/dist/resolvers/TaskGraphFrameResolver.js.map +1 -0
  73. package/dist/resolvers/VersionHistoryResolver.d.ts.map +1 -1
  74. package/dist/resolvers/VersionHistoryResolver.js +8 -12
  75. package/dist/resolvers/VersionHistoryResolver.js.map +1 -1
  76. package/dist/rest/RESTEndpointHandler.d.ts +0 -4
  77. package/dist/rest/RESTEndpointHandler.d.ts.map +1 -1
  78. package/dist/rest/RESTEndpointHandler.js +1 -15
  79. package/dist/rest/RESTEndpointHandler.js.map +1 -1
  80. package/dist/services/StartTaskGraphDispatcher.d.ts +33 -0
  81. package/dist/services/StartTaskGraphDispatcher.d.ts.map +1 -0
  82. package/dist/services/StartTaskGraphDispatcher.js +31 -0
  83. package/dist/services/StartTaskGraphDispatcher.js.map +1 -0
  84. package/dist/services/TaskGraphAgentRunner.d.ts +15 -0
  85. package/dist/services/TaskGraphAgentRunner.d.ts.map +1 -0
  86. package/dist/services/TaskGraphAgentRunner.js +74 -0
  87. package/dist/services/TaskGraphAgentRunner.js.map +1 -0
  88. package/dist/services/TaskGraphContinuationDeliverer.d.ts +70 -0
  89. package/dist/services/TaskGraphContinuationDeliverer.d.ts.map +1 -0
  90. package/dist/services/TaskGraphContinuationDeliverer.js +162 -0
  91. package/dist/services/TaskGraphContinuationDeliverer.js.map +1 -0
  92. package/dist/services/TaskGraphProviderFactory.d.ts +39 -0
  93. package/dist/services/TaskGraphProviderFactory.d.ts.map +1 -0
  94. package/dist/services/TaskGraphProviderFactory.js +28 -0
  95. package/dist/services/TaskGraphProviderFactory.js.map +1 -0
  96. package/package.json +103 -100
  97. package/src/__tests__/RealtimeBridgeResolver.test.ts +6 -0
  98. package/src/__tests__/SessionManager.test.ts +44 -0
  99. package/src/__tests__/TaskGraphContinuationDeliverer.test.ts +249 -0
  100. package/src/__tests__/TaskGraphFrameResolver.test.ts +136 -0
  101. package/src/__tests__/multiTenancy.security.test.ts +254 -22
  102. package/src/__tests__/multiTenancy.test.ts +22 -0
  103. package/src/__tests__/pushStatusResolver.filter.test.ts +56 -0
  104. package/src/__tests__/resolverBase.rls.test.ts +4 -0
  105. package/src/__tests__/search-knowledge-tags.test.ts +74 -6
  106. package/src/__tests__/sessionUserClone.test.ts +161 -0
  107. package/src/agentSessions/SessionManager.ts +26 -2
  108. package/src/auth/actingContextResolver.ts +56 -0
  109. package/src/auth/index.ts +1 -0
  110. package/src/auth/sessionUserClone.ts +50 -0
  111. package/src/context.ts +48 -6
  112. package/src/generated/generated.ts +899 -2555
  113. package/src/generic/FireAndForgetHeartbeat.ts +10 -4
  114. package/src/generic/PushStatusResolver.ts +79 -4
  115. package/src/generic/ResolverBase.ts +33 -13
  116. package/src/index.ts +21 -4
  117. package/src/multiTenancy/index.ts +92 -5
  118. package/src/resolvers/ActionResolver.ts +15 -7
  119. package/src/resolvers/MCPResolver.ts +13 -15
  120. package/src/resolvers/RealtimeClientSessionResolver.ts +15 -13
  121. package/src/resolvers/RemoteBrowserActionResolver.ts +19 -25
  122. package/src/resolvers/RunAIAgentResolver.ts +30 -40
  123. package/src/resolvers/RunTestResolver.ts +90 -112
  124. package/src/resolvers/SearchKnowledgeResolver.ts +3 -3
  125. package/src/resolvers/SearchKnowledgeStreamResolver.ts +2 -2
  126. package/src/resolvers/TaskGraphFrameResolver.ts +160 -0
  127. package/src/resolvers/VersionHistoryResolver.ts +10 -13
  128. package/src/rest/RESTEndpointHandler.ts +1 -15
  129. package/src/services/StartTaskGraphDispatcher.ts +61 -0
  130. package/src/services/TaskGraphAgentRunner.ts +81 -0
  131. package/src/services/TaskGraphContinuationDeliverer.ts +181 -0
  132. package/src/services/TaskGraphProviderFactory.ts +53 -0
  133. package/dist/resolvers/ReportResolver.d.ts +0 -24
  134. package/dist/resolvers/ReportResolver.d.ts.map +0 -1
  135. package/dist/resolvers/ReportResolver.js +0 -190
  136. package/dist/resolvers/ReportResolver.js.map +0 -1
  137. package/dist/resolvers/TaskResolver.d.ts +0 -31
  138. package/dist/resolvers/TaskResolver.d.ts.map +0 -1
  139. package/dist/resolvers/TaskResolver.js +0 -157
  140. package/dist/resolvers/TaskResolver.js.map +0 -1
  141. package/dist/services/TaskOrchestrator.d.ts +0 -130
  142. package/dist/services/TaskOrchestrator.d.ts.map +0 -1
  143. package/dist/services/TaskOrchestrator.js +0 -690
  144. package/dist/services/TaskOrchestrator.js.map +0 -1
  145. package/src/resolvers/ReportResolver.ts +0 -157
  146. package/src/resolvers/TaskResolver.ts +0 -148
  147. package/src/services/TaskOrchestrator.ts +0 -873
@@ -1,873 +0,0 @@
1
- import { DatabaseProviderBase, IMetadataProvider, Metadata, RunView, UserInfo, LogError, LogStatus } from '@memberjunction/core';
2
- import { MJTaskEntity, MJTaskDependencyEntity, MJTaskTypeEntity, MJConversationDetailEntity, MJArtifactEntity, MJArtifactVersionEntity, MJConversationDetailArtifactEntity, MJUserNotificationEntity } from '@memberjunction/core-entities';
3
- import { AgentRunner } from '@memberjunction/ai-agents';
4
- import { ChatMessageRole } from '@memberjunction/ai';
5
- import { PubSubEngine } from 'type-graphql';
6
- import { UserPayload } from '../types.js';
7
- import { PUSH_STATUS_UPDATES_TOPIC } from '../generic/PushStatusResolver.js';
8
- import { MJAIAgentEntityExtended } from '@memberjunction/ai-core-plus';
9
-
10
- /**
11
- * Task definition from LLM response
12
- */
13
- export interface TaskDefinition {
14
- tempId: string; // LLM-generated ID for reference
15
- name: string;
16
- description: string;
17
- agentName: string;
18
- dependsOn: string[]; // Array of tempIds this task depends on
19
- inputPayload?: any;
20
- }
21
-
22
- /**
23
- * Task graph response from Conversation Manager
24
- */
25
- export interface TaskGraphResponse {
26
- workflowName: string; // Name for the parent/workflow task
27
- tasks: TaskDefinition[];
28
- reasoning?: string;
29
- }
30
-
31
- /**
32
- * Task execution result
33
- */
34
- export interface TaskExecutionResult {
35
- taskId: string;
36
- success: boolean;
37
- output?: any;
38
- error?: string;
39
- }
40
-
41
- /**
42
- * TaskOrchestrator handles multi-step task execution with dependencies
43
- */
44
- export class TaskOrchestrator {
45
- // Default artifact type ID for JSON (when agent doesn't specify DefaultArtifactTypeID)
46
- private readonly JSON_ARTIFACT_TYPE_ID = 'ae674c7e-ea0d-49ea-89e4-0649f5eb20d4';
47
-
48
- private taskTypeId: string | null = null;
49
-
50
- constructor(
51
- private contextUser: UserInfo,
52
- private pubSub?: PubSubEngine,
53
- private sessionId?: string,
54
- private userPayload?: UserPayload,
55
- private createNotifications: boolean = false,
56
- private conversationDetailId?: string,
57
- private provider?: IMetadataProvider
58
- ) {}
59
-
60
- private getMetadata(): IMetadataProvider {
61
- return this.provider ?? (new Metadata() as unknown as IMetadataProvider);
62
- }
63
-
64
- /**
65
- * Initialize the orchestrator by finding/creating the AI Agent Task type
66
- */
67
- private async ensureTaskType(): Promise<string> {
68
- if (this.taskTypeId) {
69
- return this.taskTypeId;
70
- }
71
-
72
- const rv = new RunView();
73
- const result = await rv.RunView({
74
- EntityName: 'MJ: Task Types',
75
- ExtraFilter: `Name='AI Agent Execution'`,
76
- ResultType: 'entity_object'
77
- }, this.contextUser);
78
-
79
- if (result.Success && result.Results && result.Results.length > 0) {
80
- this.taskTypeId = result.Results[0].ID;
81
- return this.taskTypeId;
82
- }
83
-
84
- // Create the task type if it doesn't exist
85
- const md = this.getMetadata();
86
- const taskType = await md.GetEntityObject<MJTaskTypeEntity>('MJ: Task Types', this.contextUser);
87
- taskType.Name = 'AI Agent Execution';
88
- taskType.Description = 'Task executed by an AI agent as part of conversation workflow';
89
-
90
- const saved = await taskType.Save();
91
- if (!saved) {
92
- throw new Error('Failed to create AI Agent Execution task type');
93
- }
94
-
95
- this.taskTypeId = taskType.ID;
96
- return this.taskTypeId;
97
- }
98
-
99
- /**
100
- * Create tasks from LLM task graph response
101
- * @param taskGraph Task graph from Conversation Manager
102
- * @param conversationDetailId ID of the conversation detail that triggered this
103
- * @param environmentId Environment ID
104
- * @returns Object with parentTaskId and map of tempId -> actual MJTaskEntity ID
105
- */
106
- async createTasksFromGraph(
107
- taskGraph: TaskGraphResponse,
108
- conversationDetailId: string,
109
- environmentId: string
110
- ): Promise<{ parentTaskId: string; taskIdMap: Map<string, string> }> {
111
- const taskTypeId = await this.ensureTaskType();
112
- const md = this.getMetadata();
113
- const tempIdToRealId = new Map<string, string>();
114
-
115
- // Build the parent task, deduplicate the incoming task defs, and resolve agents
116
- // BEFORE opening the transaction so all preparatory work (cache lookups, agent
117
- // resolution RunViews) happens outside the critical section.
118
- const parentTask = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
119
- parentTask.Name = taskGraph.workflowName;
120
- parentTask.Description = taskGraph.reasoning || 'AI-orchestrated workflow';
121
- parentTask.TypeID = taskTypeId;
122
- parentTask.EnvironmentID = environmentId;
123
- parentTask.ConversationDetailID = conversationDetailId;
124
- parentTask.Status = 'In Progress';
125
- parentTask.PercentComplete = 0;
126
-
127
- const seenTempIds = new Set<string>();
128
- const uniqueTasks = taskGraph.tasks.filter(task => {
129
- if (seenTempIds.has(task.tempId)) {
130
- LogError(`Duplicate tempId detected and ignored: ${task.tempId} (${task.name})`);
131
- return false;
132
- }
133
- seenTempIds.add(task.tempId);
134
- return true;
135
- });
136
-
137
- LogStatus(`Preparing parent + ${uniqueTasks.length} unique child tasks (${taskGraph.tasks.length - uniqueTasks.length} duplicates filtered)`);
138
-
139
- const resolvedTasks: Array<{ def: TaskDefinition; agentId: string }> = [];
140
- for (const taskDef of uniqueTasks) {
141
- const agent = await this.findAgentByName(taskDef.agentName);
142
- if (!agent) {
143
- LogError(`Agent not found: ${taskDef.agentName}`);
144
- continue;
145
- }
146
- resolvedTasks.push({ def: taskDef, agentId: agent.ID });
147
- }
148
-
149
- // Persist parent + children + dependency graph in one transaction
150
- const provider = (this.provider ?? Metadata.Provider) as DatabaseProviderBase;
151
- await provider.BeginTransaction();
152
- try {
153
- if (!await parentTask.Save()) {
154
- throw new Error(`Failed to create parent workflow task: ${parentTask.LatestResult?.CompleteMessage ?? 'unknown error'}`);
155
- }
156
- LogStatus(`Created parent workflow task: ${parentTask.Name} (${parentTask.ID})`);
157
-
158
- for (const { def, agentId } of resolvedTasks) {
159
- const task = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
160
- task.Name = def.name;
161
- task.Description = def.description;
162
- task.TypeID = taskTypeId;
163
- task.EnvironmentID = environmentId;
164
- task.ParentID = parentTask.ID;
165
- task.ConversationDetailID = conversationDetailId;
166
- task.AgentID = agentId;
167
- task.Status = 'Pending';
168
- task.PercentComplete = 0;
169
-
170
- if (def.inputPayload) {
171
- const metadata = {
172
- inputPayload: def.inputPayload,
173
- tempId: def.tempId
174
- };
175
- task.Description = `${def.description}\n\n__TASK_METADATA__\n${JSON.stringify(metadata)}`;
176
- }
177
-
178
- if (!await task.Save()) {
179
- throw new Error(`Failed to create child task '${def.name}': ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
180
- }
181
- tempIdToRealId.set(def.tempId, task.ID);
182
- LogStatus(`Created child task: ${task.Name} (${task.ID}) under parent ${parentTask.ID}`);
183
- }
184
-
185
- for (const { def } of resolvedTasks) {
186
- const taskId = tempIdToRealId.get(def.tempId);
187
- if (!taskId) continue;
188
-
189
- for (const dependsOnTempId of def.dependsOn) {
190
- const dependsOnId = tempIdToRealId.get(dependsOnTempId);
191
- if (!dependsOnId) {
192
- LogError(`Dependency not found: ${dependsOnTempId}`);
193
- continue;
194
- }
195
-
196
- const dependency = await md.GetEntityObject<MJTaskDependencyEntity>('MJ: Task Dependencies', this.contextUser);
197
- dependency.TaskID = taskId;
198
- dependency.DependsOnTaskID = dependsOnId;
199
- dependency.DependencyType = 'Prerequisite';
200
-
201
- if (!await dependency.Save()) {
202
- throw new Error(`Failed to create task dependency (${taskId} -> ${dependsOnId}): ${dependency.LatestResult?.CompleteMessage ?? 'unknown error'}`);
203
- }
204
- LogStatus(`Created dependency: Task ${taskId} depends on ${dependsOnId}`);
205
- }
206
- }
207
-
208
- await provider.CommitTransaction();
209
- } catch (txErr) {
210
- await provider.RollbackTransaction();
211
- throw txErr;
212
- }
213
-
214
- return {
215
- parentTaskId: parentTask.ID,
216
- taskIdMap: tempIdToRealId
217
- };
218
- }
219
-
220
- /**
221
- * Publish task progress update via PubSub
222
- */
223
- private publishTaskProgress(taskName: string, message: string, percentComplete: number): void {
224
- if (!this.pubSub || !this.sessionId || !this.userPayload) {
225
- LogStatus(`⚠️ PubSub not available for progress updates (pubSub: ${!!this.pubSub}, sessionId: ${!!this.sessionId}, userPayload: ${!!this.userPayload})`);
226
- return;
227
- }
228
-
229
- const payload = {
230
- message: JSON.stringify({
231
- resolver: 'TaskOrchestrator',
232
- type: 'TaskProgress',
233
- status: 'ok',
234
- data: {
235
- taskName,
236
- message,
237
- percentComplete,
238
- timestamp: new Date(),
239
- conversationDetailId: this.conversationDetailId
240
- }
241
- }),
242
- sessionId: this.userPayload.sessionId
243
- };
244
-
245
- LogStatus(`📡 Publishing task progress: ${taskName} - ${message} (${percentComplete}%) to session ${this.userPayload.sessionId}`);
246
- this.pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, payload);
247
-
248
- LogStatus(`[Task: ${taskName}] ${message} (${percentComplete}%)`);
249
- }
250
-
251
- /**
252
- * Publish agent progress update (nested within task)
253
- */
254
- private publishAgentProgress(taskName: string, agentStep: string, agentMessage: string): void {
255
- if (!this.pubSub || !this.sessionId || !this.userPayload) {
256
- LogStatus(`⚠️ PubSub not available for agent progress (pubSub: ${!!this.pubSub}, sessionId: ${!!this.sessionId}, userPayload: ${!!this.userPayload})`);
257
- return;
258
- }
259
-
260
- const payload = {
261
- message: JSON.stringify({
262
- resolver: 'TaskOrchestrator',
263
- type: 'AgentProgress',
264
- status: 'ok',
265
- data: {
266
- taskName,
267
- agentStep,
268
- agentMessage,
269
- timestamp: new Date(),
270
- conversationDetailId: this.conversationDetailId
271
- }
272
- }),
273
- sessionId: this.userPayload.sessionId
274
- };
275
-
276
- LogStatus(`📡 Publishing agent progress: ${taskName} → ${agentStep} to session ${this.userPayload.sessionId}`);
277
- this.pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, payload);
278
-
279
- LogStatus(`[Task: ${taskName}] → ${agentStep}: ${agentMessage}`);
280
- }
281
-
282
- /**
283
- * Find agent by name
284
- */
285
- private async findAgentByName(agentName: string): Promise<MJAIAgentEntityExtended | null> {
286
- const rv = new RunView();
287
- const result = await rv.RunView<MJAIAgentEntityExtended>({
288
- EntityName: 'MJ: AI Agents',
289
- ExtraFilter: `Name='${agentName.replace(/'/g, "''")}'`,
290
- ResultType: 'entity_object'
291
- }, this.contextUser);
292
-
293
- if (result.Success && result.Results && result.Results.length > 0) {
294
- return result.Results[0];
295
- }
296
-
297
- return null;
298
- }
299
-
300
- /**
301
- * Execute all pending tasks for a parent task, respecting dependencies
302
- * @param parentTaskId Parent task ID
303
- * @returns Array of execution results
304
- */
305
- async executeTasksForParent(parentTaskId: string): Promise<TaskExecutionResult[]> {
306
- const results: TaskExecutionResult[] = [];
307
- let hasMore = true;
308
-
309
- // Get parent task for progress updates
310
- const md = this.getMetadata();
311
- const parentTask = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
312
- await parentTask.Load(parentTaskId);
313
-
314
- // Publish workflow start
315
- this.publishTaskProgress(parentTask.Name, 'Starting workflow execution', 0);
316
-
317
- while (hasMore) {
318
- // Find tasks that are pending and have no incomplete dependencies
319
- const eligibleTasks = await this.findEligibleTasks(parentTaskId);
320
-
321
- if (eligibleTasks.length === 0) {
322
- hasMore = false;
323
- break;
324
- }
325
-
326
- // Execute eligible tasks (could be parallelized in the future)
327
- for (const task of eligibleTasks) {
328
- // Publish task start
329
- this.publishTaskProgress(task.Name, 'Starting task', 0);
330
-
331
- const result = await this.executeTask(task);
332
- results.push(result);
333
-
334
- // Publish task complete
335
- if (result.success) {
336
- this.publishTaskProgress(task.Name, 'Task completed successfully', 100);
337
- } else {
338
- this.publishTaskProgress(task.Name, `Task failed: ${result.error}`, 100);
339
- }
340
-
341
- // Update parent task progress after each child completes
342
- await this.updateParentTaskProgress(parentTaskId);
343
- }
344
- }
345
-
346
- // Mark parent task as complete
347
- await this.completeParentTask(parentTaskId);
348
-
349
- // Publish workflow complete
350
- this.publishTaskProgress(parentTask.Name, 'Workflow completed', 100);
351
-
352
- return results;
353
- }
354
-
355
- /**
356
- * Find tasks that are ready to execute (pending with no incomplete dependencies)
357
- */
358
- private async findEligibleTasks(parentTaskId: string): Promise<MJTaskEntity[]> {
359
- const rv = new RunView();
360
-
361
- // Get all pending tasks for this parent
362
- const tasksResult = await rv.RunView<MJTaskEntity>({
363
- EntityName: 'MJ: Tasks',
364
- ExtraFilter: `ParentID='${parentTaskId}' AND Status='Pending'`,
365
- ResultType: 'entity_object'
366
- }, this.contextUser);
367
-
368
- if (!tasksResult.Success || !tasksResult.Results) {
369
- return [];
370
- }
371
-
372
- const eligibleTasks: MJTaskEntity[] = [];
373
-
374
- // Check each task for incomplete dependencies
375
- for (const task of tasksResult.Results) {
376
- const hasIncompleteDeps = await this.hasIncompleteDependencies(task.ID);
377
- if (!hasIncompleteDeps) {
378
- eligibleTasks.push(task);
379
- }
380
- }
381
-
382
- return eligibleTasks;
383
- }
384
-
385
- /**
386
- * Update parent task progress based on child task completion
387
- */
388
- private async updateParentTaskProgress(parentTaskId: string): Promise<void> {
389
- const md = this.getMetadata();
390
- const parentTask = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
391
- const loaded = await parentTask.Load(parentTaskId);
392
- if (!loaded) return;
393
-
394
- const rv = new RunView();
395
-
396
- // Get all child tasks
397
- const childrenResult = await rv.RunView<MJTaskEntity>({
398
- EntityName: 'MJ: Tasks',
399
- ExtraFilter: `ParentID='${parentTaskId}'`,
400
- ResultType: 'entity_object'
401
- }, this.contextUser);
402
-
403
- if (!childrenResult.Success || !childrenResult.Results || childrenResult.Results.length === 0) {
404
- return;
405
- }
406
-
407
- const children = childrenResult.Results;
408
- const completedCount = children.filter(t => t.Status === 'Complete').length;
409
- const totalCount = children.length;
410
-
411
- // Update percent complete
412
- parentTask.PercentComplete = Math.round((completedCount / totalCount) * 100);
413
- await parentTask.Save();
414
-
415
- LogStatus(`Parent task ${parentTask.Name} is ${parentTask.PercentComplete}% complete (${completedCount}/${totalCount} tasks)`);
416
- }
417
-
418
- /**
419
- * Mark parent task as complete when all children are done
420
- */
421
- private async completeParentTask(parentTaskId: string): Promise<void> {
422
- const md = this.getMetadata();
423
- const parentTask = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
424
- const loaded = await parentTask.Load(parentTaskId);
425
- if (!loaded) return;
426
-
427
- parentTask.Status = 'Complete';
428
- parentTask.PercentComplete = 100;
429
- parentTask.CompletedAt = new Date();
430
- const saved = await parentTask.Save();
431
-
432
- LogStatus(`Parent workflow task completed: ${parentTask.Name}`);
433
-
434
- // If notifications enabled, create user notification
435
- if (this.createNotifications && saved) {
436
- await this.createTaskGraphCompletionNotification(parentTask);
437
- }
438
- }
439
-
440
- /**
441
- * Check if a task has incomplete dependencies
442
- */
443
- private async hasIncompleteDependencies(taskId: string): Promise<boolean> {
444
- const rv = new RunView();
445
-
446
- // Get dependencies
447
- const depsResult = await rv.RunView<MJTaskDependencyEntity>({
448
- EntityName: 'MJ: Task Dependencies',
449
- ExtraFilter: `TaskID='${taskId}'`,
450
- ResultType: 'entity_object'
451
- }, this.contextUser);
452
-
453
- if (!depsResult.Success || !depsResult.Results || depsResult.Results.length === 0) {
454
- return false; // No dependencies
455
- }
456
-
457
- // Check if any dependency is not complete
458
- for (const dep of depsResult.Results) {
459
- const dependsOnTask = await this.loadTask(dep.DependsOnTaskID);
460
- if (dependsOnTask && dependsOnTask.Status !== 'Complete') {
461
- return true; // Has incomplete dependency
462
- }
463
- }
464
-
465
- return false;
466
- }
467
-
468
- /**
469
- * Load a task by ID
470
- */
471
- private async loadTask(taskId: string): Promise<MJTaskEntity | null> {
472
- const md = this.getMetadata();
473
- const task = await md.GetEntityObject<MJTaskEntity>('MJ: Tasks', this.contextUser);
474
- const loaded = await task.Load(taskId);
475
- return loaded ? task : null;
476
- }
477
-
478
- /**
479
- * Execute a single task
480
- */
481
- private async executeTask(task: MJTaskEntity): Promise<TaskExecutionResult> {
482
- try {
483
- LogStatus(`Executing task: ${task.Name} (${task.ID})`);
484
-
485
- // Update status to In Progress
486
- task.Status = 'In Progress';
487
- task.StartedAt = new Date();
488
- await task.Save();
489
-
490
- // Load the agent entity
491
- const md = this.getMetadata();
492
- const agentEntity = await md.GetEntityObject<MJAIAgentEntityExtended>('MJ: AI Agents', this.contextUser);
493
- const loaded = await agentEntity.Load(task.AgentID!);
494
- if (!loaded) {
495
- throw new Error(`Agent with ID ${task.AgentID} not found`);
496
- }
497
-
498
- // Build conversation messages with task input and dependent outputs as markdown
499
- const messages = await this.buildConversationMessages(task);
500
-
501
- // Create progress callback to publish agent progress nested under task
502
- const onProgress = (progress: any) => {
503
- this.publishAgentProgress(
504
- task.Name,
505
- progress.step || 'processing',
506
- progress.message || ''
507
- );
508
- };
509
-
510
- // Run the agent - use only conversationMessages, no payload parameter
511
- // Payload should only be used when passing an agent its own prior output for modification
512
- const agentRunner = new AgentRunner();
513
- const agentResult = await agentRunner.RunAgent({
514
- agent: agentEntity,
515
- conversationMessages: messages,
516
- contextUser: this.contextUser,
517
- conversationDetailId: task.ConversationDetailID || undefined,
518
- onProgress: onProgress
519
- });
520
-
521
- if (agentResult.success) {
522
- // Extract output - check both message and payload
523
- const output = this.extractAgentOutput(agentResult);
524
-
525
- // Store output in task metadata
526
- const outputMetadata = {
527
- outputType: output.type,
528
- output: output.content,
529
- agentRunId: agentResult.agentRun?.ID
530
- };
531
-
532
- // Update task with success
533
- task.Status = 'Complete';
534
- task.CompletedAt = new Date();
535
- task.PercentComplete = 100;
536
- // Store output in description (would be better as a separate column)
537
- task.Description = `${task.Description}\n\n__TASK_OUTPUT__\n${JSON.stringify(outputMetadata)}`;
538
- await task.Save();
539
-
540
- LogStatus(`Task completed: ${task.Name} (output type: ${output.type})`);
541
-
542
- // Always create artifact for task output (both message and payload results)
543
- let conversationDetailId = task.ConversationDetailID;
544
- if (!conversationDetailId && task.ParentID) {
545
- const parentTask = await this.loadTask(task.ParentID);
546
- conversationDetailId = parentTask?.ConversationDetailID || null;
547
- }
548
-
549
- if (conversationDetailId && output.content) {
550
- await this.createArtifactFromOutput(
551
- output,
552
- conversationDetailId,
553
- agentEntity,
554
- task.Name
555
- );
556
- } else if (!conversationDetailId) {
557
- LogError(`Cannot create artifact: No conversation detail ID found for task ${task.ID}`);
558
- }
559
-
560
- return {
561
- taskId: task.ID,
562
- success: true,
563
- output: output.content
564
- };
565
- } else {
566
- // Update task with failure
567
- task.Status = 'Failed';
568
- task.CompletedAt = new Date();
569
- await task.Save();
570
-
571
- const errorMsg = agentResult.agentRun?.ErrorMessage || 'Agent execution failed';
572
- LogError(`Task failed: ${task.Name} - ${errorMsg}`);
573
-
574
- return {
575
- taskId: task.ID,
576
- success: false,
577
- error: errorMsg
578
- };
579
- }
580
- } catch (error) {
581
- LogError(error);
582
-
583
- // Update task with failure
584
- task.Status = 'Failed';
585
- task.CompletedAt = new Date();
586
- await task.Save();
587
-
588
- return {
589
- taskId: task.ID,
590
- success: false,
591
- error: error instanceof Error ? error.message : 'Unknown error'
592
- };
593
- }
594
- }
595
-
596
- /**
597
- * Extract input payload from task metadata
598
- */
599
- private extractInputPayload(task: MJTaskEntity): any | null {
600
- if (!task.Description) return null;
601
-
602
- const metadataMatch = task.Description.match(/__TASK_METADATA__\n(.+?)(?:\n\n|$)/s);
603
- if (!metadataMatch) return null;
604
-
605
- try {
606
- const metadata = JSON.parse(metadataMatch[1]);
607
- return metadata.inputPayload || null;
608
- } catch {
609
- return null;
610
- }
611
- }
612
-
613
- /**
614
- * Get outputs from tasks that this task depends on
615
- */
616
- private async getDependentTaskOutputs(taskId: string): Promise<Map<string, any>> {
617
- const outputs = new Map<string, any>();
618
- const rv = new RunView();
619
-
620
- // Get dependencies
621
- const depsResult = await rv.RunView<MJTaskDependencyEntity>({
622
- EntityName: 'MJ: Task Dependencies',
623
- ExtraFilter: `TaskID='${taskId}'`,
624
- ResultType: 'entity_object'
625
- }, this.contextUser);
626
-
627
- if (!depsResult.Success || !depsResult.Results) {
628
- return outputs;
629
- }
630
-
631
- // Get output from each dependency
632
- for (const dep of depsResult.Results) {
633
- const dependsOnTask = await this.loadTask(dep.DependsOnTaskID);
634
- if (!dependsOnTask || !dependsOnTask.Description) continue;
635
-
636
- const outputMatch = dependsOnTask.Description.match(/__TASK_OUTPUT__\n(.+?)$/s);
637
- if (outputMatch) {
638
- try {
639
- const outputMetadata = JSON.parse(outputMatch[1]);
640
- outputs.set(dep.DependsOnTaskID, outputMetadata.output);
641
- } catch (e) {
642
- LogError(`Failed to parse output for task ${dep.DependsOnTaskID}: ${e}`);
643
- }
644
- }
645
- }
646
-
647
- return outputs;
648
- }
649
-
650
- /**
651
- * Build conversation messages with task input and dependent outputs formatted as markdown
652
- */
653
- private async buildConversationMessages(task: MJTaskEntity): Promise<any[]> {
654
- const messages: any[] = [];
655
-
656
- // Start with task description/name as base content
657
- let userContent = task.Description || task.Name;
658
-
659
- // Extract input payload from task metadata if it exists
660
- const inputPayload = this.extractInputPayload(task);
661
-
662
- // Get dependent task outputs
663
- const dependentOutputs = await this.getDependentTaskOutputs(task.ID);
664
-
665
- // If there are dependent outputs, format them as markdown blocks
666
- if (dependentOutputs.size > 0) {
667
- userContent += '\n\n## Results from Dependent Tasks:\n\n';
668
- for (const [taskId, outputData] of dependentOutputs.entries()) {
669
- const depTask = await this.loadTask(taskId);
670
- const taskName = depTask?.Name || taskId;
671
- userContent += `### ${taskName}\n\`\`\`json\n${JSON.stringify(outputData, null, 2)}\n\`\`\`\n\n`;
672
- }
673
- }
674
-
675
- // If input payload exists, add it as a separate section
676
- if (inputPayload) {
677
- userContent += '\n\n## Task Input:\n\`\`\`json\n' + JSON.stringify(inputPayload, null, 2) + '\n\`\`\`';
678
- }
679
-
680
- messages.push({
681
- role: 'user' as ChatMessageRole,
682
- content: userContent
683
- });
684
-
685
- return messages;
686
- }
687
-
688
- /**
689
- * Extract agent output - check both message and payload
690
- */
691
- private extractAgentOutput(agentResult: any): { type: 'message' | 'payload', content: any } {
692
- // Check if agent returned a message (text response)
693
- if (agentResult.agentRun?.Message) {
694
- return { type: 'message', content: agentResult.agentRun.Message };
695
- }
696
-
697
- // Check if agent returned a payload (structured data)
698
- if (agentResult.payload && Object.keys(agentResult.payload).length > 0) {
699
- return { type: 'payload', content: agentResult.payload };
700
- }
701
-
702
- // No output
703
- return { type: 'message', content: '' };
704
- }
705
-
706
- /**
707
- * Create artifact from task output (handles both message and payload types)
708
- */
709
- private async createArtifactFromOutput(
710
- output: { type: 'message' | 'payload', content: any },
711
- conversationDetailId: string,
712
- agent: MJAIAgentEntityExtended,
713
- taskName: string
714
- ): Promise<void> {
715
- const md = this.getMetadata();
716
- const provider = (this.provider ?? Metadata.Provider) as DatabaseProviderBase;
717
-
718
- await provider.BeginTransaction();
719
- try {
720
- // Create Artifact header
721
- const artifact = await md.GetEntityObject<MJArtifactEntity>('MJ: Artifacts', this.contextUser);
722
- artifact.Name = `${agent.Name} - ${taskName} - ${new Date().toLocaleString()}`;
723
- artifact.Description = `Artifact generated by ${agent.Name} for task: ${taskName} (${output.type})`;
724
-
725
- const defaultArtifactTypeId = (agent as any).DefaultArtifactTypeID;
726
- artifact.TypeID = defaultArtifactTypeId || this.JSON_ARTIFACT_TYPE_ID;
727
-
728
- artifact.UserID = this.contextUser.ID;
729
- artifact.EnvironmentID = (this.contextUser as any).EnvironmentID || 'F51358F3-9447-4176-B313-BF8025FD8D09';
730
-
731
- const creationMode = agent.ArtifactCreationMode;
732
- if (creationMode === 'System Only') {
733
- artifact.Visibility = 'System Only';
734
- LogStatus(`Task artifact marked as "System Only" per agent configuration`);
735
- } else {
736
- artifact.Visibility = 'Always';
737
- }
738
-
739
- if (!await artifact.Save()) {
740
- throw new Error(`Failed to save artifact: ${artifact.LatestResult?.CompleteMessage ?? 'unknown error'}`);
741
- }
742
- LogStatus(`Created artifact: ${artifact.Name} (${artifact.ID})`);
743
-
744
- // Create Artifact Version with content
745
- const version = await md.GetEntityObject<MJArtifactVersionEntity>('MJ: Artifact Versions', this.contextUser);
746
- version.ArtifactID = artifact.ID;
747
- version.VersionNumber = 1;
748
- version.Content = output.type === 'message' ? output.content : JSON.stringify(output.content, null, 2);
749
- version.UserID = this.contextUser.ID;
750
-
751
- if (!await version.Save()) {
752
- throw new Error(`Failed to save artifact version: ${version.LatestResult?.CompleteMessage ?? 'unknown error'}`);
753
- }
754
- LogStatus(`Created artifact version: ${version.ID}`);
755
-
756
- // If extraction produced a better name, update the artifact in the same transaction
757
- const nameAttr = (version as any).Attributes?.find((attr: any) =>
758
- attr.StandardProperty === 'name' || attr.Name?.toLowerCase() === 'name'
759
- );
760
-
761
- let extractedName = nameAttr?.Value?.trim();
762
- if (extractedName && extractedName.toLowerCase() !== 'null') {
763
- extractedName = extractedName.replace(/^["']|["']$/g, '');
764
- artifact.Name = extractedName;
765
- if (!await artifact.Save()) {
766
- throw new Error(`Failed to update artifact name: ${artifact.LatestResult?.CompleteMessage ?? 'unknown error'}`);
767
- }
768
- LogStatus(`✨ Updated artifact name to: ${artifact.Name}`);
769
- }
770
-
771
- // Create M2M relationship linking artifact to conversation detail
772
- const junction = await md.GetEntityObject<MJConversationDetailArtifactEntity>(
773
- 'MJ: Conversation Detail Artifacts',
774
- this.contextUser
775
- );
776
- junction.ConversationDetailID = conversationDetailId;
777
- junction.ArtifactVersionID = version.ID;
778
- junction.Direction = 'Output';
779
-
780
- if (!await junction.Save()) {
781
- throw new Error(`Failed to create artifact-conversation association: ${junction.LatestResult?.CompleteMessage ?? 'unknown error'}`);
782
- }
783
- LogStatus(`Linked artifact ${artifact.ID} to conversation detail ${conversationDetailId}`);
784
-
785
- await provider.CommitTransaction();
786
- } catch (error) {
787
- await provider.RollbackTransaction();
788
- LogError(`Error creating artifact from output — all changes rolled back: ${error}`);
789
- }
790
- }
791
-
792
- /**
793
- * Create user notification for task graph completion
794
- * Notifies user that their multi-step workflow has completed
795
- */
796
- private async createTaskGraphCompletionNotification(parentTask: MJTaskEntity): Promise<void> {
797
- try {
798
- if (!parentTask.ConversationDetailID) {
799
- LogStatus('Skipping notification - no conversation detail linked');
800
- return;
801
- }
802
-
803
- const md = this.getMetadata();
804
-
805
- // Load conversation detail to get conversation ID
806
- const detail = await md.GetEntityObject<MJConversationDetailEntity>(
807
- 'MJ: Conversation Details',
808
- this.contextUser
809
- );
810
- if (!(await detail.Load(parentTask.ConversationDetailID))) {
811
- throw new Error(`Failed to load conversation detail ${parentTask.ConversationDetailID}`);
812
- }
813
-
814
- // Count child tasks and success rate
815
- const rv = new RunView();
816
- const tasksResult = await rv.RunView<MJTaskEntity>({
817
- EntityName: 'MJ: Tasks',
818
- ExtraFilter: `ParentID='${parentTask.ID}'`,
819
- ResultType: 'entity_object'
820
- }, this.contextUser);
821
-
822
- const childTasks = tasksResult.Success ? (tasksResult.Results || []) : [];
823
- const successCount = childTasks.filter(t => t.Status === 'Complete').length;
824
- const totalCount = childTasks.length;
825
-
826
- // Create notification
827
- const notification = await md.GetEntityObject<MJUserNotificationEntity>(
828
- 'MJ: User Notifications',
829
- this.contextUser
830
- );
831
-
832
- notification.UserID = this.contextUser.ID;
833
- notification.Title = `Workflow "${parentTask.Name}" completed`;
834
- notification.Message = `Your ${totalCount}-step workflow has finished. ${successCount} of ${totalCount} tasks completed successfully.`;
835
-
836
- // Navigation configuration
837
- notification.ResourceConfiguration = JSON.stringify({
838
- type: 'conversation',
839
- conversationId: detail.ConversationID,
840
- messageId: parentTask.ConversationDetailID,
841
- taskId: parentTask.ID
842
- });
843
-
844
- notification.Unread = true;
845
-
846
- if (!(await notification.Save())) {
847
- throw new Error('Failed to save notification');
848
- }
849
-
850
- LogStatus(`📬 Created task graph notification ${notification.ID} for user ${this.contextUser.ID}`);
851
-
852
- // Publish real-time event if pubSub available
853
- if (this.pubSub && this.userPayload) {
854
- this.pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, {
855
- userPayload: JSON.stringify(this.userPayload),
856
- message: JSON.stringify({
857
- type: 'notification',
858
- notificationId: notification.ID,
859
- action: 'create',
860
- title: notification.Title,
861
- message: notification.Message
862
- })
863
- });
864
-
865
- LogStatus(`📡 Published task graph notification event to client`);
866
- }
867
-
868
- } catch (error) {
869
- LogError(`Failed to create task graph notification: ${(error as Error).message}`);
870
- // Don't throw - notification failure shouldn't fail the task
871
- }
872
- }
873
- }