@memberjunction/ai-agent-manager 6.2.0-edge.3 → 6.2.0-edge.5

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.
@@ -16,6 +16,7 @@ import {
16
16
  AgentSpec,
17
17
  AgentActionSpec,
18
18
  AgentStep,
19
+ AgentStepPath,
19
20
  SubAgentSpec
20
21
  } from '@memberjunction/ai-core-plus';
21
22
  import { UUIDsEqual } from '@memberjunction/global';
@@ -35,6 +36,12 @@ export interface AgentSpecSyncMutation {
35
36
  Description: string;
36
37
  }
37
38
 
39
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
40
+
41
+ function isPersistedUUID(id: string | null | undefined): id is string {
42
+ return typeof id === 'string' && UUID_REGEX.test(id.trim());
43
+ }
44
+
38
45
  /**
39
46
  * Result of SaveToDatabase operation including all mutations performed
40
47
  */
@@ -43,6 +50,8 @@ export interface AgentSpecSyncResult {
43
50
  agentId: string;
44
51
  /** Whether the operation succeeded */
45
52
  success: boolean;
53
+ /** Error message when success is false */
54
+ errorMessage?: string;
46
55
  /** Array of all database mutations performed */
47
56
  mutations: AgentSpecSyncMutation[];
48
57
  }
