@memberjunction/realtime-widget 6.3.0-edge.1 → 6.3.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.
@@ -3,18 +3,22 @@ import {
3
3
  ArtifactMetadataEngine,
4
4
  ConversationEngine,
5
5
  ConversationUtility,
6
+ DeepMergeAgentConfigObjects,
6
7
  EDGE_PRE_DISCOVERY_DATA_KEY,
7
8
  FileStorageEngineBase,
9
+ MAX_AGENT_INHERITANCE_DEPTH,
8
10
  MJAICredentialBindingEntity,
9
11
  MJAIModelPriceUnitTypeEntity,
12
+ ParseAgentConfigJsonObject,
10
13
  QueryEngine,
11
14
  SanitizeEdgePreDiscoveryHint,
12
15
  TemplateEngineBase,
16
+ UserInfoEngine,
17
+ as,
13
18
  coerceFailedExecuteAgentResult,
14
19
  g,
15
- ns,
16
- tt
17
- } from "./chunk-SXFIY47F.js";
20
+ rt
21
+ } from "./chunk-3U2F5LA6.js";
18
22
  import {
19
23
  BaseEngine,
20
24
  BaseEntity,
@@ -25,7 +29,7 @@ import {
25
29
  PermissionConstrainedError,
26
30
  RegisterForStartup,
27
31
  RunView
28
- } from "./chunk-6RWWXOZB.js";
32
+ } from "./chunk-KJ4DC2CQ.js";
29
33
  import {
30
34
  ApplyPlattCalibration,
31
35
  ParseModelConfiguration,
@@ -38,6 +42,7 @@ import {
38
42
  EMPTY,
39
43
  IndexByUUID,
40
44
  IsBrowser,
45
+ MJEventType,
41
46
  MJGlobal,
42
47
  NormalizeUUID,
43
48
  RegisterClass,
@@ -295,7 +300,100 @@ var TOKEN_PRICE_UNIT_TYPE_DIVISORS = Object.freeze(Object.fromEntries([
295
300
  ].map(([driverClass, driver]) => [driverClass, driver.UnitsPerBillingUnit])));
296
301
 
297
302
  // ../../AI/BaseAIEngine/dist/AIAgentPermissionHelper.js
303
+ var MAX_INHERITANCE_DEPTH = 5;
298
304
  var AIAgentPermissionHelper = class {
305
+ /**
306
+ * Pure synchronous computation of effective permissions for a single agent row WITHOUT
307
+ * walking `BaseAgentID` ancestors. Applies the 2x2 zero-ACL rule and hierarchical
308
+ * permission implication (`Delete -> Edit -> Run -> View`).
309
+ */
310
+ static computeDirectPermissions(agent, allPermissions, user, userRoleIds) {
311
+ const isOwner = UUIDsEqual(agent.OwnerUserID, user.ID);
312
+ if (isOwner) {
313
+ return {
314
+ canView: true,
315
+ canRun: true,
316
+ canEdit: true,
317
+ canDelete: true,
318
+ isOwner: true
319
+ };
320
+ }
321
+ const agentPermissions = allPermissions.filter((p) => UUIDsEqual(p.AgentID, agent.ID));
322
+ if (agentPermissions.length === 0) {
323
+ const isDerived = agent.BaseAgentID != null && String(agent.BaseAgentID).trim().length > 0;
324
+ if (isDerived) {
325
+ return {
326
+ canView: false,
327
+ canRun: false,
328
+ canEdit: false,
329
+ canDelete: false,
330
+ isOwner: false
331
+ };
332
+ }
333
+ return {
334
+ canView: true,
335
+ canRun: true,
336
+ canEdit: false,
337
+ canDelete: false,
338
+ isOwner: false
339
+ };
340
+ }
341
+ const matchingPermissions = agentPermissions.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID != null && userRoleIds.Has(p.RoleID));
342
+ const hasDelete = matchingPermissions.some((p) => p.CanDelete === true);
343
+ const hasEdit = matchingPermissions.some((p) => p.CanEdit === true);
344
+ const hasRun = matchingPermissions.some((p) => p.CanRun === true);
345
+ const hasView = matchingPermissions.some((p) => p.CanView === true);
346
+ const canDelete = hasDelete;
347
+ const canEdit = hasDelete || hasEdit;
348
+ const canRun = hasDelete || hasEdit || hasRun;
349
+ const canView = hasDelete || hasEdit || hasRun || hasView;
350
+ return {
351
+ canView,
352
+ canRun,
353
+ canEdit,
354
+ canDelete,
355
+ isOwner: false
356
+ };
357
+ }
358
+ /**
359
+ * Pure synchronous computation of effective permissions including the 2x2 RBAC matrix
360
+ * AND the Ancestor `CanRun` Invariant across the `BaseAgentID` inheritance chain.
361
+ *
362
+ * Used by both async {@link GetEffectivePermissions} and sync `AIEngineBase` directory/picker
363
+ * checks so every surface enforces identical semantics with zero drift.
364
+ */
365
+ static ComputeEffectivePermissionsSync(agent, allAgents, allPermissions, user, precomputedUserRoleIds) {
366
+ const userRoleIds = precomputedUserRoleIds ?? new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
367
+ const direct = this.computeDirectPermissions(agent, allPermissions, user, userRoleIds);
368
+ if (direct.canRun && agent.BaseAgentID) {
369
+ const visited = new UUIDSet([agent.ID]);
370
+ let currentBaseId = agent.BaseAgentID;
371
+ let depth = 0;
372
+ while (currentBaseId && depth < MAX_INHERITANCE_DEPTH) {
373
+ if (visited.Has(currentBaseId)) {
374
+ direct.canRun = false;
375
+ break;
376
+ }
377
+ visited.Add(currentBaseId);
378
+ const ancestor = allAgents.find((a) => UUIDsEqual(a.ID, currentBaseId));
379
+ if (!ancestor) {
380
+ direct.canRun = false;
381
+ break;
382
+ }
383
+ const ancDirect = this.computeDirectPermissions(ancestor, allPermissions, user, userRoleIds);
384
+ if (!ancDirect.canRun) {
385
+ direct.canRun = false;
386
+ break;
387
+ }
388
+ currentBaseId = ancestor.BaseAgentID;
389
+ depth++;
390
+ }
391
+ if (currentBaseId && depth >= MAX_INHERITANCE_DEPTH) {
392
+ direct.canRun = false;
393
+ }
394
+ }
395
+ return direct;
396
+ }
299
397
  /**
300
398
  * Checks if a user has a specific permission for an agent.
301
399
  * @param agentId - The ID of the agent to check
@@ -320,16 +418,7 @@ var AIAgentPermissionHelper = class {
320
418
  }
321
419
  /**
322
420
  * Gets the aggregate permissions for a user on a specific agent.
323
- * Implements hierarchical permission logic:
324
- * - Delete implies Edit, Run, and View
325
- * - Edit implies Run and View
326
- * - Run implies View
327
- *
328
- * Default behavior when no permission records exist:
329
- * - Anyone can View and Run (open by default)
330
- * - Only owner can Edit and Delete
331
- *
332
- * Checks ownership first, then combines all matching user and role permissions.
421
+ * Enforces the 2x2 RBAC matrix and the Ancestor `CanRun` Invariant across `BaseAgentID`.
333
422
  * @param agentId - The ID of the agent
334
423
  * @param user - The user to check permissions for
335
424
  * @returns Object containing all effective permissions and ownership status
@@ -337,49 +426,12 @@ var AIAgentPermissionHelper = class {
337
426
  static async GetEffectivePermissions(agentId, user) {
338
427
  try {
339
428
  await AIEngineBase.Instance.Config(false, user);
340
- const agent = AIEngineBase.Instance.Agents.find((a) => UUIDsEqual(a.ID, agentId));
429
+ const allAgents = AIEngineBase.Instance.Agents;
430
+ const agent = allAgents.find((a) => UUIDsEqual(a.ID, agentId));
341
431
  if (!agent) {
342
432
  throw new Error(`Agent ${agentId} not found in cached metadata`);
343
433
  }
344
- const isOwner = UUIDsEqual(agent.OwnerUserID, user.ID);
345
- if (isOwner) {
346
- return {
347
- canView: true,
348
- canRun: true,
349
- canEdit: true,
350
- canDelete: true,
351
- isOwner: true
352
- };
353
- }
354
- const agentPermissions = AIEngineBase.Instance.AgentPermissions.filter((p) => UUIDsEqual(p.AgentID, agentId));
355
- if (agentPermissions.length === 0) {
356
- return {
357
- canView: true,
358
- canRun: true,
359
- canEdit: false,
360
- // Only owner can edit
361
- canDelete: false,
362
- // Only owner can delete
363
- isOwner: false
364
- };
365
- }
366
- const userRoleIds = user.UserRoles?.map((ur) => ur.RoleID) || [];
367
- const matchingPermissions = agentPermissions.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID && userRoleIds.some((rid) => UUIDsEqual(rid, p.RoleID)));
368
- const hasDelete = matchingPermissions.some((p) => p.CanDelete === true);
369
- const hasEdit = matchingPermissions.some((p) => p.CanEdit === true);
370
- const hasRun = matchingPermissions.some((p) => p.CanRun === true);
371
- const hasView = matchingPermissions.some((p) => p.CanView === true);
372
- const canDelete = hasDelete;
373
- const canEdit = hasDelete || hasEdit;
374
- const canRun = hasDelete || hasEdit || hasRun;
375
- const canView = hasDelete || hasEdit || hasRun || hasView;
376
- return {
377
- canView,
378
- canRun,
379
- canEdit,
380
- canDelete,
381
- isOwner: false
382
- };
434
+ return this.ComputeEffectivePermissionsSync(agent, allAgents, AIEngineBase.Instance.AgentPermissions, user);
383
435
  } catch (error) {
384
436
  LogError(`Error getting effective permissions for agent: ${error instanceof Error ? error.message : String(error)}`);
385
437
  return {
@@ -433,14 +485,15 @@ var AIAgentPermissionHelper = class {
433
485
  return includeInactive ? runnable : runnable.filter((a) => a.Status === "Active");
434
486
  }
435
487
  /**
436
- * Whether an agent is meant to be found and delegated to directly. Sub-Agents and child agents
437
- * are meant to be called by other agents, not discovered directly, so an agent whose
438
- * InvocationMode is 'Sub-Agent', or that has a ParentID, is not.
488
+ * Whether an agent is meant to be found and delegated to directly. Sub-Agents, child agents
489
+ * (`ParentID`), and instantiation-required prototype templates (`InstantiationMode === 'Required'`)
490
+ * are not directly discoverable for ad-hoc delegation — users and orchestrators like Sage
491
+ * delegate to the user's materialized derived instance instead.
439
492
  * @param agent - The agent to check
440
493
  * @returns True when the agent can be discovered directly
441
494
  */
442
495
  static IsDirectlyDiscoverable(agent) {
443
- return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID;
496
+ return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID && agent.InstantiationMode !== "Required";
444
497
  }
445
498
  /**
446
499
  * Clears the AIEngineBase cache. Useful when permissions have been modified.
@@ -655,8 +708,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
655
708
  this._agentsByID = null;
656
709
  this._agentsByName = null;
657
710
  this._childAgentsByParentID = null;
711
+ this._agentInheritanceChainCache = /* @__PURE__ */ new Map();
658
712
  this._agentsIndexedRef = null;
659
713
  this._agentsIndexedLen = -1;
714
+ this._preferredPrimaryByGroup = /* @__PURE__ */ new Map();
660
715
  this._agentRelationshipsByAgentID = null;
661
716
  this._agentRelationshipsIndexedRef = null;
662
717
  this._agentRelationshipsIndexedLen = -1;
@@ -984,13 +1039,181 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
984
1039
  }
985
1040
  }
986
1041
  static {
987
- this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set(["_vectorIndexes"]);
1042
+ this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set([
1043
+ "_vectorIndexes",
1044
+ "_agentPersonas",
1045
+ "_agentPermissions"
1046
+ ]);
988
1047
  }
989
1048
  canUseImmediateMutation(config, skipAdditionalLoadingCheck = false) {
990
1049
  const independent = AIEngineBase_1.IMMEDIATE_MUTATION_PROPERTIES.has(config.PropertyName);
991
1050
  return super.canUseImmediateMutation(config, skipAdditionalLoadingCheck || independent);
992
1051
  }
1052
+ /**
1053
+ * Intercepts `MJ: AI Agents`, `MJ: AI Agent Personas`, and `MJ: AI Agent Permissions` events so
1054
+ * in-memory caches (`_agents`, `_agentsByID`, `_userRunnableAgentDirectoryCache`, and sibling
1055
+ * `IsPrimaryInstance` flags) update synchronously at `t = 0ms` without waiting for BaseEngine's
1056
+ * 1.5s debounced full reload — enabling immediate UI reflection of avatar (`LogoURL` / `IconClass`),
1057
+ * name, persona, and primary-instance edits without a browser refresh.
1058
+ */
1059
+ async HandleIndividualBaseEntityEvent(event) {
1060
+ let shouldEmitAgentsChange = false;
1061
+ const isSave = event.type === "save";
1062
+ const isDelete = event.type === "delete";
1063
+ const isRemoteInvalidate = event.type === "remote-invalidate";
1064
+ const localEntityName = event.baseEntity?.EntityInfo?.Name?.trim().toLowerCase() ?? "";
1065
+ const remoteEntityName = event.entityName?.trim().toLowerCase() ?? "";
1066
+ if (isSave && localEntityName === "mj: ai agents" && event.baseEntity) {
1067
+ const savedAgent = event.baseEntity;
1068
+ this.applyImmediateAgentUpsert(savedAgent);
1069
+ if (this.isActiveDerivedPrimaryAgent(savedAgent)) {
1070
+ this.demotePrimarySiblingsForAgent(savedAgent);
1071
+ }
1072
+ shouldEmitAgentsChange = true;
1073
+ } else if (isDelete && localEntityName === "mj: ai agents" && event.baseEntity) {
1074
+ const deletedAgent = event.baseEntity;
1075
+ shouldEmitAgentsChange = this.applyImmediateAgentDelete(deletedAgent.ID);
1076
+ } else if (isRemoteInvalidate && remoteEntityName === "mj: ai agents") {
1077
+ this.recordPreferredPrimaryFromRemotePayload(event.payload);
1078
+ } else if ((isSave || isDelete || isRemoteInvalidate) && (localEntityName === "mj: ai agent permissions" || remoteEntityName === "mj: ai agent permissions")) {
1079
+ this.invalidateUserRunnableAgentDirectoryCache();
1080
+ }
1081
+ const result = await super.HandleIndividualBaseEntityEvent(event);
1082
+ if (shouldEmitAgentsChange) {
1083
+ this.emitPropertyChange("_agents");
1084
+ }
1085
+ return result;
1086
+ }
1087
+ /**
1088
+ * Synchronously patches or inserts a just-saved `MJ: AI Agents` entity into `this._agents` and
1089
+ * invalidates derived agent indexes so `GetAgentByID` / `Agents` immediately reflect updated
1090
+ * `LogoURL`, `IconClass`, `Name`, `Description`, `AdditionalInstructions`, `Status`, and
1091
+ * `IsPrimaryInstance` before BaseEngine's background reload settles.
1092
+ */
1093
+ applyImmediateAgentUpsert(savedAgent) {
1094
+ if (!savedAgent?.ID) {
1095
+ return;
1096
+ }
1097
+ const existingIdx = this._agents.findIndex((a) => UUIDsEqual(a.ID, savedAgent.ID));
1098
+ if (existingIdx >= 0) {
1099
+ const existing = this._agents[existingIdx];
1100
+ if (existing !== savedAgent) {
1101
+ this.syncAgentScalarFieldsInPlace(existing, savedAgent);
1102
+ if (typeof savedAgent.Actions !== "undefined") {
1103
+ if (existing.Notes?.length && (!savedAgent.Notes || savedAgent.Notes.length === 0)) {
1104
+ savedAgent.Notes.splice(0, savedAgent.Notes.length, ...existing.Notes);
1105
+ }
1106
+ this._agents[existingIdx] = savedAgent;
1107
+ }
1108
+ }
1109
+ } else {
1110
+ this._agents.push(savedAgent);
1111
+ }
1112
+ this.invalidateAgentLookupIndexes();
1113
+ }
1114
+ applyImmediateAgentDelete(agentId) {
1115
+ if (!agentId) {
1116
+ return false;
1117
+ }
1118
+ const existingIdx = this._agents.findIndex((a) => UUIDsEqual(a.ID, agentId));
1119
+ if (existingIdx < 0) {
1120
+ return false;
1121
+ }
1122
+ this._agents.splice(existingIdx, 1);
1123
+ this.invalidateAgentLookupIndexes();
1124
+ return true;
1125
+ }
1126
+ syncAgentScalarFieldsInPlace(target, source) {
1127
+ const touchedFields = [];
1128
+ if (source.Name !== void 0) {
1129
+ target.Name = source.Name;
1130
+ touchedFields.push("Name");
1131
+ }
1132
+ if (source.Description !== void 0) {
1133
+ target.Description = source.Description;
1134
+ touchedFields.push("Description");
1135
+ }
1136
+ if (source.LogoURL !== void 0) {
1137
+ target.LogoURL = source.LogoURL;
1138
+ touchedFields.push("LogoURL");
1139
+ }
1140
+ if (source.IconClass !== void 0) {
1141
+ target.IconClass = source.IconClass;
1142
+ touchedFields.push("IconClass");
1143
+ }
1144
+ if (source.ParentID !== void 0) {
1145
+ target.ParentID = source.ParentID;
1146
+ touchedFields.push("ParentID");
1147
+ }
1148
+ if (source.BaseAgentID !== void 0) {
1149
+ target.BaseAgentID = source.BaseAgentID;
1150
+ touchedFields.push("BaseAgentID");
1151
+ }
1152
+ if (source.OwnerUserID !== void 0) {
1153
+ target.OwnerUserID = source.OwnerUserID;
1154
+ touchedFields.push("OwnerUserID");
1155
+ }
1156
+ if (source.InstantiationMode !== void 0) {
1157
+ target.InstantiationMode = source.InstantiationMode;
1158
+ touchedFields.push("InstantiationMode");
1159
+ }
1160
+ if (source.IsPrimaryInstance !== void 0) {
1161
+ target.IsPrimaryInstance = source.IsPrimaryInstance;
1162
+ touchedFields.push("IsPrimaryInstance");
1163
+ }
1164
+ if (source.AdditionalInstructions !== void 0) {
1165
+ target.AdditionalInstructions = source.AdditionalInstructions;
1166
+ touchedFields.push("AdditionalInstructions");
1167
+ }
1168
+ if (source.Status !== void 0) {
1169
+ target.Status = source.Status;
1170
+ touchedFields.push("Status");
1171
+ }
1172
+ if (source.TypeID !== void 0) {
1173
+ target.TypeID = source.TypeID;
1174
+ touchedFields.push("TypeID");
1175
+ }
1176
+ if (source.TypeConfiguration !== void 0) {
1177
+ target.TypeConfiguration = source.TypeConfiguration;
1178
+ touchedFields.push("TypeConfiguration");
1179
+ }
1180
+ if (source.InvocationMode !== void 0) {
1181
+ target.InvocationMode = source.InvocationMode;
1182
+ touchedFields.push("InvocationMode");
1183
+ }
1184
+ if (source.CategoryID !== void 0) {
1185
+ target.CategoryID = source.CategoryID;
1186
+ touchedFields.push("CategoryID");
1187
+ }
1188
+ if (source.IsRestricted !== void 0) {
1189
+ target.IsRestricted = source.IsRestricted;
1190
+ touchedFields.push("IsRestricted");
1191
+ }
1192
+ if (typeof target.GetFieldByName === "function") {
1193
+ for (const fieldName of touchedFields) {
1194
+ target.GetFieldByName(fieldName)?.ResetOldValue();
1195
+ }
1196
+ }
1197
+ }
1198
+ invalidateAgentLookupIndexes() {
1199
+ this._agentsByID = null;
1200
+ this._agentsByName = null;
1201
+ this._childAgentsByParentID = null;
1202
+ this._agentInheritanceChainCache.clear();
1203
+ this._agentsIndexedRef = null;
1204
+ this._agentsIndexedLen = -1;
1205
+ this.invalidateUserRunnableAgentDirectoryCache();
1206
+ }
1207
+ invalidateUserRunnableAgentDirectoryCache() {
1208
+ this._userRunnableAgentDirectoryCache.clear();
1209
+ this._userRunnableAgentsRef = null;
1210
+ this._userRunnableAgentsLen = -1;
1211
+ this._userRunnablePermissionsRef = null;
1212
+ this._userRunnablePermissionsLen = -1;
1213
+ }
993
1214
  async AdditionalLoading(contextUser) {
1215
+ this.normalizeExclusivePrimaryInstances();
1216
+ this._preferredPrimaryByGroup.clear();
994
1217
  this._configurationChainCache.clear();
995
1218
  this._userRunnableAgentDirectoryCache.clear();
996
1219
  this._userRunnableAgentsRef = null;
@@ -1008,6 +1231,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1008
1231
  this._agentsByID = null;
1009
1232
  this._agentsByName = null;
1010
1233
  this._childAgentsByParentID = null;
1234
+ this._agentInheritanceChainCache.clear();
1011
1235
  this._agentsIndexedRef = null;
1012
1236
  this._agentsIndexedLen = -1;
1013
1237
  this._agentRelationshipsByAgentID = null;
@@ -1079,6 +1303,190 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1079
1303
  replaceContents(model.ModelVendors, vendorsByModel.get(keyFor(model.ID)) ?? []);
1080
1304
  }
