@memberjunction/realtime-widget 6.3.0-edge.0 → 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,15 +3,22 @@ import {
3
3
  ArtifactMetadataEngine,
4
4
  ConversationEngine,
5
5
  ConversationUtility,
6
- Fe,
6
+ DeepMergeAgentConfigObjects,
7
+ EDGE_PRE_DISCOVERY_DATA_KEY,
7
8
  FileStorageEngineBase,
9
+ MAX_AGENT_INHERITANCE_DEPTH,
8
10
  MJAICredentialBindingEntity,
9
11
  MJAIModelPriceUnitTypeEntity,
12
+ ParseAgentConfigJsonObject,
13
+ QueryEngine,
14
+ SanitizeEdgePreDiscoveryHint,
10
15
  TemplateEngineBase,
16
+ UserInfoEngine,
17
+ as,
11
18
  coerceFailedExecuteAgentResult,
12
- h,
13
- vr
14
- } from "./chunk-CFNJUN5T.js";
19
+ g,
20
+ rt
21
+ } from "./chunk-3U2F5LA6.js";
15
22
  import {
16
23
  BaseEngine,
17
24
  BaseEntity,
@@ -22,17 +29,20 @@ import {
22
29
  PermissionConstrainedError,
23
30
  RegisterForStartup,
24
31
  RunView
25
- } from "./chunk-PYHZMJHO.js";
32
+ } from "./chunk-KJ4DC2CQ.js";
26
33
  import {
34
+ ApplyPlattCalibration,
27
35
  ParseModelConfiguration,
28
36
  ParseVendorConfiguration,
29
37
  ResolveEffectiveModelConfiguration
30
- } from "./chunk-MIJGWKAT.js";
38
+ } from "./chunk-CIZSPKQR.js";
31
39
  import {
32
40
  BaseSingleton,
33
41
  BehaviorSubject,
34
42
  EMPTY,
35
43
  IndexByUUID,
44
+ IsBrowser,
45
+ MJEventType,
36
46
  MJGlobal,
37
47
  NormalizeUUID,
38
48
  RegisterClass,
@@ -44,7 +54,7 @@ import {
44
54
  ValidationErrorInfo,
45
55
  ValidationErrorType,
46
56
  throttleTime
47
- } from "./chunk-3SGPPDAR.js";
57
+ } from "./chunk-KHEWGJIZ.js";
48
58
 
49
59
  // ../../AI/BaseAIEngine/dist/PriceUnitTypes.js
50
60
  var __decorate = function(decorators, target, key, desc) {
@@ -290,7 +300,100 @@ var TOKEN_PRICE_UNIT_TYPE_DIVISORS = Object.freeze(Object.fromEntries([
290
300
  ].map(([driverClass, driver]) => [driverClass, driver.UnitsPerBillingUnit])));
291
301
 
292
302
  // ../../AI/BaseAIEngine/dist/AIAgentPermissionHelper.js
303
+ var MAX_INHERITANCE_DEPTH = 5;
293
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
+ }
294
397
  /**
295
398
  * Checks if a user has a specific permission for an agent.
296
399
  * @param agentId - The ID of the agent to check
@@ -315,16 +418,7 @@ var AIAgentPermissionHelper = class {
315
418
  }
316
419
  /**
317
420
  * Gets the aggregate permissions for a user on a specific agent.
318
- * Implements hierarchical permission logic:
319
- * - Delete implies Edit, Run, and View
320
- * - Edit implies Run and View
321
- * - Run implies View
322
- *
323
- * Default behavior when no permission records exist:
324
- * - Anyone can View and Run (open by default)
325
- * - Only owner can Edit and Delete
326
- *
327
- * Checks ownership first, then combines all matching user and role permissions.
421
+ * Enforces the 2x2 RBAC matrix and the Ancestor `CanRun` Invariant across `BaseAgentID`.
328
422
  * @param agentId - The ID of the agent
329
423
  * @param user - The user to check permissions for
330
424
  * @returns Object containing all effective permissions and ownership status
@@ -332,49 +426,12 @@ var AIAgentPermissionHelper = class {
332
426
  static async GetEffectivePermissions(agentId, user) {
333
427
  try {
334
428
  await AIEngineBase.Instance.Config(false, user);
335
- 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));
336
431
  if (!agent) {
337
432
  throw new Error(`Agent ${agentId} not found in cached metadata`);
338
433
  }
339
- const isOwner = UUIDsEqual(agent.OwnerUserID, user.ID);
340
- if (isOwner) {
341
- return {
342
- canView: true,
343
- canRun: true,
344
- canEdit: true,
345
- canDelete: true,
346
- isOwner: true
347
- };
348
- }
349
- const agentPermissions = AIEngineBase.Instance.AgentPermissions.filter((p) => UUIDsEqual(p.AgentID, agentId));
350
- if (agentPermissions.length === 0) {
351
- return {
352
- canView: true,
353
- canRun: true,
354
- canEdit: false,
355
- // Only owner can edit
356
- canDelete: false,
357
- // Only owner can delete
358
- isOwner: false
359
- };
360
- }
361
- const userRoleIds = user.UserRoles?.map((ur) => ur.RoleID) || [];
362
- const matchingPermissions = agentPermissions.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID && userRoleIds.some((rid) => UUIDsEqual(rid, p.RoleID)));
363
- const hasDelete = matchingPermissions.some((p) => p.CanDelete === true);
364
- const hasEdit = matchingPermissions.some((p) => p.CanEdit === true);
365
- const hasRun = matchingPermissions.some((p) => p.CanRun === true);
366
- const hasView = matchingPermissions.some((p) => p.CanView === true);
367
- const canDelete = hasDelete;
368
- const canEdit = hasDelete || hasEdit;
369
- const canRun = hasDelete || hasEdit || hasRun;
370
- const canView = hasDelete || hasEdit || hasRun || hasView;
371
- return {
372
- canView,
373
- canRun,
374
- canEdit,
375
- canDelete,
376
- isOwner: false
377
- };
434
+ return this.ComputeEffectivePermissionsSync(agent, allAgents, AIEngineBase.Instance.AgentPermissions, user);
378
435
  } catch (error) {
379
436
  LogError(`Error getting effective permissions for agent: ${error instanceof Error ? error.message : String(error)}`);
380
437
  return {
@@ -428,14 +485,15 @@ var AIAgentPermissionHelper = class {
428
485
  return includeInactive ? runnable : runnable.filter((a) => a.Status === "Active");
429
486
  }
430
487
  /**
431
- * Whether an agent is meant to be found and delegated to directly. Sub-Agents and child agents
432
- * are meant to be called by other agents, not discovered directly, so an agent whose
433
- * 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.
434
492
  * @param agent - The agent to check
435
493
  * @returns True when the agent can be discovered directly
436
494
  */