@@ -180,6 +189,13 @@ export class AgentSpecSync {
180
189
  */
181
190
  private _mutations: AgentSpecSyncMutation[] = [];
182
191
 
192
+ /**
193
+ * Maps synthetic/pre-save step correlation IDs (e.g. 'wf-node-1') and step names to
194
+ * their persisted database UUIDs so saveStepPaths can resolve OriginStepID and DestinationStepID.
195
+ * @private
196
+ */
197
+ private _stepIdMap = new Map<string, string>();
198
+
183
199
  /**
184
200
  * Create a new AgentSpecSync instance.
185
201
  *
@@ -733,7 +749,9 @@ export class AgentSpecSync {
733
749
  }
734
750
 
735
751
  /**
736
- * Map MJAIAgentStepEntity to AgentStep format.
752
+ * Map MJAIAgentStepEntity to AgentStep format, preserving execution policy
753
+ * (`TimeoutSeconds`, `RetryCount`, `OnErrorBehavior`) and canvas geometry
754
+ * (`PositionX`, `PositionY`, `Width`, `Height`) across save/load round trips.
737
755
  *
738
756
  * @private
739
757
  * @param step - The agent step entity
@@ -755,25 +773,34 @@ export class AgentSpecSync {
755
773
  LoopBodyType: step.LoopBodyType || undefined,
756
774
  Configuration: step.Configuration || undefined,
757
775
  ActionInputMapping: this.parseJsonField<Record<string, unknown>>(step.ActionInputMapping),
758
- ActionOutputMapping: this.parseJsonField<Record<string, unknown>>(step.ActionOutputMapping)
776
+ ActionOutputMapping: this.parseJsonField<Record<string, unknown>>(step.ActionOutputMapping),
777
+ TimeoutSeconds: step.TimeoutSeconds ?? undefined,
778
+ RetryCount: step.RetryCount ?? undefined,
779
+ OnErrorBehavior: step.OnErrorBehavior || undefined,
780
+ PositionX: step.PositionX ?? undefined,
781
+ PositionY: step.PositionY ?? undefined,
782
+ Width: step.Width ?? undefined,
783
+ Height: step.Height ?? undefined
759
784
  };
760
785
  }
761
786
 
762
787
  /**
763
- * Map MJAIAgentStepPathEntity to AgentStepPath format.
788
+ * Map MJAIAgentStepPathEntity to AgentStepPath format, preserving canvas routing
789
+ * (`PathPoints`) across save/load round trips.
764
790
  *
765
791
  * @private
766
792
  * @param path - The agent step path entity
767
793
  * @returns Mapped path spec
768
794
  */
769
- private mapPathEntityToSpec(path: MJAIAgentStepPathEntity): any {
795
+ private mapPathEntityToSpec(path: MJAIAgentStepPathEntity): AgentStepPath {
770
796
  return {
771
797
  ID: path.ID,
772
798
  OriginStepID: path.OriginStepID,
773
799
  DestinationStepID: path.DestinationStepID,
774
800
  Condition: path.Condition || undefined,
775
801
  Description: path.Description || undefined,
776
- Priority: path.Priority
802
+ Priority: path.Priority,
803
+ PathPoints: path.PathPoints || undefined
777
804
  };
778
805
  }
779
806
 
@@ -859,10 +886,13 @@ export class AgentSpecSync {
859
886
  mutations: this.GetMutations()
860
887
  };
861
888
  } catch (error) {
889
+ const errorMessage = error instanceof Error ? error.message : String(error);
890
+ LogError(`AgentSpecSync.SaveToDatabase failed: ${errorMessage}`);
862
891
  // Return failure with whatever mutations were completed before error
863
892
  return {
864
893
  agentId: this.Spec.ID || '',
865
894
  success: false,
895
+ errorMessage,
866
896
  mutations: this.GetMutations()
867
897
  };
868
898
  }
@@ -883,15 +913,18 @@ export class AgentSpecSync {
883
913
  this._contextUser
884
914
  );
885
915
 
886
- // Track if this is an update or create
887
- const isUpdate = !!this.Spec.ID;
888
-
889
- // If ID exists, load existing record
890
- if (this.Spec.ID) {
916
+ // Only treat Spec.ID as an existing database record when it is a real UUID.
917
+ // Callers such as WorkflowAgentWriter pass a correlation ID (e.g. 'workflow-...')
918
+ // on a brand-new spec; calling Load() with a non-UUID fails SQL uniqueidentifier conversion.
919
+ let isUpdate = false;
920
+ if (isPersistedUUID(this.Spec.ID)) {
891
921
  const loaded = await agentEntity.Load(this.Spec.ID);
892
922
  if (!loaded) {
893
923
  throw new Error(`Cannot update non-existent agent with ID ${this.Spec.ID}`);
894
924
  }
925
+ isUpdate = true;
926
+ } else {
927
+ agentEntity.NewRecord?.();
895
928
  }
896
929
 
897
930
  // Map spec to entity fields
@@ -1355,6 +1388,7 @@ export class AgentSpecSync {
1355
1388
  */
1356
1389
  private async saveSteps(agentId: string): Promise<void> {
1357
1390
  console.log(`🔷 saveSteps: Called with agentId=${agentId}, Steps=${this.Spec.Steps ? this.Spec.Steps.length : 'undefined'}`);
1391
+ this._stepIdMap.clear();
1358
1392
 
1359
1393
  if (!this.Spec.Steps || this.Spec.Steps.length === 0) {
1360
1394
  console.log('🔷 saveSteps: No steps to save, returning early');
@@ -1365,15 +1399,20 @@ export class AgentSpecSync {
1365
1399
  const md = this.providerToUse;
1366
1400
 
1367
1401
  for (const stepSpec of this.Spec.Steps) {
1402
+ const originalStepId = stepSpec.ID;
1368
1403
  const stepEntity = await md.GetEntityObject<MJAIAgentStepEntity>(
1369
1404
  'MJ: AI Agent Steps',
1370
1405
  this._contextUser
1371
1406
  );
1372
1407
 
1373
- // Load existing if ID provided
1374
- const isUpdate = !!(stepSpec.ID && stepSpec.ID !== '');
1375
- if (isUpdate) {
1376
- await stepEntity.Load(stepSpec.ID);
1408
+ // Only load from DB when stepSpec.ID is a real persisted UUID; synthetic IDs
1409
+ // (such as 'wf-node-1' from ConvertTaskGraphToAgentSpec) are new step records.
1410
+ let isUpdate = false;
1411
+ if (isPersistedUUID(stepSpec.ID)) {
1412
+ isUpdate = await stepEntity.Load(stepSpec.ID);
1413
+ }
1414
+ if (!isUpdate) {
1415
+ stepEntity.NewRecord?.();
1377
1416
  }
1378
1417
 
1379
1418
  // Map fields
@@ -1393,6 +1432,29 @@ export class AgentSpecSync {
1393
1432
  // normalized: the text the Architect's validator compiled.
1394
1433
  stepEntity.Configuration = StepConfigurationText(stepSpec);
1395
1434
 
1435
+ // Map execution policy and canvas geometry when provided on the spec
1436
+ if (stepSpec.TimeoutSeconds !== undefined) {
1437
+ stepEntity.TimeoutSeconds = stepSpec.TimeoutSeconds ?? null;
1438
+ }
1439
+ if (stepSpec.RetryCount !== undefined) {
1440
+ stepEntity.RetryCount = stepSpec.RetryCount ?? null;
1441
+ }
1442
+ if (stepSpec.OnErrorBehavior !== undefined) {
1443
+ stepEntity.OnErrorBehavior = stepSpec.OnErrorBehavior ?? 'fail';
1444
+ }
1445
+ if (stepSpec.PositionX !== undefined) {
1446
+ stepEntity.PositionX = Math.round(stepSpec.PositionX);
1447
+ }
1448
+ if (stepSpec.PositionY !== undefined) {
1449
+ stepEntity.PositionY = Math.round(stepSpec.PositionY);
1450
+ }
1451
+ if (stepSpec.Width !== undefined) {
1452
+ stepEntity.Width = Math.round(stepSpec.Width);
1453
+ }
1454
+ if (stepSpec.Height !== undefined) {
1455
+ stepEntity.Height = Math.round(stepSpec.Height);
1456
+ }
1457
+
1396
1458
  // Handle inline prompt creation for Prompt-type steps
1397
1459
  // If StepType is Prompt and PromptID is empty, create a new AIPrompt record
1398
1460
  if (stepSpec.StepType === 'Prompt' && (!stepSpec.PromptID || stepSpec.PromptID === '')) {
@@ -1471,6 +1533,16 @@ export class AgentSpecSync {
1471
1533
  `${isUpdate ? 'Updated' : 'Created'} step: ${stepSpec.Name}`
1472
1534
  );
1473
1535
 
1536
+ // Record both the pre-save correlation ID (e.g. 'wf-node-1') and the step Name
1537
+ // so saveStepPaths can resolve OriginStepID and DestinationStepID to the persisted UUID.
1538
+ if (originalStepId) {
1539
+ this._stepIdMap.set(originalStepId, stepEntity.ID);
1540
+ }
1541
+ if (stepSpec.Name) {
1542
+ this._stepIdMap.set(stepSpec.Name, stepEntity.ID);
1543
+ }
1544
+ this._stepIdMap.set(stepEntity.ID, stepEntity.ID);
1545
+
1474
1546
  // Update the spec with the saved ID so paths can reference it
1475
1547
  stepSpec.ID = stepEntity.ID;
1476
1548
 
@@ -1501,12 +1573,14 @@ export class AgentSpecSync {
1501
1573
  console.log(`🔶 saveStepPaths: Processing ${this.Spec.Paths.length} path(s)...`);
1502
1574
  const md = this.providerToUse;
1503
1575
 
1504
- // Create a map of step names to IDs for easy lookup
1505
- const stepNameToId = new Map<string, string>();
1576
+ // Combine _stepIdMap (populated during saveSteps, including synthetic IDs like 'wf-node-1')
1577
+ // with stepNameToId for any steps not saved in this pass.
1578
+ const stepRefToId = new Map<string, string>(this._stepIdMap);
1506
1579
  if (this.Spec.Steps) {
1507
1580
  for (const step of this.Spec.Steps) {
1508
1581
  if (step.ID) {
1509
- stepNameToId.set(step.Name, step.ID);
1582
+ stepRefToId.set(step.Name, step.ID);
1583
+ stepRefToId.set(step.ID, step.ID);
1510
1584
  }
1511
1585
  }
1512
1586
  }
@@ -1517,32 +1591,29 @@ export class AgentSpecSync {
1517
1591
  this._contextUser
1518
1592
  );
1519
1593
 
1520
- // Load existing if ID provided
1521
- const isUpdate = !!(pathSpec.ID && pathSpec.ID !== '');
1522
- if (isUpdate) {
1523
- await pathEntity.Load(pathSpec.ID);
1524
- }
1525
-
1526
- // Resolve step IDs from step names
1527
- // OriginStepID and DestinationStepID can be either step IDs or step names
1528
- // If they're names, look them up in our map
1529
- let originStepId = pathSpec.OriginStepID;
1530
- let destinationStepId = pathSpec.DestinationStepID;
1531
-
1532
- // Try to resolve as step names first
1533
- if (stepNameToId.has(pathSpec.OriginStepID)) {
1534
- originStepId = stepNameToId.get(pathSpec.OriginStepID)!;
1594
+ // Only load from DB when pathSpec.ID is a real persisted UUID; synthetic IDs
1595
+ // (such as 'wf-node-3') are new path records.
1596
+ let isUpdate = false;
1597
+ if (isPersistedUUID(pathSpec.ID)) {
1598
+ isUpdate = await pathEntity.Load(pathSpec.ID);
1535
1599
  }
1536
- if (stepNameToId.has(pathSpec.DestinationStepID)) {
1537
- destinationStepId = stepNameToId.get(pathSpec.DestinationStepID)!;
1600
+ if (!isUpdate) {
1601
+ pathEntity.NewRecord?.();
1538
1602
  }
1539
1603
 
1604
+ // Resolve step IDs from synthetic step IDs or step names
1605
+ const originStepId = stepRefToId.get(pathSpec.OriginStepID) ?? pathSpec.OriginStepID;
1606
+ const destinationStepId = stepRefToId.get(pathSpec.DestinationStepID) ?? pathSpec.DestinationStepID;
1607
+
1540
1608
  // Map fields
1541
1609
  pathEntity.OriginStepID = originStepId;
1542
1610
  pathEntity.DestinationStepID = destinationStepId;
1543
1611
  pathEntity.Condition = pathSpec.Condition || null;
1544
1612
  pathEntity.Description = pathSpec.Description || null;
1545
1613
  pathEntity.Priority = pathSpec.Priority;
1614
+ if (pathSpec.PathPoints !== undefined) {
1615
+ pathEntity.PathPoints = pathSpec.PathPoints || null;
1616
+ }
1546
1617
 
1547
1618
  const saved = await pathEntity.Save();
1548
1619
  if (!saved) {
@@ -1557,8 +1628,10 @@ export class AgentSpecSync {
1557
1628
  `${isUpdate ? 'Updated' : 'Created'} path from "${pathSpec.OriginStepID}" to "${pathSpec.DestinationStepID}"`
1558
1629
  );
1559
1630
 
1560
- // Update the spec with the saved ID
1631
+ // Update the spec with the saved IDs
1561
1632
  pathSpec.ID = pathEntity.ID;
1633
+ pathSpec.OriginStepID = originStepId;
1634
+ pathSpec.DestinationStepID = destinationStepId;
1562
1635
 
1563
1636
  console.log(`✅ saveStepPaths: Created AIAgentStepPath with ID: ${pathEntity.ID}`);
1564
1637
  }
@@ -88,7 +88,11 @@ export class WorkflowAgentWriter extends WorkflowAgentWriterBase {
88
88
  // consumed by MCP tools, so it is left alone rather than renamed under this change.
89
89
  const saved = await sync.SaveToDatabase();
90
90
  if (!saved?.success) {
91
- throw new Error(`Could not save the workflow's agent "${spec.name}".`);
91
+ throw new Error(
92
+ saved?.errorMessage
93
+ ? `Could not save the workflow's agent "${spec.name}": ${saved.errorMessage}`
94
+ : `Could not save the workflow's agent "${spec.name}".`,
95
+ );
92
96
  }
93
97
  return saved.agentId;
94
98
  }
@@ -105,8 +109,8 @@ export class WorkflowAgentWriter extends WorkflowAgentWriterBase {
105
109
  }
106
110
 
107
111
  /**
108
- * Name → ID for every agent, action and prompt, in one batch, lowercased so a spec's
109
- * human-entered name still resolves.
112
+ * Name (and ID) → ID for every agent, action and prompt, in one batch, lowercased so a spec's
113
+ * human-entered name or projected ID fallback still resolves.
110
114
  *
111
115
  * A failed load throws rather than leaving an index empty: an empty index resolves nothing, and
112
116
  * every agent, action and prompt in the workflow would then be reported lost — or, for an action,
@@ -130,8 +134,14 @@ export class WorkflowAgentWriter extends WorkflowAgentWriterBase {
130
134
  throw new Error(`Could not load the names a workflow's steps refer to (${reasons.join('; ')}).`);
131
135
  }
132
136
  const [agents, actions, prompts] = results;
133
- const index = (rows: Array<{ ID: string; Name: string }>): Map<string, string> =>
134
- new Map(rows.map((r) => [r.Name.trim().toLowerCase(), r.ID]));
137
+ const index = (rows: Array<{ ID: string; Name: string }>): Map<string, string> => {
138
+ const map = new Map<string, string>();
139
+ for (const r of rows) {
140
+ if (r.Name?.trim()) map.set(r.Name.trim().toLowerCase(), r.ID);
141
+ if (r.ID?.trim()) map.set(r.ID.trim().toLowerCase(), r.ID);
142
+ }
143
+ return map;
144
+ };
135
145
  return { Agents: index(agents.Results), Actions: index(actions.Results), Prompts: index(prompts.Results) };
136
146
  }
137
147
  }