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