@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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +87 -0
- package/dist/agent-spec-sync.d.ts +45 -0
- package/dist/agent-spec-sync.d.ts.map +1 -1
- package/dist/agent-spec-sync.js +170 -27
- package/dist/agent-spec-sync.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +9 -9
- package/src/__tests__/agent-spec-sync-step-links.test.ts +312 -0
- package/src/agent-spec-sync.ts +201 -41
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/ai-agent-manager",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.3.0-edge.
|
|
4
|
+
"version": "6.3.0-edge.1",
|
|
5
5
|
"description": "Core interfaces and types for the MemberJunction Agent Manager system",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -14,14 +14,14 @@
|
|
|
14
14
|
"author": "MemberJunction",
|
|
15
15
|
"license": "BUSL-1.1",
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@memberjunction/ai-agents": "6.3.0-edge.
|
|
18
|
-
"@memberjunction/ai-core-plus": "6.3.0-edge.
|
|
19
|
-
"@memberjunction/ai-engine-base": "6.3.0-edge.
|
|
20
|
-
"@memberjunction/aiengine": "6.3.0-edge.
|
|
21
|
-
"@memberjunction/core": "6.3.0-edge.
|
|
22
|
-
"@memberjunction/core-entities": "6.3.0-edge.
|
|
23
|
-
"@memberjunction/global": "6.3.0-edge.
|
|
24
|
-
"@memberjunction/templates": "6.3.0-edge.
|
|
17
|
+
"@memberjunction/ai-agents": "6.3.0-edge.1",
|
|
18
|
+
"@memberjunction/ai-core-plus": "6.3.0-edge.1",
|
|
19
|
+
"@memberjunction/ai-engine-base": "6.3.0-edge.1",
|
|
20
|
+
"@memberjunction/aiengine": "6.3.0-edge.1",
|
|
21
|
+
"@memberjunction/core": "6.3.0-edge.1",
|
|
22
|
+
"@memberjunction/core-entities": "6.3.0-edge.1",
|
|
23
|
+
"@memberjunction/global": "6.3.0-edge.1",
|
|
24
|
+
"@memberjunction/templates": "6.3.0-edge.1"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/node": "^24.10.11",
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coverage for how AgentSpecSync links a Flow step to what it runs when the spec leaves the ID empty
|
|
3
|
+
* (#4914):
|
|
4
|
+
* - a Sub-Agent step, or a loop whose body is a sub-agent, links by its Name to the spec's own
|
|
5
|
+
* sub-agent or to an active agent, and refuses the save on zero or several matches;
|
|
6
|
+
* - a loop whose body is a prompt written inline as PromptText gets an AIPrompt created and linked.
|
|
7
|
+
*
|
|
8
|
+
* A dedicated mock (not the shared one in agent-spec-sync.test.ts) is used because a save needs
|
|
9
|
+
* `Metadata.Provider` and `RunView.FromMetadataProvider`, distinct IDs per created record, and a
|
|
10
|
+
* scripted agent lookup.
|
|
11
|
+
*/
|
|
12
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
13
|
+
|
|
14
|
+
interface CapturedEntity {
|
|
15
|
+
EntityName: string;
|
|
16
|
+
ID: string;
|
|
17
|
+
[field: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface AgentLookupResult {
|
|
21
|
+
Success: boolean;
|
|
22
|
+
Results: { ID: string }[];
|
|
23
|
+
RowCount: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const { captured, mockGetEntityObject, mockRunView, mockRunViews, agentLookup } = vi.hoisted(() => {
|
|
27
|
+
const captured: CapturedEntity[] = [];
|
|
28
|
+
let counter = 0;
|
|
29
|
+
const agentLookup: { rows: { ID: string }[]; filters: string[] } = { rows: [], filters: [] };
|
|
30
|
+
|
|
31
|
+
const makeEntity = (entityName: string): CapturedEntity => {
|
|
32
|
+
counter++;
|
|
33
|
+
const entity: CapturedEntity = {
|
|
34
|
+
EntityName: entityName,
|
|
35
|
+
ID: `00000000-0000-4000-8000-${String(counter).padStart(12, '0')}`,
|
|
36
|
+
Load: vi.fn().mockResolvedValue(true),
|
|
37
|
+
Save: vi.fn().mockResolvedValue(true),
|
|
38
|
+
Delete: vi.fn().mockResolvedValue(true),
|
|
39
|
+
NewRecord: vi.fn(),
|
|
40
|
+
Validate: vi.fn().mockReturnValue({ Success: true, Errors: [] }),
|
|
41
|
+
};
|
|
42
|
+
captured.push(entity);
|
|
43
|
+
return entity;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const empty = { Success: true, Results: [], RowCount: 0 };
|
|
47
|
+
return {
|
|
48
|
+
captured,
|
|
49
|
+
agentLookup,
|
|
50
|
+
mockGetEntityObject: vi.fn((name: string) => Promise.resolve(makeEntity(name))),
|
|
51
|
+
mockRunView: vi.fn((params: { EntityName: string; ExtraFilter?: string }): Promise<AgentLookupResult> => {
|
|
52
|
+
if (params.EntityName === 'MJ: AI Agents') {
|
|
53
|
+
agentLookup.filters.push(params.ExtraFilter ?? '');
|
|
54
|
+
return Promise.resolve({ Success: true, Results: agentLookup.rows, RowCount: agentLookup.rows.length });
|
|
55
|
+
}
|
|
56
|
+
return Promise.resolve(empty);
|
|
57
|
+
}),
|
|
58
|
+
mockRunViews: vi.fn(() => Promise.resolve([empty, empty, empty, empty, empty])),
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
vi.mock('@memberjunction/core', () => {
|
|
63
|
+
const rvInstance = { RunView: mockRunView, RunViews: mockRunViews };
|
|
64
|
+
return {
|
|
65
|
+
Metadata: Object.assign(
|
|
66
|
+
vi.fn().mockImplementation(() => ({ GetEntityObject: mockGetEntityObject })),
|
|
67
|
+
{ Provider: { GetEntityObject: mockGetEntityObject } }
|
|
68
|
+
),
|
|
69
|
+
RunView: Object.assign(
|
|
70
|
+
vi.fn().mockImplementation(() => rvInstance),
|
|
71
|
+
{ FromMetadataProvider: vi.fn(() => rvInstance) }
|
|
72
|
+
),
|
|
73
|
+
UserInfo: vi.fn(),
|
|
74
|
+
LogError: vi.fn(),
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
vi.mock('@memberjunction/core-entities', () => ({
|
|
79
|
+
MJAIAgentEntity: vi.fn(),
|
|
80
|
+
MJAIAgentActionEntity: vi.fn(),
|
|
81
|
+
MJAIAgentRelationshipEntity: vi.fn(),
|
|
82
|
+
MJAIAgentStepEntity: vi.fn(),
|
|
83
|
+
MJAIAgentStepPathEntity: vi.fn(),
|
|
84
|
+
}));
|
|
85
|
+
|
|
86
|
+
vi.mock('@memberjunction/ai-core-plus', () => ({
|
|
87
|
+
AgentSpec: vi.fn(),
|
|
88
|
+
AgentActionSpec: vi.fn(),
|
|
89
|
+
SubAgentSpec: vi.fn(),
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
import { UserInfo } from '@memberjunction/core';
|
|
93
|
+
import type { AgentSpec, AgentStep, SubAgentSpec } from '@memberjunction/ai-core-plus';
|
|
94
|
+
import { AgentSpecSync } from '../agent-spec-sync';
|
|
95
|
+
|
|
96
|
+
const FLOW_TYPE_ID = '4F6A189B-C068-4736-9F23-3FF540B40FDD';
|
|
97
|
+
const EXISTING_AGENT_ID = 'A1B2C3D4-0000-4000-8000-000000000001';
|
|
98
|
+
const OTHER_AGENT_ID = 'A1B2C3D4-0000-4000-8000-000000000002';
|
|
99
|
+
|
|
100
|
+
const forEachConfig = { itemVariable: 'item', collectionPath: 'payload.items' };
|
|
101
|
+
|
|
102
|
+
function flowSpec(steps: AgentStep[], subAgents: SubAgentSpec[] = []): Partial<AgentSpec> {
|
|
103
|
+
return {
|
|
104
|
+
ID: '',
|
|
105
|
+
Name: 'Ticket Flow',
|
|
106
|
+
TypeID: FLOW_TYPE_ID,
|
|
107
|
+
Steps: steps,
|
|
108
|
+
Paths: [],
|
|
109
|
+
SubAgents: subAgents,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function relatedSubAgent(id: string, name: string): SubAgentSpec {
|
|
114
|
+
return { Type: 'related', SubAgent: { ID: id, Name: name } as AgentSpec } as SubAgentSpec;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function childSubAgent(name: string): SubAgentSpec {
|
|
118
|
+
return { Type: 'child', SubAgent: { ID: '', Name: name, Steps: [], SubAgents: [] } as AgentSpec } as SubAgentSpec;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function savedStep(name: string): CapturedEntity | undefined {
|
|
122
|
+
return captured.find(e => e.EntityName === 'MJ: AI Agent Steps' && e.Name === name);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
describe('AgentSpecSync step links', () => {
|
|
126
|
+
// UserInfo is mocked above, so this is the mock's instance.
|
|
127
|
+
const mockUser = new UserInfo();
|
|
128
|
+
|
|
129
|
+
beforeEach(() => {
|
|
130
|
+
vi.clearAllMocks();
|
|
131
|
+
captured.length = 0;
|
|
132
|
+
agentLookup.rows = [];
|
|
133
|
+
agentLookup.filters = [];
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
describe('Sub-Agent steps with an empty SubAgentID', () => {
|
|
137
|
+
it("links to the spec's related sub-agent of the same name", async () => {
|
|
138
|
+
const sync = new AgentSpecSync(
|
|
139
|
+
flowSpec(
|
|
140
|
+
[{ ID: '', Name: 'Ticket Analyzer', StepType: 'Sub-Agent', StartingStep: true, SubAgentID: '' }],
|
|
141
|
+
[relatedSubAgent(EXISTING_AGENT_ID, 'Ticket Analyzer')]
|
|
142
|
+
),
|
|
143
|
+
mockUser
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const result = await sync.SaveToDatabase();
|
|
147
|
+
|
|
148
|
+
expect(result.success).toBe(true);
|
|
149
|
+
expect(savedStep('Ticket Analyzer')?.SubAgentID).toBe(EXISTING_AGENT_ID);
|
|
150
|
+
// The spec match wins; the database is not searched.
|
|
151
|
+
expect(agentLookup.filters).toEqual([]);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('links to a child sub-agent the same save creates', async () => {
|
|
155
|
+
const sync = new AgentSpecSync(
|
|
156
|
+
flowSpec(
|
|
157
|
+
[{ ID: '', Name: 'ticket analyzer ', StepType: 'Sub-Agent', StartingStep: true, SubAgentID: '' }],
|
|
158
|
+
[childSubAgent('Ticket Analyzer')]
|
|
159
|
+
),
|
|
160
|
+
mockUser
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
const result = await sync.SaveToDatabase();
|
|
164
|
+
|
|
165
|
+
expect(result.success).toBe(true);
|
|
166
|
+
const childAgent = captured.find(e => e.EntityName === 'MJ: AI Agents' && e.Name === 'Ticket Analyzer');
|
|
167
|
+
expect(childAgent).toBeDefined();
|
|
168
|
+
expect(savedStep('ticket analyzer ')?.SubAgentID).toBe(childAgent?.ID);
|
|
169
|
+
expect(sync.spec.Steps?.[0].SubAgentID).toBe(childAgent?.ID);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('links to the one active agent of that name when the spec has none', async () => {
|
|
173
|
+
agentLookup.rows = [{ ID: EXISTING_AGENT_ID }];
|
|
174
|
+
const sync = new AgentSpecSync(
|
|
175
|
+
flowSpec([{ ID: '', Name: "Rep's Helper", StepType: 'Sub-Agent', StartingStep: true }]),
|
|
176
|
+
mockUser
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
const result = await sync.SaveToDatabase();
|
|
180
|
+
|
|
181
|
+
expect(result.success).toBe(true);
|
|
182
|
+
expect(savedStep("Rep's Helper")?.SubAgentID).toBe(EXISTING_AGENT_ID);
|
|
183
|
+
expect(agentLookup.filters).toEqual(["Name='Rep''s Helper' AND Status='Active'"]);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it('keeps a SubAgentID the spec already sets', async () => {
|
|
187
|
+
const sync = new AgentSpecSync(
|
|
188
|
+
flowSpec([{ ID: '', Name: 'Ticket Analyzer', StepType: 'Sub-Agent', StartingStep: true, SubAgentID: OTHER_AGENT_ID }]),
|
|
189
|
+
mockUser
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
const result = await sync.SaveToDatabase();
|
|
193
|
+
|
|
194
|
+
expect(result.success).toBe(true);
|
|
195
|
+
expect(savedStep('Ticket Analyzer')?.SubAgentID).toBe(OTHER_AGENT_ID);
|
|
196
|
+
expect(agentLookup.filters).toEqual([]);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('refuses the save, writing nothing, when no sub-agent has the name', async () => {
|
|
200
|
+
const sync = new AgentSpecSync(
|
|
201
|
+
flowSpec([{ ID: '', Name: 'Missing Agent', StepType: 'Sub-Agent', StartingStep: true, SubAgentID: '' }]),
|
|
202
|
+
mockUser
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
const result = await sync.SaveToDatabase();
|
|
206
|
+
|
|
207
|
+
expect(result.success).toBe(false);
|
|
208
|
+
expect(result.errorMessage).toContain('step "Missing Agent" has no SubAgentID');
|
|
209
|
+
expect(captured).toEqual([]);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('refuses the save when several active agents have the name', async () => {
|
|
213
|
+
agentLookup.rows = [{ ID: EXISTING_AGENT_ID }, { ID: OTHER_AGENT_ID }];
|
|
214
|
+
const sync = new AgentSpecSync(
|
|
215
|
+
flowSpec([{ ID: '', Name: 'Analyzer', StepType: 'Sub-Agent', StartingStep: true }]),
|
|
216
|
+
mockUser
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
const result = await sync.SaveToDatabase();
|
|
220
|
+
|
|
221
|
+
expect(result.success).toBe(false);
|
|
222
|
+
expect(result.errorMessage).toContain('matches 2 active agents');
|
|
223
|
+
expect(captured).toEqual([]);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('counts one active agent once when IDs differ only in case', async () => {
|
|
227
|
+
agentLookup.rows = [{ ID: EXISTING_AGENT_ID }, { ID: EXISTING_AGENT_ID.toLowerCase() }];
|
|
228
|
+
const sync = new AgentSpecSync(
|
|
229
|
+
flowSpec([{ ID: '', Name: 'Analyzer', StepType: 'Sub-Agent', StartingStep: true }]),
|
|
230
|
+
mockUser
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
const result = await sync.SaveToDatabase();
|
|
234
|
+
|
|
235
|
+
expect(result.success).toBe(true);
|
|
236
|
+
expect(savedStep('Analyzer')?.SubAgentID).toBe(EXISTING_AGENT_ID);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('refuses the save when several spec sub-agents have the name', async () => {
|
|
240
|
+
const sync = new AgentSpecSync(
|
|
241
|
+
flowSpec(
|
|
242
|
+
[{ ID: '', Name: 'Analyzer', StepType: 'Sub-Agent', StartingStep: true }],
|
|
243
|
+
[childSubAgent('Analyzer'), relatedSubAgent(OTHER_AGENT_ID, 'Analyzer')]
|
|
244
|
+
),
|
|
245
|
+
mockUser
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
const result = await sync.SaveToDatabase();
|
|
249
|
+
|
|
250
|
+
expect(result.success).toBe(false);
|
|
251
|
+
expect(result.errorMessage).toContain('matches 2 sub-agents in the spec');
|
|
252
|
+
expect(captured).toEqual([]);
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
describe('loop steps', () => {
|
|
257
|
+
it('links a loop whose body is a sub-agent by its name', async () => {
|
|
258
|
+
const sync = new AgentSpecSync(
|
|
259
|
+
flowSpec(
|
|
260
|
+
[{
|
|
261
|
+
ID: '', Name: 'Item Worker', StepType: 'ForEach', StartingStep: true,
|
|
262
|
+
LoopBodyType: 'Sub-Agent', Configuration: forEachConfig,
|
|
263
|
+
}],
|
|
264
|
+
[relatedSubAgent(EXISTING_AGENT_ID, 'Item Worker')]
|
|
265
|
+
),
|
|
266
|
+
mockUser
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
const result = await sync.SaveToDatabase();
|
|
270
|
+
|
|
271
|
+
expect(result.success).toBe(true);
|
|
272
|
+
expect(savedStep('Item Worker')?.SubAgentID).toBe(EXISTING_AGENT_ID);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it('creates and links the inline prompt of a loop whose body is a prompt', async () => {
|
|
276
|
+
const sync = new AgentSpecSync(
|
|
277
|
+
flowSpec([{
|
|
278
|
+
ID: '', Name: 'Summarize Items', StepType: 'ForEach', StartingStep: true,
|
|
279
|
+
LoopBodyType: 'Prompt', PromptID: '', PromptName: 'Item Summary',
|
|
280
|
+
PromptText: 'Summarize {{ item }}.', Configuration: forEachConfig,
|
|
281
|
+
}]),
|
|
282
|
+
mockUser
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
const result = await sync.SaveToDatabase();
|
|
286
|
+
|
|
287
|
+
expect(result.success).toBe(true);
|
|
288
|
+
const prompt = captured.find(e => e.EntityName === 'MJ: AI Prompts');
|
|
289
|
+
expect(prompt?.Name).toBe('Item Summary');
|
|
290
|
+
expect(prompt?.TemplateText).toBe('Summarize {{ item }}.');
|
|
291
|
+
expect(savedStep('Summarize Items')?.PromptID).toBe(prompt?.ID);
|
|
292
|
+
expect(result.mutations.some(m => m.Entity === 'MJ: AI Prompts' && m.Operation === 'Create')).toBe(true);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('creates no prompt for a loop whose body is an action', async () => {
|
|
296
|
+
const sync = new AgentSpecSync(
|
|
297
|
+
flowSpec([{
|
|
298
|
+
ID: '', Name: 'Send Each', StepType: 'ForEach', StartingStep: true,
|
|
299
|
+
LoopBodyType: 'Action', ActionID: OTHER_AGENT_ID,
|
|
300
|
+
PromptText: 'ignored', Configuration: forEachConfig,
|
|
301
|
+
}]),
|
|
302
|
+
mockUser
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
const result = await sync.SaveToDatabase();
|
|
306
|
+
|
|
307
|
+
expect(result.success).toBe(true);
|
|
308
|
+
expect(captured.some(e => e.EntityName === 'MJ: AI Prompts')).toBe(false);
|
|
309
|
+
expect(savedStep('Send Each')?.PromptID).toBeNull();
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
});
|
package/src/agent-spec-sync.ts
CHANGED
|
@@ -19,8 +19,9 @@ import {
|
|
|
19
19
|
AgentStepPath,
|
|
20
20
|
SubAgentSpec
|
|
21
21
|
} from '@memberjunction/ai-core-plus';
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
22
|
+
import type { MJAIPromptEntityExtended } from '@memberjunction/ai-core-plus';
|
|
23
|
+
import { UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
24
|
+
import { IsLoopStep, StepConfigurationText } from './flow-step-validation';
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* Represents a single database mutation performed by AgentSpecSync
|
|
@@ -42,6 +43,30 @@ function isPersistedUUID(id: string | null | undefined): id is string {
|
|
|
42
43
|
return typeof id === 'string' && UUID_REGEX.test(id.trim());
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
/** The seeded "Chat" AI Prompt Type that inline step prompts are created under. */
|
|
47
|
+
const CHAT_PROMPT_TYPE_ID = 'a6da423e-f36b-1410-8dac-00021f8b792e';
|
|
48
|
+
|
|
49
|
+
/** A Sub-Agent step, or a loop step whose body is a sub-agent. */
|
|
50
|
+
function stepRunsSubAgent(step: AgentStep): boolean {
|
|
51
|
+
return step.StepType === 'Sub-Agent' || (IsLoopStep(step) && step.LoopBodyType === 'Sub-Agent');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A Prompt step, or a loop step whose body is a prompt. */
|
|
55
|
+
function stepRunsPrompt(step: AgentStep): boolean {
|
|
56
|
+
return step.StepType === 'Prompt' || (IsLoopStep(step) && step.LoopBodyType === 'Prompt');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Names compare the way SQL Server's default collation does: trimmed, case-insensitive. */
|
|
60
|
+
function sameName(a: string | null | undefined, b: string | null | undefined): boolean {
|
|
61
|
+
return (a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Where a step with an empty `SubAgentID` gets its sub-agent: one of this spec's own sub-agents
|
|
66
|
+
* (whose ID exists only after `saveSubAgents`), or an existing active agent.
|
|
67
|
+
*/
|
|
68
|
+
type StepSubAgentLink = { Source: 'spec'; SubAgent: SubAgentSpec } | { Source: 'existing'; AgentID: string };
|
|
69
|
+
|
|
45
70
|
/**
|
|
46
71
|
* Result of SaveToDatabase operation including all mutations performed
|
|
47
72
|
*/
|
|
@@ -196,6 +221,13 @@ export class AgentSpecSync {
|
|
|
196
221
|
*/
|
|
197
222
|
private _stepIdMap = new Map<string, string>();
|
|
198
223
|
|
|
224
|
+
/**
|
|
225
|
+
* Sub-agent links for steps saved with an empty `SubAgentID`, keyed by the step spec. Resolved
|
|
226
|
+
* before anything is written, so a step that names no sub-agent, or several, refuses the save.
|
|
227
|
+
* @private
|
|
228
|
+
*/
|
|
229
|
+
private _stepSubAgentLinks = new Map<AgentStep, StepSubAgentLink>();
|
|
230
|
+
|
|
199
231
|
/**
|
|
200
232
|
* Create a new AgentSpecSync instance.
|
|
201
233
|
*
|
|
@@ -848,6 +880,10 @@ export class AgentSpecSync {
|
|
|
848
880
|
}
|
|
849
881
|
|
|
850
882
|
try {
|
|
883
|
+
// Resolve name-linked sub-agent steps first, so a step naming no sub-agent (or several)
|
|
884
|
+
// refuses the save before any record is written.
|
|
885
|
+
await this.resolveStepSubAgentLinks();
|
|
886
|
+
|
|
851
887
|
// Step 0: Delete orphaned records (if this is an update)
|
|
852
888
|
if (this._isLoaded && this.Spec.ID) {
|
|
853
889
|
console.log(`🗑️ SaveToDatabase: Loading current database state for agent ${this.Spec.ID}...`);
|
|
@@ -1382,6 +1418,161 @@ export class AgentSpecSync {
|
|
|
1382
1418
|
console.log(`✅ savePrompts: Successfully saved all ${this.Spec.Prompts.length} prompt(s)`);
|
|
1383
1419
|
}
|
|
1384
1420
|
|
|
1421
|
+
/**
|
|
1422
|
+
* Resolve the sub-agent of every step that runs one (a Sub-Agent step, or a loop whose body is a
|
|
1423
|
+
* sub-agent) and leaves `SubAgentID` empty. The step's Name links it: first to this spec's own
|
|
1424
|
+
* sub-agents, then to active agents in the database. Zero or several matches refuse the save
|
|
1425
|
+
* rather than leave the step unlinked or pick one arbitrarily.
|
|
1426
|
+
*
|
|
1427
|
+
* @private
|
|
1428
|
+
* @throws {Error} Listing every step that names no sub-agent, or several
|
|
1429
|
+
*/
|
|
1430
|
+
private async resolveStepSubAgentLinks(): Promise<void> {
|
|
1431
|
+
this._stepSubAgentLinks.clear();
|
|
1432
|
+
const unlinked = (this.Spec.Steps ?? []).filter(step => stepRunsSubAgent(step) && !step.SubAgentID);
|
|
1433
|
+
if (unlinked.length === 0) {
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
const errors: string[] = [];
|
|
1438
|
+
for (const step of unlinked) {
|
|
1439
|
+
const link = await this.findStepSubAgent(step, errors);
|
|
1440
|
+
if (link) {
|
|
1441
|
+
this._stepSubAgentLinks.set(step, link);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
if (errors.length > 0) {
|
|
1445
|
+
throw new Error(`Cannot link sub-agent steps: ${errors.join('; ')}`);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
/**
|
|
1450
|
+
* Find the one sub-agent a step's Name links to, or record why there is none.
|
|
1451
|
+
* @private
|
|
1452
|
+
*/
|
|
1453
|
+
private async findStepSubAgent(step: AgentStep, errors: string[]): Promise<StepSubAgentLink | null> {
|
|
1454
|
+
const specMatches = this.distinctSubAgents(
|
|
1455
|
+
(this.Spec.SubAgents ?? []).filter(sub => sameName(sub.SubAgent?.Name, step.Name))
|
|
1456
|
+
);
|
|
1457
|
+
if (specMatches.length === 1) {
|
|
1458
|
+
return { Source: 'spec', SubAgent: specMatches[0] };
|
|
1459
|
+
}
|
|
1460
|
+
if (specMatches.length > 1) {
|
|
1461
|
+
errors.push(`step "${step.Name}" matches ${specMatches.length} sub-agents in the spec; set its SubAgentID`);
|
|
1462
|
+
return null;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
const existingIds = await this.findActiveAgentIdsByName(step.Name);
|
|
1466
|
+
if (existingIds.length === 1) {
|
|
1467
|
+
return { Source: 'existing', AgentID: existingIds[0] };
|
|
1468
|
+
}
|
|
1469
|
+
errors.push(existingIds.length === 0
|
|
1470
|
+
? `step "${step.Name}" has no SubAgentID and no sub-agent in the spec or active agent has that name`
|
|
1471
|
+
: `step "${step.Name}" matches ${existingIds.length} active agents; set its SubAgentID`);
|
|
1472
|
+
return null;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
* The spec sub-agents with duplicates removed: entries naming the same saved agent count once.
|
|
1477
|
+
* Entries not yet saved (empty ID) are each a separate agent to create.
|
|
1478
|
+
* @private
|
|
1479
|
+
*/
|
|
1480
|
+
private distinctSubAgents(subAgents: SubAgentSpec[]): SubAgentSpec[] {
|
|
1481
|
+
const distinct: SubAgentSpec[] = [];
|
|
1482
|
+
const seen = new UUIDSet();
|
|
1483
|
+
for (const sub of subAgents) {
|
|
1484
|
+
const id = sub.SubAgent?.ID;
|
|
1485
|
+
if (id) {
|
|
1486
|
+
if (seen.Has(id)) continue;
|
|
1487
|
+
seen.Add(id);
|
|
1488
|
+
}
|
|
1489
|
+
distinct.push(sub);
|
|
1490
|
+
}
|
|
1491
|
+
return distinct;
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
/**
|
|
1495
|
+
* IDs of the active agents with this name, other than the agent being saved.
|
|
1496
|
+
* @private
|
|
1497
|
+
*/
|
|
1498
|
+
private async findActiveAgentIdsByName(name: string): Promise<string[]> {
|
|
1499
|
+
const rv = RunView.FromMetadataProvider(this.providerToUse);
|
|
1500
|
+
const result = await rv.RunView<{ ID: string }>({
|
|
1501
|
+
EntityName: 'MJ: AI Agents',
|
|
1502
|
+
ExtraFilter: `Name='${name.trim().replace(/'/g, "''")}' AND Status='Active'`,
|
|
1503
|
+
Fields: ['ID'],
|
|
1504
|
+
ResultType: 'simple'
|
|
1505
|
+
}, this._contextUser);
|
|
1506
|
+
if (!result.Success) {
|
|
1507
|
+
throw new Error(`Failed to look up agent "${name}": ${result.ErrorMessage}`);
|
|
1508
|
+
}
|
|
1509
|
+
const ids: string[] = [];
|
|
1510
|
+
const seen = new UUIDSet();
|
|
1511
|
+
for (const row of result.Results ?? []) {
|
|
1512
|
+
if (this.Spec.ID && UUIDsEqual(row.ID, this.Spec.ID)) continue;
|
|
1513
|
+
if (seen.Has(row.ID)) continue;
|
|
1514
|
+
seen.Add(row.ID);
|
|
1515
|
+
ids.push(row.ID);
|
|
1516
|
+
}
|
|
1517
|
+
return ids;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/**
|
|
1521
|
+
* The SubAgentID to save on a step: its own, or the one its Name resolved to.
|
|
1522
|
+
* @private
|
|
1523
|
+
*/
|
|
1524
|
+
private stepSubAgentID(stepSpec: AgentStep): string | null {
|
|
1525
|
+
if (stepSpec.SubAgentID) {
|
|
1526
|
+
return stepSpec.SubAgentID;
|
|
1527
|
+
}
|
|
1528
|
+
const link = this._stepSubAgentLinks.get(stepSpec);
|
|
1529
|
+
if (!link) {
|
|
1530
|
+
return null;
|
|
1531
|
+
}
|
|
1532
|
+
const id = link.Source === 'spec' ? link.SubAgent.SubAgent?.ID : link.AgentID;
|
|
1533
|
+
if (!id) {
|
|
1534
|
+
throw new Error(`Sub-agent "${stepSpec.Name}" has no ID after saving sub-agents`);
|
|
1535
|
+
}
|
|
1536
|
+
stepSpec.SubAgentID = id; // Update spec too
|
|
1537
|
+
return id;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
/**
|
|
1541
|
+
* Create the AIPrompt for a step whose prompt is written inline as PromptText.
|
|
1542
|
+
*
|
|
1543
|
+
* @private
|
|
1544
|
+
* @returns The new prompt's ID
|
|
1545
|
+
* @throws {Error} If the prompt save fails
|
|
1546
|
+
*/
|
|
1547
|
+
private async createInlineStepPrompt(stepSpec: AgentStep): Promise<string> {
|
|
1548
|
+
console.log(`🔷 saveSteps: Creating inline prompt for step "${stepSpec.Name}"`);
|
|
1549
|
+
const promptEntity = await this.providerToUse.GetEntityObject<MJAIPromptEntityExtended>(
|
|
1550
|
+
'MJ: AI Prompts',
|
|
1551
|
+
this._contextUser
|
|
1552
|
+
);
|
|
1553
|
+
|
|
1554
|
+
promptEntity.Name = stepSpec.PromptName || `${stepSpec.Name} Prompt`;
|
|
1555
|
+
promptEntity.Description = stepSpec.PromptDescription || `Prompt for step: ${stepSpec.Name}`;
|
|
1556
|
+
promptEntity.TypeID = CHAT_PROMPT_TYPE_ID;
|
|
1557
|
+
promptEntity.Status = 'Active';
|
|
1558
|
+
promptEntity.ResponseFormat = 'JSON';
|
|
1559
|
+
promptEntity.TemplateText = stepSpec.PromptText ?? '';
|
|
1560
|
+
|
|
1561
|
+
const promptSaved = await promptEntity.Save();
|
|
1562
|
+
if (!promptSaved) {
|
|
1563
|
+
throw new Error(`Failed to save inline prompt for step "${stepSpec.Name}"`);
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
this.trackMutation(
|
|
1567
|
+
'MJ: AI Prompts',
|
|
1568
|
+
'Create',
|
|
1569
|
+
promptEntity.ID,
|
|
1570
|
+
`Created inline prompt: ${promptEntity.Name}`
|
|
1571
|
+
);
|
|
1572
|
+
console.log(`✅ saveSteps: Created inline AIPrompt with ID: ${promptEntity.ID}`);
|
|
1573
|
+
return promptEntity.ID;
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1385
1576
|
/**
|
|
1386
1577
|
* Save all steps for this agent (Flow agents only).
|
|
1387
1578
|
*
|
|
@@ -1428,7 +1619,7 @@ export class AgentSpecSync {
|
|
|
1428
1619
|
stepEntity.StepType = stepSpec.StepType;
|
|
1429
1620
|
stepEntity.StartingStep = stepSpec.StartingStep;
|
|
1430
1621
|
stepEntity.ActionID = stepSpec.ActionID || null;
|
|
1431
|
-
stepEntity.SubAgentID = stepSpec
|
|
1622
|
+
stepEntity.SubAgentID = this.stepSubAgentID(stepSpec);
|
|
1432
1623
|
stepEntity.Status = 'Active'; // Default to Active
|
|
1433
1624
|
// Loop steps: the body type says which of Action/Prompt/Sub-Agent runs each pass, and
|
|
1434
1625
|
// Configuration carries the bounds. Written for every step because a step that STOPS
|
|
@@ -1461,46 +1652,15 @@ export class AgentSpecSync {
|
|
|
1461
1652
|
stepEntity.Height = Math.round(stepSpec.Height);
|
|
1462
1653
|
}
|
|
1463
1654
|
|
|
1464
|
-
//
|
|
1465
|
-
//
|
|
1466
|
-
if (stepSpec
|
|
1655
|
+
// A Prompt step, or a loop whose body is a prompt, with an empty PromptID and inline
|
|
1656
|
+
// PromptText gets a new AIPrompt created and linked.
|
|
1657
|
+
if (stepRunsPrompt(stepSpec) && !stepSpec.PromptID) {
|
|
1467
1658
|
if (stepSpec.PromptText) {
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
const promptEntity = await md.GetEntityObject<any>(
|
|
1472
|
-
'MJ: AI Prompts',
|
|
1473
|
-
this._contextUser
|
|
1474
|
-
);
|
|
1475
|
-
|
|
1476
|
-
// Set prompt fields
|
|
1477
|
-
promptEntity.Name = stepSpec.PromptName || `${stepSpec.Name} Prompt`;
|
|
1478
|
-
promptEntity.Description = stepSpec.PromptDescription || `Prompt for step: ${stepSpec.Name}`;
|
|
1479
|
-
promptEntity.TypeID = 'a6da423e-f36b-1410-8dac-00021f8b792e'; // Chat type
|
|
1480
|
-
promptEntity.Status = 'Active';
|
|
1481
|
-
promptEntity.ResponseFormat = 'JSON';
|
|
1482
|
-
promptEntity.TemplateText = stepSpec.PromptText; // TemplateText is a dynamic property
|
|
1483
|
-
|
|
1484
|
-
const promptSaved = await promptEntity.Save();
|
|
1485
|
-
if (!promptSaved) {
|
|
1486
|
-
throw new Error(`Failed to save inline prompt for step "${stepSpec.Name}"`);
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
// Track mutation
|
|
1490
|
-
this.trackMutation(
|
|
1491
|
-
'MJ: AI Prompts',
|
|
1492
|
-
'Create',
|
|
1493
|
-
promptEntity.ID,
|
|
1494
|
-
`Created inline prompt: ${promptEntity.Name}`
|
|
1495
|
-
);
|
|
1496
|
-
|
|
1497
|
-
console.log(`✅ saveSteps: Created inline AIPrompt with ID: ${promptEntity.ID}`);
|
|
1498
|
-
|
|
1499
|
-
// Link the created prompt to this step
|
|
1500
|
-
stepEntity.PromptID = promptEntity.ID;
|
|
1501
|
-
stepSpec.PromptID = promptEntity.ID; // Update spec too
|
|
1659
|
+
const promptId = await this.createInlineStepPrompt(stepSpec);
|
|
1660
|
+
stepEntity.PromptID = promptId;
|
|
1661
|
+
stepSpec.PromptID = promptId; // Update spec too
|
|
1502
1662
|
} else {
|
|
1503
|
-
console.warn(`⚠️ saveSteps: Step "${stepSpec.Name}"
|
|
1663
|
+
console.warn(`⚠️ saveSteps: Step "${stepSpec.Name}" runs a prompt with empty PromptID but no PromptText provided`);
|
|
1504
1664
|
stepEntity.PromptID = null;
|
|
1505
1665
|
}
|
|
1506
1666
|
} else {
|