437
495
  static IsDirectlyDiscoverable(agent) {
438
- return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID;
496
+ return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID && agent.InstantiationMode !== "Required";
439
497
  }
440
498
  /**
441
499
  * Clears the AIEngineBase cache. Useful when permissions have been modified.
@@ -650,8 +708,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
650
708
  this._agentsByID = null;
651
709
  this._agentsByName = null;
652
710
  this._childAgentsByParentID = null;
711
+ this._agentInheritanceChainCache = /* @__PURE__ */ new Map();
653
712
  this._agentsIndexedRef = null;
654
713
  this._agentsIndexedLen = -1;
714
+ this._preferredPrimaryByGroup = /* @__PURE__ */ new Map();
655
715
  this._agentRelationshipsByAgentID = null;
656
716
  this._agentRelationshipsIndexedRef = null;
657
717
  this._agentRelationshipsIndexedLen = -1;
@@ -979,13 +1039,181 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
979
1039
  }
980
1040
  }
981
1041
  static {
982
- this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set(["_vectorIndexes"]);
1042
+ this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set([
1043
+ "_vectorIndexes",
1044
+ "_agentPersonas",
1045
+ "_agentPermissions"
1046
+ ]);
983
1047
  }
984
1048
  canUseImmediateMutation(config, skipAdditionalLoadingCheck = false) {
985
1049
  const independent = AIEngineBase_1.IMMEDIATE_MUTATION_PROPERTIES.has(config.PropertyName);
986
1050
  return super.canUseImmediateMutation(config, skipAdditionalLoadingCheck || independent);
987
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
+ }
988
1214
  async AdditionalLoading(contextUser) {
1215
+ this.normalizeExclusivePrimaryInstances();
1216
+ this._preferredPrimaryByGroup.clear();
989
1217
  this._configurationChainCache.clear();
990
1218
  this._userRunnableAgentDirectoryCache.clear();
991
1219
  this._userRunnableAgentsRef = null;
@@ -1003,6 +1231,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1003
1231
  this._agentsByID = null;
1004
1232
  this._agentsByName = null;
1005
1233
  this._childAgentsByParentID = null;
1234
+ this._agentInheritanceChainCache.clear();
1006
1235
  this._agentsIndexedRef = null;
1007
1236
  this._agentsIndexedLen = -1;
1008
1237
  this._agentRelationshipsByAgentID = null;
@@ -1074,6 +1303,190 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1074
1303
  replaceContents(model.ModelVendors, vendorsByModel.get(keyFor(model.ID)) ?? []);
1075
1304
  }
1076
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
+ }
1077
1490
  /**
1078
1491
  * The collections {@link AdditionalLoading} attaches to parents. When these read zero while
1079
1492
  * the child arrays are full, the derived state has been lost — the failure that row counts
@@ -1294,33 +1707,303 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1294
1707
  GetSubAgents(agentID, status, relationshipStatus) {
1295
1708
  this.ensureAgentsIndex();
1296
1709
  this.ensureAgentRelationshipsIndex();
1297
- const normAgentId = NormalizeUUID(agentID);
1298
- const rawChildAgents = this._childAgentsByParentID.get(normAgentId) ?? [];
1299
- 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)];
1300
1712
  const relStatus = relationshipStatus ?? "Active";
1301
- const rawRelationships = this._agentRelationshipsByAgentID.get(normAgentId) ?? [];
1302
- const uniqueAgentIDs = /* @__PURE__ */ new Set();
1303
- const allSubAgents = [];
1304
- for (const agent of childAgents) {
1305
- const normId = NormalizeUUID(agent.ID);
1306
- if (!uniqueAgentIDs.has(normId)) {
1307
- uniqueAgentIDs.add(normId);
1308
- allSubAgents.push(agent);
1309
- }
1310
- }
1311
- for (const ar of rawRelationships) {
1312
- if (ar.Status !== relStatus || !ar.SubAgentID)
1313
- continue;
1314
- const agent = this._agentsByID.get(NormalizeUUID(ar.SubAgentID));
1315
- if (agent && (!status || agent.Status === status)) {
1316
- const normId = NormalizeUUID(agent.ID);
1317
- if (!uniqueAgentIDs.has(normId)) {
1318
- uniqueAgentIDs.add(normId);
1319
- 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;
1320
1866
  }
1321
1867
  }
1322
1868
  }
1323
- return allSubAgents;
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);
1983
+ }
1984
+ }
1985
+ }
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;
1324
2007
  }
1325
2008
  get AgentTypes() {
1326
2009
  return this.GetConfigData("_agentTypes");
@@ -1519,19 +2202,158 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1519
2202
  }
1520
2203
  }
1521
2204
  /**
1522
- * Synchronous permission check using already-loaded `_agentPermissions` metadata.
1523
- * Mirrors `AIAgentPermissionHelper.GetEffectivePermissions` without async `Config()` overhead.
2205
+ * Synchronous check for whether `user` has `CanView` permission on `agent` under the
2206
+ * 2x2 RBAC matrix.
1524
2207
  */
1525
- canUserRunAgentSync(agent, allPermissions, user, userRoleIds) {
1526
- if (UUIDsEqual(agent.OwnerUserID, user.ID)) {
1527
- 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;
2221
+ }
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 [];
1528
2231
  }