1081
1305
  }
1306
+ isActiveDerivedPrimaryAgent(agent) {
1307
+ return Boolean(agent && agent.Status === "Active" && agent.BaseAgentID != null && agent.BaseAgentID.length > 0 && agent.OwnerUserID != null && agent.OwnerUserID.length > 0 && agent.IsPrimaryInstance === true);
1308
+ }
1309
+ /**
1310
+ * Resolves the top-level root base agent ID for a derived agent by walking `BaseAgentID` links
1311
+ * through `agentsById` with cycle protection. When an ancestor row is not present in `agentsById`,
1312
+ * returns the highest referenced `BaseAgentID` so siblings pointing to the same template still match.
1313
+ */
1314
+ resolveRootBaseAgentIdForSync(agent, agentsById) {
1315
+ let currentBaseId = agent.BaseAgentID;
1316
+ if (!currentBaseId) {
1317
+ return null;
1318
+ }
1319
+ const visited = /* @__PURE__ */ new Set([NormalizeUUID(agent.ID)]);
1320
+ let depth = 0;
1321
+ while (currentBaseId && depth < MAX_AGENT_INHERITANCE_DEPTH) {
1322
+ const normCurrent = NormalizeUUID(currentBaseId);
1323
+ if (visited.has(normCurrent)) {
1324
+ break;
1325
+ }
1326
+ visited.add(normCurrent);
1327
+ const parent = agentsById.get(normCurrent);
1328
+ if (!parent || !parent.BaseAgentID) {
1329
+ return currentBaseId;
1330
+ }
1331
+ currentBaseId = parent.BaseAgentID;
1332
+ depth++;
1333
+ }
1334
+ return currentBaseId;
1335
+ }
1336
+ primaryGroupKey(ownerUserId, rootBaseAgentId) {
1337
+ return `${NormalizeUUID(ownerUserId)}::${NormalizeUUID(rootBaseAgentId)}`;
1338
+ }
1339
+ /**
1340
+ * Sets `IsPrimaryInstance = false` on a cached agent without leaving a real `BaseEntity` marked dirty.
1341
+ */
1342
+ setCachedAgentPrimaryFlag(agent, isPrimary) {
1343
+ agent.IsPrimaryInstance = isPrimary;
1344
+ if (typeof agent.GetFieldByName === "function") {
1345
+ agent.GetFieldByName("IsPrimaryInstance")?.ResetOldValue();
1346
+ }
1347
+ }
1348
+ /**
1349
+ * Records an incoming remote-invalidate save payload as the preferred primary winner for its
1350
+ * `(OwnerUserID, RootBaseAgentID)` group before `applyRemoteRecordData` invokes `AdditionalLoading`.
1351
+ */
1352
+ recordPreferredPrimaryFromRemotePayload(payload) {
1353
+ if (typeof payload !== "object" || payload === null) {
1354
+ return;
1355
+ }
1356
+ const remote = payload;
1357
+ if (remote.action !== "save" || typeof remote.recordData !== "string") {
1358
+ return;
1359
+ }
1360
+ try {
1361
+ const parsed = JSON.parse(remote.recordData);
1362
+ if (!parsed || !parsed.ID || !this.isActiveDerivedPrimaryAgent(parsed)) {
1363
+ return;
1364
+ }
1365
+ const agentsById = /* @__PURE__ */ new Map();
1366
+ for (const a of this._agents) {
1367
+ agentsById.set(NormalizeUUID(a.ID), a);
1368
+ }
1369
+ const rootId = this.resolveRootBaseAgentIdForSync({ ID: parsed.ID, BaseAgentID: parsed.BaseAgentID ?? null }, agentsById);
1370
+ if (rootId && parsed.OwnerUserID) {
1371
+ this._preferredPrimaryByGroup.set(this.primaryGroupKey(parsed.OwnerUserID, rootId), NormalizeUUID(parsed.ID));
1372
+ }
1373
+ } catch {
1374
+ }
1375
+ }
1376
+ /**
1377
+ * Immediately demotes all active cached siblings sharing `(OwnerUserID, RootBaseAgentID)` with
1378
+ * `savedAgent` and records `savedAgent.ID` as the preferred primary winner for upcoming reloads.
1379
+ */
1380
+ demotePrimarySiblingsForAgent(savedAgent) {
1381
+ if (!this.isActiveDerivedPrimaryAgent(savedAgent) || !savedAgent.OwnerUserID) {
1382
+ return false;
1383
+ }
1384
+ const agentsById = /* @__PURE__ */ new Map();
1385
+ for (const a of this._agents) {
1386
+ agentsById.set(NormalizeUUID(a.ID), a);
1387
+ }
1388
+ agentsById.set(NormalizeUUID(savedAgent.ID), savedAgent);
1389
+ const targetRootId = this.resolveRootBaseAgentIdForSync(savedAgent, agentsById);
1390
+ if (!targetRootId) {
1391
+ return false;
1392
+ }
1393
+ const groupKey = this.primaryGroupKey(savedAgent.OwnerUserID, targetRootId);
1394
+ this._preferredPrimaryByGroup.set(groupKey, NormalizeUUID(savedAgent.ID));
1395
+ let mutated = false;
1396
+ for (const candidate of this._agents) {
1397
+ if (UUIDsEqual(candidate.ID, savedAgent.ID)) {
1398
+ if (candidate.IsPrimaryInstance !== true) {
1399
+ this.setCachedAgentPrimaryFlag(candidate, true);
1400
+ mutated = true;
1401
+ }
1402
+ continue;
1403
+ }
1404
+ if (!this.isActiveDerivedPrimaryAgent(candidate) || !candidate.OwnerUserID) {
1405
+ continue;
1406
+ }
1407
+ if (!UUIDsEqual(candidate.OwnerUserID, savedAgent.OwnerUserID)) {
1408
+ continue;
1409
+ }
1410
+ const candidateRootId = this.resolveRootBaseAgentIdForSync(candidate, agentsById);
1411
+ if (candidateRootId && UUIDsEqual(candidateRootId, targetRootId)) {
1412
+ this.setCachedAgentPrimaryFlag(candidate, false);
1413
+ mutated = true;
1414
+ }
1415
+ }
1416
+ return mutated;
1417
+ }
1418
+ /**
1419
+ * Ensures at most one active derived agent per `(OwnerUserID, RootBaseAgentID)` has
1420
+ * `IsPrimaryInstance === true` inside `this._agents`. Prefers any agent recorded via
1421
+ * `_preferredPrimaryByGroup` (from a just-saved or remote-invalidated row), otherwise keeps
1422
+ * the most recently updated row (`__mj_UpdatedAt`, falling back to `__mj_CreatedAt`).
1423
+ */
1424
+ normalizeExclusivePrimaryInstances() {
1425
+ if (!this._agents || this._agents.length < 2) {
1426
+ return false;
1427
+ }
1428
+ const agentsById = /* @__PURE__ */ new Map();
1429
+ for (const agent of this._agents) {
1430
+ agentsById.set(NormalizeUUID(agent.ID), agent);
1431
+ }
1432
+ const primaryGroups = /* @__PURE__ */ new Map();
1433
+ for (const agent of this._agents) {
1434
+ if (!this.isActiveDerivedPrimaryAgent(agent) || !agent.OwnerUserID) {
1435
+ continue;
1436
+ }
1437
+ const rootId = this.resolveRootBaseAgentIdForSync(agent, agentsById);
1438
+ if (!rootId) {
1439
+ continue;
1440
+ }
1441
+ const key = this.primaryGroupKey(agent.OwnerUserID, rootId);
1442
+ const bucket = primaryGroups.get(key);
1443
+ if (bucket) {
1444
+ bucket.push(agent);
1445
+ } else {
1446
+ primaryGroups.set(key, [agent]);
1447
+ }
1448
+ }
1449
+ let mutated = false;
1450
+ for (const [groupKey, bucket] of primaryGroups.entries()) {
1451
+ if (bucket.length < 2) {
1452
+ continue;
1453
+ }
1454
+ const preferredId = this._preferredPrimaryByGroup.get(groupKey);
1455
+ let winner = preferredId ? IndexByUUID(bucket).Get(preferredId) : void 0;
1456
+ if (!winner) {
1457
+ const sorted = [...bucket].sort((a, b) => {
1458
+ const updatedDiff = this.agentTimestampMs(b.__mj_UpdatedAt) - this.agentTimestampMs(a.__mj_UpdatedAt);
1459
+ if (updatedDiff !== 0) {
1460
+ return updatedDiff;
1461
+ }
1462
+ const createdDiff = this.agentTimestampMs(b.__mj_CreatedAt) - this.agentTimestampMs(a.__mj_CreatedAt);
1463
+ if (createdDiff !== 0) {
1464
+ return createdDiff;
1465
+ }
1466
+ return a.ID.localeCompare(b.ID);
1467
+ });
1468
+ winner = sorted[0];
1469
+ }
1470
+ for (const agent of bucket) {
1471
+ if (!UUIDsEqual(agent.ID, winner.ID)) {
1472
+ this.setCachedAgentPrimaryFlag(agent, false);
1473
+ mutated = true;
1474
+ }
1475
+ }
1476
+ }
1477
+ return mutated;
1478
+ }
1479
+ agentTimestampMs(value) {
1480
+ if (!value) {
1481
+ return 0;
1482
+ }
1483
+ if (value instanceof Date) {
1484
+ const ms = value.getTime();
1485
+ return Number.isFinite(ms) ? ms : 0;
1486
+ }
1487
+ const parsed = Date.parse(value);
1488
+ return Number.isFinite(parsed) ? parsed : 0;
1489
+ }
1082
1490
  /**
1083
1491
  * The collections {@link AdditionalLoading} attaches to parents. When these read zero while
1084
1492
  * the child arrays are full, the derived state has been lost — the failure that row counts
@@ -1299,33 +1707,303 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1299
1707
  GetSubAgents(agentID, status, relationshipStatus) {
1300
1708
  this.ensureAgentsIndex();
1301
1709
  this.ensureAgentRelationshipsIndex();
1302
- const normAgentId = NormalizeUUID(agentID);
1303
- const rawChildAgents = this._childAgentsByParentID.get(normAgentId) ?? [];
1304
- const childAgents = status ? rawChildAgents.filter((a) => a.Status === status) : rawChildAgents;
1710
+ const chain = this.GetAgentInheritanceChain(agentID);
1711
+ const chainIds = chain.length > 0 ? chain.map((a) => NormalizeUUID(a.ID)) : [NormalizeUUID(agentID)];
1305
1712
  const relStatus = relationshipStatus ?? "Active";
1306
- const rawRelationships = this._agentRelationshipsByAgentID.get(normAgentId) ?? [];
1307
- const uniqueAgentIDs = /* @__PURE__ */ new Set();
1308
- const allSubAgents = [];
1309
- for (const agent of childAgents) {
1310
- const normId = NormalizeUUID(agent.ID);
1311
- if (!uniqueAgentIDs.has(normId)) {
1312
- uniqueAgentIDs.add(normId);
1313
- allSubAgents.push(agent);
1314
- }
1315
- }
1316
- for (const ar of rawRelationships) {
1317
- if (ar.Status !== relStatus || !ar.SubAgentID)
1318
- continue;
1319
- const agent = this._agentsByID.get(NormalizeUUID(ar.SubAgentID));
1320
- if (agent && (!status || agent.Status === status)) {
1321
- const normId = NormalizeUUID(agent.ID);
1322
- if (!uniqueAgentIDs.has(normId)) {
1323
- uniqueAgentIDs.add(normId);
1324
- allSubAgents.push(agent);
1713
+ const subAgentsById = /* @__PURE__ */ new Map();
1714
+ for (const normChainAgentId of chainIds) {
1715
+ const rawChildAgents = this._childAgentsByParentID.get(normChainAgentId) ?? [];
1716
+ const childAgents = status ? rawChildAgents.filter((a) => a.Status === status) : rawChildAgents;
1717
+ for (const child of childAgents) {
1718
+ const normChildId = NormalizeUUID(child.ID);
1719
+ if (!subAgentsById.has(normChildId)) {
1720
+ subAgentsById.set(normChildId, child);
1721
+ }
1722
+ }
1723
+ const rawRelationships = this._agentRelationshipsByAgentID.get(normChainAgentId) ?? [];
1724
+ for (const ar of rawRelationships) {
1725
+ if (!ar.SubAgentID)
1726
+ continue;
1727
+ const normSubId = NormalizeUUID(ar.SubAgentID);
1728
+ if (ar.Status !== relStatus) {
1729
+ subAgentsById.delete(normSubId);
1730
+ continue;
1731
+ }
1732
+ const subAgent = this._agentsByID.get(normSubId);
1733
+ if (subAgent && (!status || subAgent.Status === status)) {
1734
+ subAgentsById.set(normSubId, subAgent);
1735
+ }
1736
+ }
1737
+ }
1738
+ return Array.from(subAgentsById.values());
1739
+ }
1740
+ /**
1741
+ * Resolves the `BaseAgentID` prototype inheritance chain for `agentId`, ordered from
1742
+ * outermost prototype root down to the agent itself: `[rootAgent, ..., leafAgent]`.
1743
+ *
1744
+ * Cycle-safe and bounded to `MAX_AGENT_INHERITANCE_DEPTH` (5 hops, up to 6 nodes).
1745
+ * Memoized per loaded `_agents` snapshot.
1746
+ */
1747
+ GetAgentInheritanceChain(agentId) {
1748
+ if (!agentId) {
1749
+ return [];
1750
+ }
1751
+ this.ensureAgentsIndex();
1752
+ const normId = NormalizeUUID(agentId);
1753
+ const cached = this._agentInheritanceChainCache.get(normId);
1754
+ if (cached) {
1755
+ return cached.slice();
1756
+ }
1757
+ const leaf = this._agentsByID.get(normId);
1758
+ if (!leaf) {
1759
+ return [];
1760
+ }
1761
+ const chainFromLeaf = [leaf];
1762
+ const visited = new UUIDSet([leaf.ID]);
1763
+ let currentBaseId = leaf.BaseAgentID;
1764
+ let hops = 0;
1765
+ while (currentBaseId && hops < MAX_AGENT_INHERITANCE_DEPTH) {
1766
+ if (visited.Has(currentBaseId)) {
1767
+ break;
1768
+ }
1769
+ visited.Add(currentBaseId);
1770
+ const baseAgent = this._agentsByID.get(NormalizeUUID(currentBaseId));
1771
+ if (!baseAgent) {
1772
+ break;
1773
+ }
1774
+ chainFromLeaf.push(baseAgent);
1775
+ currentBaseId = baseAgent.BaseAgentID;
1776
+ hops++;
1777
+ }
1778
+ const ordered = chainFromLeaf.reverse();
1779
+ this._agentInheritanceChainCache.set(normId, ordered);
1780
+ return ordered.slice();
1781
+ }
1782
+ /**
1783
+ * Returns the top-level prototype root agent (`BaseAgentID == null`) for `agentId`,
1784
+ * or the agent itself if it is already a root agent.
1785
+ */
1786
+ GetRootAgent(agentId) {
1787
+ const chain = this.GetAgentInheritanceChain(agentId);
1788
+ return chain.length > 0 ? chain[0] : void 0;
1789
+ }
1790
+ /**
1791
+ * Builds the root-to-leaf inheritance chain for an already-provided `MJAIAgentEntityExtended`
1792
+ * instance, keeping `agent` itself as the leaf so caller-supplied in-memory field overrides
1793
+ * (such as tests cloning a cached agent with different `AcceptsSkills` / `SkillActivationMode`)
1794
+ * are never shadowed by the cached copy in `_agents`.
1795
+ */
1796
+ resolveInheritanceNodesForAgent(agent) {
1797
+ if (!agent.BaseAgentID) {
1798
+ return [agent];
1799
+ }
1800
+ const ancestors = this.GetAgentInheritanceChain(agent.BaseAgentID).filter((a) => !UUIDsEqual(a.ID, agent.ID));
1801
+ return [...ancestors, agent];
1802
+ }
1803
+ /**
1804
+ * Resolves effective scalar properties and deep-merged `TypeConfiguration` /
1805
+ * `AgentTypePromptParams` across the agent's `BaseAgentID` prototype inheritance chain
1806
+ * (`[rootAgent, ..., leafAgent]`).
1807
+ */
1808
+ ResolveEffectiveAgentProperties(agentOrId) {
1809
+ const leaf = typeof agentOrId === "string" ? this.GetAgentByID(agentOrId) : agentOrId;
1810
+ const nodes = leaf ? this.resolveInheritanceNodesForAgent(leaf) : [];
1811
+ const root = nodes[0];
1812
+ const nearestNonNull = (picker) => {
1813
+ for (let i = nodes.length - 1; i >= 0; i--) {
1814
+ const v = picker(nodes[i]);
1815
+ if (v !== null && v !== void 0 && (typeof v !== "string" || v.trim().length > 0)) {
1816
+ return v;
1817
+ }
1818
+ }
1819
+ return null;
1820
+ };
1821
+ const isolationRank = {
1822
+ InProcess: 0,
1823
+ Worker: 1,
1824
+ Process: 2,
1825
+ Container: 3
1826
+ };
1827
+ let effectiveIsolation = "InProcess";
1828
+ for (const node of nodes) {
1829
+ const iso = node.Isolation ?? "InProcess";
1830
+ if ((isolationRank[iso] ?? 0) > (isolationRank[effectiveIsolation] ?? 0)) {
1831
+ effectiveIsolation = iso;
1832
+ }
1833
+ }
1834
+ const acceptsRank = {
1835
+ None: 0,
1836
+ Limited: 1,
1837
+ All: 2
1838
+ };
1839
+ let effectiveAcceptsSkills = root?.AcceptsSkills ?? "None";
1840
+ for (let i = 1; i < nodes.length; i++) {
1841
+ const nodeAccepts = nodes[i].AcceptsSkills;
1842
+ if (nodeAccepts != null && (acceptsRank[nodeAccepts] ?? 0) < (acceptsRank[effectiveAcceptsSkills] ?? 0)) {
1843
+ effectiveAcceptsSkills = nodeAccepts;
1844
+ }
1845
+ }
1846
+ const skillModeRank = {
1847
+ RequestedOnly: 0,
1848
+ Auto: 1
1849
+ };
1850
+ let effectiveSkillActivationMode = root?.SkillActivationMode ?? "RequestedOnly";
1851
+ for (let i = 1; i < nodes.length; i++) {
1852
+ const nodeMode = nodes[i].SkillActivationMode;
1853
+ if (nodeMode != null && (skillModeRank[nodeMode] ?? 0) < (skillModeRank[effectiveSkillActivationMode] ?? 0)) {
1854
+ effectiveSkillActivationMode = nodeMode;
1855
+ }
1856
+ }
1857
+ const activePromptAgentIds = new UUIDSet(this._agentPrompts.filter((ap) => ap.Status === "Active").map((ap) => ap.AgentID));
1858
+ const leafHasOwnPrompts = leaf ? activePromptAgentIds.Has(leaf.ID) : false;
1859
+ let effectiveModelSelectionMode = leaf?.ModelSelectionMode ?? "Agent Type";
1860
+ if (!leafHasOwnPrompts && nodes.length > 1) {
1861
+ for (let i = nodes.length - 1; i >= 0; i--) {
1862
+ const candidate = nodes[i];
1863
+ if (activePromptAgentIds.Has(candidate.ID)) {
1864
+ effectiveModelSelectionMode = candidate.ModelSelectionMode ?? "Agent Type";
1865
+ break;
1866
+ }
1867
+ }
1868
+ }
1869
+ let mergedTypeConfig = null;
1870
+ for (const node of nodes) {
1871
+ const parsed = ParseAgentConfigJsonObject(node.TypeConfiguration);
1872
+ if (parsed) {
1873
+ mergedTypeConfig = mergedTypeConfig ? DeepMergeAgentConfigObjects(mergedTypeConfig, parsed) : { ...parsed };
1874
+ }
1875
+ }
1876
+ if (mergedTypeConfig && leaf && leaf.BaseAgentID && (leaf.InstantiationMode ?? "None") === "None") {
1877
+ delete mergedTypeConfig["instantiation"];
1878
+ }
1879
+ let mergedPromptParams = null;
1880
+ for (const node of nodes) {
1881
+ const parsed = ParseAgentConfigJsonObject(node.AgentTypePromptParams);
1882
+ if (parsed) {
1883
+ mergedPromptParams = mergedPromptParams ? DeepMergeAgentConfigObjects(mergedPromptParams, parsed) : { ...parsed };
1884
+ }
1885
+ }
1886
+ const effectiveRequirePlanMode = nodes.some((n) => n.RequirePlanMode === true);
1887
+ const effectiveSupportsPlanMode = nodes.length > 0 ? nodes.every((n) => n.SupportsPlanMode !== false) : true;
1888
+ const effectiveSearchScopeAccess = leaf?.SearchScopeAccess && leaf.SearchScopeAccess !== "None" ? leaf.SearchScopeAccess : nearestNonNull((a) => a.SearchScopeAccess && a.SearchScopeAccess !== "None" ? a.SearchScopeAccess : null) ?? leaf?.SearchScopeAccess ?? "None";
1889
+ const effectiveArtifactCreationMode = leaf?.ArtifactCreationMode && leaf.ArtifactCreationMode !== "Never" ? leaf.ArtifactCreationMode : nearestNonNull((a) => a.ArtifactCreationMode && a.ArtifactCreationMode !== "Never" ? a.ArtifactCreationMode : null) ?? leaf?.ArtifactCreationMode ?? "Never";
1890
+ return {
1891
+ TypeID: nearestNonNull((a) => a.TypeID),
1892
+ DriverClass: nearestNonNull((a) => a.DriverClass),
1893
+ ModelSelectionMode: effectiveModelSelectionMode,
1894
+ Isolation: effectiveIsolation,
1895
+ ContextWindowMaxTokens: nearestNonNull((a) => a.ContextWindowMaxTokens),
1896
+ CompactionTriggerPercent: nearestNonNull((a) => a.CompactionTriggerPercent),
1897
+ CompactionTargetPercent: nearestNonNull((a) => a.CompactionTargetPercent),
1898
+ ConversationSummaryPromptID: nearestNonNull((a) => a.ConversationSummaryPromptID),
1899
+ EnableContextCompression: nodes.some((n) => n.EnableContextCompression === true),
1900
+ ContextCompressionMessageThreshold: nearestNonNull((a) => a.ContextCompressionMessageThreshold),
1901
+ ContextCompressionPromptID: nearestNonNull((a) => a.ContextCompressionPromptID),
1902
+ ContextCompressionMessageRetentionCount: nearestNonNull((a) => a.ContextCompressionMessageRetentionCount),
1903
+ RerankerConfiguration: nearestNonNull((a) => a.RerankerConfiguration),
1904
+ ScopeConfig: nearestNonNull((a) => a.ScopeConfig),
1905
+ DefaultPromptEffortLevel: nearestNonNull((a) => a.DefaultPromptEffortLevel),
1906
+ ChatHandlingOption: nearestNonNull((a) => a.ChatHandlingOption),
1907
+ DefaultArtifactTypeID: nearestNonNull((a) => a.DefaultArtifactTypeID),
1908
+ ArtifactCreationMode: effectiveArtifactCreationMode,
1909
+ DeclareActionsAsNativeTools: nodes.some((n) => n.DeclareActionsAsNativeTools === true),
1910
+ SupportsPlanMode: effectiveSupportsPlanMode,
1911
+ RequirePlanMode: effectiveRequirePlanMode,
1912
+ AcceptsSkills: effectiveAcceptsSkills,
1913
+ SkillActivationMode: effectiveSkillActivationMode,
1914
+ SearchScopeAccess: effectiveSearchScopeAccess,
1915
+ AllowMemoryWrite: nodes.some((n) => n.AllowMemoryWrite === true),
1916
+ InjectNotes: nodes.some((n) => n.InjectNotes === true),
1917
+ MaxNotesToInject: nearestNonNull((a) => a.MaxNotesToInject),
1918
+ NoteInjectionStrategy: nearestNonNull((a) => a.NoteInjectionStrategy) ?? "Relevant",
1919
+ InjectExamples: nodes.some((n) => n.InjectExamples === true),
1920
+ MaxExamplesToInject: nearestNonNull((a) => a.MaxExamplesToInject),
1921
+ ExampleInjectionStrategy: nearestNonNull((a) => a.ExampleInjectionStrategy) ?? "Semantic",
1922
+ LogoURL: nearestNonNull((a) => a.LogoURL),
1923
+ IconClass: nearestNonNull((a) => a.IconClass),
1924
+ TypeConfiguration: mergedTypeConfig && Object.keys(mergedTypeConfig).length > 0 ? JSON.stringify(mergedTypeConfig) : null,
1925
+ AgentTypePromptParams: mergedPromptParams && Object.keys(mergedPromptParams).length > 0 ? JSON.stringify(mergedPromptParams) : null
1926
+ };
1927
+ }
1928
+ /**
1929
+ * Resolves effective `AIAgentPrompt` rows for `agentId` along its `BaseAgentID` chain:
1930
+ * if the agent defines its own matching prompts, those are returned; otherwise walks up
1931
+ * `BaseAgentID` to the nearest ancestor with matching prompts.
1932
+ */
1933
+ GetEffectiveAgentPrompts(agentId, status = "Active") {
1934
+ const chain = this.GetAgentInheritanceChain(agentId);
1935
+ const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : agentId ? [agentId] : [];
1936
+ const chainIdSet = new UUIDSet(idsLeafToRoot);
1937
+ const promptsByAgentId = /* @__PURE__ */ new Map();
1938
+ for (const ap of this._agentPrompts) {
1939
+ if (ap.Status === status && chainIdSet.Has(ap.AgentID)) {
1940
+ const key = NormalizeUUID(ap.AgentID);
1941
+ const list = promptsByAgentId.get(key) ?? [];
1942
+ list.push(ap);
1943
+ promptsByAgentId.set(key, list);
1944
+ }
1945
+ }
1946
+ for (const id of idsLeafToRoot) {
1947
+ const matches = promptsByAgentId.get(NormalizeUUID(id));
1948
+ if (matches && matches.length > 0) {
1949
+ return matches.sort((a, b) => a.ExecutionOrder - b.ExecutionOrder);
1950
+ }
1951
+ }
1952
+ return [];
1953
+ }
1954
+ /**
1955
+ * Resolves effective `AIAgentAction` rows for `agentId` across its `BaseAgentID` chain
1956
+ * (root -> leaf, keyed by `ActionID`). A descendant row with `Status !== 'Active'`
1957
+ * (e.g. `'Disabled'` or `'Revoked'`) vetoes an inherited action.
1958
+ */
1959
+ GetEffectiveAgentActions(agentId) {
1960
+ const chain = this.GetAgentInheritanceChain(agentId);
1961
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : agentId ? [agentId] : [];
1962
+ const chainIdSet = new UUIDSet(idsRootToLeaf);
1963
+ const actionsByAgentId = /* @__PURE__ */ new Map();
1964
+ for (const aa of this._agentActions) {
1965
+ if (chainIdSet.Has(aa.AgentID)) {
1966
+ const key = NormalizeUUID(aa.AgentID);
1967
+ const list = actionsByAgentId.get(key) ?? [];
1968
+ list.push(aa);
1969
+ actionsByAgentId.set(key, list);
1970
+ }
1971
+ }
1972
+ const effectiveByActionId = /* @__PURE__ */ new Map();
1973
+ for (const id of idsRootToLeaf) {
1974
+ const rows = actionsByAgentId.get(NormalizeUUID(id)) ?? [];
1975
+ for (const row of rows) {
1976
+ if (!row.ActionID)
1977
+ continue;
1978
+ const normActionId = NormalizeUUID(row.ActionID);
1979
+ if (row.Status === "Active") {
1980
+ effectiveByActionId.set(normActionId, row);
1981
+ } else {
1982
+ effectiveByActionId.delete(normActionId);
1325
1983
  }
1326
1984
  }
1327
1985
  }
1328
- return allSubAgents;
1986
+ return Array.from(effectiveByActionId.values());
1987
+ }
1988
+ /**
1989
+ * Collects non-empty `AdditionalInstructions` stacked down the `BaseAgentID` chain from
1990
+ * root template to leaf instance.
1991
+ */
1992
+ GetStackedAdditionalInstructions(agentId) {
1993
+ const chain = this.GetAgentInheritanceChain(agentId);
1994
+ const stacked = [];
1995
+ for (const node of chain) {
1996
+ const text = node.AdditionalInstructions?.trim();
1997
+ if (text && text.length > 0) {
1998
+ stacked.push({
1999
+ AgentID: node.ID,
2000
+ AgentName: node.Name ?? node.ID,
2001
+ IsRootOrTemplate: !node.BaseAgentID || node.InstantiationMode !== "None",
2002
+ Instructions: text
2003
+ });
2004
+ }
2005
+ }
2006
+ return stacked;
1329
2007
  }
1330
2008
  get AgentTypes() {
1331
2009
  return this.GetConfigData("_agentTypes");
@@ -1524,19 +2202,158 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1524
2202
  }
1525
2203
  }
1526
2204
  /**
1527
- * Synchronous permission check using already-loaded `_agentPermissions` metadata.
1528
- * Mirrors `AIAgentPermissionHelper.GetEffectivePermissions` without async `Config()` overhead.
2205
+ * Synchronous check for whether `user` has `CanView` permission on `agent` under the
2206
+ * 2x2 RBAC matrix.
1529
2207
  */
1530
- canUserRunAgentSync(agent, allPermissions, user, userRoleIds) {
1531
- if (UUIDsEqual(agent.OwnerUserID, user.ID)) {
1532
- return true;
2208
+ CanUserViewAgentSync(agent, user) {
2209
+ if (!agent || !user) {
2210
+ return false;
2211
+ }
2212
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, this._agentPermissions, user).canView;
2213
+ }
2214
+ /**
2215
+ * Synchronous check for whether `user` has `CanRun` permission on `agent` under the
2216
+ * 2x2 RBAC matrix AND the Ancestor `CanRun` Invariant across `BaseAgentID`.
2217
+ */
2218
+ CanUserRunAgentSync(agent, user) {
2219
+ if (!agent || !user) {
2220
+ return false;
1533
2221
  }
1534
- const agentPerms = allPermissions.filter((p) => UUIDsEqual(p.AgentID, agent.ID));
1535
- if (agentPerms.length === 0) {
2222
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, this._agentPermissions, user).canRun;
2223
+ }
2224
+ /**
2225
+ * Returns active agents that can be instantiated as templates (`InstantiationMode` is
2226
+ * `'Required'` or `'Optional'`) and that `user` is permitted to run.
2227
+ */
2228
+ GetInstantiableAgents(user) {
2229
+ if (!user) {
2230
+ return [];
2231
+ }
2232
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
2233
+ return this._agents.filter((a) => a.Status === "Active" && (a.InstantiationMode === "Required" || a.InstantiationMode === "Optional") && this.canUserRunAgentSync(a, this._agentPermissions, user, userRoleIds)).sort((a, b) => (a.Name ?? "").localeCompare(b.Name ?? ""));
2234
+ }
2235
+ /**
2236
+ * Returns active derived agents (`BaseAgentID != null`) owned by or shared with `user`.
2237
+ * Optionally filters to instances descending from `rootOrBaseAgentId` (matching either
2238
+ * direct `BaseAgentID` or top-level `GetRootAgent(a.ID)`).
2239
+ *
2240
+ * Ordered: owned instances first, `IsPrimaryInstance` first, then alphabetically by `Name`.
2241
+ */
2242
+ GetUserDerivedAgents(user, rootOrBaseAgentId) {
2243
+ if (!user) {
2244
+ return [];
2245
+ }
2246
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
2247
+ const filtered = this._agents.filter((a) => {
2248
+ if (a.Status !== "Active" || !a.BaseAgentID) {
2249
+ return false;
2250
+ }
2251
+ const perms = AIAgentPermissionHelper.ComputeEffectivePermissionsSync(a, this._agents, this._agentPermissions, user, userRoleIds);
2252
+ if (!perms.canView) {
2253
+ return false;
2254
+ }
2255
+ if (rootOrBaseAgentId) {
2256
+ const root = this.GetRootAgent(a.ID);
2257
+ const matchesDirect = UUIDsEqual(a.BaseAgentID, rootOrBaseAgentId);
2258
+ const matchesRoot = root ? UUIDsEqual(root.ID, rootOrBaseAgentId) : false;
2259
+ if (!matchesDirect && !matchesRoot) {
2260
+ return false;
2261
+ }
2262
+ }
1536
2263
  return true;
2264
+ });
2265
+ return filtered.sort((a, b) => {
2266
+ const aOwned = UUIDsEqual(a.OwnerUserID, user.ID) ? 1 : 0;
2267
+ const bOwned = UUIDsEqual(b.OwnerUserID, user.ID) ? 1 : 0;
2268
+ if (aOwned !== bOwned)
2269
+ return bOwned - aOwned;
2270
+ const aPrimary = a.IsPrimaryInstance ? 1 : 0;
2271
+ const bPrimary = b.IsPrimaryInstance ? 1 : 0;
2272
+ if (aPrimary !== bPrimary)
2273
+ return bPrimary - aPrimary;
2274
+ return (a.Name ?? "").localeCompare(b.Name ?? "");
2275
+ });
2276
+ }
2277
+ /**
2278
+ * User-scoped agent resolution by UUID or display name so multiple users naming their
2279
+ * personal bots `"Pepper"`, `"Jarvis"`, or `"Sage"` never collide or shadow system agents.
2280
+ *
2281
+ * Resolution precedence:
2282
+ * 1. Exact UUID match (visible to `user`, or any agent if `user` is omitted)
2283
+ * 2. User's owned active derived agents (`BaseAgentID != null && OwnerUserID === user.ID`)
2284
+ * 3. Shared active derived agents visible to `user`
2285
+ * 4. Root catalog agents (`BaseAgentID == null`) visible to `user`
2286
+ */
2287
+ ResolveAgentForUser(nameOrId, user) {
2288
+ const trimmed = nameOrId?.trim();
2289
+ if (!trimmed) {
2290
+ return void 0;
2291
+ }
2292
+ this.ensureAgentsIndex();
2293
+ const byId = this._agentsByID.get(NormalizeUUID(trimmed));
2294
+ if (byId) {
2295
+ if (!user || this.CanUserViewAgentSync(byId, user)) {
2296
+ return byId;
2297
+ }
2298
+ return void 0;
2299
+ }
2300
+ const normName = trimmed.toLowerCase();
2301
+ if (!user) {
2302
+ return this._agentsByName.get(normName);
2303
+ }
2304
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
2305
+ const ownedDerived = this._agents.find((a) => a.Status === "Active" && a.BaseAgentID != null && UUIDsEqual(a.OwnerUserID, user.ID) && (a.Name ?? "").trim().toLowerCase() === normName);
2306
+ if (ownedDerived) {
2307
+ return ownedDerived;
2308
+ }
2309
+ const sharedDerived = this._agents.find((a) => a.Status === "Active" && a.BaseAgentID != null && (a.Name ?? "").trim().toLowerCase() === normName && AIAgentPermissionHelper.ComputeEffectivePermissionsSync(a, this._agents, this._agentPermissions, user, userRoleIds).canView);
2310
+ if (sharedDerived) {
2311
+ return sharedDerived;
2312
+ }
2313
+ const rootMatch = this._agents.find((a) => !a.BaseAgentID && (a.Name ?? "").trim().toLowerCase() === normName && AIAgentPermissionHelper.ComputeEffectivePermissionsSync(a, this._agents, this._agentPermissions, user, userRoleIds).canView);
2314
+ return rootMatch;
2315
+ }
2316
+ /**
2317
+ * Deterministically resolves a user's primary active derived instance descending from
2318
+ * `rootAgentIdOrName` (for example, resolving *"Alice's Chief of Staff"* to Alice's
2319
+ * `IsPrimaryInstance = true` *Pepper* agent for inbound email wakes, inter-agent requests,
2320
+ * and Agent Channels).
2321
+ *
2322
+ * Preference order among `userId`'s active owned instances under the root:
2323
+ * 1. Instance with `IsPrimaryInstance === true`
2324
+ * 2. Earliest-created active instance (fallback when no primary flag is set)
2325
+ * 3. `undefined` when the user has not instantiated an instance under that root yet.
2326
+ */
2327
+ ResolvePrimaryUserAgentInstance(rootAgentIdOrName, userId) {
2328
+ if (!rootAgentIdOrName || !userId) {
2329
+ return void 0;
1537
2330
  }
1538
- const matching = agentPerms.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID != null && userRoleIds.Has(p.RoleID));
1539
- return matching.some((p) => p.CanDelete === true || p.CanEdit === true || p.CanRun === true);
2331
+ this.ensureAgentsIndex();
2332
+ const rootAgent = this._agentsByID.get(NormalizeUUID(rootAgentIdOrName)) ?? this._agentsByName.get(rootAgentIdOrName.trim().toLowerCase());
2333
+ const targetRootId = rootAgent?.ID ?? rootAgentIdOrName;
2334
+ const candidates = this._agents.filter((a) => {
2335
+ if (a.Status !== "Active" || !a.BaseAgentID || !UUIDsEqual(a.OwnerUserID, userId)) {
2336
+ return false;
2337
+ }
2338
+ const chainRoot = this.GetRootAgent(a.ID);
2339
+ return UUIDsEqual(a.BaseAgentID, targetRootId) || chainRoot != null && UUIDsEqual(chainRoot.ID, targetRootId);
2340
+ });
2341
+ if (candidates.length === 0) {
2342
+ return void 0;
2343
+ }
2344
+ const explicitPrimary = candidates.find((a) => a.IsPrimaryInstance === true);
2345
+ if (explicitPrimary) {
2346
+ return explicitPrimary;
2347
+ }
2348
+ return candidates.sort((a, b) => (a.Name ?? "").localeCompare(b.Name ?? ""))[0];
2349
+ }
2350
+ /**
2351
+ * Synchronous permission check using already-loaded `_agentPermissions` metadata.
2352
+ * Delegates to {@link AIAgentPermissionHelper.ComputeEffectivePermissionsSync} so
2353
+ * 2x2 RBAC and Ancestor `CanRun` semantics stay 100% consistent everywhere.
2354
+ */
2355
+ canUserRunAgentSync(agent, allPermissions, user, userRoleIds) {
2356
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, allPermissions, user, userRoleIds).canRun;
1540
2357
  }
