@memberjunction/ai-agent-manager 6.3.0-edge.0 → 6.3.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @memberjunction/ai-agent-manager@6.3.0-edge.0 build /home/runner/work/MJ/MJ/packages/AI/AgentManager/core
2
+ > @memberjunction/ai-agent-manager@6.3.0-edge.1 build /home/runner/work/MJ/MJ/packages/AI/AgentManager/core
3
3
  > tsc && tsc-alias -f
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,92 @@
1
1
  # @memberjunction/ai-agent-manager
2
2
 
3
+ ## 6.3.0-edge.1
4
+
5
+ ### Minor Changes
6
+
7
+ - 11f5574: Agent spec sync links sub-agent steps by name and creates loop-step prompts (#4914): a Sub-Agent step, or a loop whose body is a sub-agent, saved with an empty `SubAgentID` links to the spec's sub-agent of the same name, else to the one active agent of that name; zero or several matches refuse the save before anything is written. A loop whose body is a prompt written inline as `PromptText` gets its AIPrompt created and linked, as a Prompt step does. The Architect prompt template now describes this linking.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [13a71da]
12
+ - Updated dependencies [d4350c0]
13
+ - Updated dependencies [1be3915]
14
+ - Updated dependencies [ae69eec]
15
+ - Updated dependencies [2b07be4]
16
+ - Updated dependencies [019fd49]
17
+ - Updated dependencies [8e41e43]
18
+ - Updated dependencies [1618217]
19
+ - Updated dependencies [a1d83dc]
20
+ - Updated dependencies [367a259]
21
+ - Updated dependencies [49731ee]
22
+ - Updated dependencies [b5c4a3c]
23
+ - Updated dependencies [2f64a46]
24
+ - Updated dependencies [e5a392f]
25
+ - Updated dependencies [5c0fba9]
26
+ - Updated dependencies [2d938cf]
27
+ - Updated dependencies [2006748]
28
+ - Updated dependencies [7a3333e]
29
+ - Updated dependencies [0f4d357]
30
+ - Updated dependencies [1351528]
31
+ - Updated dependencies [236ecf3]
32
+ - Updated dependencies [3abebb3]
33
+ - Updated dependencies [4ba5642]
34
+ - Updated dependencies [44b885a]
35
+ - Updated dependencies [e768fd4]
36
+ - Updated dependencies [e912249]
37
+ - Updated dependencies [acd082e]
38
+ - Updated dependencies [e73f729]
39
+ - Updated dependencies [7b84db6]
40
+ - Updated dependencies [8c2b0d0]
41
+ - Updated dependencies [c5a5197]
42
+ - Updated dependencies [8c2b0d0]
43
+ - Updated dependencies [0fdcb51]
44
+ - Updated dependencies [880a114]
45
+ - Updated dependencies [fa811cc]
46
+ - Updated dependencies [bc39181]
47
+ - Updated dependencies [09cdf29]
48
+ - Updated dependencies [c67470e]
49
+ - Updated dependencies [1f24d8a]
50
+ - Updated dependencies [c51c6f3]
51
+ - Updated dependencies [35bffba]
52
+ - Updated dependencies [86326f2]
53
+ - Updated dependencies [a9e640a]
54
+ - Updated dependencies [46173bd]
55
+ - Updated dependencies [31c2439]
56
+ - Updated dependencies [4262206]
57
+ - Updated dependencies [f53f828]
58
+ - Updated dependencies [346a8d6]
59
+ - Updated dependencies [2b4969f]
60
+ - Updated dependencies [dc30912]
61
+ - Updated dependencies [116cb9a]
62
+ - Updated dependencies [1864853]
63
+ - Updated dependencies [d1bf1c9]
64
+ - Updated dependencies [442014c]
65
+ - Updated dependencies [0af123e]
66
+ - Updated dependencies [cdcbfd1]
67
+ - Updated dependencies [05100bd]
68
+ - Updated dependencies [fff3a52]
69
+ - Updated dependencies [f5ccd44]
70
+ - Updated dependencies [38ca94f]
71
+ - Updated dependencies [6ea73e6]
72
+ - Updated dependencies [7ad8b8a]
73
+ - Updated dependencies [9066253]
74
+ - Updated dependencies [e781aec]
75
+ - Updated dependencies [1197598]
76
+ - Updated dependencies [ce32cbf]
77
+ - Updated dependencies [64cc6f4]
78
+ - Updated dependencies [7747b73]
79
+ - Updated dependencies [3e9d745]
80
+ - Updated dependencies [687393c]
81
+ - @memberjunction/ai-core-plus@6.3.0-edge.1
82
+ - @memberjunction/ai-agents@6.3.0-edge.1
83
+ - @memberjunction/core@6.3.0-edge.1
84
+ - @memberjunction/core-entities@6.3.0-edge.1
85
+ - @memberjunction/global@6.3.0-edge.1
86
+ - @memberjunction/ai-engine-base@6.3.0-edge.1
87
+ - @memberjunction/aiengine@6.3.0-edge.1
88
+ - @memberjunction/templates@6.3.0-edge.1
89
+
3
90
  ## 6.3.0-edge.0
4
91
 
5
92
  ### Patch Changes
@@ -123,6 +123,12 @@ export declare class AgentSpecSync {
123
123
  * @private
124
124
  */
125
125
  private _stepIdMap;
126
+ /**
127
+ * Sub-agent links for steps saved with an empty `SubAgentID`, keyed by the step spec. Resolved
128
+ * before anything is written, so a step that names no sub-agent, or several, refuses the save.
129
+ * @private
130
+ */
131
+ private _stepSubAgentLinks;
126
132
  /**
127
133
  * Create a new AgentSpecSync instance.
128
134
  *
@@ -403,6 +409,45 @@ export declare class AgentSpecSync {
403
409
  * @throws {Error} If any prompt save fails
404
410
  */
405
411
  private savePrompts;
412
+ /**
413
+ * Resolve the sub-agent of every step that runs one (a Sub-Agent step, or a loop whose body is a
414
+ * sub-agent) and leaves `SubAgentID` empty. The step's Name links it: first to this spec's own
415
+ * sub-agents, then to active agents in the database. Zero or several matches refuse the save
416
+ * rather than leave the step unlinked or pick one arbitrarily.
417
+ *
418
+ * @private
419
+ * @throws {Error} Listing every step that names no sub-agent, or several
420
+ */
421
+ private resolveStepSubAgentLinks;
422
+ /**
423
+ * Find the one sub-agent a step's Name links to, or record why there is none.
424
+ * @private
425
+ */
426
+ private findStepSubAgent;
427
+ /**
428
+ * The spec sub-agents with duplicates removed: entries naming the same saved agent count once.
429
+ * Entries not yet saved (empty ID) are each a separate agent to create.
430
+ * @private
431
+ */
432
+ private distinctSubAgents;
433
+ /**
434
+ * IDs of the active agents with this name, other than the agent being saved.
435
+ * @private
436
+ */
437
+ private findActiveAgentIdsByName;
438
+ /**
439
+ * The SubAgentID to save on a step: its own, or the one its Name resolved to.
440
+ * @private
441
+ */
442
+ private stepSubAgentID;
443
+ /**
444
+ * Create the AIPrompt for a step whose prompt is written inline as PromptText.
445
+ *
446
+ * @private
447
+ * @returns The new prompt's ID
448
+ * @throws {Error} If the prompt save fails
449
+ */
450
+ private createInlineStepPrompt;
406
451
  /**
407
452
  * Save all steps for this agent (Flow agents only).
408
453
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent-spec-sync.d.ts","sourceRoot":"","sources":["../src/agent-spec-sync.ts"],"names":[],"mappings":"AAAA,OAAO,EAGH,QAAQ,EAER,iBAAiB,EACpB,MAAM,sBAAsB,CAAC;AAQ9B,OAAO,EACH,SAAS,EAKZ,MAAM,8BAA8B,CAAC;AAItC;;GAEG;AACH,MAAM,WAAW,qBAAqB;IAClC,6EAA6E;IAC7E,MAAM,EAAE,MAAM,CAAC;IACf,qBAAqB;IACrB,SAAS,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;IAC1C,gBAAgB;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;CACvB;AAQD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,4BAA4B;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,OAAO,EAAE,OAAO,CAAC;IACjB,0CAA0C;IAC1C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gDAAgD;IAChD,SAAS,EAAE,qBAAqB,EAAE,CAAC;CACtC;AA8BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,qBAAa,aAAa;IACtB;;OAEG;IACI,IAAI,EAAE,SAAS,CAAC;IAEvB,oCAAoC;IACpC,IAAW,IAAI,IAAI,SAAS,CAE3B;IACD,oCAAoC;IACpC,IAAW,IAAI,CAAC,KAAK,EAAE,SAAS,EAE/B;IAED;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAkB;IAEnC;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAkB;IAElC;;;OAGG;IACH,OAAO,CAAC,YAAY,CAA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;;;;;;;;;;;;OAcG;IACI,SAAS,IAAI,IAAI;IAIxB,yCAAyC;IAClC,SAAS,IAAI,IAAI;IAIxB;;;;;;;;;;;;;;;;OAgBG;IACI,UAAU,IAAI,IAAI;IAIzB,0CAA0C;IACnC,UAAU,IAAI,IAAI;IAMzB;;;;;;;;;;OAUG;YACW,wBAAwB;IAuEtC;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,eAAe;IAsCvB;;;;;;;;;;;;;;OAcG;YACW,aAAa;IAuH3B;;;;;;;;;;;;;;OAcG;YACW,gBAAgB;CAmBjC"}
@@ -1,10 +1,24 @@
1
1
  import { Metadata, RunView, LogError } from '@memberjunction/core';
2
- import { UUIDsEqual } from '@memberjunction/global';
3
- import { StepConfigurationText } from './flow-step-validation.js';
2
+ import { UUIDsEqual, UUIDSet } from '@memberjunction/global';
3
+ import { IsLoopStep, StepConfigurationText } from './flow-step-validation.js';
4
4
  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
5
  function isPersistedUUID(id) {
6
6
  return typeof id === 'string' && UUID_REGEX.test(id.trim());
7
7
  }
8
+ /** The seeded "Chat" AI Prompt Type that inline step prompts are created under. */
9
+ const CHAT_PROMPT_TYPE_ID = 'a6da423e-f36b-1410-8dac-00021f8b792e';
10
+ /** A Sub-Agent step, or a loop step whose body is a sub-agent. */
11
+ function stepRunsSubAgent(step) {
12
+ return step.StepType === 'Sub-Agent' || (IsLoopStep(step) && step.LoopBodyType === 'Sub-Agent');
13
+ }
14
+ /** A Prompt step, or a loop step whose body is a prompt. */
15
+ function stepRunsPrompt(step) {
16
+ return step.StepType === 'Prompt' || (IsLoopStep(step) && step.LoopBodyType === 'Prompt');
17
+ }
18
+ /** Names compare the way SQL Server's default collation does: trimmed, case-insensitive. */
19
+ function sameName(a, b) {
20
+ return (a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
21
+ }
8
22
  /**
9
23
  * AgentSpecSync provides a high-level interface for working with AI Agent metadata in MemberJunction.
10
24
  *
@@ -105,6 +119,12 @@ export class AgentSpecSync {
105
119
  * @private
106
120
  */
107
121
  this._stepIdMap = new Map();
122
+ /**
123
+ * Sub-agent links for steps saved with an empty `SubAgentID`, keyed by the step spec. Resolved
124
+ * before anything is written, so a step that names no sub-agent, or several, refuses the save.
125
+ * @private
126
+ */
127
+ this._stepSubAgentLinks = new Map();
108
128
  if (spec) {
109
129
  this.Spec = this.initializeSpec(spec);
110
130
  this._isDirty = true;
@@ -655,6 +675,9 @@ export class AgentSpecSync {
655
675
  };
656
676
  }
657
677
  try {
678
+ // Resolve name-linked sub-agent steps first, so a step naming no sub-agent (or several)
679
+ // refuses the save before any record is written.
680
+ await this.resolveStepSubAgentLinks();
658
681
  // Step 0: Delete orphaned records (if this is an update)
659
682
  if (this._isLoaded && this.Spec.ID) {
660
683
  console.log(`🗑️ SaveToDatabase: Loading current database state for agent ${this.Spec.ID}...`);
@@ -1075,6 +1098,143 @@ export class AgentSpecSync {
1075
1098
  }
1076
1099
  console.log(`✅ savePrompts: Successfully saved all ${this.Spec.Prompts.length} prompt(s)`);
1077
1100
  }
1101
+ /**
1102
+ * Resolve the sub-agent of every step that runs one (a Sub-Agent step, or a loop whose body is a
1103
+ * sub-agent) and leaves `SubAgentID` empty. The step's Name links it: first to this spec's own
1104
+ * sub-agents, then to active agents in the database. Zero or several matches refuse the save
1105
+ * rather than leave the step unlinked or pick one arbitrarily.
1106
+ *
1107
+ * @private
1108
+ * @throws {Error} Listing every step that names no sub-agent, or several
1109
+ */
1110
+ async resolveStepSubAgentLinks() {
1111
+ this._stepSubAgentLinks.clear();
1112
+ const unlinked = (this.Spec.Steps ?? []).filter(step => stepRunsSubAgent(step) && !step.SubAgentID);
1113
+ if (unlinked.length === 0) {
1114
+ return;
1115
+ }
1116
+ const errors = [];
1117
+ for (const step of unlinked) {
1118
+ const link = await this.findStepSubAgent(step, errors);
1119
+ if (link) {
1120
+ this._stepSubAgentLinks.set(step, link);
1121
+ }
1122
+ }
1123
+ if (errors.length > 0) {
1124
+ throw new Error(`Cannot link sub-agent steps: ${errors.join('; ')}`);
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Find the one sub-agent a step's Name links to, or record why there is none.
1129
+ * @private
1130
+ */
1131
+ async findStepSubAgent(step, errors) {
1132
+ const specMatches = this.distinctSubAgents((this.Spec.SubAgents ?? []).filter(sub => sameName(sub.SubAgent?.Name, step.Name)));
1133
+ if (specMatches.length === 1) {
1134
+ return { Source: 'spec', SubAgent: specMatches[0] };
1135
+ }
1136
+ if (specMatches.length > 1) {
1137
+ errors.push(`step "${step.Name}" matches ${specMatches.length} sub-agents in the spec; set its SubAgentID`);
1138
+ return null;
1139
+ }
1140
+ const existingIds = await this.findActiveAgentIdsByName(step.Name);
1141
+ if (existingIds.length === 1) {
1142
+ return { Source: 'existing', AgentID: existingIds[0] };
1143
+ }
1144
+ errors.push(existingIds.length === 0
1145
+ ? `step "${step.Name}" has no SubAgentID and no sub-agent in the spec or active agent has that name`
1146
+ : `step "${step.Name}" matches ${existingIds.length} active agents; set its SubAgentID`);
1147
+ return null;
1148
+ }
1149
+ /**
1150
+ * The spec sub-agents with duplicates removed: entries naming the same saved agent count once.
1151
+ * Entries not yet saved (empty ID) are each a separate agent to create.
1152
+ * @private
1153
+ */
1154
+ distinctSubAgents(subAgents) {
1155
+ const distinct = [];
1156
+ const seen = new UUIDSet();
1157
+ for (const sub of subAgents) {
1158
+ const id = sub.SubAgent?.ID;
1159
+ if (id) {
1160
+ if (seen.Has(id))
1161
+ continue;
1162
+ seen.Add(id);
1163
+ }
1164
+ distinct.push(sub);
1165
+ }
1166
+ return distinct;
1167
+ }
1168
+ /**
1169
+ * IDs of the active agents with this name, other than the agent being saved.
1170
+ * @private
1171
+ */
1172
+ async findActiveAgentIdsByName(name) {
1173
+ const rv = RunView.FromMetadataProvider(this.providerToUse);
1174
+ const result = await rv.RunView({
1175
+ EntityName: 'MJ: AI Agents',
1176
+ ExtraFilter: `Name='${name.trim().replace(/'/g, "''")}' AND Status='Active'`,
1177
+ Fields: ['ID'],
1178
+ ResultType: 'simple'
1179
+ }, this._contextUser);
1180
+ if (!result.Success) {
1181
+ throw new Error(`Failed to look up agent "${name}": ${result.ErrorMessage}`);
1182
+ }
1183
+ const ids = [];
1184
+ const seen = new UUIDSet();
1185
+ for (const row of result.Results ?? []) {
1186
+ if (this.Spec.ID && UUIDsEqual(row.ID, this.Spec.ID))
1187
+ continue;
1188
+ if (seen.Has(row.ID))
1189
+ continue;
1190
+ seen.Add(row.ID);
1191
+ ids.push(row.ID);
1192
+ }
1193
+ return ids;
1194
+ }
1195
+ /**
1196
+ * The SubAgentID to save on a step: its own, or the one its Name resolved to.
1197
+ * @private
1198
+ */
1199
+ stepSubAgentID(stepSpec) {
1200
+ if (stepSpec.SubAgentID) {
1201
+ return stepSpec.SubAgentID;
1202
+ }
1203
+ const link = this._stepSubAgentLinks.get(stepSpec);
1204
+ if (!link) {
1205
+ return null;
1206
+ }
1207
+ const id = link.Source === 'spec' ? link.SubAgent.SubAgent?.ID : link.AgentID;
1208
+ if (!id) {
1209
+ throw new Error(`Sub-agent "${stepSpec.Name}" has no ID after saving sub-agents`);
1210
+ }
1211
+ stepSpec.SubAgentID = id; // Update spec too
1212
+ return id;
1213
+ }
1214
+ /**
1215
+ * Create the AIPrompt for a step whose prompt is written inline as PromptText.
1216
+ *
1217
+ * @private
1218
+ * @returns The new prompt's ID
1219
+ * @throws {Error} If the prompt save fails
1220
+ */
1221
+ async createInlineStepPrompt(stepSpec) {
1222
+ console.log(`🔷 saveSteps: Creating inline prompt for step "${stepSpec.Name}"`);
1223
+ const promptEntity = await this.providerToUse.GetEntityObject('MJ: AI Prompts', this._contextUser);
1224
+ promptEntity.Name = stepSpec.PromptName || `${stepSpec.Name} Prompt`;
1225
+ promptEntity.Description = stepSpec.PromptDescription || `Prompt for step: ${stepSpec.Name}`;
1226
+ promptEntity.TypeID = CHAT_PROMPT_TYPE_ID;
1227
+ promptEntity.Status = 'Active';
1228
+ promptEntity.ResponseFormat = 'JSON';
1229
+ promptEntity.TemplateText = stepSpec.PromptText ?? '';
1230
+ const promptSaved = await promptEntity.Save();
1231
+ if (!promptSaved) {
1232
+ throw new Error(`Failed to save inline prompt for step "${stepSpec.Name}"`);
1233
+ }
1234
+ this.trackMutation('MJ: AI Prompts', 'Create', promptEntity.ID, `Created inline prompt: ${promptEntity.Name}`);
1235
+ console.log(`✅ saveSteps: Created inline AIPrompt with ID: ${promptEntity.ID}`);
1236
+ return promptEntity.ID;
1237
+ }
1078
1238
  /**
1079
1239
  * Save all steps for this agent (Flow agents only).
1080
1240
  *
@@ -1113,7 +1273,7 @@ export class AgentSpecSync {
1113
1273
  stepEntity.StepType = stepSpec.StepType;
1114
1274
  stepEntity.StartingStep = stepSpec.StartingStep;
1115
1275
  stepEntity.ActionID = stepSpec.ActionID || null;
1116
- stepEntity.SubAgentID = stepSpec.SubAgentID || null;
1276
+ stepEntity.SubAgentID = this.stepSubAgentID(stepSpec);
1117
1277
  stepEntity.Status = 'Active'; // Default to Active
1118
1278
  // Loop steps: the body type says which of Action/Prompt/Sub-Agent runs each pass, and
1119
1279
  // Configuration carries the bounds. Written for every step because a step that STOPS
@@ -1144,33 +1304,16 @@ export class AgentSpecSync {
1144
1304
  if (stepSpec.Height !== undefined) {
1145
1305
  stepEntity.Height = Math.round(stepSpec.Height);
1146
1306
  }
1147
- // Handle inline prompt creation for Prompt-type steps
1148
- // If StepType is Prompt and PromptID is empty, create a new AIPrompt record
1149
- if (stepSpec.StepType === 'Prompt' && (!stepSpec.PromptID || stepSpec.PromptID === '')) {
1307
+ // A Prompt step, or a loop whose body is a prompt, with an empty PromptID and inline
1308
+ // PromptText gets a new AIPrompt created and linked.
1309
+ if (stepRunsPrompt(stepSpec) && !stepSpec.PromptID) {
1150
1310
  if (stepSpec.PromptText) {
1151
- console.log(`🔷 saveSteps: Creating inline prompt for step "${stepSpec.Name}"`);
1152
- // Create AIPrompt entity (using any type for TemplateText dynamic property)
1153
- const promptEntity = await md.GetEntityObject('MJ: AI Prompts', this._contextUser);
1154
- // Set prompt fields
1155
- promptEntity.Name = stepSpec.PromptName || `${stepSpec.Name} Prompt`;
1156
- promptEntity.Description = stepSpec.PromptDescription || `Prompt for step: ${stepSpec.Name}`;
1157
- promptEntity.TypeID = 'a6da423e-f36b-1410-8dac-00021f8b792e'; // Chat type
1158
- promptEntity.Status = 'Active';
1159
- promptEntity.ResponseFormat = 'JSON';
1160
- promptEntity.TemplateText = stepSpec.PromptText; // TemplateText is a dynamic property
1161
- const promptSaved = await promptEntity.Save();
1162
- if (!promptSaved) {
1163
- throw new Error(`Failed to save inline prompt for step "${stepSpec.Name}"`);
1164
- }
1165
- // Track mutation
1166
- this.trackMutation('MJ: AI Prompts', 'Create', promptEntity.ID, `Created inline prompt: ${promptEntity.Name}`);
1167
- console.log(`✅ saveSteps: Created inline AIPrompt with ID: ${promptEntity.ID}`);
1168
- // Link the created prompt to this step
1169
- stepEntity.PromptID = promptEntity.ID;
1170
- stepSpec.PromptID = promptEntity.ID; // Update spec too
1311
+ const promptId = await this.createInlineStepPrompt(stepSpec);
1312
+ stepEntity.PromptID = promptId;
1313
+ stepSpec.PromptID = promptId; // Update spec too
1171
1314
  }
1172
1315
  else {
1173
- console.warn(`⚠️ saveSteps: Step "${stepSpec.Name}" is Prompt type with empty PromptID but no PromptText provided`);
1316
+ console.warn(`⚠️ saveSteps: Step "${stepSpec.Name}" runs a prompt with empty PromptID but no PromptText provided`);
1174
1317
  stepEntity.PromptID = null;
1175
1318
  }
1176
1319
  }