1529
- const agentPerms = allPermissions.filter((p) => UUIDsEqual(p.AgentID, agent.ID));
1530
- if (agentPerms.length === 0) {
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
+ }
1531
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;
1532
2330
  }
1533
- const matching = agentPerms.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID != null && userRoleIds.Has(p.RoleID));
1534
- 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;
1535
2357
  }
1536
2358
  summarizeAgentDescription(rawDescription) {
1537
2359
  if (!rawDescription) {
@@ -1593,16 +2415,82 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1593
2415
  * @param user - Optional user; when present, filters to skills the user can Run.
1594
2416
  * @returns MJAISkillEntity[] - Active skills the agent may activate (empty if AcceptsSkills is 'None').
1595
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
+ }
1596
2457
  GetSkillsForAgent(agent, user) {
1597
- if (!agent || agent.AcceptsSkills === "None") {
2458
+ if (!agent) {
2459
+ return [];
2460
+ }
2461
+ const effectiveAcceptsSkills = this.resolveEffectiveAcceptsSkills(agent);
2462
+ if (effectiveAcceptsSkills === "None") {
1598
2463
  return [];
1599
2464
  }
1600
2465
  const activeSkills = this._skills.filter((s) => s.Status === "Active");
1601
2466
  let agentSkills;
1602
- if (agent.AcceptsSkills === "All") {
2467
+ if (effectiveAcceptsSkills === "All") {
1603
2468
  agentSkills = activeSkills;
1604
2469
  } else {
1605
- 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
+ }
1606
2494
  agentSkills = activeSkills.filter((s) => grantedSkillIDs.has(NormalizeUUID(s.ID)));
1607
2495
  }
1608
2496
  if (!user) {
@@ -1639,7 +2527,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1639
2527
  * gate is 'RequestedOnly', or when no availability gate passes).
1640
2528
  */
1641
2529
  GetAutoActivatableSkillsForAgent(agent, user) {
1642
- if (!agent || agent.SkillActivationMode !== "Auto") {
2530
+ if (!agent) {
2531
+ return [];
2532
+ }
2533
+ if (this.resolveEffectiveSkillActivationMode(agent) !== "Auto") {
1643
2534
  return [];
1644
2535
  }
1645
2536
  return this.GetSkillsForAgent(agent, user).filter((s) => s.ActivationMode === "Auto");
@@ -1664,6 +2555,33 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1664
2555
  GetSkillExposedActionIDs(skillID) {
1665
2556
  return this._skillActions.filter((sa) => UUIDsEqual(sa.SkillID, skillID) && sa.ExposeToModel !== false).map((sa) => sa.ActionID);
1666
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
+ }
1667
2585
  /**
1668
2586
  * Returns the sub-agent IDs bundled into a skill (via "MJ: AI Skill Sub Agents"). Callers
1669
2587
  * resolve the full `MJAIAgentEntityExtended` objects via `this.Agents` / `GetAgentByID`.
@@ -1689,9 +2607,21 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1689
2607
  */
1690
2608
  GetAgentConfigurationPresets(agentId, activeOnly = true) {
1691
2609
  this.ensureAgentConfigurationsIndex();
1692
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId)) ?? [];
1693
- const presets = activeOnly ? raw.filter((ac) => ac.Status === "Active") : raw.slice();
1694
- 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);
1695
2625
  }
1696
2626
  /**
1697
2627
  * Gets the default configuration preset for an agent
@@ -1709,11 +2639,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1709
2639
  * @returns The configuration preset, or undefined if not found
1710
2640
  */
1711
2641
  GetAgentConfigurationPresetByName(agentId, presetName) {
1712
- this.ensureAgentConfigurationsIndex();
1713
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId));
1714
- if (!raw)
1715
- return void 0;
1716
- 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);
1717
2644
  }
1718
2645
  get AgentNoteTypes() {
1719
2646
  return this.GetConfigData("_agentNoteTypes");
@@ -1896,7 +2823,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1896
2823
  if (a.ID) {
1897
2824
  byId.set(NormalizeUUID(a.ID), a);
1898
2825
  }
1899
- if (a.Name) {
2826
+ if (a.Name && !a.BaseAgentID) {
1900
2827
  const normName = a.Name.trim().toLowerCase();
1901
2828
  if (!byName.has(normName)) {
1902
2829
  byName.set(normName, a);
@@ -1912,9 +2839,18 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1912
2839
  list.push(a);
1913
2840
  }
1914
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
+ }
1915
2850
  this._agentsByID = byId;
1916
2851
  this._agentsByName = byName;
1917
2852
  this._childAgentsByParentID = byParentId;
2853
+ this._agentInheritanceChainCache.clear();
1918
2854
  this._agentsIndexedRef = this._agents;
1919
2855
  this._agentsIndexedLen = this._agents.length;
1920
2856
  }
@@ -2134,6 +3070,66 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2134
3070
  const vendor = modelVendor?.VendorID ? this.VendorsByID.get(NormalizeUUID(modelVendor.VendorID)) : void 0;
2135
3071
  return ResolveEffectiveModelConfiguration(ParseModelConfiguration(modelType?.ModelConfiguration), ParseModelConfiguration(model.ModelConfiguration), ParseVendorConfiguration(vendor?.Configuration)?.ModelDefaults, ParseModelConfiguration(modelVendor?.ModelConfiguration));
2136
3072
  }