1541
2358
  summarizeAgentDescription(rawDescription) {
1542
2359
  if (!rawDescription) {
@@ -1598,16 +2415,82 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1598
2415
  * @param user - Optional user; when present, filters to skills the user can Run.
1599
2416
  * @returns MJAISkillEntity[] - Active skills the agent may activate (empty if AcceptsSkills is 'None').
1600
2417
  */
2418
+ /**
2419
+ * Resolves the effective narrowed `AcceptsSkills` value down the agent's `BaseAgentID`
2420
+ * chain (`All` -> `Limited` -> `None`) without reading unrelated scalar columns.
2421
+ */
2422
+ resolveEffectiveAcceptsSkills(agent) {
2423
+ const nodes = this.resolveInheritanceNodesForAgent(agent);
2424
+ const acceptsRank = {
2425
+ None: 0,
2426
+ Limited: 1,
2427
+ All: 2
2428
+ };
2429
+ let effective = nodes[0]?.AcceptsSkills ?? "None";
2430
+ for (let i = 1; i < nodes.length; i++) {
2431
+ const nodeAccepts = nodes[i].AcceptsSkills;
2432
+ if (nodeAccepts != null && (acceptsRank[nodeAccepts] ?? 0) < (acceptsRank[effective] ?? 0)) {
2433
+ effective = nodeAccepts;
2434
+ }
2435
+ }
2436
+ return effective;
2437
+ }
2438
+ /**
2439
+ * Resolves the effective narrowed `SkillActivationMode` value down the agent's `BaseAgentID`
2440
+ * chain (`Auto` -> `RequestedOnly`).
2441
+ */
2442
+ resolveEffectiveSkillActivationMode(agent) {
2443
+ const nodes = this.resolveInheritanceNodesForAgent(agent);
2444
+ const skillModeRank = {
2445
+ RequestedOnly: 0,
2446
+ Auto: 1
2447
+ };
2448
+ let effective = nodes[0]?.SkillActivationMode ?? "RequestedOnly";
2449
+ for (let i = 1; i < nodes.length; i++) {
2450
+ const nodeMode = nodes[i].SkillActivationMode;
2451
+ if (nodeMode != null && (skillModeRank[nodeMode] ?? 0) < (skillModeRank[effective] ?? 0)) {
2452
+ effective = nodeMode;
2453
+ }
2454
+ }
2455
+ return effective;
2456
+ }
1601
2457
  GetSkillsForAgent(agent, user) {
1602
- if (!agent || agent.AcceptsSkills === "None") {
2458
+ if (!agent) {
2459
+ return [];
2460
+ }
2461
+ const effectiveAcceptsSkills = this.resolveEffectiveAcceptsSkills(agent);
2462
+ if (effectiveAcceptsSkills === "None") {
1603
2463
  return [];
1604
2464
  }
1605
2465
  const activeSkills = this._skills.filter((s) => s.Status === "Active");
1606
2466
  let agentSkills;
1607
- if (agent.AcceptsSkills === "All") {
2467
+ if (effectiveAcceptsSkills === "All") {
1608
2468
  agentSkills = activeSkills;
1609
2469
  } else {
1610
- const grantedSkillIDs = new Set(this._agentSkills.filter((gs) => UUIDsEqual(gs.AgentID, agent.ID) && gs.Status === "Active").map((gs) => NormalizeUUID(gs.SkillID)));
2470
+ const nodes = this.resolveInheritanceNodesForAgent(agent);
2471
+ const chainIds = nodes.map((a) => a.ID);
2472
+ const chainIdSet = new UUIDSet(chainIds);
2473
+ const grantsByAgentId = /* @__PURE__ */ new Map();
2474
+ for (const gs of this._agentSkills) {
2475
+ if (chainIdSet.Has(gs.AgentID)) {
2476
+ const key = NormalizeUUID(gs.AgentID);
2477
+ const list = grantsByAgentId.get(key) ?? [];
2478
+ list.push(gs);
2479
+ grantsByAgentId.set(key, list);
2480
+ }
2481
+ }
2482
+ const grantedSkillIDs = /* @__PURE__ */ new Set();
2483
+ for (const chainAgentId of chainIds) {
2484
+ const grants = grantsByAgentId.get(NormalizeUUID(chainAgentId)) ?? [];
2485
+ for (const grant of grants) {
2486
+ const normSkillId = NormalizeUUID(grant.SkillID);
2487
+ if (grant.Status === "Active") {
2488
+ grantedSkillIDs.add(normSkillId);
2489
+ } else {
2490
+ grantedSkillIDs.delete(normSkillId);
2491
+ }
2492
+ }
2493
+ }
1611
2494
  agentSkills = activeSkills.filter((s) => grantedSkillIDs.has(NormalizeUUID(s.ID)));
1612
2495
  }
1613
2496
  if (!user) {
@@ -1644,7 +2527,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1644
2527
  * gate is 'RequestedOnly', or when no availability gate passes).
1645
2528
  */
1646
2529
  GetAutoActivatableSkillsForAgent(agent, user) {
1647
- if (!agent || agent.SkillActivationMode !== "Auto") {
2530
+ if (!agent) {
2531
+ return [];
2532
+ }
2533
+ if (this.resolveEffectiveSkillActivationMode(agent) !== "Auto") {
1648
2534
  return [];
1649
2535
  }
1650
2536
  return this.GetSkillsForAgent(agent, user).filter((s) => s.ActivationMode === "Auto");
@@ -1669,6 +2555,33 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1669
2555
  GetSkillExposedActionIDs(skillID) {
1670
2556
  return this._skillActions.filter((sa) => UUIDsEqual(sa.SkillID, skillID) && sa.ExposeToModel !== false).map((sa) => sa.ActionID);
1671
2557
  }
2558
+ /**
2559
+ * The subset of {@link GetSkillActionIDs} marked as briefing contributors (`Role = 'Briefing' | 'Both'`).
2560
+ * Invoked in parallel by `Assemble My Briefing` so a Loop agent (such as Chief of Staff) collects
2561
+ * deterministic per-app briefing sections without relying on prompt memory or cluttering its tool list.
2562
+ */
2563
+ GetSkillBriefingActionIDs(skillID) {
2564
+ return this._skillActions.filter((sa) => UUIDsEqual(sa.SkillID, skillID) && (sa.Role === "Briefing" || sa.Role === "Both")).map((sa) => sa.ActionID);
2565
+ }
2566
+ /**
2567
+ * Returns every briefing contributor (`Role = 'Briefing' | 'Both'`) across all skills granted
2568
+ * to `agent` that `user` is permitted to use (via {@link GetSkillsForAgent}). Deduplicates by `ActionID`.
2569
+ */
2570
+ GetBriefingActionsForAgent(agent, user) {
2571
+ const skills = this.GetSkillsForAgent(agent, user);
2572
+ const seen = /* @__PURE__ */ new Set();
2573
+ const entries = [];
2574
+ for (const skill of skills) {
2575
+ for (const actionID of this.GetSkillBriefingActionIDs(skill.ID)) {
2576
+ const key = actionID.trim().toLowerCase();
2577
+ if (!seen.has(key)) {
2578
+ seen.add(key);
2579
+ entries.push({ skill, actionID });
2580
+ }
2581
+ }
2582
+ }
2583
+ return entries;
2584
+ }
1672
2585
  /**
1673
2586
  * Returns the sub-agent IDs bundled into a skill (via "MJ: AI Skill Sub Agents"). Callers
1674
2587
  * resolve the full `MJAIAgentEntityExtended` objects via `this.Agents` / `GetAgentByID`.
@@ -1694,9 +2607,21 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1694
2607
  */
1695
2608
  GetAgentConfigurationPresets(agentId, activeOnly = true) {
1696
2609
  this.ensureAgentConfigurationsIndex();
1697
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId)) ?? [];
1698
- const presets = activeOnly ? raw.filter((ac) => ac.Status === "Active") : raw.slice();
1699
- return presets.sort((a, b) => a.Priority - b.Priority);
2610
+ const chain = this.GetAgentInheritanceChain(agentId);
2611
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => NormalizeUUID(a.ID)) : [NormalizeUUID(agentId)];
2612
+ const byPresetName = /* @__PURE__ */ new Map();
2613
+ for (const id of idsRootToLeaf) {
2614
+ const raw = this._agentConfigurationsByAgentID.get(id) ?? [];
2615
+ for (const preset of raw) {
2616
+ const key = (preset.Name ?? preset.ID).trim().toLowerCase();
2617
+ if (activeOnly && preset.Status !== "Active") {
2618
+ byPresetName.delete(key);
2619
+ } else {
2620
+ byPresetName.set(key, preset);
2621
+ }
2622
+ }
2623
+ }
2624
+ return Array.from(byPresetName.values()).sort((a, b) => a.Priority - b.Priority);
1700
2625
  }
1701
2626
  /**
1702
2627
  * Gets the default configuration preset for an agent
@@ -1714,11 +2639,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1714
2639
  * @returns The configuration preset, or undefined if not found
1715
2640
  */
1716
2641
  GetAgentConfigurationPresetByName(agentId, presetName) {
1717
- this.ensureAgentConfigurationsIndex();
1718
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId));
1719
- if (!raw)
1720
- return void 0;
1721
- return raw.find((ac) => ac.Name === presetName && ac.Status === "Active");
2642
+ const presets = this.GetAgentConfigurationPresets(agentId, true);
2643
+ return presets.find((ac) => ac.Name === presetName);
1722
2644
  }
1723
2645
  get AgentNoteTypes() {
1724
2646
  return this.GetConfigData("_agentNoteTypes");
@@ -1901,7 +2823,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1901
2823
  if (a.ID) {
1902
2824
  byId.set(NormalizeUUID(a.ID), a);
1903
2825
  }
1904
- if (a.Name) {
2826
+ if (a.Name && !a.BaseAgentID) {
1905
2827
  const normName = a.Name.trim().toLowerCase();
1906
2828
  if (!byName.has(normName)) {
1907
2829
  byName.set(normName, a);
@@ -1917,9 +2839,18 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1917
2839
  list.push(a);
1918
2840
  }
1919
2841
  }
2842
+ for (const a of this._agents) {
2843
+ if (a.Name && a.BaseAgentID) {
2844
+ const normName = a.Name.trim().toLowerCase();
2845
+ if (!byName.has(normName)) {
2846
+ byName.set(normName, a);
2847
+ }
2848
+ }
2849
+ }
1920
2850
  this._agentsByID = byId;
1921
2851
  this._agentsByName = byName;
1922
2852
  this._childAgentsByParentID = byParentId;
2853
+ this._agentInheritanceChainCache.clear();
1923
2854
  this._agentsIndexedRef = this._agents;
1924
2855
  this._agentsIndexedLen = this._agents.length;
1925
2856
  }
@@ -2478,7 +3409,28 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2478
3409
  * Joins through the junction table to return full tool definition entities.
2479
3410
  */
2480
3411
  GetClientToolsForAgent(agentId) {
2481
- const junctions = this._agentClientTools.filter((j) => UUIDsEqual(j.AgentID, agentId)).sort((a, b) => a.Priority - b.Priority);
3412
+ const chain = this.GetAgentInheritanceChain(agentId);
3413
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
3414
+ const chainIdSet = new UUIDSet(idsRootToLeaf);
3415
+ const toolsByAgentId = /* @__PURE__ */ new Map();
3416
+ for (const j of this._agentClientTools) {
3417
+ if (chainIdSet.Has(j.AgentID)) {
3418
+ const key = NormalizeUUID(j.AgentID);
3419
+ const list = toolsByAgentId.get(key) ?? [];
3420
+ list.push(j);
3421
+ toolsByAgentId.set(key, list);
3422
+ }
3423
+ }
3424
+ const mergedByToolId = /* @__PURE__ */ new Map();
3425
+ for (const id of idsRootToLeaf) {
3426
+ const rows = toolsByAgentId.get(NormalizeUUID(id)) ?? [];
3427
+ for (const row of rows) {
3428
+ if (!row.ClientToolDefinitionID)
3429
+ continue;
3430
+ mergedByToolId.set(NormalizeUUID(row.ClientToolDefinitionID), row);
3431
+ }
3432
+ }
3433
+ const junctions = Array.from(mergedByToolId.values()).sort((a, b) => a.Priority - b.Priority);
2482
3434
  const tools = [];
2483
3435
  for (const junction of junctions) {
2484
3436
  const tool = this._clientToolDefinitions.find((t) => UUIDsEqual(t.ID, junction.ClientToolDefinitionID));
@@ -2515,8 +3467,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2515
3467
  if (!agent) {
2516
3468
  return void 0;
2517
3469
  }
2518
- if (agent.ModelSelectionMode === "Agent") {
2519
- const agentPrompt = this._agentPrompts.filter((ap) => UUIDsEqual(ap.AgentID, agent.ID) && ap.Status === "Active").sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
3470
+ const effectiveProps = this.ResolveEffectiveAgentProperties(agent);
3471
+ const effectivePrompts = this.GetEffectiveAgentPrompts(agent.ID, "Active");
3472
+ if (effectiveProps.ModelSelectionMode === "Agent") {
3473
+ const agentPrompt = effectivePrompts[0];
2520
3474
  if (agentPrompt) {
2521
3475
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2522
3476
  if (promptModels && promptModels.length > 0) {
@@ -2524,8 +3478,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2524
3478
  }
2525
3479
  }
2526
3480
  }
2527
- if (agent.TypeID) {
2528
- const agentType = this._agentTypes.find((at) => UUIDsEqual(at.ID, agent.TypeID));
3481
+ if (effectiveProps.TypeID) {
3482
+ const agentType = this._agentTypes.find((at) => UUIDsEqual(at.ID, effectiveProps.TypeID));
2529
3483
  if (agentType?.SystemPromptID) {
2530
3484
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentType.SystemPromptID));
2531
3485
  if (promptModels && promptModels.length > 0) {
@@ -2533,8 +3487,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2533
3487
  }
2534
3488
  }
2535
3489
  }
2536
- if (agent.ModelSelectionMode !== "Agent") {
2537
- const agentPrompt = this._agentPrompts.filter((ap) => UUIDsEqual(ap.AgentID, agent.ID) && ap.Status === "Active").sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
3490
+ if (effectiveProps.ModelSelectionMode !== "Agent") {
3491
+ const agentPrompt = effectivePrompts[0];
2538
3492
  if (agentPrompt) {
2539
3493
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2540
3494
  if (promptModels && promptModels.length > 0) {
@@ -2546,13 +3500,9 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2546
3500
  }
2547
3501
  /**
2548
3502
  * Gets all modalities supported by an agent for a given direction.
2549
- * Follows precedence chain: Agent → Model → System → Default.
3503
+ * Follows precedence chain: Agent (walked BaseAgentID root -> leaf) → Model → System → Default.
2550
3504
  * If no explicit agent modality records exist, falls through to the agent's model's effective modalities.
2551
3505
  * Any explicit AIAgentModality records override: IsAllowed = 1 adds/retains, IsAllowed = 0 acts as a hard veto.
2552
- * @param agentId - The agent ID
2553
- * @param direction - 'Input' or 'Output'
2554
- * @param modelId - Optional model ID override
2555
- * @returns Array of modality entities the agent supports
2556
3506
  */
2557
3507
  GetAgentModalities(agentId, direction, modelId) {
2558
3508
  this.ensureModalitiesIndex();
@@ -2562,17 +3512,31 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2562
3512
  for (const m of baseModalities) {
2563
3513
  resultMap.set(NormalizeUUID(m.ID), m);
2564
3514
  }
2565
- const agentRecords = this._agentModalities.filter((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction);
2566
- for (const am of agentRecords) {
2567
- const normId = NormalizeUUID(am.ModalityID);
2568
- const isAllowed = am.IsAllowed !== false;
2569
- if (isAllowed) {
2570
- const modality = this._modalitiesByID.get(normId);
2571
- if (modality) {
2572
- resultMap.set(normId, modality);
3515
+ const chain = this.GetAgentInheritanceChain(agentId);
3516
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
3517
+ const chainIdSet = new UUIDSet(idsRootToLeaf);
3518
+ const modalitiesByAgentId = /* @__PURE__ */ new Map();
3519
+ for (const am of this._agentModalities) {
3520
+ if (am.Direction === direction && chainIdSet.Has(am.AgentID)) {
3521
+ const key = NormalizeUUID(am.AgentID);
3522
+ const list = modalitiesByAgentId.get(key) ?? [];
3523
+ list.push(am);
3524
+ modalitiesByAgentId.set(key, list);
3525
+ }
3526
+ }
3527
+ for (const id of idsRootToLeaf) {
3528
+ const agentRecords = modalitiesByAgentId.get(NormalizeUUID(id)) ?? [];
3529
+ for (const am of agentRecords) {
3530
+ const normId = NormalizeUUID(am.ModalityID);
3531
+ const isAllowed = am.IsAllowed !== false;
3532
+ if (isAllowed) {
3533
+ const modality = this._modalitiesByID.get(normId);
3534
+ if (modality) {
3535
+ resultMap.set(normId, modality);
3536
+ }
3537
+ } else {
3538
+ resultMap.delete(normId);
2573
3539
  }
2574
- } else {
2575
- resultMap.delete(normId);
2576
3540
  }
2577
3541
  }
2578
3542
  return Array.from(resultMap.values());
@@ -2634,9 +3598,23 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2634
3598
  this.ensureModalitiesIndex();
2635
3599
  const targetModality = this._modalitiesByName.get(modalityName.toLowerCase());
2636
3600
  if (targetModality) {
2637
- const agentRecord = this._agentModalities.find((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID));
2638
- if (agentRecord) {
2639
- return agentRecord.IsAllowed !== false;
3601
+ const chain = this.GetAgentInheritanceChain(agentId);
3602
+ const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : [agentId];
3603
+ const chainIdSet = new UUIDSet(idsLeafToRoot);
3604
+ const recordByAgentId = /* @__PURE__ */ new Map();
3605
+ for (const am of this._agentModalities) {
3606
+ if (am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID) && chainIdSet.Has(am.AgentID)) {
3607
+ const key = NormalizeUUID(am.AgentID);
3608
+ if (!recordByAgentId.has(key)) {
3609
+ recordByAgentId.set(key, am);
3610
+ }
3611
+ }
3612
+ }
3613
+ for (const id of idsLeafToRoot) {
3614
+ const agentRecord = recordByAgentId.get(NormalizeUUID(id));
3615
+ if (agentRecord) {
3616
+ return agentRecord.IsAllowed !== false;
3617
+ }
2640
3618
  }
2641
3619
  }
2642
3620
  const resolvedModelId = this.resolveAgentModelId(agentId, modelId);
@@ -2705,7 +3683,26 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2705
3683
  source: "Default"
2706
3684
  };
2707
3685
  }
2708
- const agentModality = this._agentModalities.find((am) => UUIDsEqual(am.AgentID, agentId) && UUIDsEqual(am.ModalityID, modality.ID) && am.Direction === "Input");
3686
+ const chain = this.GetAgentInheritanceChain(agentId);
3687
+ const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : [agentId];
3688
+ const chainIdSet = new UUIDSet(idsLeafToRoot);
3689
+ const modalityByAgentId = /* @__PURE__ */ new Map();
3690
+ for (const am of this._agentModalities) {
3691
+ if (am.Direction === "Input" && UUIDsEqual(am.ModalityID, modality.ID) && chainIdSet.Has(am.AgentID)) {
3692
+ const key = NormalizeUUID(am.AgentID);
3693
+ if (!modalityByAgentId.has(key)) {
3694
+ modalityByAgentId.set(key, am);
3695
+ }
3696
+ }
3697
+ }
3698
+ let agentModality;
3699
+ for (const id of idsLeafToRoot) {
3700
+ const found = modalityByAgentId.get(NormalizeUUID(id));
3701
+ if (found) {
3702
+ agentModality = found;
3703
+ break;
3704
+ }
3705
+ }
2709
3706
  if (agentModality) {
2710
3707
  return {
2711
3708
  maxSizeBytes: agentModality.MaxSizeBytes,
@@ -2978,16 +3975,56 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2978
3975
  return excludedApiNames;
2979
3976
  }
2980
3977
  /**
2981
- * Gets all personas configured for an agent, ordered by Sequence.
2982
- * Only returns personas where IsAllowed is true and the persona record is active.
3978
+ * Gets all personas configured for an agent across its `BaseAgentID` inheritance chain
3979
+ * (root -> leaf), ordered by `Sequence`. Descendant rows override ancestor rows for the
3980
+ * same `PersonaID`, and descendant `IsAllowed === false` vetoes an inherited persona.
2983
3981
  *
2984
3982
  * @param agentId - The agent ID
2985
3983
  * @returns Array of resolved agent personas
2986
3984
  */
2987
3985
  GetAgentPersonas(agentId) {
2988
- const agentRecords = this._agentPersonas.filter((ap) => UUIDsEqual(ap.AgentID, agentId) && ap.IsAllowed).sort((a, b) => (a.Sequence ?? 0) - (b.Sequence ?? 0));
3986
+ const chain = this.GetAgentInheritanceChain(agentId);
3987
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
3988
+ const chainIdSet = new UUIDSet(idsRootToLeaf);
3989
+ const personasByAgentId = /* @__PURE__ */ new Map();
3990
+ for (const ap of this._agentPersonas) {
3991
+ if (chainIdSet.Has(ap.AgentID)) {
3992
+ const key = NormalizeUUID(ap.AgentID);
3993
+ const list = personasByAgentId.get(key) ?? [];
3994
+ list.push(ap);
3995
+ personasByAgentId.set(key, list);
3996
+ }
3997
+ }
3998
+ const mergedByPersonaId = /* @__PURE__ */ new Map();
3999
+ const depthByPersonaId = /* @__PURE__ */ new Map();
4000
+ idsRootToLeaf.forEach((id, depth) => {
4001
+ const rows = personasByAgentId.get(NormalizeUUID(id)) ?? [];
4002
+ for (const ap of rows) {
4003
+ if (!ap.PersonaID)
4004
+ continue;
4005
+ const normPersonaId = NormalizeUUID(ap.PersonaID);
4006
+ if (ap.IsAllowed === false) {
4007
+ mergedByPersonaId.delete(normPersonaId);
4008
+ depthByPersonaId.delete(normPersonaId);
4009
+ } else {
4010
+ mergedByPersonaId.set(normPersonaId, ap);
4011
+ depthByPersonaId.set(normPersonaId, depth);
4012
+ }
4013
+ }
4014
+ });
4015
+ const sortedRecords = Array.from(mergedByPersonaId.entries()).sort(([idA, a], [idB, b]) => {
4016
+ const aDef = a.IsDefault ? 1 : 0;
4017
+ const bDef = b.IsDefault ? 1 : 0;
4018
+ if (aDef !== bDef)
4019
+ return bDef - aDef;
4020
+ const depthA = depthByPersonaId.get(idA) ?? 0;
4021
+ const depthB = depthByPersonaId.get(idB) ?? 0;
4022
+ if (aDef === 1 && depthA !== depthB)
4023
+ return depthB - depthA;
4024
+ return (a.Sequence ?? 0) - (b.Sequence ?? 0);
4025
+ }).map(([, ap]) => ap);
2989
4026
  const result = [];
2990
- for (const ap of agentRecords) {
4027
+ for (const ap of sortedRecords) {
2991
4028
  const persona = this._personas.find((p) => UUIDsEqual(p.ID, ap.PersonaID) && p.IsActive);
2992
4029
  if (persona) {
2993
4030
  result.push({
@@ -3000,21 +4037,35 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3000
4037
  }
3001
4038
  /**
3002
4039
  * Resolves the effective persona for an agent using the precedence chain:
3003
- * 1. Agent's default persona (AIAgentPersona where IsDefault = 1 and IsAllowed = 1)
3004
- * 2. First allowed agent persona (by Sequence)
3005
- * 3. Model/vendor default persona (from GetModelPersonas)
4040
+ * 1. Explicit `options.preferredPersonaId` (e.g. from `AIAgentUserPolicy.PreferredPersonaID`)
4041
+ * 2. Agent's default persona across its `BaseAgentID` chain (`AIAgentPersona` where `IsDefault = 1`, leaf wins)
4042
+ * 3. First allowed agent persona (by Sequence)
4043
+ * 4. Model/vendor default persona (from GetModelPersonas)
3006
4044
  *
3007
4045
  * In all cases, merges agent-level StyleOverride (Tone, SpeakingStyle) over the persona's defaults.
3008
4046
  *
3009
4047
  * @param agentId - The agent ID
3010
- * @param options - Optional overrides for modelId, vendorId, modalityName
4048
+ * @param options - Optional overrides for modelId, vendorId, modalityName, preferredPersonaId
3011
4049
  */
3012
4050
  ResolveAgentPersona(agentId, options) {
3013
4051
  const modalityName = options?.modalityName ?? "Audio";
3014
4052
  const agentPersonas = this.GetAgentPersonas(agentId);
3015
4053
  let chosenPersona = null;
3016
4054
  let chosenAgentPersona = void 0;
3017
- if (agentPersonas.length > 0) {
4055
+ if (options?.preferredPersonaId) {
4056
+ const matchedAgentPersona = agentPersonas.find((ap) => UUIDsEqual(ap.Persona.ID, options.preferredPersonaId));
4057
+ if (matchedAgentPersona) {
4058
+ chosenPersona = matchedAgentPersona.Persona;
4059
+ chosenAgentPersona = matchedAgentPersona.AgentPersona;
4060
+ } else {
4061
+ const catalogPersona = this._personas.find((p) => UUIDsEqual(p.ID, options.preferredPersonaId) && p.IsActive);
4062
+ if (catalogPersona) {
4063
+ chosenPersona = catalogPersona;
4064
+ chosenAgentPersona = agentPersonas.find((ap) => ap.AgentPersona.IsDefault)?.AgentPersona ?? agentPersonas[0]?.AgentPersona;
4065
+ }
4066
+ }
4067
+ }
4068
+ if (!chosenPersona && agentPersonas.length > 0) {
3018
4069
  const defaultAP = agentPersonas.find((ap) => ap.AgentPersona.IsDefault);
3019
4070
  const selected = defaultAP ?? agentPersonas[0];
3020
4071
  chosenPersona = selected.Persona;
@@ -3715,7 +4766,7 @@ var AgentClientSession = class {
3715
4766
  if (!provider) {
3716
4767
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3717
4768
  }
3718
- const aiClient = new tt(provider);
4769
+ const aiClient = new rt(provider);
3719
4770
  try {
3720
4771
  const agentShim = { ID: params.AgentId };
3721
4772
  const messages = params.Messages.map((m) => ({
@@ -3773,7 +4824,7 @@ var AgentClientSession = class {
3773
4824
  if (!provider) {
3774
4825
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3775
4826
  }
3776
- const aiClient = new tt(provider);
4827
+ const aiClient = new rt(provider);
3777
4828
  try {
3778
4829
  const gqlParams = {
3779
4830
  userMessageId: params.UserMessageId,
@@ -4214,6 +5265,24 @@ function IntersectAcceptedSkills(runnable, accepted) {
4214
5265
  }
4215
5266
 
4216
5267
  // ../../ConversationsRuntime/dist/mentions/MentionAutocomplete.js
5268
+ var GROUP_LABELS = {
5269
+ frequent: "Frequent & Recent",
5270
+ "my-agents": "My Agents",
5271
+ shared: "Shared",
5272
+ people: "People",
5273
+ results: "Results"
5274
+ };
5275
+ var FRECENCY_SETTING_KEY = "chat.mentionFrecency";
5276
+ var MAX_FRECENCY_ENTRIES = 100;
5277
+ var FRECENCY_DECAY_HOURS = 72;
5278
+ var FRECENCY_USE_WEIGHT = 6;
5279
+ var BOOST_IN_THREAD = 25;
5280
+ var BOOST_DEFAULT_CHAT_AGENT = 18;
5281
+ var BOOST_MY_AGENT = 12;
5282
+ var MAX_FREQUENT_ITEMS = 3;
5283
+ var AUTO_SYNC_DEBOUNCE_MS = 50;
5284
+ var AGENT_WATCHED_ENTITIES = /* @__PURE__ */ new Set(["mj: ai agents", "mj: ai agent permissions"]);
5285
+ var SKILL_WATCHED_ENTITIES = /* @__PURE__ */ new Set(["mj: ai skills"]);
4217
5286
  var MentionAutocomplete = class extends BaseSingleton {
4218
5287
  constructor() {
4219
5288
  super();
@@ -4226,53 +5295,309 @@ var MentionAutocomplete = class extends BaseSingleton {
4226
5295
  this.queriesEntityIcon = "fa-solid fa-database";
4227
5296
  this.isInitialized = false;
4228
5297
  this.initializationPromise = null;
5298
+ this.frecencyMap = /* @__PURE__ */ new Map();
5299
+ this.lastSyncedFrecencyRaw = null;
5300
+ this.entityEventSubscription = null;
5301
+ this.syncDebounceTimer = null;
5302
+ this.pendingAgentSync = false;
5303
+ this.pendingSkillSync = false;
4229
5304
  }
4230
5305
  /** The process-wide shared instance (Global Object Store backed). */
4231
5306
  static get Instance() {
4232
5307
  return super.getInstance();
4233
5308
  }
4234
- /** True once the caches have loaded (agents/users/entities/queries/skills). */
4235
- get IsInitialized() {
4236
- return this.isInitialized;
5309
+ /** True once the caches have loaded (agents/users/entities/queries/skills). */
5310
+ get IsInitialized() {
5311
+ return this.isInitialized;
5312
+ }
5313
+ /**
5314
+ * Initialize the service by loading agents and users
5315
+ * Prevents concurrent initialization with promise lock
5316
+ */
5317
+ async initialize(currentUser, provider) {
5318
+ if (this.isInitialized) {
5319
+ return;
5320
+ }
5321
+ if (this.initializationPromise) {
5322
+ return this.initializationPromise;
5323
+ }
5324
+ this.initializationPromise = this._initializeInternal(currentUser, provider);
5325
+ try {
5326
+ await this.initializationPromise;
5327
+ } finally {
5328
+ this.initializationPromise = null;
5329
+ }
5330
+ }
5331
+ /**
5332
+ * Internal initialization logic
5333
+ */
5334
+ async _initializeInternal(currentUser, provider) {
5335
+ try {
5336
+ this.currentUser = currentUser;
5337
+ this.provider = provider;
5338
+ const aiEngine = this.aiEngineFor(provider);
5339
+ await aiEngine.Config(false);
5340
+ this.agentsCache = await this.loadRunnableAgents(currentUser, provider);
5341
+ this.usersCache = [currentUser];
5342
+ this.entitiesCache = this.loadReadableEntities(currentUser, provider);
5343
+ this.queriesCache = await this.loadRunnableQueries(currentUser, provider);
5344
+ this.queriesEntityIcon = this.resolveQueriesEntityIcon(provider);
5345
+ this.skillsCache = await this.filterSkillsByRunPermission(currentUser);
5346
+ this.syncFrecencyFromUserSettings();
5347
+ this.ensureEntityEventSubscription();
5348
+ this.isInitialized = true;
5349
+ } catch (error) {
5350
+ console.error("Failed to initialize MentionAutocomplete:", error);
5351
+ throw error;
5352
+ }
5353
+ }
5354
+ /**
5355
+ * Returns the AIEngineBase for the given provider, or the global singleton when none is given.
5356
+ */
5357
+ aiEngineFor(provider) {
5358
+ if (provider && typeof AIEngineBase.GetProviderInstance === "function") {
5359
+ return AIEngineBase.GetProviderInstance(provider, AIEngineBase);
5360
+ }
5361
+ return AIEngineBase.Instance;
5362
+ }
5363
+ /**
5364
+ * Reads `AIEngineBase.ReadableAgents`, applies eligibility filters, and filters by run permission.
5365
+ */
5366
+ async loadRunnableAgents(currentUser, provider) {
5367
+ const aiEngine = this.aiEngineFor(provider);
5368
+ const allAgents = aiEngine.ReadableAgents;
5369
+ const candidateAgents = allAgents.filter((a) => !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent" && !a.IsRestricted && a.InstantiationMode !== "Required");
5370
+ return this.filterAgentsByRunPermission(candidateAgents, currentUser);
5371
+ }
5372
+ /**
5373
+ * Subscribe once to MJGlobal `BaseEntity` events (`save`, `delete`, `remote-invalidate`) for
5374
+ * `'MJ: AI Agents'`, `'MJ: AI Agent Permissions'`, and `'MJ: AI Skills'`, debouncing cache
5375
+ * re-syncs (~50ms) so callers never need manual `Refresh()` calls.
5376
+ */
5377
+ ensureEntityEventSubscription() {
5378
+ if (this.entityEventSubscription) {
5379
+ return;
5380
+ }
5381
+ if (!MJGlobal?.Instance || typeof MJGlobal.Instance.GetEventListener !== "function") {
5382
+ return;
5383
+ }
5384
+ const listener = MJGlobal.Instance.GetEventListener(false);
5385
+ if (!listener || typeof listener.subscribe !== "function") {
5386
+ return;
5387
+ }
5388
+ this.entityEventSubscription = listener.subscribe((event) => {
5389
+ this.handleGlobalEvent(event);
5390
+ });
5391
+ }
5392
+ /**
5393
+ * Filters MJGlobal events down to relevant BaseEntity mutations and schedules a debounced sync.
5394
+ */
5395
+ handleGlobalEvent(event) {
5396
+ const baseEventCode = BaseEntity?.BaseEventCode ?? "BaseEntityEvent";
5397
+ if (event.event !== MJEventType.ComponentEvent || event.eventCode !== baseEventCode) {
5398
+ return;
5399
+ }
5400
+ const entityEvent = this.extractBaseEntityEvent(event.args);
5401
+ if (!entityEvent) {
5402
+ return;
5403
+ }
5404
+ if (entityEvent.type !== "save" && entityEvent.type !== "delete" && entityEvent.type !== "remote-invalidate") {
5405
+ return;
5406
+ }
5407
+ const rawName = entityEvent.baseEntity?.EntityInfo?.Name || entityEvent.entityName || "";
5408
+ const entityName = rawName.trim().toLowerCase();
5409
+ if (!entityName) {
5410
+ return;
5411
+ }
5412
+ let shouldSchedule = false;
5413
+ if (AGENT_WATCHED_ENTITIES.has(entityName)) {
5414
+ this.pendingAgentSync = true;
5415
+ shouldSchedule = true;
5416
+ }
5417
+ if (SKILL_WATCHED_ENTITIES.has(entityName)) {
5418
+ this.pendingSkillSync = true;
5419
+ shouldSchedule = true;
5420
+ }
5421
+ if (shouldSchedule) {
5422
+ this.scheduleAutoSync();
5423
+ }
5424
+ }
5425
+ /**
5426
+ * Type guard narrowing an `MJEvent.args` payload into a `BaseEntityEvent` shape.
5427
+ */
5428
+ extractBaseEntityEvent(args) {
5429
+ if (typeof args !== "object" || args === null) {
5430
+ return null;
5431
+ }
5432
+ const candidate = args;
5433
+ if (typeof candidate.type !== "string") {
5434
+ return null;
5435
+ }
5436
+ return candidate;
5437
+ }
5438
+ /**
5439
+ * Debounces cache re-sync so bursts of entity events coalesce into a single re-sync after ~50ms.
5440
+ */
5441
+ scheduleAutoSync() {
5442
+ if (this.syncDebounceTimer) {
5443
+ clearTimeout(this.syncDebounceTimer);
5444
+ }
5445
+ this.syncDebounceTimer = setTimeout(() => {
5446
+ this.syncDebounceTimer = null;
5447
+ this.flushAutoSync().catch((err) => {
5448
+ console.error("MentionAutocomplete: auto-sync failed:", err);
5449
+ });
5450
+ }, AUTO_SYNC_DEBOUNCE_MS);
4237
5451
  }
4238
5452
  /**
4239
- * Initialize the service by loading agents and users
4240
- * Prevents concurrent initialization with promise lock
5453
+ * Re-syncs `agentsCache` and/or `skillsCache` from `AIEngineBase` without forcing a server reload.
4241
5454
  */
4242
- async initialize(currentUser, provider) {
4243
- if (this.isInitialized) {
5455
+ async flushAutoSync() {
5456
+ const syncAgents = this.pendingAgentSync;
5457
+ const syncSkills = this.pendingSkillSync;
5458
+ this.pendingAgentSync = false;
5459
+ this.pendingSkillSync = false;
5460
+ const user = this.currentUser ?? this.usersCache[0];
5461
+ if (!user) {
4244
5462
  return;
4245
5463
  }
4246
- if (this.initializationPromise) {
4247
- return this.initializationPromise;
5464
+ if (syncAgents) {
5465
+ this.agentsCache = await this.loadRunnableAgents(user, this.provider);
4248
5466
  }
4249
- this.initializationPromise = this._initializeInternal(currentUser, provider);
5467
+ if (syncSkills) {
5468
+ this.skillsCache = await this.filterSkillsByRunPermission(user);
5469
+ }
5470
+ }
5471
+ /**
5472
+ * Record that the user selected a mention suggestion so future suggestions boost it via
5473
+ * exponentially decayed frecency (`uses * 6 * exp(-hours / 72)`).
5474
+ *
5475
+ * Persists to `UserInfoEngine.Instance` under `'chat.mentionFrecency'` (capped at top 100 entries)
5476
+ * when user/setting context is available, while always updating the in-memory map immediately.
5477
+ */
5478
+ RecordMentionUse(id, type, currentUser) {
5479
+ const normalizedId = id?.trim().toLowerCase();
5480
+ if (!normalizedId || !type) {
5481
+ return;
5482
+ }
5483
+ this.syncFrecencyFromUserSettings();
5484
+ const nowMs = Date.now();
5485
+ const existing = this.frecencyMap.get(normalizedId);
5486
+ const updatedEntry = {
5487
+ uses: (existing?.uses ?? 0) + 1,
5488
+ lastUsedAt: new Date(nowMs).toISOString()
5489
+ };
5490
+ this.frecencyMap.set(normalizedId, updatedEntry);
5491
+ this.pruneFrecencyMap(nowMs);
5492
+ const serialized = this.serializeFrecencyMap();
5493
+ this.lastSyncedFrecencyRaw = serialized;
5494
+ this.persistFrecencySetting(serialized, currentUser);
5495
+ }
5496
+ /**
5497
+ * Reads `chat.mentionFrecency` from `UserInfoEngine.Instance` if it changed since last sync.
5498
+ * Safe no-op in mocked or uninitialized test environments.
5499
+ */
5500
+ syncFrecencyFromUserSettings() {
5501
+ const raw = this.readUserSetting(FRECENCY_SETTING_KEY);
5502
+ if (raw == null || raw === this.lastSyncedFrecencyRaw) {
5503
+ return;
5504
+ }
5505
+ this.lastSyncedFrecencyRaw = raw;
5506
+ this.frecencyMap.clear();
4250
5507
  try {
4251
- await this.initializationPromise;
4252
- } finally {
4253
- this.initializationPromise = null;
5508
+ const parsed = JSON.parse(raw);
5509
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5510
+ return;
5511
+ }
5512
+ for (const [key, candidate] of Object.entries(parsed)) {
5513
+ if (typeof candidate === "object" && candidate !== null && !Array.isArray(candidate)) {
5514
+ if (typeof candidate.uses === "number" && Number.isFinite(candidate.uses) && candidate.uses > 0 && typeof candidate.lastUsedAt === "string" && candidate.lastUsedAt.length > 0) {
5515
+ this.frecencyMap.set(key.trim().toLowerCase(), {
5516
+ uses: candidate.uses,
5517
+ lastUsedAt: candidate.lastUsedAt
5518
+ });
5519
+ }
5520
+ }
5521
+ }
5522
+ } catch {
4254
5523
  }
4255
5524
  }
4256
5525
  /**
4257
- * Internal initialization logic
5526
+ * Caps `frecencyMap` at {@link MAX_FRECENCY_ENTRIES} entries ranked by current frecency score.
4258
5527
  */
4259
- async _initializeInternal(currentUser, provider) {
5528
+ pruneFrecencyMap(nowMs) {
5529
+ if (this.frecencyMap.size <= MAX_FRECENCY_ENTRIES) {
5530
+ return;
5531
+ }
5532
+ const ranked = Array.from(this.frecencyMap.entries()).sort((a, b) => {
5533
+ const scoreDiff = this.calculateFrecencyValue(b[1], nowMs) - this.calculateFrecencyValue(a[1], nowMs);
5534
+ if (scoreDiff !== 0) {
5535
+ return scoreDiff;
5536
+ }
5537
+ return b[1].lastUsedAt.localeCompare(a[1].lastUsedAt);
5538
+ });
5539
+ this.frecencyMap = new Map(ranked.slice(0, MAX_FRECENCY_ENTRIES));
5540
+ }
5541
+ serializeFrecencyMap() {
5542
+ const record = {};
5543
+ for (const [key, entry] of this.frecencyMap.entries()) {
5544
+ record[key] = entry;
5545
+ }
5546
+ return JSON.stringify(record);
5547
+ }
5548
+ readUserSetting(settingKey) {
4260
5549
  try {
4261
- await AIEngineBase.Instance.Config(false);
4262
- const allAgents = AIEngineBase.Instance.ReadableAgents;
4263
- const candidateAgents = allAgents.filter((a) => !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent" && !a.IsRestricted);
4264
- this.agentsCache = await this.filterAgentsByRunPermission(candidateAgents, currentUser);
4265
- this.usersCache = [currentUser];
4266
- this.entitiesCache = this.loadReadableEntities(currentUser, provider);
4267
- this.queriesCache = await this.loadRunnableQueries(currentUser, provider);
4268
- this.queriesEntityIcon = this.resolveQueriesEntityIcon(provider);
4269
- this.skillsCache = await this.filterSkillsByRunPermission(currentUser);
4270
- this.provider = provider;
4271
- this.isInitialized = true;
4272
- } catch (error) {
4273
- console.error("Failed to initialize MentionAutocomplete:", error);
4274
- throw error;
5550
+ if (!UserInfoEngine?.Instance || typeof UserInfoEngine.Instance.GetSetting !== "function") {
5551
+ return void 0;
5552
+ }
5553
+ return UserInfoEngine.Instance.GetSetting(settingKey);
5554
+ } catch {
5555
+ return void 0;
5556
+ }
5557
+ }
5558
+ persistFrecencySetting(serialized, currentUser) {
5559
+ try {
5560
+ if (!UserInfoEngine?.Instance || typeof UserInfoEngine.Instance.SetSettingDebounced !== "function") {
5561
+ return;
5562
+ }
5563
+ const engine = UserInfoEngine.Instance;
5564
+ const userForSetting = currentUser ?? this.currentUser ?? this.getMetadataCurrentUser();
5565
+ const hasUserContext = Boolean(userForSetting?.ID);
5566
+ if (engine.Loaded === false || !hasUserContext && engine.Loaded !== true) {
5567
+ return;
5568
+ }
5569
+ engine.SetSettingDebounced(FRECENCY_SETTING_KEY, serialized, userForSetting);
5570
+ } catch {
5571
+ }
5572
+ }
5573
+ getMetadataCurrentUser() {
5574
+ try {
5575
+ const md = this.provider ?? Metadata?.Provider;
5576
+ return md?.CurrentUser;
5577
+ } catch {
5578
+ return void 0;
5579
+ }
5580
+ }
5581
+ calculateFrecencyValue(entry, nowMs) {
5582
+ if (!entry || entry.uses <= 0) {
5583
+ return 0;
5584
+ }
5585
+ const lastUsedMs = Date.parse(entry.lastUsedAt);
5586
+ if (!Number.isFinite(lastUsedMs)) {
5587
+ return 0;
5588
+ }
5589
+ const hoursSinceLastUse = Math.max(0, (nowMs - lastUsedMs) / 36e5);
5590
+ return entry.uses * FRECENCY_USE_WEIGHT * Math.exp(-hoursSinceLastUse / FRECENCY_DECAY_HOURS);
5591
+ }
5592
+ getFrecencyForId(id, nowMs) {
5593
+ const entry = this.frecencyMap.get(id.trim().toLowerCase());
5594
+ if (!entry) {
5595
+ return { uses: 0, score: 0 };
4275
5596
  }
5597
+ return {
5598
+ uses: entry.uses,
5599
+ score: this.calculateFrecencyValue(entry, nowMs)
5600
+ };
4276
5601
  }
4277
5602
  /**
4278
5603
  * Filter agents to only those the current user has 'run' permission for.
@@ -4325,16 +5650,17 @@ var MentionAutocomplete = class extends BaseSingleton {
4325
5650
  }
4326
5651
  }
4327
5652
  /**
4328
- * Load queries the current user can run, from the provider's QueryEngine (loaded here if it
4329
- * has not loaded yet). A query is runnable when the user holds its run permission and, for a
4330
- * query without explicit permission rows, can read every entity it references.
4331
- * These are the candidates surfaced for #query mentions.
5653
+ * Load Approved queries the current user can run, from the provider's QueryEngine (loaded here
5654
+ * if it has not loaded yet). A query is runnable when the user holds its run permission and, for
5655
+ * a query without explicit permission rows, can read every entity it references. Pending queries
5656
+ * are drafts (for example one saved from a conversation so a list can refresh from it) and are
5657
+ * not offered. These are the candidates surfaced for #query mentions.
4332
5658
  */
4333
5659
  async loadRunnableQueries(user, provider) {
4334
5660
  try {
4335
5661
  const engine = this.queryEngineFor(provider);
4336
5662
  await engine.Config(false, user, provider);
4337
- return engine.Queries.filter((query) => this.userCanRunQuery(query, user));
5663
+ return engine.Queries.filter((query) => query.Status === "Approved" && this.userCanRunQuery(query, user));
4338
5664
  } catch (error) {
4339
5665
  console.error("Failed to load queries for mention autocomplete:", error);
4340
5666
  return [];
@@ -4373,10 +5699,10 @@ var MentionAutocomplete = class extends BaseSingleton {
4373
5699
  * `MJ: AI Agent Skills` grants — via {@link AIEngineBase.GetSkillsForAgent}. Without it (or for an
4374
5700
  * agent not in the user's runnable set) the user's full runnable catalog is shown, as before, and
4375
5701
  * the server's `RequestedSkills` guard is the backstop.
4376
- * @param scope Narrows the '@' list for one composer: the agents it may offer and the people it
4377
- * offers. Passed per call, never stored, because this engine is shared by every composer on the
4378
- * page. Omitted keeps today's list: every agent the user can run, and the current user.
4379
- * @returns Filtered and ranked suggestions
5702
+ * @param scope Narrows the '@' list for one composer: the agents it may offer, the people it
5703
+ * offers, population/field filters, and thread/default-agent context boosts. Passed per call,
5704
+ * never stored, because this engine is shared by every composer on the page.
5705
+ * @returns Filtered, ranked, and grouped suggestions
4380
5706
  */
4381
5707
  GetSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4382
5708
  if (trigger === "#") {
@@ -4385,57 +5711,337 @@ var MentionAutocomplete = class extends BaseSingleton {
4385
5711
  if (trigger === "/") {
4386
5712
  return this.getSkillSuggestions(query, targetAgentId);
4387
5713
  }
5714
+ this.syncFrecencyFromUserSettings();
4388
5715
  const lowerQuery = query.toLowerCase().trim();
4389
- const suggestions = [
4390
- ...this.getAgentSuggestions(lowerQuery, scope?.AllowedAgentIDs ?? null),
4391
- ...includeUsers ? this.getPeopleSuggestions(lowerQuery, scope?.People ?? null) : []
5716
+ const populationFilter = scope?.PopulationFilter ?? "all";
5717
+ const searchField = scope?.SearchField ?? "all";
5718
+ const nowMs = Date.now();
5719
+ const includeAgents = populationFilter !== "people";
5720
+ const includePeople = includeUsers && (populationFilter === "all" || populationFilter === "people");
5721
+ const rankedItems = [
5722
+ ...includeAgents ? this.getRankedAgentSuggestions(lowerQuery, scope, populationFilter, searchField, nowMs) : [],
5723
+ ...includePeople ? this.getRankedPeopleSuggestions(lowerQuery, scope?.People ?? null, searchField, nowMs) : []
4392
5724
  ];
4393
- return suggestions.sort((a, b) => {
4394
- const scoreA = this.calculateMatchScore(a.name, lowerQuery);
4395
- const scoreB = this.calculateMatchScore(b.name, lowerQuery);
4396
- if (scoreB !== scoreA)
4397
- return scoreB - scoreA;
4398
- if (a.type !== b.type)
4399
- return a.type === "agent" ? -1 : 1;
4400
- return a.name.localeCompare(b.name);
4401
- });
5725
+ if (!lowerQuery && populationFilter === "all") {
5726
+ return this.groupEmptyAllSuggestions(rankedItems);
5727
+ }
5728
+ rankedItems.sort((a, b) => this.compareRankedItems(a, b));
5729
+ const groupKey = lowerQuery ? "results" : populationFilter === "my-agents" ? "my-agents" : populationFilter === "shared" ? "shared" : "people";
5730
+ const groupLabel = GROUP_LABELS[groupKey];
5731
+ return rankedItems.map((item) => ({
5732
+ ...item.suggestion,
5733
+ group: groupKey,
5734
+ groupLabel
5735
+ }));
4402
5736
  }
4403
5737
  /** @deprecated Use {@link GetSuggestions}. */
4404
5738
  getSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4405
5739
  return this.GetSuggestions(query, includeUsers, trigger, targetAgentId, scope);
4406
5740
  }
4407
5741
  /**
4408
- * Agent suggestions for '@': the user's runnable agents that match the query, narrowed to
4409
- * `allowedAgentIDs` when one is given (null offers every runnable agent).
4410
- */
4411
- getAgentSuggestions(lowerQuery, allowedAgentIDs) {
4412
- return this.agentsCache.filter((agent) => allowedAgentIDs == null || allowedAgentIDs.some((id) => UUIDsEqual(id, agent.ID))).filter((agent) => !lowerQuery || this.calculateMatchScore(agent.Name || "", lowerQuery) > 0).map((agent) => ({
4413
- type: "agent",
4414
- id: agent.ID,
4415
- name: agent.Name || "Unknown",
4416
- displayName: agent.Name || "Unknown",
4417
- description: agent.Description || void 0,
4418
- imageUrl: agent.LogoURL || void 0,
4419
- // Agent logo/avatar image
4420
- icon: this.getAgentIcon(agent),
4421
- // Configuration presets ride on the suggestion — the (AI-blind) composer
4422
- // renders a preset picker on the inserted chip when there are 2+.
4423
- presets: this.getAgentPresets(agent.ID)
4424
- }));
5742
+ * Groups empty-query `'all'` suggestions into:
5743
+ * 1. `'frequent'` (top up-to-3 items with `uses >= 1 || isInCurrentThread || isDefaultChatAgent`)
5744
+ * 2. `'my-agents'` (remaining personal derived instances)
5745
+ * 3. `'shared'` (remaining shared agents)
5746
+ * 4. `'people'` (remaining users)
5747
+ * ordered by group sequence and by `totalScore` descending within each group.
5748
+ */
5749
+ groupEmptyAllSuggestions(items) {
5750
+ const sorted = [...items].sort((a, b) => this.compareRankedItems(a, b));
5751
+ const frequentItems = [];
5752
+ const frequentIds = /* @__PURE__ */ new Set();
5753
+ for (const item of sorted) {
5754
+ if (frequentItems.length >= MAX_FREQUENT_ITEMS) {
5755
+ break;
5756
+ }
5757
+ const isFrequentCandidate = item.uses >= 1 || Boolean(item.suggestion.isInCurrentThread) || Boolean(item.suggestion.isDefaultChatAgent);
5758
+ if (isFrequentCandidate) {
5759
+ frequentItems.push(item);
5760
+ frequentIds.add(`${item.suggestion.type}:${item.suggestion.id.toLowerCase()}`);
5761
+ }
5762
+ }
5763
+ const myAgentItems = [];
5764
+ const sharedItems = [];
5765
+ const peopleItems = [];
5766
+ for (const item of sorted) {
5767
+ const compositeKey = `${item.suggestion.type}:${item.suggestion.id.toLowerCase()}`;
5768
+ if (frequentIds.has(compositeKey)) {
5769
+ continue;
5770
+ }
5771
+ if (item.suggestion.type === "agent") {
5772
+ if (item.suggestion.isMyAgent) {
5773
+ myAgentItems.push(item);
5774
+ } else {
5775
+ sharedItems.push(item);
5776
+ }
5777
+ } else {
5778
+ peopleItems.push(item);
5779
+ }
5780
+ }
5781
+ const assignGroup = (list, group) => {
5782
+ const groupLabel = GROUP_LABELS[group];
5783
+ return list.map((item) => ({
5784
+ ...item.suggestion,
5785
+ group,
5786
+ groupLabel
5787
+ }));
5788
+ };
5789
+ return [
5790
+ ...assignGroup(frequentItems, "frequent"),
5791
+ ...assignGroup(myAgentItems, "my-agents"),
5792
+ ...assignGroup(sharedItems, "shared"),
5793
+ ...assignGroup(peopleItems, "people")
5794
+ ];
5795
+ }
5796
+ compareRankedItems(a, b) {
5797
+ if (b.totalScore !== a.totalScore) {
5798
+ return b.totalScore - a.totalScore;
5799
+ }
5800
+ if (a.suggestion.type !== b.suggestion.type) {
5801
+ return a.suggestion.type === "agent" ? -1 : 1;
5802
+ }
5803
+ return a.suggestion.name.localeCompare(b.suggestion.name);
5804
+ }
5805
+ /**
5806
+ * Resolves the current user ID for personal-agent ownership checks (`isMyAgent`).
5807
+ */
5808
+ resolveCurrentUserId() {
5809
+ return this.currentUser?.ID ?? this.usersCache[0]?.ID ?? this.getMetadataCurrentUser()?.ID ?? null;
5810
+ }
5811
+ /**
5812
+ * Resolves the human-readable base agent name for a derived agent instance.
5813
+ */
5814
+ resolveBaseAgentName(agent) {
5815
+ if (!agent.BaseAgentID) {
5816
+ return null;
5817
+ }
5818
+ if (typeof agent.BaseAgent === "string" && agent.BaseAgent.trim().length > 0) {
5819
+ return agent.BaseAgent.trim();
5820
+ }
5821
+ try {
5822
+ const aiEngine = this.aiEngineFor(this.provider);
5823
+ if (typeof aiEngine.GetAgentByID === "function") {
5824
+ const base = aiEngine.GetAgentByID(agent.BaseAgentID);
5825
+ if (base?.Name) {
5826
+ return base.Name;
5827
+ }
5828
+ }
5829
+ const readable = aiEngine.ReadableAgents;
5830
+ if (Array.isArray(readable)) {
5831
+ const base = readable.find((a) => UUIDsEqual(a.ID, agent.BaseAgentID));
5832
+ if (base?.Name) {
5833
+ return base.Name;
5834
+ }
5835
+ }
5836
+ } catch {
5837
+ }
5838
+ const fromCache = this.agentsCache.find((a) => UUIDsEqual(a.ID, agent.BaseAgentID));
5839
+ return fromCache?.Name ?? null;
5840
+ }
5841
+ /**
5842
+ * Builds the provenance/lineage badge text for an agent.
5843
+ */
5844
+ formatAgentLineage(isMyAgent, baseAgentName) {
5845
+ if (isMyAgent) {
5846
+ return baseAgentName ? `${baseAgentName} \xB7 My Agent` : "My Agent";
5847
+ }
5848
+ return baseAgentName ? `Shared \xB7 ${baseAgentName}` : "Shared";
5849
+ }
5850
+ /**
5851
+ * Ranked agent suggestions for '@' with frecency, context boosts, lineage, and multi-field matching.
5852
+ */
5853
+ getRankedAgentSuggestions(lowerQuery, scope, populationFilter, searchField, nowMs) {
5854
+ const allowedAgentIDs = scope?.AllowedAgentIDs ?? null;
5855
+ const inThreadIDs = scope?.InThreadAgentIDs ?? null;
5856
+ const inThreadAgentSet = inThreadIDs ? new UUIDSet(inThreadIDs) : null;
5857
+ const defaultChatAgentID = scope?.DefaultChatAgentID ?? null;
5858
+ const currentUserId = this.resolveCurrentUserId();
5859
+ const results = [];
5860
+ for (const agent of this.agentsCache) {
5861
+ if (allowedAgentIDs != null && !allowedAgentIDs.some((id) => UUIDsEqual(id, agent.ID))) {
5862
+ continue;
5863
+ }
5864
+ const isMyAgent = Boolean(agent.BaseAgentID != null && currentUserId != null && agent.OwnerUserID != null && UUIDsEqual(agent.OwnerUserID, currentUserId));
5865
+ if (populationFilter === "my-agents" && !isMyAgent) {
5866
+ continue;
5867
+ }
5868
+ if (populationFilter === "shared" && isMyAgent) {
5869
+ continue;
5870
+ }
5871
+ const name = agent.Name || "Unknown";
5872
+ const description = agent.Description || void 0;
5873
+ const baseAgentName = this.resolveBaseAgentName(agent);
5874
+ const lineage = this.formatAgentLineage(isMyAgent, baseAgentName);
5875
+ const queryScore = lowerQuery ? this.scoreAgentQuery(name, description, baseAgentName, lineage, lowerQuery, searchField) : 0;
5876
+ if (lowerQuery && queryScore <= 0) {
5877
+ continue;
5878
+ }
5879
+ const isInCurrentThread = Boolean(inThreadAgentSet?.Has(agent.ID));
5880
+ const isDefaultChatAgent = Boolean(defaultChatAgentID && UUIDsEqual(defaultChatAgentID, agent.ID));
5881
+ const { uses, score: frecencyScore } = this.getFrecencyForId(agent.ID, nowMs);
5882
+ const contextBoost = (isInCurrentThread ? BOOST_IN_THREAD : 0) + (isDefaultChatAgent ? BOOST_DEFAULT_CHAT_AGENT : 0) + (isMyAgent ? BOOST_MY_AGENT : 0);
5883
+ const suggestion = {
5884
+ type: "agent",
5885
+ id: agent.ID,
5886
+ name,
5887
+ displayName: name,
5888
+ description,
5889
+ imageUrl: agent.LogoURL || void 0,
5890
+ icon: this.getAgentIcon(agent),
5891
+ // Configuration presets ride on the suggestion — the (AI-blind) composer
5892
+ // renders a preset picker on the inserted chip when there are 2+.
5893
+ presets: this.getAgentPresets(agent.ID),
5894
+ lineage,
5895
+ isMyAgent,
5896
+ isDefaultChatAgent,
5897
+ isInCurrentThread,
5898
+ frecencyScore
5899
+ };
5900
+ results.push({
5901
+ suggestion,
5902
+ queryScore,
5903
+ totalScore: queryScore + frecencyScore + contextBoost,
5904
+ uses
5905
+ });
5906
+ }
5907
+ return results;
4425
5908
  }
4426
5909
  /**
4427
- * People suggestions for '@': the host's list when a composer supplies one, otherwise the
5910
+ * Ranked people suggestions for '@': the host's list when a composer supplies one, otherwise the
4428
5911
  * engine's own (which holds only the current user).
4429
5912
  */
4430
- getPeopleSuggestions(lowerQuery, people) {
5913
+ getRankedPeopleSuggestions(lowerQuery, people, searchField, nowMs) {
4431
5914
  const candidates = people ?? this.usersCache.map((user) => ({ ID: user.ID, Name: user.Name, Email: user.Email }));
4432
- return candidates.filter((person) => !lowerQuery || this.calculateMatchScore(person.Name, lowerQuery) > 0).map((person) => ({
4433
- type: "user",
4434
- id: person.ID,
4435
- name: person.Name,
4436
- displayName: person.Name,
4437
- description: person.Email || void 0
4438
- }));
5915
+ const results = [];
5916
+ for (const person of candidates) {
5917
+ const name = person.Name || "Unknown";
5918
+ const email = person.Email || void 0;
5919
+ const queryScore = lowerQuery ? this.scorePersonQuery(name, email, lowerQuery, searchField) : 0;
5920
+ if (lowerQuery && queryScore <= 0) {
5921
+ continue;
5922
+ }
5923
+ const { uses, score: frecencyScore } = this.getFrecencyForId(person.ID, nowMs);
5924
+ const suggestion = {
5925
+ type: "user",
5926
+ id: person.ID,
5927
+ name,
5928
+ displayName: name,
5929
+ description: email,
5930
+ isMyAgent: false,
5931
+ isDefaultChatAgent: false,
5932
+ isInCurrentThread: false,
5933
+ frecencyScore
5934
+ };
5935
+ results.push({
5936
+ suggestion,
5937
+ queryScore,
5938
+ totalScore: queryScore + frecencyScore,
5939
+ uses
5940
+ });
5941
+ }
5942
+ return results;
5943
+ }
5944
+ /**
5945
+ * Multi-field + acronym query scorer for agents:
5946
+ * - Exact name: 140
5947
+ * - Prefix name: 105
5948
+ * - Multi-word acronym prefix (len >= 2, e.g. `fcs` -> `FDA Clinical Scout`): 88
5949
+ * - Substring name: 70
5950
+ * - Base-agent lineage match: 58
5951
+ * - Token-AND match across name + description + lineage (e.g. `sql` -> `Query Builder`): 48
5952
+ */
5953
+ scoreAgentQuery(name, description, baseAgentName, lineage, lowerQuery, searchField) {
5954
+ let best = 0;
5955
+ if (searchField === "all" || searchField === "name") {
5956
+ best = Math.max(best, this.calculateNameMatchScore(name, lowerQuery));
5957
+ }
5958
+ if (searchField === "all" || searchField === "lineage") {
5959
+ best = Math.max(best, this.calculateLineageMatchScore(baseAgentName, lineage, lowerQuery));
5960
+ }
5961
+ if (searchField === "capabilities") {
5962
+ best = Math.max(best, this.calculateTokenAndScore(description ?? "", lowerQuery));
5963
+ } else if (searchField === "all") {
5964
+ const combined = `${name} ${description ?? ""} ${baseAgentName ?? ""} ${lineage}`;
5965
+ best = Math.max(best, this.calculateTokenAndScore(combined, lowerQuery));
5966
+ }
5967
+ return best;
5968
+ }
5969
+ /**
5970
+ * Multi-field + acronym query scorer for people.
5971
+ */
5972
+ scorePersonQuery(name, email, lowerQuery, searchField) {
5973
+ if (searchField === "lineage") {
5974
+ return 0;
5975
+ }
5976
+ if (searchField === "capabilities") {
5977
+ return this.calculateTokenAndScore(email ?? "", lowerQuery);
5978
+ }
5979
+ const nameScore = this.calculateNameMatchScore(name, lowerQuery);
5980
+ if (searchField === "name") {
5981
+ return nameScore;
5982
+ }
5983
+ return Math.max(nameScore, this.calculateTokenAndScore(`${name} ${email ?? ""}`, lowerQuery));
5984
+ }
5985
+ /**
5986
+ * Name scorer supporting exact (140), prefix (105), multi-word acronym prefix length >= 2 (88),
5987
+ * and substring (70).
5988
+ */
5989
+ calculateNameMatchScore(name, lowerQuery) {
5990
+ const lowerName = name.toLowerCase().trim();
5991
+ if (!lowerName || !lowerQuery) {
5992
+ return 0;
5993
+ }
5994
+ if (lowerName === lowerQuery) {
5995
+ return 140;
5996
+ }
5997
+ if (lowerName.startsWith(lowerQuery)) {
5998
+ return 105;
5999
+ }
6000
+ if (lowerQuery.length >= 2 && !/\s/.test(lowerQuery)) {
6001
+ const words = lowerName.split(/[\s\-_/.]+/).filter(Boolean);
6002
+ if (words.length >= 2) {
6003
+ const acronym = words.map((w) => w[0]).join("");
6004
+ if (acronym.startsWith(lowerQuery)) {
6005
+ return 88;
6006
+ }
6007
+ }
6008
+ }
6009
+ if (lowerName.includes(lowerQuery)) {
6010
+ return 70;
6011
+ }
6012
+ return 0;
6013
+ }
6014
+ /**
6015
+ * Base-agent / lineage scorer (58).
6016
+ */
6017
+ calculateLineageMatchScore(baseAgentName, lineage, lowerQuery) {
6018
+ if (!lowerQuery) {
6019
+ return 0;
6020
+ }
6021
+ const lowerBase = baseAgentName?.toLowerCase() ?? "";
6022
+ const lowerLineage = lineage.toLowerCase();
6023
+ if (lowerBase.includes(lowerQuery) || lowerLineage.includes(lowerQuery)) {
6024
+ return 58;
6025
+ }
6026
+ const tokens = lowerQuery.split(/\s+/).filter(Boolean);
6027
+ if (tokens.length > 0 && tokens.every((t) => lowerBase.includes(t) || lowerLineage.includes(t))) {
6028
+ return 58;
6029
+ }
6030
+ return 0;
6031
+ }
6032
+ /**
6033
+ * Token-AND matcher across a combined text haystack (48).
6034
+ */
6035
+ calculateTokenAndScore(haystack, lowerQuery) {
6036
+ if (!haystack || !lowerQuery) {
6037
+ return 0;
6038
+ }
6039
+ const lowerHaystack = haystack.toLowerCase();
6040
+ const tokens = lowerQuery.split(/\s+/).filter(Boolean);
6041
+ if (tokens.length === 0) {
6042
+ return 0;
6043
+ }
6044
+ return tokens.every((token) => lowerHaystack.includes(token)) ? 48 : 0;
4439
6045
  }
4440
6046
  /**
4441
6047
  * Get entity + query suggestions for #mentions, ranked by query match.
@@ -4490,7 +6096,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4490
6096
  if (!agent) {
4491
6097
  return this.skillsCache;
4492
6098
  }
4493
- const engine = this.provider ? AIEngineBase.GetProviderInstance(this.provider, AIEngineBase) : AIEngineBase.Instance;
6099
+ const engine = this.aiEngineFor(this.provider);
4494
6100
  return IntersectAcceptedSkills(this.skillsCache, engine.GetSkillsForAgent(agent));
4495
6101
  }
4496
6102
  /**
@@ -4518,8 +6124,8 @@ var MentionAutocomplete = class extends BaseSingleton {
4518
6124
  }).slice(0, MAX_SUGGESTIONS).map((x) => x.suggestion);
4519
6125
  }
4520
6126
  /**
4521
- * Calculate match score for ranking
4522
- * Higher score = better match
6127
+ * Calculate match score for ranking `#` (entities/queries) and `/` (skills) triggers.
6128
+ * Higher score = better match.
4523
6129
  */
4524
6130
  calculateMatchScore(name, query) {
4525
6131
  if (!query)
@@ -4549,7 +6155,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4549
6155
  */
4550
6156
  getAgentPresets(agentId) {
4551
6157
  try {
4552
- const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agentId, true);
6158
+ const presets = this.aiEngineFor(this.provider).GetAgentConfigurationPresets(agentId, true);
4553
6159
  if (!presets || presets.length === 0) {
4554
6160
  return void 0;
4555
6161
  }
@@ -4640,7 +6246,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4640
6246
  async Refresh(currentUser) {
4641
6247
  this.isInitialized = false;
4642
6248
  this.initializationPromise = null;
4643
- await this.initialize(currentUser);
6249
+ await this.initialize(currentUser, this.provider);
4644
6250
  }
4645
6251
  /** @deprecated Use {@link Refresh}. */
4646
6252
  async refresh(currentUser) {
@@ -4725,68 +6331,223 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4725
6331
  static {
4726
6332
  this.SETTING_NAME = "Conversations.DefaultAgentID";
4727
6333
  }
6334
+ static {
6335
+ this.LEGACY_USER_SETTING_NAME = "chat.defaultAgentId";
6336
+ }
4728
6337
  static {
4729
6338
  this.FALLBACK_AGENT_NAME = "Sage";
4730
6339
  }
4731
6340
  /**
4732
- * Resolve the default agent for this turn. Walks the 4-step chain; throws a descriptive
4733
- * error if every step misses (vs. the previous code path's silent `null` return, which
4734
- * made misconfigurations hard to spot at the call site).
4735
- *
4736
- * @example
4737
- * ```typescript
4738
- * const agent = await runtime.DefaultAgent.resolve({
4739
- * explicitAgentId: widgetInput.DefaultAgentId, // wins if non-null and matches
4740
- * applicationId: currentAppId, // scopes the settings lookup
4741
- * contextUser: this.ProviderToUse.CurrentUser,
4742
- * provider: this.ProviderToUse,
4743
- * });
4744
- * ```
6341
+ * Resolve the default agent for this turn. Walks the full resolution chain; throws a descriptive
6342
+ * error if every step misses.
4745
6343
  */
4746
6344
  async Resolve(options = {}) {
4747
- const { explicitAgentId, applicationId, contextUser, provider } = options;
4748
- await AIEngineBase.Instance.Config(false, contextUser, provider);
4749
- await ApplicationSettingEngine.Instance.Config(false, contextUser, provider);
6345
+ const result = await this.ResolveWithDetails(options);
6346
+ return result.agent;
6347
+ }
6348
+ /**
6349
+ * Resolve the default agent along with provenance and any user-default fallback details
6350
+ * (so UI surfaces can display a one-time non-blocking notice if the user's saved default
6351
+ * was deactivated or revoked).
6352
+ */
6353
+ async ResolveWithDetails(options = {}) {
6354
+ const { explicitAgentId, applicationId, contextUser, provider, ignoreUserDefault } = options;
6355
+ const aiEngine = this.getAIEngine(provider);
6356
+ const appSettingEngine = this.getApplicationSettingEngine(provider);
6357
+ const userInfoEngine = this.getUserInfoEngine(provider);
6358
+ await aiEngine.Config(false, contextUser, provider);
6359
+ await appSettingEngine.Config(false, contextUser, provider);
6360
+ if (userInfoEngine && !ignoreUserDefault) {
6361
+ try {
6362
+ await userInfoEngine.Config(false, contextUser, provider);
6363
+ } catch (e) {
6364
+ console.warn(`DefaultAgentResolver: UserInfoEngine.Config failed \u2014 continuing without user preference: ${e instanceof Error ? e.message : String(e)}`);
6365
+ }
6366
+ }
4750
6367
  if (explicitAgentId) {
4751
- const explicit = this.findAgentById(explicitAgentId);
4752
- if (explicit)
4753
- return explicit;
4754
- console.warn(`DefaultAgentResolver: explicitAgentId "${explicitAgentId}" did not match any known agent \u2014 falling through to settings chain.`);
6368
+ const explicit = this.findAgentById(aiEngine, explicitAgentId);
6369
+ if (explicit && this.isAgentActive(explicit)) {
6370
+ return { agent: explicit, source: "explicit" };
6371
+ }
6372
+ console.warn(`DefaultAgentResolver: explicitAgentId "${explicitAgentId}" did not match any active known agent \u2014 falling through to user/org default chain.`);
6373
+ }
6374
+ let unavailableInfo = null;
6375
+ if (!ignoreUserDefault && userInfoEngine) {
6376
+ const rawUserDefault = this.readUserDefaultSetting(userInfoEngine);
6377
+ if (rawUserDefault) {
6378
+ const validation = this.validateCandidateAgent(aiEngine, rawUserDefault, contextUser);
6379
+ if (validation.valid) {
6380
+ return { agent: validation.agent, source: "user-setting" };
6381
+ }
6382
+ unavailableInfo = {
6383
+ userDefaultUnavailable: true,
6384
+ userDefaultUnavailableReason: validation.reason,
6385
+ unavailableUserDefaultAgentId: rawUserDefault
6386
+ };
6387
+ console.warn(`DefaultAgentResolver: user default "${rawUserDefault}" is unavailable (${validation.reason}) \u2014 falling through to org default.`);
6388
+ }
4755
6389
  }
6390
+ let orgDefault;
6391
+ let orgDefaultSource = "app-or-global-setting";
6392
+ let settingValue;
4756
6393
  if (applicationId) {
4757
6394
  const fromAppSettings = await this.getAppDefaultAgentId(applicationId, contextUser, provider);
4758
6395
  if (fromAppSettings) {
4759
- const resolved = this.findAgentById(fromAppSettings);
4760
- if (resolved)
4761
- return resolved;
4762
- console.warn(`DefaultAgentResolver: Application.AgentSettings.DefaultAgentID = "${fromAppSettings}" but no matching agent was found \u2014 falling through to the settings chain.`);
6396
+ const resolved = this.findAgentById(aiEngine, fromAppSettings);
6397
+ if (resolved && this.isAgentActive(resolved)) {
6398
+ orgDefault = resolved;
6399
+ orgDefaultSource = "app-agent-settings";
6400
+ } else {
6401
+ console.warn(`DefaultAgentResolver: Application.AgentSettings.DefaultAgentID = "${fromAppSettings}" did not resolve to an active agent \u2014 falling through to the settings chain.`);
6402
+ }
6403
+ }
6404
+ }
6405
+ if (!orgDefault) {
6406
+ settingValue = appSettingEngine.GetSetting(_DefaultAgentResolver.SETTING_NAME, applicationId ?? void 0);
6407
+ if (settingValue) {
6408
+ const fromSetting = this.findAgentById(aiEngine, settingValue);
6409
+ if (fromSetting && this.isAgentActive(fromSetting)) {
6410
+ orgDefault = fromSetting;
6411
+ orgDefaultSource = "app-or-global-setting";
6412
+ } else {
6413
+ console.warn(`DefaultAgentResolver: Application Setting "${_DefaultAgentResolver.SETTING_NAME}" resolved to "${settingValue}" but no active matching agent was found \u2014 falling through to code-const fallback.`);
6414
+ }
6415
+ }
6416
+ }
6417
+ if (orgDefault) {
6418
+ const primaryInstance = this.findUserPrimaryInstance(aiEngine, orgDefault, contextUser);
6419
+ if (primaryInstance) {
6420
+ return {
6421
+ agent: primaryInstance,
6422
+ source: "user-primary-instance",
6423
+ ...unavailableInfo ?? {}
6424
+ };
4763
6425
  }
6426
+ return {
6427
+ agent: orgDefault,
6428
+ source: orgDefaultSource,
6429
+ ...unavailableInfo ?? {}
6430
+ };
4764
6431
  }
4765
- const settingValue = ApplicationSettingEngine.Instance.GetSetting(_DefaultAgentResolver.SETTING_NAME, applicationId ?? void 0);
4766
- if (settingValue) {
4767
- const fromSetting = this.findAgentById(settingValue);
4768
- if (fromSetting)
4769
- return fromSetting;
4770
- console.warn(`DefaultAgentResolver: Application Setting "${_DefaultAgentResolver.SETTING_NAME}" resolved to "${settingValue}" but no matching agent was found \u2014 falling through to code-const fallback.`);
6432
+ const fallback = this.getSearchableAgents(aiEngine).find((a) => a.Name === _DefaultAgentResolver.FALLBACK_AGENT_NAME && this.isAgentActive(a));
6433
+ if (fallback) {
6434
+ return {
6435
+ agent: fallback,
6436
+ source: "code-fallback",
6437
+ ...unavailableInfo ?? {}
6438
+ };
4771
6439
  }
4772
- const fallback = AIEngineBase.Instance.ReadableAgents.find((a) => a.Name === _DefaultAgentResolver.FALLBACK_AGENT_NAME);
4773
- if (fallback)
4774
- return fallback;
4775
- throw new Error(`DefaultAgentResolver: could not resolve a default conversation manager agent. Tried (1) explicitAgentId=${explicitAgentId ?? "null"}, (2) Application.AgentSettings.DefaultAgentID (applicationId=${applicationId ?? "null"}), (3)+(4) Application Setting "${_DefaultAgentResolver.SETTING_NAME}" = "${settingValue ?? "undefined"}", (5) code-const fallback agent name = "${_DefaultAgentResolver.FALLBACK_AGENT_NAME}". Configure Application.AgentSettings, the Application Setting, or seed the fallback agent.`);
6440
+ throw new Error(`DefaultAgentResolver: could not resolve a default conversation manager agent. Tried (1) explicitAgentId=${explicitAgentId ?? "null"}, (2) UserInfoEngine "${_DefaultAgentResolver.SETTING_NAME}"=${unavailableInfo?.unavailableUserDefaultAgentId ?? "null"}, (3) user primary instance of org default template, (4a) Application.AgentSettings.DefaultAgentID (applicationId=${applicationId ?? "null"}), (4b) Application Setting "${_DefaultAgentResolver.SETTING_NAME}" = "${settingValue ?? "undefined"}", (5) code-const fallback agent name = "${_DefaultAgentResolver.FALLBACK_AGENT_NAME}". Configure Application.AgentSettings, the Application Setting, or seed the fallback agent.`);
4776
6441
  }
4777
6442
  /** @deprecated Use {@link Resolve}. */
4778
6443
  async resolve(options = {}) {
4779
6444
  return this.Resolve(options);
4780
6445
  }
6446
+ getAIEngine(provider) {
6447
+ if (provider && typeof AIEngineBase.GetProviderInstance === "function") {
6448
+ return AIEngineBase.GetProviderInstance(provider, AIEngineBase);
6449
+ }
6450
+ return AIEngineBase.Instance;
6451
+ }
6452
+ getApplicationSettingEngine(provider) {
6453
+ if (provider && typeof ApplicationSettingEngine.GetProviderInstance === "function") {
6454
+ return ApplicationSettingEngine.GetProviderInstance(provider, ApplicationSettingEngine);
6455
+ }
6456
+ return ApplicationSettingEngine.Instance;
6457
+ }
6458
+ getUserInfoEngine(provider) {
6459
+ if (!UserInfoEngine) {
6460
+ return null;
6461
+ }
6462
+ if (provider && typeof UserInfoEngine.GetProviderInstance === "function") {
6463
+ return UserInfoEngine.GetProviderInstance(provider, UserInfoEngine);
6464
+ }
6465
+ return UserInfoEngine.Instance ?? null;
6466
+ }
6467
+ readUserDefaultSetting(userInfoEngine) {
6468
+ if (typeof userInfoEngine.GetSetting !== "function") {
6469
+ return null;
6470
+ }
6471
+ const primary = userInfoEngine.GetSetting(_DefaultAgentResolver.SETTING_NAME)?.trim();
6472
+ if (primary) {
6473
+ return primary;
6474
+ }
6475
+ const legacy = userInfoEngine.GetSetting(_DefaultAgentResolver.LEGACY_USER_SETTING_NAME)?.trim();
6476
+ return legacy || null;
6477
+ }
6478
+ validateCandidateAgent(aiEngine, agentId, contextUser) {
6479
+ const agent = this.findAgentById(aiEngine, agentId);
6480
+ if (!agent) {
6481
+ return { valid: false, reason: "agent no longer exists or is not visible" };
6482
+ }
6483
+ if (!this.isAgentActive(agent)) {
6484
+ return { valid: false, reason: `agent "${agent.Name}" is inactive (${agent.Status})` };
6485
+ }
6486
+ if (agent.InstantiationMode === "Required") {
6487
+ return {
6488
+ valid: false,
6489
+ reason: `agent "${agent.Name}" is a template that requires a personal instance`
6490
+ };
6491
+ }
6492
+ if (contextUser && !this.canUserRunAgent(aiEngine, agent, contextUser)) {
6493
+ return {
6494
+ valid: false,
6495
+ reason: `you no longer have run permission for "${agent.Name}"`
6496
+ };
6497
+ }
6498
+ return { valid: true, agent };
6499
+ }
6500
+ /**
6501
+ * Finds the user's active primary instance (`IsPrimaryInstance = true`) descending from
6502
+ * `templateAgent` when `templateAgent` is an instantiable template (`Required` or `Optional`).
6503
+ * Validates that the primary instance is `Active` and the user holds `CanRun` across its
6504
+ * `BaseAgentID` ancestor chain.
6505
+ */
6506
+ findUserPrimaryInstance(aiEngine, templateAgent, contextUser) {
6507
+ if (!contextUser) {
6508
+ return null;
6509
+ }
6510
+ const mode = templateAgent.InstantiationMode;
6511
+ if (mode !== "Required" && mode !== "Optional") {
6512
+ return null;
6513
+ }
6514
+ const candidates = this.getUserDerivedAgentsForTemplate(aiEngine, templateAgent.ID, contextUser);
6515
+ const primary = candidates.find((a) => a.IsPrimaryInstance === true && this.isAgentActive(a) && UUIDsEqual(a.OwnerUserID, contextUser.ID) && this.canUserRunAgent(aiEngine, a, contextUser));
6516
+ return primary ?? null;
6517
+ }
6518
+ getUserDerivedAgentsForTemplate(aiEngine, templateId, contextUser) {
6519
+ if (typeof aiEngine.GetUserDerivedAgents === "function") {
6520
+ return aiEngine.GetUserDerivedAgents(contextUser, templateId);
6521
+ }
6522
+ const all = this.getSearchableAgents(aiEngine);
6523
+ return all.filter((a) => {
6524
+ if (!a.BaseAgentID || !this.isAgentActive(a)) {
6525
+ return false;
6526
+ }
6527
+ if (UUIDsEqual(a.BaseAgentID, templateId)) {
6528
+ return true;
6529
+ }
6530
+ if (typeof aiEngine.GetRootAgent === "function") {
6531
+ const root = aiEngine.GetRootAgent(a.ID);
6532
+ return root ? UUIDsEqual(root.ID, templateId) : false;
6533
+ }
6534
+ return false;
6535
+ });
6536
+ }
6537
+ isAgentActive(agent) {
6538
+ return agent.Status === void 0 || agent.Status === "Active";
6539
+ }
6540
+ canUserRunAgent(aiEngine, agent, contextUser) {
6541
+ if (typeof aiEngine.CanUserRunAgentSync === "function") {
6542
+ return aiEngine.CanUserRunAgentSync(agent, contextUser);
6543
+ }
6544
+ return true;
6545
+ }
4781
6546
  /**
4782
6547
  * Read `Application.AgentSettings.DefaultAgentID` for the given app via a targeted
4783
6548
  * `RunView` (single row by ID, `entity_object` so the typed `AgentSettingsObject`
4784
6549
  * accessor is available). Returns `undefined` when the app, the column, or the field
4785
6550
  * is absent.
4786
- *
4787
- * Kept query-light: one tiny by-ID read, served from the provider's RunView cache on
4788
- * repeat calls (server trusts its cache; the client caches too), and only reached when
4789
- * no explicit agent was supplied — i.e. at most once per conversation-turn start.
4790
6551
  */
4791
6552
  async getAppDefaultAgentId(applicationId, contextUser, provider) {
4792
6553
  try {
@@ -4817,13 +6578,24 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4817
6578
  const candidate = provider;
4818
6579
  return candidate && typeof candidate.RunView === "function" ? provider : void 0;
4819
6580
  }
6581
+ getSearchableAgents(aiEngine) {
6582
+ return aiEngine.ReadableAgents ?? aiEngine.Agents ?? [];
6583
+ }
4820
6584
  /**
4821
6585
  * Find an agent by ID from the AIEngineBase cache. Returns `undefined` if not found.
4822
6586
  * Uses {@link UUIDsEqual} per the standing rule about comparing UUIDs across
4823
6587
  * SQL Server / Postgres (case differences would silently miss).
4824
6588
  */
4825
- findAgentById(id) {
4826
- return AIEngineBase.Instance.ReadableAgents.find((a) => UUIDsEqual(a.ID, id));
6589
+ findAgentById(aiEngine, id) {
6590
+ const searchable = this.getSearchableAgents(aiEngine);
6591
+ const fromReadable = searchable.find((a) => UUIDsEqual(a.ID, id));
6592
+ if (fromReadable) {
6593
+ return fromReadable;
6594
+ }
6595
+ if (typeof aiEngine.GetAgentByID === "function") {
6596
+ return aiEngine.GetAgentByID(id);
6597
+ }
6598
+ return void 0;
4827
6599
  }
4828
6600
  };
4829
6601
 
@@ -5571,7 +7343,7 @@ var ConversationTail = class {
5571
7343
  if (!provider) {
5572
7344
  return void 0;
5573
7345
  }
5574
- this.client = new ns(provider);
7346
+ this.client = new as(provider);
5575
7347
  return this.client;
5576
7348
  } catch {
5577
7349
  return void 0;
@@ -5607,6 +7379,7 @@ var ConversationAgentRunner = class {
5607
7379
  this._activeRunCount = 0;
5608
7380
  this._provider = null;
5609
7381
  this.IsProcessing$ = this._isProcessing$.asObservable();
7382
+ this._notifiedUnavailableDefaultIds = /* @__PURE__ */ new Set();
5610
7383
  this.session = new AgentClientSession(toolRegistry);
5611
7384
  }
5612
7385
  /**
@@ -5707,19 +7480,29 @@ var ConversationAgentRunner = class {
5707
7480
  return this.ProcessMessage(input);
5708
7481
  }
5709
7482
  /**
5710
- * Resolve the agent that should handle this turn — explicit ID wins, then the
5711
- * Application Settings chain, then the Sage code-const fallback. Surfaces a
5712
- * notification on failure rather than throwing, so the caller (UI thread)
5713
- * sees a friendly message.
7483
+ * Resolve the agent that should handle this turn — explicit ID wins, then the user's
7484
+ * default / primary instance, then Application Settings, then the code-const fallback.
7485
+ * Surfaces a one-time non-blocking warning if the user's saved default is unavailable,
7486
+ * and notifies on total resolution failure rather than throwing.
5714
7487
  */
5715
7488
  async resolveAgent(input) {
5716
7489
  try {
5717
- return await this.resolver.resolve({
7490
+ const resolveOpts = {
5718
7491
  explicitAgentId: input.explicitAgentId,
5719
7492
  applicationId: input.applicationId,
5720
7493
  contextUser: this.Provider.CurrentUser ?? void 0,
5721
7494
  provider: this.Provider
5722
- });
7495
+ };
7496
+ const result = typeof this.resolver.ResolveWithDetails === "function" ? await this.resolver.ResolveWithDetails(resolveOpts) : { agent: await this.resolver.resolve(resolveOpts), source: "code-fallback" };
7497
+ if (result.userDefaultUnavailable && result.unavailableUserDefaultAgentId) {
7498
+ const key = result.unavailableUserDefaultAgentId.toLowerCase();
7499
+ if (!this._notifiedUnavailableDefaultIds.has(key)) {
7500
+ this._notifiedUnavailableDefaultIds.add(key);
7501
+ const detail = result.userDefaultUnavailableReason ? ` (${result.userDefaultUnavailableReason})` : "";
7502
+ this.context.Notification.Notify("warning", `Your default agent is currently unavailable${detail}. Using ${result.agent.Name} instead.`, 6e3);
7503
+ }
7504
+ }
7505
+ return result.agent;
5723
7506
  } catch (error) {
5724
7507
  const errorMsg = "Could not resolve a default conversation manager agent: " + (error instanceof Error ? error.message : String(error));
5725
7508
  console.error("[ConversationAgentRunner] Agent resolution failed:", error);