3073
+ /**
3074
+ * Every Platt calibration declared for a decision model: its effective
3075
+ * `ModelConfiguration.Decision.Calibrations` at the model layer (the model type's bag, then the
3076
+ * model's own), or an empty list when the model is unknown or declares none (before the engine
3077
+ * loads, every model is unknown).
3078
+ * Consumers look a fit up with {@link FindDecisionCalibration}, which matches the use, the
3079
+ * question and the exact resolved model.
3080
+ *
3081
+ * @param modelName The MJ decision model's name (`Jev`, `LLM Decision`), as the decision run
3082
+ * reports it. Matched case-insensitively, ignoring surrounding spaces.
3083
+ */
3084
+ GetDecisionCalibrations(modelName) {
3085
+ const target = modelName?.trim().toLowerCase();
3086
+ if (!target) {
3087
+ return [];
3088
+ }
3089
+ let models;
3090
+ try {
3091
+ models = this.Models;
3092
+ } catch (err) {
3093
+ if (err instanceof PermissionConstrainedError) {
3094
+ return [];
3095
+ }
3096
+ throw err;
3097
+ }
3098
+ const model = models.find((m) => m.Name?.trim().toLowerCase() === target);
3099
+ const calibrations = model ? this.GetEffectiveModelConfiguration(model.ID)?.Decision?.Calibrations : void 0;
3100
+ return Array.isArray(calibrations) ? calibrations : [];
3101
+ }
3102
+ /**
3103
+ * The calibration fitted for this use and question on the exact model that answered, or null when
3104
+ * there is none, so the consumer treats the answer as unsure. The model's name selects its declared
3105
+ * calibrations ({@link GetDecisionCalibrations}); the use, the question and the resolved model must
3106
+ * then match one entry exactly, after trimming. A missing name or resolved model, or an entry whose
3107
+ * `A` or `B` is not a finite number, matches nothing.
3108
+ *
3109
+ * @param key The decision use and the question within it.
3110
+ * @param answeredBy The MJ decision model that answered and the exact model behind it.
3111
+ */
3112
+ FindDecisionCalibration(key, answeredBy) {
3113
+ const modelName = answeredBy.ModelName?.trim();
3114
+ const resolvedModel = answeredBy.ResolvedModel?.trim();
3115
+ if (!modelName || !resolvedModel) {
3116
+ return null;
3117
+ }
3118
+ const entry = this.GetDecisionCalibrations(modelName).find((c) => c.Use?.trim() === key.Use && c.Question?.trim() === key.Question && c.ResolvedModel?.trim() === resolvedModel && Number.isFinite(c.A) && Number.isFinite(c.B));
3119
+ return entry ? { A: entry.A, B: entry.B } : null;
3120
+ }
3121
+ /**
3122
+ * A raw probability (a Likelihood, or a Choice's confidence) calibrated for the model that
3123
+ * answered, or null when it has no calibration for this use and question.
3124
+ *
3125
+ * @param key The decision use and the question within it.
3126
+ * @param probability The raw probability.
3127
+ * @param answeredBy The MJ decision model that answered and the exact model behind it.
3128
+ */
3129
+ CalibrateDecisionProbability(key, probability, answeredBy) {
3130
+ const calibration = this.FindDecisionCalibration(key, answeredBy);
3131
+ return calibration ? ApplyPlattCalibration(probability, calibration) : null;
3132
+ }
2137
3133
  get Prompts() {
2138
3134
  return this.GetConfigData("_prompts");
2139
3135
  }
@@ -2413,7 +3409,28 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2413
3409
  * Joins through the junction table to return full tool definition entities.
2414
3410
  */
2415
3411
  GetClientToolsForAgent(agentId) {
2416
- 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);
2417
3434
  const tools = [];
2418
3435
  for (const junction of junctions) {
2419
3436
  const tool = this._clientToolDefinitions.find((t) => UUIDsEqual(t.ID, junction.ClientToolDefinitionID));
@@ -2450,8 +3467,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2450
3467
  if (!agent) {
2451
3468
  return void 0;
2452
3469
  }
2453
- if (agent.ModelSelectionMode === "Agent") {
2454
- 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];
2455
3474
  if (agentPrompt) {
2456
3475
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2457
3476
  if (promptModels && promptModels.length > 0) {
@@ -2459,8 +3478,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2459
3478
  }
2460
3479
  }
2461
3480
  }
2462
- if (agent.TypeID) {
2463
- 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));
2464
3483
  if (agentType?.SystemPromptID) {
2465
3484
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentType.SystemPromptID));
2466
3485
  if (promptModels && promptModels.length > 0) {
@@ -2468,8 +3487,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2468
3487
  }
2469
3488
  }
2470
3489
  }
2471
- if (agent.ModelSelectionMode !== "Agent") {
2472
- 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];
2473
3492
  if (agentPrompt) {
2474
3493
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2475
3494
  if (promptModels && promptModels.length > 0) {
@@ -2481,13 +3500,9 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2481
3500
  }
2482
3501
  /**
2483
3502
  * Gets all modalities supported by an agent for a given direction.
2484
- * Follows precedence chain: Agent → Model → System → Default.
3503
+ * Follows precedence chain: Agent (walked BaseAgentID root -> leaf) → Model → System → Default.
2485
3504
  * If no explicit agent modality records exist, falls through to the agent's model's effective modalities.
2486
3505
  * Any explicit AIAgentModality records override: IsAllowed = 1 adds/retains, IsAllowed = 0 acts as a hard veto.
2487
- * @param agentId - The agent ID
2488
- * @param direction - 'Input' or 'Output'
2489
- * @param modelId - Optional model ID override
2490
- * @returns Array of modality entities the agent supports
2491
3506
  */
2492
3507
  GetAgentModalities(agentId, direction, modelId) {
2493
3508
  this.ensureModalitiesIndex();
@@ -2497,17 +3512,31 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2497
3512
  for (const m of baseModalities) {
2498
3513
  resultMap.set(NormalizeUUID(m.ID), m);
2499
3514
  }
2500
- const agentRecords = this._agentModalities.filter((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction);
2501
- for (const am of agentRecords) {
2502
- const normId = NormalizeUUID(am.ModalityID);
2503
- const isAllowed = am.IsAllowed !== false;
2504
- if (isAllowed) {
2505
- const modality = this._modalitiesByID.get(normId);
2506
- if (modality) {
2507
- 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);
2508
3539
  }
2509
- } else {
2510
- resultMap.delete(normId);
2511
3540
  }
2512
3541
  }
2513
3542
  return Array.from(resultMap.values());
@@ -2569,9 +3598,23 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2569
3598
  this.ensureModalitiesIndex();
2570
3599
  const targetModality = this._modalitiesByName.get(modalityName.toLowerCase());
2571
3600
  if (targetModality) {
2572
- const agentRecord = this._agentModalities.find((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID));
2573
- if (agentRecord) {
2574
- 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
+ }
2575
3618
  }
2576
3619
  }
2577
3620
  const resolvedModelId = this.resolveAgentModelId(agentId, modelId);
@@ -2640,7 +3683,26 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2640
3683
  source: "Default"
2641
3684
  };
2642
3685
  }
2643
- 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
+ }
2644
3706
  if (agentModality) {
2645
3707
  return {
2646
3708
  maxSizeBytes: agentModality.MaxSizeBytes,
@@ -2913,16 +3975,56 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2913
3975
  return excludedApiNames;
2914
3976
  }
2915
3977
  /**
2916
- * Gets all personas configured for an agent, ordered by Sequence.
2917
- * 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.
2918
3981
  *
2919
3982
  * @param agentId - The agent ID
2920
3983
  * @returns Array of resolved agent personas
2921
3984
  */
2922
3985
  GetAgentPersonas(agentId) {
2923
- 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);
2924
4026
  const result = [];
2925
- for (const ap of agentRecords) {
4027
+ for (const ap of sortedRecords) {
2926
4028
  const persona = this._personas.find((p) => UUIDsEqual(p.ID, ap.PersonaID) && p.IsActive);
2927
4029
  if (persona) {
2928
4030
  result.push({
@@ -2935,21 +4037,35 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2935
4037
  }
2936
4038
  /**
2937
4039
  * Resolves the effective persona for an agent using the precedence chain:
2938
- * 1. Agent's default persona (AIAgentPersona where IsDefault = 1 and IsAllowed = 1)
2939
- * 2. First allowed agent persona (by Sequence)
2940
- * 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)
2941
4044
  *
2942
4045
  * In all cases, merges agent-level StyleOverride (Tone, SpeakingStyle) over the persona's defaults.
2943
4046
  *
2944
4047
  * @param agentId - The agent ID
2945
- * @param options - Optional overrides for modelId, vendorId, modalityName
4048
+ * @param options - Optional overrides for modelId, vendorId, modalityName, preferredPersonaId
2946
4049
  */
2947
4050
  ResolveAgentPersona(agentId, options) {
2948
4051
  const modalityName = options?.modalityName ?? "Audio";
2949
4052
  const agentPersonas = this.GetAgentPersonas(agentId);
2950
4053
  let chosenPersona = null;
2951
4054
  let chosenAgentPersona = void 0;
2952
- 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) {
2953
4069
  const defaultAP = agentPersonas.find((ap) => ap.AgentPersona.IsDefault);
2954
4070
  const selected = defaultAP ?? agentPersonas[0];
2955
4071
  chosenPersona = selected.Persona;
@@ -3195,7 +4311,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3195
4311
  }
3196
4312
  };
3197
4313
  AIEngineBase = AIEngineBase_1 = __decorate2([
3198
- RegisterForStartup()
4314
+ RegisterForStartup({ deferred: IsBrowser() })
3199
4315
  ], AIEngineBase);
3200
4316
 
3201
4317
  // ../../AI/BaseAIEngine/dist/RealtimeCostLines.js
@@ -3650,7 +4766,7 @@ var AgentClientSession = class {
3650
4766
  if (!provider) {
3651
4767
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3652
4768
  }
3653
- const aiClient = new Fe(provider);
4769
+ const aiClient = new rt(provider);
3654
4770
  try {
3655
4771
  const agentShim = { ID: params.AgentId };
3656
4772
  const messages = params.Messages.map((m) => ({
@@ -3708,7 +4824,7 @@ var AgentClientSession = class {
3708
4824
  if (!provider) {
3709
4825
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3710
4826
  }
3711
- const aiClient = new Fe(provider);
4827
+ const aiClient = new rt(provider);
3712
4828
  try {
3713
4829
  const gqlParams = {
3714
4830
  userMessageId: params.UserMessageId,
@@ -4149,6 +5265,24 @@ function IntersectAcceptedSkills(runnable, accepted) {
4149
5265
  }
4150
5266
 
4151
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"]);
4152
5286
  var MentionAutocomplete = class extends BaseSingleton {
4153
5287
  constructor() {
4154
5288
  super();
@@ -4161,6 +5295,12 @@ var MentionAutocomplete = class extends BaseSingleton {
4161
5295
  this.queriesEntityIcon = "fa-solid fa-database";
4162
5296
  this.isInitialized = false;
4163
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;
4164
5304
  }
4165
5305
  /** The process-wide shared instance (Global Object Store backed). */
4166
5306
  static get Instance() {
@@ -4171,43 +5311,293 @@ var MentionAutocomplete = class extends BaseSingleton {
4171
5311
  return this.isInitialized;
4172
5312
  }
4173
5313
  /**
4174
- * Initialize the service by loading agents and users
4175
- * Prevents concurrent initialization with promise lock
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);
5451
+ }
5452
+ /**
5453
+ * Re-syncs `agentsCache` and/or `skillsCache` from `AIEngineBase` without forcing a server reload.
5454
+ */
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) {
5462
+ return;
5463
+ }
5464
+ if (syncAgents) {
5465
+ this.agentsCache = await this.loadRunnableAgents(user, this.provider);
5466
+ }
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.
4176
5477
  */
4177
- async initialize(currentUser, provider) {
4178
- if (this.isInitialized) {
5478
+ RecordMentionUse(id, type, currentUser) {
5479
+ const normalizedId = id?.trim().toLowerCase();
5480
+ if (!normalizedId || !type) {
4179
5481
  return;
4180
5482
  }
4181
- if (this.initializationPromise) {
4182
- return this.initializationPromise;
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;
4183
5504
  }
4184
- this.initializationPromise = this._initializeInternal(currentUser, provider);
5505
+ this.lastSyncedFrecencyRaw = raw;
5506
+ this.frecencyMap.clear();
4185
5507
  try {
4186
- await this.initializationPromise;
4187
- } finally {
4188
- 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 {
4189
5523
  }
4190
5524
  }
4191
5525
  /**
4192
- * Internal initialization logic
5526
+ * Caps `frecencyMap` at {@link MAX_FRECENCY_ENTRIES} entries ranked by current frecency score.
4193
5527
  */
4194
- 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) {
4195
5549
  try {
4196
- await AIEngineBase.Instance.Config(false);
4197
- const allAgents = AIEngineBase.Instance.ReadableAgents;
4198
- const candidateAgents = allAgents.filter((a) => !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent" && !a.IsRestricted);
4199
- this.agentsCache = await this.filterAgentsByRunPermission(candidateAgents, currentUser);
4200
- this.usersCache = [currentUser];
4201
- this.entitiesCache = this.loadReadableEntities(currentUser, provider);
4202
- this.queriesCache = this.loadRunnableQueries(currentUser, provider);
4203
- this.queriesEntityIcon = this.resolveQueriesEntityIcon(provider);
4204
- this.skillsCache = await this.filterSkillsByRunPermission(currentUser);
4205
- this.provider = provider;
4206
- this.isInitialized = true;
4207
- } catch (error) {
4208
- console.error("Failed to initialize MentionAutocomplete:", error);
4209
- 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;
4210
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 };
5596
+ }
5597
+ return {
5598
+ uses: entry.uses,
5599
+ score: this.calculateFrecencyValue(entry, nowMs)
5600
+ };
4211
5601
  }
4212
5602
  /**
4213
5603
  * Filter agents to only those the current user has 'run' permission for.
@@ -4260,24 +5650,34 @@ var MentionAutocomplete = class extends BaseSingleton {
4260
5650
  }
4261
5651
  }
4262
5652
  /**
4263
- * Load queries the current user has run permission for.
4264
- * 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.
4265
5658
  */
4266
- loadRunnableQueries(user, provider) {
5659
+ async loadRunnableQueries(user, provider) {
4267
5660
  try {
4268
- const md = provider ?? Metadata.Provider;
4269
- return (md.Queries || []).filter((query) => {
4270
- try {
4271
- return query.UserCanRun(user);
4272
- } catch {
4273
- return false;
4274
- }
4275
- });
5661
+ const engine = this.queryEngineFor(provider);
5662
+ await engine.Config(false, user, provider);
5663
+ return engine.Queries.filter((query) => query.Status === "Approved" && this.userCanRunQuery(query, user));
4276
5664
  } catch (error) {
4277
5665
  console.error("Failed to load queries for mention autocomplete:", error);
4278
5666
  return [];
4279
5667
  }
4280
5668
  }
5669
+ /** The QueryEngine for the given provider, or the global one when no provider is given. */
5670
+ queryEngineFor(provider) {
5671
+ return provider ? QueryEngine.GetProviderInstance(provider, QueryEngine) : QueryEngine.Instance;
5672
+ }
5673
+ /** Whether the user can run the query; a permission-check error excludes it (fail closed). */
5674
+ userCanRunQuery(query, user) {
5675
+ try {
5676
+ return query.UserCanRun(user).canRun;
5677
+ } catch {
5678
+ return false;
5679
+ }
5680
+ }
4281
5681
  /**
4282
5682
  * Resolve the generic icon used for all query mentions from the 'MJ: Queries' entity.
4283
5683
  */
@@ -4299,10 +5699,10 @@ var MentionAutocomplete = class extends BaseSingleton {
4299
5699
  * `MJ: AI Agent Skills` grants — via {@link AIEngineBase.GetSkillsForAgent}. Without it (or for an
4300
5700
  * agent not in the user's runnable set) the user's full runnable catalog is shown, as before, and
4301
5701
  * the server's `RequestedSkills` guard is the backstop.
4302
- * @param scope Narrows the '@' list for one composer: the agents it may offer and the people it
4303
- * offers. Passed per call, never stored, because this engine is shared by every composer on the
4304
- * page. Omitted keeps today's list: every agent the user can run, and the current user.
4305
- * @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
4306
5706
  */
4307
5707
  GetSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4308
5708
  if (trigger === "#") {
@@ -4311,57 +5711,337 @@ var MentionAutocomplete = class extends BaseSingleton {
4311
5711
  if (trigger === "/") {
4312
5712
  return this.getSkillSuggestions(query, targetAgentId);
4313
5713
  }
5714
+ this.syncFrecencyFromUserSettings();
4314
5715
  const lowerQuery = query.toLowerCase().trim();
4315
- const suggestions = [
4316
- ...this.getAgentSuggestions(lowerQuery, scope?.AllowedAgentIDs ?? null),
4317
- ...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) : []
4318
5724
  ];
4319
- return suggestions.sort((a, b) => {
4320
- const scoreA = this.calculateMatchScore(a.name, lowerQuery);
4321
- const scoreB = this.calculateMatchScore(b.name, lowerQuery);
4322
- if (scoreB !== scoreA)
4323
- return scoreB - scoreA;
4324
- if (a.type !== b.type)
4325
- return a.type === "agent" ? -1 : 1;
4326
- return a.name.localeCompare(b.name);
4327
- });
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
+ }));
4328
5736
  }
4329
5737
  /** @deprecated Use {@link GetSuggestions}. */
4330
5738
  getSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4331
5739
  return this.GetSuggestions(query, includeUsers, trigger, targetAgentId, scope);
4332
5740
  }
4333
5741
  /**
4334
- * Agent suggestions for '@': the user's runnable agents that match the query, narrowed to
4335
- * `allowedAgentIDs` when one is given (null offers every runnable agent).
4336
- */
4337
- getAgentSuggestions(lowerQuery, allowedAgentIDs) {
4338
- 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) => ({
4339
- type: "agent",
4340
- id: agent.ID,
4341
- name: agent.Name || "Unknown",
4342
- displayName: agent.Name || "Unknown",
4343
- description: agent.Description || void 0,
4344
- imageUrl: agent.LogoURL || void 0,
4345
- // Agent logo/avatar image
4346
- icon: this.getAgentIcon(agent),
4347
- // Configuration presets ride on the suggestion — the (AI-blind) composer
4348
- // renders a preset picker on the inserted chip when there are 2+.
4349
- presets: this.getAgentPresets(agent.ID)
4350
- }));
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;
4351
5908
  }
4352
5909
  /**
4353
- * 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
4354
5911
  * engine's own (which holds only the current user).
4355
5912
  */
4356
- getPeopleSuggestions(lowerQuery, people) {
5913
+ getRankedPeopleSuggestions(lowerQuery, people, searchField, nowMs) {
4357
5914
  const candidates = people ?? this.usersCache.map((user) => ({ ID: user.ID, Name: user.Name, Email: user.Email }));
4358
- return candidates.filter((person) => !lowerQuery || this.calculateMatchScore(person.Name, lowerQuery) > 0).map((person) => ({
4359
- type: "user",
4360
- id: person.ID,
4361
- name: person.Name,
4362
- displayName: person.Name,
4363
- description: person.Email || void 0
4364
- }));
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;
4365
6045
  }
4366
6046
  /**
4367
6047
  * Get entity + query suggestions for #mentions, ranked by query match.
@@ -4416,7 +6096,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4416
6096
  if (!agent) {
4417
6097
  return this.skillsCache;
4418
6098
  }
4419
- const engine = this.provider ? AIEngineBase.GetProviderInstance(this.provider, AIEngineBase) : AIEngineBase.Instance;
6099
+ const engine = this.aiEngineFor(this.provider);
4420
6100
  return IntersectAcceptedSkills(this.skillsCache, engine.GetSkillsForAgent(agent));
4421
6101
  }
4422
6102
  /**
@@ -4444,8 +6124,8 @@ var MentionAutocomplete = class extends BaseSingleton {
4444
6124
  }).slice(0, MAX_SUGGESTIONS).map((x) => x.suggestion);
4445
6125
  }
4446
6126
  /**
4447
- * Calculate match score for ranking
4448
- * Higher score = better match
6127
+ * Calculate match score for ranking `#` (entities/queries) and `/` (skills) triggers.
6128
+ * Higher score = better match.
4449
6129
  */
4450
6130
  calculateMatchScore(name, query) {
4451
6131
  if (!query)
@@ -4475,7 +6155,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4475
6155
  */
4476
6156
  getAgentPresets(agentId) {
4477
6157
  try {
4478
- const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agentId, true);
6158
+ const presets = this.aiEngineFor(this.provider).GetAgentConfigurationPresets(agentId, true);
4479
6159
  if (!presets || presets.length === 0) {
4480
6160
  return void 0;
4481
6161
  }
@@ -4566,7 +6246,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4566
6246
  async Refresh(currentUser) {
4567
6247
  this.isInitialized = false;
4568
6248
  this.initializationPromise = null;
4569
- await this.initialize(currentUser);
6249
+ await this.initialize(currentUser, this.provider);
4570
6250
  }
4571
6251
  /** @deprecated Use {@link Refresh}. */
4572
6252
  async refresh(currentUser) {
@@ -4651,68 +6331,223 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4651
6331
  static {
4652
6332
  this.SETTING_NAME = "Conversations.DefaultAgentID";
4653
6333
  }
6334
+ static {
6335
+ this.LEGACY_USER_SETTING_NAME = "chat.defaultAgentId";
6336
+ }
4654
6337
  static {
4655
6338
  this.FALLBACK_AGENT_NAME = "Sage";
4656
6339
  }
4657
6340
  /**
4658
- * Resolve the default agent for this turn. Walks the 4-step chain; throws a descriptive
4659
- * error if every step misses (vs. the previous code path's silent `null` return, which
4660
- * made misconfigurations hard to spot at the call site).
4661
- *
4662
- * @example
4663
- * ```typescript
4664
- * const agent = await runtime.DefaultAgent.resolve({
4665
- * explicitAgentId: widgetInput.DefaultAgentId, // wins if non-null and matches
4666
- * applicationId: currentAppId, // scopes the settings lookup
4667
- * contextUser: this.ProviderToUse.CurrentUser,
4668
- * provider: this.ProviderToUse,
4669
- * });
4670
- * ```
6341
+ * Resolve the default agent for this turn. Walks the full resolution chain; throws a descriptive
6342
+ * error if every step misses.
4671
6343
  */
4672
6344
  async Resolve(options = {}) {
4673
- const { explicitAgentId, applicationId, contextUser, provider } = options;
4674
- await AIEngineBase.Instance.Config(false, contextUser, provider);
4675
- 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
+ }
4676
6367
  if (explicitAgentId) {
4677
- const explicit = this.findAgentById(explicitAgentId);
4678
- if (explicit)
4679
- return explicit;
4680
- 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
+ }
4681
6389
  }
6390
+ let orgDefault;
6391
+ let orgDefaultSource = "app-or-global-setting";
6392
+ let settingValue;
4682
6393
  if (applicationId) {
4683
6394
  const fromAppSettings = await this.getAppDefaultAgentId(applicationId, contextUser, provider);
4684
6395
  if (fromAppSettings) {
4685
- const resolved = this.findAgentById(fromAppSettings);
4686
- if (resolved)
4687
- return resolved;
4688
- 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
+ };
4689
6425
  }
6426
+ return {
6427
+ agent: orgDefault,
6428
+ source: orgDefaultSource,
6429
+ ...unavailableInfo ?? {}
6430
+ };
4690
6431
  }
4691
- const settingValue = ApplicationSettingEngine.Instance.GetSetting(_DefaultAgentResolver.SETTING_NAME, applicationId ?? void 0);
4692
- if (settingValue) {
4693
- const fromSetting = this.findAgentById(settingValue);
4694
- if (fromSetting)
4695
- return fromSetting;
4696
- 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
+ };
4697
6439
  }
4698
- const fallback = AIEngineBase.Instance.ReadableAgents.find((a) => a.Name === _DefaultAgentResolver.FALLBACK_AGENT_NAME);
4699
- if (fallback)
4700
- return fallback;
4701
- 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.`);
4702
6441
  }
4703
6442
  /** @deprecated Use {@link Resolve}. */
4704
6443
  async resolve(options = {}) {
4705
6444
  return this.Resolve(options);
4706
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
+ }
4707
6546
  /**
4708
6547
  * Read `Application.AgentSettings.DefaultAgentID` for the given app via a targeted
4709
6548
  * `RunView` (single row by ID, `entity_object` so the typed `AgentSettingsObject`
4710
6549
  * accessor is available). Returns `undefined` when the app, the column, or the field
4711
6550
  * is absent.
4712
- *
4713
- * Kept query-light: one tiny by-ID read, served from the provider's RunView cache on
4714
- * repeat calls (server trusts its cache; the client caches too), and only reached when
4715
- * no explicit agent was supplied — i.e. at most once per conversation-turn start.
4716
6551
  */
4717
6552
  async getAppDefaultAgentId(applicationId, contextUser, provider) {
4718
6553
  try {
@@ -4743,13 +6578,24 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4743
6578
  const candidate = provider;
4744
6579
  return candidate && typeof candidate.RunView === "function" ? provider : void 0;
4745
6580
  }
6581
+ getSearchableAgents(aiEngine) {
6582
+ return aiEngine.ReadableAgents ?? aiEngine.Agents ?? [];
6583
+ }
4746
6584
  /**
4747
6585
  * Find an agent by ID from the AIEngineBase cache. Returns `undefined` if not found.
4748
6586
  * Uses {@link UUIDsEqual} per the standing rule about comparing UUIDs across
4749
6587
  * SQL Server / Postgres (case differences would silently miss).
4750
6588
  */
4751
- findAgentById(id) {
4752
- 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;
4753
6599
  }
4754
6600
  };
4755
6601
 
@@ -4861,7 +6707,7 @@ var ConversationStreaming = class {
4861
6707
  return;
4862
6708
  }
4863
6709
  try {
4864
- const dataProvider = h.Instance;
6710
+ const dataProvider = g.Instance;
4865
6711
  this.watchSocketAcknowledgement(dataProvider);
4866
6712
  this.pushStatusSubscription = dataProvider.PushStatusUpdates().subscribe({
4867
6713
  next: (status) => {
@@ -5395,7 +7241,7 @@ var ConversationLiveness = class {
5395
7241
  }
5396
7242
  let socketWired = false;
5397
7243
  try {
5398
- const provider = h.Instance;
7244
+ const provider = g.Instance;
5399
7245
  if (provider) {
5400
7246
  this.subscriptions.add(provider.SocketReconnected$.subscribe(() => this.Trigger("socket-reconnected")));
5401
7247
  socketWired = true;
@@ -5493,11 +7339,11 @@ var ConversationTail = class {
5493
7339
  return this.client;
5494
7340
  }
5495
7341
  try {
5496
- const provider = h.Instance;
7342
+ const provider = g.Instance;
5497
7343
  if (!provider) {
5498
7344
  return void 0;
5499
7345
  }
5500
- this.client = new vr(provider);
7346
+ this.client = new as(provider);
5501
7347
  return this.client;
5502
7348
  } catch {
5503
7349
  return void 0;
@@ -5533,6 +7379,7 @@ var ConversationAgentRunner = class {
5533
7379
  this._activeRunCount = 0;
5534
7380
  this._provider = null;
5535
7381
  this.IsProcessing$ = this._isProcessing$.asObservable();
7382
+ this._notifiedUnavailableDefaultIds = /* @__PURE__ */ new Set();
5536
7383
  this.session = new AgentClientSession(toolRegistry);
5537
7384
  }
5538
7385
  /**
@@ -5570,6 +7417,7 @@ var ConversationAgentRunner = class {
5570
7417
  const candidateAgents = AIEngineBase.Instance.Agents.filter((a) => !UUIDsEqual(a.ID, agent.ID) && !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent");
5571
7418
  const permittedAgents = currentUser ? await this.filterAgentsByPermissions(candidateAgents, currentUser) : candidateAgents;
5572
7419
  const availableAgents = NarrowToAllowedAgents(permittedAgents, input.AllowedAgentIDs);
7420
+ const sanitizedEdgeHint = input.EdgePreDiscoveryHint ? SanitizeEdgePreDiscoveryHint(input.EdgePreDiscoveryHint, availableAgents) : null;
5573
7421
  LogStatusEx({
5574
7422
  message: `[ConversationAgentRunner] Available agents for routing: ${availableAgents.length} (filtered from ${candidateAgents.length} candidates)`,
5575
7423
  verboseOnly: true
@@ -5585,6 +7433,7 @@ var ConversationAgentRunner = class {
5585
7433
  Name: a.Name,
5586
7434
  Description: a.Description
5587
7435
  })),
7436
+ ...sanitizedEdgeHint ? { [EDGE_PRE_DISCOVERY_DATA_KEY]: sanitizedEdgeHint } : {},
5588
7437
  conversationId: input.conversationId,
5589
7438
  latestMessageId: input.message.ID,
5590
7439
  ...input.appContext ? { appContext: input.appContext } : {},
@@ -5631,19 +7480,29 @@ var ConversationAgentRunner = class {
5631
7480
  return this.ProcessMessage(input);
5632
7481
  }
5633
7482
  /**
5634
- * Resolve the agent that should handle this turn — explicit ID wins, then the
5635
- * Application Settings chain, then the Sage code-const fallback. Surfaces a
5636
- * notification on failure rather than throwing, so the caller (UI thread)
5637
- * 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.
5638
7487
  */
5639
7488
  async resolveAgent(input) {
5640
7489
  try {
5641
- return await this.resolver.resolve({
7490
+ const resolveOpts = {
5642
7491
  explicitAgentId: input.explicitAgentId,
5643
7492
  applicationId: input.applicationId,
5644
7493
  contextUser: this.Provider.CurrentUser ?? void 0,
5645
7494
  provider: this.Provider
5646
- });
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;
5647
7506
  } catch (error) {
5648
7507
  const errorMsg = "Could not resolve a default conversation manager agent: " + (error instanceof Error ? error.message : String(error));
5649
7508
  console.error("[ConversationAgentRunner] Agent resolution failed:", error);