@memberjunction/realtime-widget 6.3.0-edge.1 → 6.3.0-edge.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,47 @@
1
1
  import {
2
+ AGENT_ACCEPTS_SKILLS_RANK,
3
+ AGENT_ARTIFACT_CREATION_MODE_RANK,
4
+ AGENT_FINAL_VALIDATION_MODE_RANK,
5
+ AGENT_ISOLATION_RANK,
6
+ AGENT_MESSAGE_MODE_RANK,
7
+ AGENT_SEARCH_SCOPE_ACCESS_RANK,
8
+ AGENT_SKILL_ACTIVATION_RANK,
9
+ AGENT_STARTING_VALIDATION_MODE_RANK,
2
10
  ApplicationSettingEngine,
3
11
  ArtifactMetadataEngine,
12
+ BuildAgentTypeConfigurationFromLegacyFields,
13
+ ComputeDirectAIAgentPermissions,
14
+ ComputeDirectAISkillPermissions,
4
15
  ConversationEngine,
5
16
  ConversationUtility,
17
+ DeepMergeAgentConfigObjects,
18
+ DeepMergeAgentConfigurations,
19
+ DoesAgentAllowWidenFromBase,
6
20
  EDGE_PRE_DISCOVERY_DATA_KEY,
7
21
  FileStorageEngineBase,
22
+ FoldRebaseAwareChain,
23
+ HasPathTraversalSegment,
24
+ IntersectPayloadPathSets,
25
+ MAX_AGENT_INHERITANCE_DEPTH,
8
26
  MJAICredentialBindingEntity,
9
27
  MJAIModelPriceUnitTypeEntity,
28
+ NARROW_ONLY_PROMPT_PARAM_GATES,
29
+ NarrowAttachmentRootPath,
30
+ NarrowPayloadScope,
31
+ NarrowScopeConfigObjects,
32
+ ParseAgentConfigJsonObject,
33
+ ParseAgentConfiguration,
34
+ ParseAgentHelperPlugins,
35
+ ParseAgentInstantiationConfig,
10
36
  QueryEngine,
11
37
  SanitizeEdgePreDiscoveryHint,
12
38
  TemplateEngineBase,
39
+ UserInfoEngine,
40
+ as,
13
41
  coerceFailedExecuteAgentResult,
14
42
  g,
15
- ns,
16
- tt
17
- } from "./chunk-SXFIY47F.js";
43
+ rt
44
+ } from "./chunk-P3UR75T6.js";
18
45
  import {
19
46
  BaseEngine,
20
47
  BaseEntity,
@@ -25,19 +52,20 @@ import {
25
52
  PermissionConstrainedError,
26
53
  RegisterForStartup,
27
54
  RunView
28
- } from "./chunk-6RWWXOZB.js";
55
+ } from "./chunk-VCGHPATD.js";
29
56
  import {
30
57
  ApplyPlattCalibration,
31
58
  ParseModelConfiguration,
32
59
  ParseVendorConfiguration,
33
60
  ResolveEffectiveModelConfiguration
34
- } from "./chunk-CIZSPKQR.js";
61
+ } from "./chunk-IHM3SRNY.js";
35
62
  import {
36
63
  BaseSingleton,
37
64
  BehaviorSubject,
38
65
  EMPTY,
39
66
  IndexByUUID,
40
67
  IsBrowser,
68
+ MJEventType,
41
69
  MJGlobal,
42
70
  NormalizeUUID,
43
71
  RegisterClass,
@@ -49,7 +77,7 @@ import {
49
77
  ValidationErrorInfo,
50
78
  ValidationErrorType,
51
79
  throttleTime
52
- } from "./chunk-KHEWGJIZ.js";
80
+ } from "./chunk-CUZ32HGY.js";
53
81
 
54
82
  // ../../AI/BaseAIEngine/dist/PriceUnitTypes.js
55
83
  var __decorate = function(decorators, target, key, desc) {
@@ -295,7 +323,56 @@ var TOKEN_PRICE_UNIT_TYPE_DIVISORS = Object.freeze(Object.fromEntries([
295
323
  ].map(([driverClass, driver]) => [driverClass, driver.UnitsPerBillingUnit])));
296
324
 
297
325
  // ../../AI/BaseAIEngine/dist/AIAgentPermissionHelper.js
326
+ var MAX_INHERITANCE_DEPTH = 5;
298
327
  var AIAgentPermissionHelper = class {
328
+ /**
329
+ * Pure synchronous computation of effective permissions for a single agent row WITHOUT
330
+ * walking `BaseAgentID` ancestors. Delegates directly to {@link ComputeDirectAIAgentPermissions}
331
+ * in `@memberjunction/core-entities` so graph access policies and `AIAgentPermissionHelper`
332
+ * always share one single source of truth (Finding 308).
333
+ */
334
+ static computeDirectPermissions(agent, allPermissions, user, userRoleIds) {
335
+ return ComputeDirectAIAgentPermissions(agent, allPermissions, user, userRoleIds);
336
+ }
337
+ /**
338
+ * Pure synchronous computation of effective permissions including the 2x2 RBAC matrix
339
+ * AND the Ancestor `CanRun` Invariant across the `BaseAgentID` inheritance chain.
340
+ *
341
+ * Used by both async {@link GetEffectivePermissions} and sync `AIEngineBase` directory/picker
342
+ * checks so every surface enforces identical semantics with zero drift.
343
+ */
344
+ static ComputeEffectivePermissionsSync(agent, allAgents, allPermissions, user, precomputedUserRoleIds) {
345
+ const userRoleIds = precomputedUserRoleIds ?? new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
346
+ const direct = this.computeDirectPermissions(agent, allPermissions, user, userRoleIds);
347
+ if (direct.canRun && agent.BaseAgentID) {
348
+ const visited = new UUIDSet([agent.ID]);
349
+ let currentBaseId = agent.BaseAgentID;
350
+ let depth = 0;
351
+ while (currentBaseId && depth < MAX_INHERITANCE_DEPTH) {
352
+ if (visited.Has(currentBaseId)) {
353
+ direct.canRun = false;
354
+ break;
355
+ }
356
+ visited.Add(currentBaseId);
357
+ const ancestor = allAgents.find((a) => UUIDsEqual(a.ID, currentBaseId));
358
+ if (!ancestor) {
359
+ direct.canRun = false;
360
+ break;
361
+ }
362
+ const ancDirect = this.computeDirectPermissions(ancestor, allPermissions, user, userRoleIds);
363
+ if (!ancDirect.canRun) {
364
+ direct.canRun = false;
365
+ break;
366
+ }
367
+ currentBaseId = ancestor.BaseAgentID;
368
+ depth++;
369
+ }
370
+ if (currentBaseId && depth >= MAX_INHERITANCE_DEPTH) {
371
+ direct.canRun = false;
372
+ }
373
+ }
374
+ return direct;
375
+ }
299
376
  /**
300
377
  * Checks if a user has a specific permission for an agent.
301
378
  * @param agentId - The ID of the agent to check
@@ -320,16 +397,7 @@ var AIAgentPermissionHelper = class {
320
397
  }
321
398
  /**
322
399
  * Gets the aggregate permissions for a user on a specific agent.
323
- * Implements hierarchical permission logic:
324
- * - Delete implies Edit, Run, and View
325
- * - Edit implies Run and View
326
- * - Run implies View
327
- *
328
- * Default behavior when no permission records exist:
329
- * - Anyone can View and Run (open by default)
330
- * - Only owner can Edit and Delete
331
- *
332
- * Checks ownership first, then combines all matching user and role permissions.
400
+ * Enforces the 2x2 RBAC matrix and the Ancestor `CanRun` Invariant across `BaseAgentID`.
333
401
  * @param agentId - The ID of the agent
334
402
  * @param user - The user to check permissions for
335
403
  * @returns Object containing all effective permissions and ownership status
@@ -337,49 +405,12 @@ var AIAgentPermissionHelper = class {
337
405
  static async GetEffectivePermissions(agentId, user) {
338
406
  try {
339
407
  await AIEngineBase.Instance.Config(false, user);
340
- const agent = AIEngineBase.Instance.Agents.find((a) => UUIDsEqual(a.ID, agentId));
408
+ const allAgents = AIEngineBase.Instance.Agents;
409
+ const agent = allAgents.find((a) => UUIDsEqual(a.ID, agentId));
341
410
  if (!agent) {
342
411
  throw new Error(`Agent ${agentId} not found in cached metadata`);
343
412
  }
344
- const isOwner = UUIDsEqual(agent.OwnerUserID, user.ID);
345
- if (isOwner) {
346
- return {
347
- canView: true,
348
- canRun: true,
349
- canEdit: true,
350
- canDelete: true,
351
- isOwner: true
352
- };
353
- }
354
- const agentPermissions = AIEngineBase.Instance.AgentPermissions.filter((p) => UUIDsEqual(p.AgentID, agentId));
355
- if (agentPermissions.length === 0) {
356
- return {
357
- canView: true,
358
- canRun: true,
359
- canEdit: false,
360
- // Only owner can edit
361
- canDelete: false,
362
- // Only owner can delete
363
- isOwner: false
364
- };
365
- }
366
- const userRoleIds = user.UserRoles?.map((ur) => ur.RoleID) || [];
367
- const matchingPermissions = agentPermissions.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID && userRoleIds.some((rid) => UUIDsEqual(rid, p.RoleID)));
368
- const hasDelete = matchingPermissions.some((p) => p.CanDelete === true);
369
- const hasEdit = matchingPermissions.some((p) => p.CanEdit === true);
370
- const hasRun = matchingPermissions.some((p) => p.CanRun === true);
371
- const hasView = matchingPermissions.some((p) => p.CanView === true);
372
- const canDelete = hasDelete;
373
- const canEdit = hasDelete || hasEdit;
374
- const canRun = hasDelete || hasEdit || hasRun;
375
- const canView = hasDelete || hasEdit || hasRun || hasView;
376
- return {
377
- canView,
378
- canRun,
379
- canEdit,
380
- canDelete,
381
- isOwner: false
382
- };
413
+ return this.ComputeEffectivePermissionsSync(agent, allAgents, AIEngineBase.Instance.AgentPermissions, user);
383
414
  } catch (error) {
384
415
  LogError(`Error getting effective permissions for agent: ${error instanceof Error ? error.message : String(error)}`);
385
416
  return {
@@ -433,14 +464,15 @@ var AIAgentPermissionHelper = class {
433
464
  return includeInactive ? runnable : runnable.filter((a) => a.Status === "Active");
434
465
  }
435
466
  /**
436
- * Whether an agent is meant to be found and delegated to directly. Sub-Agents and child agents
437
- * are meant to be called by other agents, not discovered directly, so an agent whose
438
- * InvocationMode is 'Sub-Agent', or that has a ParentID, is not.
467
+ * Whether an agent is meant to be found and delegated to directly. Sub-Agents, child agents
468
+ * (`ParentID`), and instantiation-required prototype templates (`InstantiationMode === 'Required'`)
469
+ * are not directly discoverable for ad-hoc delegation — users and orchestrators like Sage
470
+ * delegate to the user's materialized derived instance instead.
439
471
  * @param agent - The agent to check
440
472
  * @returns True when the agent can be discovered directly
441
473
  */
442
474
  static IsDirectlyDiscoverable(agent) {
443
- return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID;
475
+ return agent.InvocationMode !== "Sub-Agent" && !agent.ParentID && agent.InstantiationMode !== "Required";
444
476
  }
445
477
  /**
446
478
  * Clears the AIEngineBase cache. Useful when permissions have been modified.
@@ -506,34 +538,15 @@ var AISkillPermissionHelper = class {
506
538
  }
507
539
  /**
508
540
  * Synchronous core of the permission calculation, operating on already-loaded cache arrays.
509
- * Exposed so hot-path callers (e.g. `AIEngineBase.GetSkillsForAgent(agent, user)`) can filter
510
- * without an async round-trip once the engine is configured.
541
+ * Delegates directly to {@link ComputeDirectAISkillPermissions} in `@memberjunction/core-entities`
542
+ * so graph access policies and `AISkillPermissionHelper` share one single source of truth (Finding 308).
511
543
  *
512
544
  * @param skill - The skill entity (owner is `CreatedByUserID`).
513
545
  * @param allPermissions - The full `SkillPermissions` cache (filtered internally by skill).
514
546
  * @param user - The user to evaluate for.
515
547
  */
516
548
  static ComputeEffectivePermissions(skill, allPermissions, user) {
517
- if (UUIDsEqual(skill.CreatedByUserID, user.ID)) {
518
- return { canView: true, canRun: true, canEdit: true, canDelete: true, isOwner: true };
519
- }
520
- const skillPermissions = allPermissions.filter((p) => UUIDsEqual(p.SkillID, skill.ID));
521
- if (skillPermissions.length === 0) {
522
- return { canView: true, canRun: true, canEdit: false, canDelete: false, isOwner: false };
523
- }
524
- const userRoleIds = user.UserRoles?.map((ur) => ur.RoleID) ?? [];
525
- const matching = skillPermissions.filter((p) => p.UserID && UUIDsEqual(p.UserID, user.ID) || p.RoleID && userRoleIds.some((rid) => UUIDsEqual(rid, p.RoleID)));
526
- const hasDelete = matching.some((p) => p.CanDelete === true);
527
- const hasEdit = matching.some((p) => p.CanEdit === true);
528
- const hasRun = matching.some((p) => p.CanRun === true);
529
- const hasView = matching.some((p) => p.CanView === true);
530
- return {
531
- canDelete: hasDelete,
532
- canEdit: hasDelete || hasEdit,
533
- canRun: hasDelete || hasEdit || hasRun,
534
- canView: hasDelete || hasEdit || hasRun || hasView,
535
- isOwner: false
536
- };
549
+ return ComputeDirectAISkillPermissions(skill, allPermissions, user);
537
550
  }
538
551
  /**
539
552
  * Gets all skills a user can access with at least the given permission level, from cache.
@@ -606,6 +619,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
606
619
  this._agents = [];
607
620
  this._agentRelationships = [];
608
621
  this._agentTypes = [];
622
+ this._agentStepTypes = [];
609
623
  this._agentRequestTypes = [];
610
624
  this._vendorTypeDefinitions = [];
611
625
  this._vendors = [];
@@ -655,8 +669,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
655
669
  this._agentsByID = null;
656
670
  this._agentsByName = null;
657
671
  this._childAgentsByParentID = null;
672
+ this._agentInheritanceChainCache = /* @__PURE__ */ new Map();
658
673
  this._agentsIndexedRef = null;
659
674
  this._agentsIndexedLen = -1;
675
+ this._preferredPrimaryByGroup = /* @__PURE__ */ new Map();
660
676
  this._agentRelationshipsByAgentID = null;
661
677
  this._agentRelationshipsIndexedRef = null;
662
678
  this._agentRelationshipsIndexedLen = -1;
@@ -741,6 +757,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
741
757
  PropertyName: "_agentNotes",
742
758
  EntityName: "MJ: AI Agent Notes",
743
759
  CacheLocal: true,
760
+ Filter: AIEngineBase_1.INJECTABLE_NOTE_FILTER,
744
761
  // Binary vector column: loaded server-side (the AIEngine reads it), skipped over the wire.
745
762
  IncludeBinaryFields: "DatabaseProviderOnly"
746
763
  },
@@ -973,6 +990,11 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
973
990
  PropertyName: "_agentPersonas",
974
991
  EntityName: "MJ: AI Agent Personas",
975
992
  CacheLocal: true
993
+ },
994
+ {
995
+ PropertyName: "_agentStepTypes",
996
+ EntityName: "MJ: AI Agent Step Types",
997
+ CacheLocal: true
976
998
  }
977
999
  ];
978
1000
  for (const config of conditional) {
@@ -984,13 +1006,235 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
984
1006
  }
985
1007
  }
986
1008
  static {
987
- this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set(["_vectorIndexes"]);
1009
+ this.INJECTABLE_NOTE_STATUSES = [
1010
+ "Active",
1011
+ "Provisional"
1012
+ ];
1013
+ }
1014
+ static {
1015
+ this.INJECTABLE_NOTE_FILTER = {
1016
+ logic: "or",
1017
+ filters: AIEngineBase_1.INJECTABLE_NOTE_STATUSES.map((status) => ({
1018
+ field: "Status",
1019
+ operator: "eq",
1020
+ value: status
1021
+ }))
1022
+ };
1023
+ }
1024
+ static {
1025
+ this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set([
1026
+ "_vectorIndexes",
1027
+ "_agentPersonas",
1028
+ "_agentPermissions",
1029
+ "_agentNotes"
1030
+ ]);
988
1031
  }
989
1032
  canUseImmediateMutation(config, skipAdditionalLoadingCheck = false) {
990
1033
  const independent = AIEngineBase_1.IMMEDIATE_MUTATION_PROPERTIES.has(config.PropertyName);
991
1034
  return super.canUseImmediateMutation(config, skipAdditionalLoadingCheck || independent);
992
1035
  }
1036
+ NotifyDataChange(config, data, changeType = "refresh", affectedEntity) {
1037
+ if (config.PropertyName === "_agentNotes" && changeType !== "refresh") {
1038
+ this.syncAgentNotesCollections();
1039
+ }
1040
+ super.NotifyDataChange(config, data, changeType, affectedEntity);
1041
+ }
1042
+ static {
1043
+ this.MAX_SPREAD_SPLICE_LENGTH = 3e4;
1044
+ }
1045
+ /**
1046
+ * Re-synchronizes each cached agent's `.Notes` array from `this._agentNotes` in memory after an
1047
+ * immediate or remote `_agentNotes` mutation without triggering a full-table reload.
1048
+ */
1049
+ syncAgentNotesCollections() {
1050
+ const notesByAgent = /* @__PURE__ */ new Map();
1051
+ for (const note of this._agentNotes) {
1052
+ const key = note.AgentID ? NormalizeUUID(note.AgentID) : "";
1053
+ const bucket = notesByAgent.get(key);
1054
+ if (bucket) {
1055
+ bucket.push(note);
1056
+ } else {
1057
+ notesByAgent.set(key, [note]);
1058
+ }
1059
+ }
1060
+ for (const agent of this._agents) {
1061
+ if (!agent.Notes)
1062
+ continue;
1063
+ const nextNotes = notesByAgent.get(NormalizeUUID(agent.ID)) ?? [];
1064
+ if (nextNotes.length <= AIEngineBase_1.MAX_SPREAD_SPLICE_LENGTH) {
1065
+ agent.Notes.splice(0, agent.Notes.length, ...nextNotes);
1066
+ } else {
1067
+ agent.Notes.length = 0;
1068
+ for (const item of nextNotes)
1069
+ agent.Notes.push(item);
1070
+ }
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Intercepts `MJ: AI Agents`, `MJ: AI Agent Personas`, and `MJ: AI Agent Permissions` events so
1075
+ * in-memory caches (`_agents`, `_agentsByID`, `_userRunnableAgentDirectoryCache`, and sibling
1076
+ * `IsPrimaryInstance` flags) update synchronously at `t = 0ms` without waiting for BaseEngine's
1077
+ * 1.5s debounced full reload — enabling immediate UI reflection of avatar (`LogoURL` / `IconClass`),
1078
+ * name, persona, and primary-instance edits without a browser refresh.
1079
+ */
1080
+ async HandleIndividualBaseEntityEvent(event) {
1081
+ let shouldEmitAgentsChange = false;
1082
+ const isSave = event.type === "save";
1083
+ const isDelete = event.type === "delete";
1084
+ const isRemoteInvalidate = event.type === "remote-invalidate";
1085
+ const localEntityName = event.baseEntity?.EntityInfo?.Name?.trim().toLowerCase() ?? "";
1086
+ const remoteEntityName = event.entityName?.trim().toLowerCase() ?? "";
1087
+ if (isSave && localEntityName === "mj: ai agents" && event.baseEntity) {
1088
+ const savedAgent = event.baseEntity;
1089
+ this.applyImmediateAgentUpsert(savedAgent);
1090
+ if (this.isActiveDerivedPrimaryAgent(savedAgent)) {
1091
+ this.demotePrimarySiblingsForAgent(savedAgent);
1092
+ }
1093
+ shouldEmitAgentsChange = true;
1094
+ } else if (isDelete && localEntityName === "mj: ai agents" && event.baseEntity) {
1095
+ const deletedAgent = event.baseEntity;
1096
+ shouldEmitAgentsChange = this.applyImmediateAgentDelete(deletedAgent.ID);
1097
+ } else if (isRemoteInvalidate && remoteEntityName === "mj: ai agents") {
1098
+ this.recordPreferredPrimaryFromRemotePayload(event.payload);
1099
+ } else if ((isSave || isDelete || isRemoteInvalidate) && (localEntityName === "mj: ai agent permissions" || remoteEntityName === "mj: ai agent permissions")) {
1100
+ this.invalidateUserRunnableAgentDirectoryCache();
1101
+ }
1102
+ const result = await super.HandleIndividualBaseEntityEvent(event);
1103
+ if (shouldEmitAgentsChange) {
1104
+ this.emitPropertyChange("_agents");
1105
+ }
1106
+ return result;
1107
+ }
1108
+ /**
1109
+ * Synchronously patches or inserts a just-saved `MJ: AI Agents` entity into `this._agents` and
1110
+ * invalidates derived agent indexes so `GetAgentByID` / `Agents` immediately reflect updated
1111
+ * `LogoURL`, `IconClass`, `Name`, `Description`, `AdditionalInstructions`, `Status`, and
1112
+ * `IsPrimaryInstance` before BaseEngine's background reload settles.
1113
+ */
1114
+ applyImmediateAgentUpsert(savedAgent) {
1115
+ if (!savedAgent?.ID) {
1116
+ return;
1117
+ }
1118
+ const existingIdx = this._agents.findIndex((a) => UUIDsEqual(a.ID, savedAgent.ID));
1119
+ if (existingIdx >= 0) {
1120
+ const existing = this._agents[existingIdx];
1121
+ if (existing !== savedAgent) {
1122
+ this.syncAgentScalarFieldsInPlace(existing, savedAgent);
1123
+ if (typeof savedAgent.Actions !== "undefined") {
1124
+ if (existing.Notes?.length && (!savedAgent.Notes || savedAgent.Notes.length === 0)) {
1125
+ savedAgent.Notes.splice(0, savedAgent.Notes.length, ...existing.Notes);
1126
+ }
1127
+ this._agents[existingIdx] = savedAgent;
1128
+ }
1129
+ }
1130
+ } else {
1131
+ this._agents.push(savedAgent);
1132
+ }
1133
+ this.invalidateAgentLookupIndexes();
1134
+ }
1135
+ applyImmediateAgentDelete(agentId) {
1136
+ if (!agentId) {
1137
+ return false;
1138
+ }
1139
+ const existingIdx = this._agents.findIndex((a) => UUIDsEqual(a.ID, agentId));
1140
+ if (existingIdx < 0) {
1141
+ return false;
1142
+ }
1143
+ this._agents.splice(existingIdx, 1);
1144
+ this.invalidateAgentLookupIndexes();
1145
+ return true;
1146
+ }
1147
+ syncAgentScalarFieldsInPlace(target, source) {
1148
+ const touchedFields = [];
1149
+ if (source.Name !== void 0) {
1150
+ target.Name = source.Name;
1151
+ touchedFields.push("Name");
1152
+ }
1153
+ if (source.Description !== void 0) {
1154
+ target.Description = source.Description;
1155
+ touchedFields.push("Description");
1156
+ }
1157
+ if (source.LogoURL !== void 0) {
1158
+ target.LogoURL = source.LogoURL;
1159
+ touchedFields.push("LogoURL");
1160
+ }
1161
+ if (source.IconClass !== void 0) {
1162
+ target.IconClass = source.IconClass;
1163
+ touchedFields.push("IconClass");
1164
+ }
1165
+ if (source.ParentID !== void 0) {
1166
+ target.ParentID = source.ParentID;
1167
+ touchedFields.push("ParentID");
1168
+ }
1169
+ if (source.BaseAgentID !== void 0) {
1170
+ target.BaseAgentID = source.BaseAgentID;
1171
+ touchedFields.push("BaseAgentID");
1172
+ }
1173
+ if (source.OwnerUserID !== void 0) {
1174
+ target.OwnerUserID = source.OwnerUserID;
1175
+ touchedFields.push("OwnerUserID");
1176
+ }
1177
+ if (source.InstantiationMode !== void 0) {
1178
+ target.InstantiationMode = source.InstantiationMode;
1179
+ touchedFields.push("InstantiationMode");
1180
+ }
1181
+ if (source.IsPrimaryInstance !== void 0) {
1182
+ target.IsPrimaryInstance = source.IsPrimaryInstance;
1183
+ touchedFields.push("IsPrimaryInstance");
1184
+ }
1185
+ if (source.AdditionalInstructions !== void 0) {
1186
+ target.AdditionalInstructions = source.AdditionalInstructions;
1187
+ touchedFields.push("AdditionalInstructions");
1188
+ }
1189
+ if (source.Status !== void 0) {
1190
+ target.Status = source.Status;
1191
+ touchedFields.push("Status");
1192
+ }
1193
+ if (source.TypeID !== void 0) {
1194
+ target.TypeID = source.TypeID;
1195
+ touchedFields.push("TypeID");
1196
+ }
1197
+ if (source.TypeConfiguration !== void 0) {
1198
+ target.TypeConfiguration = source.TypeConfiguration;
1199
+ touchedFields.push("TypeConfiguration");
1200
+ }
1201
+ if (source.InvocationMode !== void 0) {
1202
+ target.InvocationMode = source.InvocationMode;
1203
+ touchedFields.push("InvocationMode");
1204
+ }
1205
+ if (source.CategoryID !== void 0) {
1206
+ target.CategoryID = source.CategoryID;
1207
+ touchedFields.push("CategoryID");
1208
+ }
1209
+ if (source.IsRestricted !== void 0) {
1210
+ target.IsRestricted = source.IsRestricted;
1211
+ touchedFields.push("IsRestricted");
1212
+ }
1213
+ if (typeof target.GetFieldByName === "function") {
1214
+ for (const fieldName of touchedFields) {
1215
+ target.GetFieldByName(fieldName)?.ResetOldValue();
1216
+ }
1217
+ }
1218
+ }
1219
+ invalidateAgentLookupIndexes() {
1220
+ this._agentsByID = null;
1221
+ this._agentsByName = null;
1222
+ this._childAgentsByParentID = null;
1223
+ this._agentInheritanceChainCache.clear();
1224
+ this._agentsIndexedRef = null;
1225
+ this._agentsIndexedLen = -1;
1226
+ this.invalidateUserRunnableAgentDirectoryCache();
1227
+ }
1228
+ invalidateUserRunnableAgentDirectoryCache() {
1229
+ this._userRunnableAgentDirectoryCache.clear();
1230
+ this._userRunnableAgentsRef = null;
1231
+ this._userRunnableAgentsLen = -1;
1232
+ this._userRunnablePermissionsRef = null;
1233
+ this._userRunnablePermissionsLen = -1;
1234
+ }
993
1235
  async AdditionalLoading(contextUser) {
1236
+ this.normalizeExclusivePrimaryInstances();
1237
+ this._preferredPrimaryByGroup.clear();
994
1238
  this._configurationChainCache.clear();
995
1239
  this._userRunnableAgentDirectoryCache.clear();
996
1240
  this._userRunnableAgentsRef = null;
@@ -1008,6 +1252,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1008
1252
  this._agentsByID = null;
1009
1253
  this._agentsByName = null;
1010
1254
  this._childAgentsByParentID = null;
1255
+ this._agentInheritanceChainCache.clear();
1011
1256
  this._agentsIndexedRef = null;
1012
1257
  this._agentsIndexedLen = -1;
1013
1258
  this._agentRelationshipsByAgentID = null;
@@ -1050,7 +1295,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1050
1295
  };
1051
1296
  const keyFor = (id) => id ? id.toUpperCase() : "";
1052
1297
  const replaceContents = (target, next) => {
1053
- if (next.length <= 3e4) {
1298
+ if (next.length <= AIEngineBase_1.MAX_SPREAD_SPLICE_LENGTH) {
1054
1299
  target.splice(0, target.length, ...next);
1055
1300
  return;
1056
1301
  }
@@ -1079,6 +1324,190 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1079
1324
  replaceContents(model.ModelVendors, vendorsByModel.get(keyFor(model.ID)) ?? []);
1080
1325
  }
1081
1326
  }
1327
+ isActiveDerivedPrimaryAgent(agent) {
1328
+ return Boolean(agent && agent.Status === "Active" && agent.BaseAgentID != null && agent.BaseAgentID.length > 0 && agent.OwnerUserID != null && agent.OwnerUserID.length > 0 && agent.IsPrimaryInstance === true);
1329
+ }
1330
+ /**
1331
+ * Resolves the top-level root base agent ID for a derived agent by walking `BaseAgentID` links
1332
+ * through `agentsById` with cycle protection. When an ancestor row is not present in `agentsById`,
1333
+ * returns the highest referenced `BaseAgentID` so siblings pointing to the same template still match.
1334
+ */
1335
+ resolveRootBaseAgentIdForSync(agent, agentsById) {
1336
+ let currentBaseId = agent.BaseAgentID;
1337
+ if (!currentBaseId) {
1338
+ return null;
1339
+ }
1340
+ const visited = /* @__PURE__ */ new Set([NormalizeUUID(agent.ID)]);
1341
+ let depth = 0;
1342
+ while (currentBaseId && depth < MAX_AGENT_INHERITANCE_DEPTH) {
1343
+ const normCurrent = NormalizeUUID(currentBaseId);
1344
+ if (visited.has(normCurrent)) {
1345
+ break;
1346
+ }
1347
+ visited.add(normCurrent);
1348
+ const parent = agentsById.get(normCurrent);
1349
+ if (!parent || !parent.BaseAgentID) {
1350
+ return currentBaseId;
1351
+ }
1352
+ currentBaseId = parent.BaseAgentID;
1353
+ depth++;
1354
+ }
1355
+ return currentBaseId;
1356
+ }
1357
+ primaryGroupKey(ownerUserId, rootBaseAgentId) {
1358
+ return `${NormalizeUUID(ownerUserId)}::${NormalizeUUID(rootBaseAgentId)}`;
1359
+ }
1360
+ /**
1361
+ * Sets `IsPrimaryInstance = false` on a cached agent without leaving a real `BaseEntity` marked dirty.
1362
+ */
1363
+ setCachedAgentPrimaryFlag(agent, isPrimary) {
1364
+ agent.IsPrimaryInstance = isPrimary;
1365
+ if (typeof agent.GetFieldByName === "function") {
1366
+ agent.GetFieldByName("IsPrimaryInstance")?.ResetOldValue();
1367
+ }
1368
+ }
1369
+ /**
1370
+ * Records an incoming remote-invalidate save payload as the preferred primary winner for its
1371
+ * `(OwnerUserID, RootBaseAgentID)` group before `applyRemoteRecordData` invokes `AdditionalLoading`.
1372
+ */
1373
+ recordPreferredPrimaryFromRemotePayload(payload) {
1374
+ if (typeof payload !== "object" || payload === null) {
1375
+ return;
1376
+ }
1377
+ const remote = payload;
1378
+ if (remote.action !== "save" || typeof remote.recordData !== "string") {
1379
+ return;
1380
+ }
1381
+ try {
1382
+ const parsed = JSON.parse(remote.recordData);
1383
+ if (!parsed || !parsed.ID || !this.isActiveDerivedPrimaryAgent(parsed)) {
1384
+ return;
1385
+ }
1386
+ const agentsById = /* @__PURE__ */ new Map();
1387
+ for (const a of this._agents) {
1388
+ agentsById.set(NormalizeUUID(a.ID), a);
1389
+ }
1390
+ const rootId = this.resolveRootBaseAgentIdForSync({ ID: parsed.ID, BaseAgentID: parsed.BaseAgentID ?? null }, agentsById);
1391
+ if (rootId && parsed.OwnerUserID) {
1392
+ this._preferredPrimaryByGroup.set(this.primaryGroupKey(parsed.OwnerUserID, rootId), NormalizeUUID(parsed.ID));
1393
+ }
1394
+ } catch {
1395
+ }
1396
+ }
1397
+ /**
1398
+ * Immediately demotes all active cached siblings sharing `(OwnerUserID, RootBaseAgentID)` with
1399
+ * `savedAgent` and records `savedAgent.ID` as the preferred primary winner for upcoming reloads.
1400
+ */
1401
+ demotePrimarySiblingsForAgent(savedAgent) {
1402
+ if (!this.isActiveDerivedPrimaryAgent(savedAgent) || !savedAgent.OwnerUserID) {
1403
+ return false;
1404
+ }
1405
+ const agentsById = /* @__PURE__ */ new Map();
1406
+ for (const a of this._agents) {
1407
+ agentsById.set(NormalizeUUID(a.ID), a);
1408
+ }
1409
+ agentsById.set(NormalizeUUID(savedAgent.ID), savedAgent);
1410
+ const targetRootId = this.resolveRootBaseAgentIdForSync(savedAgent, agentsById);
1411
+ if (!targetRootId) {
1412
+ return false;
1413
+ }
1414
+ const groupKey = this.primaryGroupKey(savedAgent.OwnerUserID, targetRootId);
1415
+ this._preferredPrimaryByGroup.set(groupKey, NormalizeUUID(savedAgent.ID));
1416
+ let mutated = false;
1417
+ for (const candidate of this._agents) {
1418
+ if (UUIDsEqual(candidate.ID, savedAgent.ID)) {
1419
+ if (candidate.IsPrimaryInstance !== true) {
1420
+ this.setCachedAgentPrimaryFlag(candidate, true);
1421
+ mutated = true;
1422
+ }
1423
+ continue;
1424
+ }
1425
+ if (!this.isActiveDerivedPrimaryAgent(candidate) || !candidate.OwnerUserID) {
1426
+ continue;
1427
+ }
1428
+ if (!UUIDsEqual(candidate.OwnerUserID, savedAgent.OwnerUserID)) {
1429
+ continue;
1430
+ }
1431
+ const candidateRootId = this.resolveRootBaseAgentIdForSync(candidate, agentsById);
1432
+ if (candidateRootId && UUIDsEqual(candidateRootId, targetRootId)) {
1433
+ this.setCachedAgentPrimaryFlag(candidate, false);
1434
+ mutated = true;
1435
+ }
1436
+ }
1437
+ return mutated;
1438
+ }
1439
+ /**
1440
+ * Ensures at most one active derived agent per `(OwnerUserID, RootBaseAgentID)` has
1441
+ * `IsPrimaryInstance === true` inside `this._agents`. Prefers any agent recorded via
1442
+ * `_preferredPrimaryByGroup` (from a just-saved or remote-invalidated row), otherwise keeps
1443
+ * the most recently updated row (`__mj_UpdatedAt`, falling back to `__mj_CreatedAt`).
1444
+ */
1445
+ normalizeExclusivePrimaryInstances() {
1446
+ if (!this._agents || this._agents.length < 2) {
1447
+ return false;
1448
+ }
1449
+ const agentsById = /* @__PURE__ */ new Map();
1450
+ for (const agent of this._agents) {
1451
+ agentsById.set(NormalizeUUID(agent.ID), agent);
1452
+ }
1453
+ const primaryGroups = /* @__PURE__ */ new Map();
1454
+ for (const agent of this._agents) {
1455
+ if (!this.isActiveDerivedPrimaryAgent(agent) || !agent.OwnerUserID) {
1456
+ continue;
1457
+ }
1458
+ const rootId = this.resolveRootBaseAgentIdForSync(agent, agentsById);
1459
+ if (!rootId) {
1460
+ continue;
1461
+ }
1462
+ const key = this.primaryGroupKey(agent.OwnerUserID, rootId);
1463
+ const bucket = primaryGroups.get(key);
1464
+ if (bucket) {
1465
+ bucket.push(agent);
1466
+ } else {
1467
+ primaryGroups.set(key, [agent]);
1468
+ }
1469
+ }
1470
+ let mutated = false;
1471
+ for (const [groupKey, bucket] of primaryGroups.entries()) {
1472
+ if (bucket.length < 2) {
1473
+ continue;
1474
+ }
1475
+ const preferredId = this._preferredPrimaryByGroup.get(groupKey);
1476
+ let winner = preferredId ? IndexByUUID(bucket).Get(preferredId) : void 0;
1477
+ if (!winner) {
1478
+ const sorted = [...bucket].sort((a, b) => {
1479
+ const updatedDiff = this.agentTimestampMs(b.__mj_UpdatedAt) - this.agentTimestampMs(a.__mj_UpdatedAt);
1480
+ if (updatedDiff !== 0) {
1481
+ return updatedDiff;
1482
+ }
1483
+ const createdDiff = this.agentTimestampMs(b.__mj_CreatedAt) - this.agentTimestampMs(a.__mj_CreatedAt);
1484
+ if (createdDiff !== 0) {
1485
+ return createdDiff;
1486
+ }
1487
+ return a.ID.localeCompare(b.ID);
1488
+ });
1489
+ winner = sorted[0];
1490
+ }
1491
+ for (const agent of bucket) {
1492
+ if (!UUIDsEqual(agent.ID, winner.ID)) {
1493
+ this.setCachedAgentPrimaryFlag(agent, false);
1494
+ mutated = true;
1495
+ }
1496
+ }
1497
+ }
1498
+ return mutated;
1499
+ }
1500
+ agentTimestampMs(value) {
1501
+ if (!value) {
1502
+ return 0;
1503
+ }
1504
+ if (value instanceof Date) {
1505
+ const ms = value.getTime();
1506
+ return Number.isFinite(ms) ? ms : 0;
1507
+ }
1508
+ const parsed = Date.parse(value);
1509
+ return Number.isFinite(parsed) ? parsed : 0;
1510
+ }
1082
1511
  /**
1083
1512
  * The collections {@link AdditionalLoading} attaches to parents. When these read zero while
1084
1513
  * the child arrays are full, the derived state has been lost — the failure that row counts
@@ -1296,40 +1725,1333 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1296
1725
  * @returns MJAIAgentEntityExtended[] - Array of sub-agent entities matching the criteria (deduplicated by ID).
1297
1726
  * @memberof
1298
1727
  */
1728
+ /**
1729
+ * Resolves effective `MJAIAgentRelationshipEntity` rows for `agentID` along its `BaseAgentID`
1730
+ * inheritance chain (root -> leaf, keyed by `SubAgentID`).
1731
+ *
1732
+ * - On derived hops without `allowWidenFromBase: true`, only vetoes (`Status !== relStatus`) or
1733
+ * narrowing overrides on already-inherited `SubAgentID`s are applied (`MessageMode` via min rank,
1734
+ * `MaxMessages` via `Math.min`, `SubAgentContextPaths` via glob intersection); net-new
1735
+ * `SubAgentID` rows are ignored.
1736
+ * - On derived hops with `allowWidenFromBase: true`, active rows may add net-new `SubAgentID`s
1737
+ * and rebase per-relationship bounds.
1738
+ */
1739
+ GetEffectiveAgentRelationships(agentID, relationshipStatus) {
1740
+ this.ensureAgentsIndex();
1741
+ this.ensureAgentRelationshipsIndex();
1742
+ const chain = this.GetAgentInheritanceChain(agentID);
1743
+ const relStatus = relationshipStatus ?? "Active";
1744
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
1745
+ id: NormalizeUUID(a.ID),
1746
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
1747
+ })) : [{ id: NormalizeUUID(agentID), canWiden: false }];
1748
+ const parsePaths = (raw) => {
1749
+ if (!raw || raw.trim().length === 0)
1750
+ return null;
1751
+ try {
1752
+ const parsed = JSON.parse(raw);
1753
+ if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
1754
+ return parsed;
1755
+ }
1756
+ } catch {
1757
+ }
1758
+ return null;
1759
+ };
1760
+ const effectiveBySubId = /* @__PURE__ */ new Map();
1761
+ for (let idx = 0; idx < nodes.length; idx++) {
1762
+ const { id: normChainAgentId, canWiden } = nodes[idx];
1763
+ const isRoot = idx === 0;
1764
+ const rawRelationships = this._agentRelationshipsByAgentID.get(normChainAgentId) ?? [];
1765
+ for (const ar of rawRelationships) {
1766
+ if (!ar.SubAgentID)
1767
+ continue;
1768
+ const normSubId = NormalizeUUID(ar.SubAgentID);
1769
+ if (ar.Status !== relStatus) {
1770
+ effectiveBySubId.delete(normSubId);
1771
+ continue;
1772
+ }
1773
+ const prev = effectiveBySubId.get(normSubId);
1774
+ if (!prev) {
1775
+ if (isRoot || canWiden) {
1776
+ effectiveBySubId.set(normSubId, ar);
1777
+ }
1778
+ continue;
1779
+ }
1780
+ if (canWiden) {
1781
+ effectiveBySubId.set(normSubId, ar);
1782
+ continue;
1783
+ }
1784
+ const narrowedMsgMode = AGENT_MESSAGE_MODE_RANK[ar.MessageMode] < AGENT_MESSAGE_MODE_RANK[prev.MessageMode] ? ar.MessageMode : prev.MessageMode;
1785
+ const narrowedMaxMessages = typeof prev.MaxMessages === "number" && typeof ar.MaxMessages === "number" ? Math.min(prev.MaxMessages, ar.MaxMessages) : typeof ar.MaxMessages === "number" ? ar.MaxMessages : prev.MaxMessages;
1786
+ const prevCtx = parsePaths(prev.SubAgentContextPaths);
1787
+ const nextCtx = parsePaths(ar.SubAgentContextPaths);
1788
+ const narrowedCtx = IntersectPayloadPathSets(prevCtx, nextCtx);
1789
+ const narrowed = Object.create(ar);
1790
+ Object.defineProperty(narrowed, "MessageMode", { value: narrowedMsgMode, enumerable: true, configurable: true });
1791
+ Object.defineProperty(narrowed, "MaxMessages", { value: narrowedMaxMessages, enumerable: true, configurable: true });
1792
+ if (narrowedCtx !== null) {
1793
+ Object.defineProperty(narrowed, "SubAgentContextPaths", {
1794
+ value: JSON.stringify(narrowedCtx),
1795
+ enumerable: true,
1796
+ configurable: true
1797
+ });
1798
+ }
1799
+ effectiveBySubId.set(normSubId, narrowed);
1800
+ }
1801
+ }
1802
+ return Array.from(effectiveBySubId.values());
1803
+ }
1299
1804
  GetSubAgents(agentID, status, relationshipStatus) {
1300
1805
  this.ensureAgentsIndex();
1301
1806
  this.ensureAgentRelationshipsIndex();
1302
- const normAgentId = NormalizeUUID(agentID);
1303
- const rawChildAgents = this._childAgentsByParentID.get(normAgentId) ?? [];
1304
- const childAgents = status ? rawChildAgents.filter((a) => a.Status === status) : rawChildAgents;
1807
+ const chain = this.GetAgentInheritanceChain(agentID);
1808
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
1809
+ id: NormalizeUUID(a.ID),
1810
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
1811
+ })) : [{ id: NormalizeUUID(agentID), canWiden: false }];
1305
1812
  const relStatus = relationshipStatus ?? "Active";
1306
- const rawRelationships = this._agentRelationshipsByAgentID.get(normAgentId) ?? [];
1307
- const uniqueAgentIDs = /* @__PURE__ */ new Set();
1308
- const allSubAgents = [];
1309
- for (const agent of childAgents) {
1310
- const normId = NormalizeUUID(agent.ID);
1311
- if (!uniqueAgentIDs.has(normId)) {
1312
- uniqueAgentIDs.add(normId);
1313
- allSubAgents.push(agent);
1314
- }
1315
- }
1316
- for (const ar of rawRelationships) {
1317
- if (ar.Status !== relStatus || !ar.SubAgentID)
1813
+ const subAgentsById = /* @__PURE__ */ new Map();
1814
+ for (let idx = 0; idx < nodes.length; idx++) {
1815
+ const { id: normChainAgentId, canWiden } = nodes[idx];
1816
+ const isRoot = idx === 0;
1817
+ if (isRoot || canWiden) {
1818
+ const rawChildAgents = this._childAgentsByParentID.get(normChainAgentId) ?? [];
1819
+ const childAgents = status ? rawChildAgents.filter((a) => a.Status === status) : rawChildAgents;
1820
+ for (const child of childAgents) {
1821
+ const normChildId = NormalizeUUID(child.ID);
1822
+ if (!subAgentsById.has(normChildId)) {
1823
+ subAgentsById.set(normChildId, child);
1824
+ }
1825
+ }
1826
+ }
1827
+ const rawRelationships = this._agentRelationshipsByAgentID.get(normChainAgentId) ?? [];
1828
+ for (const ar of rawRelationships) {
1829
+ if (!ar.SubAgentID)
1830
+ continue;
1831
+ const normSubId = NormalizeUUID(ar.SubAgentID);
1832
+ if (ar.Status !== relStatus) {
1833
+ subAgentsById.delete(normSubId);
1834
+ continue;
1835
+ }
1836
+ if (!isRoot && !canWiden && !subAgentsById.has(normSubId)) {
1837
+ continue;
1838
+ }
1839
+ const subAgent = this._agentsByID.get(normSubId);
1840
+ if (subAgent && (!status || subAgent.Status === status)) {
1841
+ subAgentsById.set(normSubId, subAgent);
1842
+ }
1843
+ }
1844
+ }
1845
+ return Array.from(subAgentsById.values());
1846
+ }
1847
+ /**
1848
+ * Resolves the `BaseAgentID` prototype inheritance chain for `agentId`, ordered from
1849
+ * outermost prototype root down to the agent itself: `[rootAgent, ..., leafAgent]`.
1850
+ *
1851
+ * Cycle-safe and bounded to `MAX_AGENT_INHERITANCE_DEPTH` (5 hops, up to 6 nodes).
1852
+ * Memoized per loaded `_agents` snapshot.
1853
+ */
1854
+ GetAgentInheritanceChain(agentId) {
1855
+ if (!agentId) {
1856
+ return [];
1857
+ }
1858
+ this.ensureAgentsIndex();
1859
+ const normId = NormalizeUUID(agentId);
1860
+ const cached = this._agentInheritanceChainCache.get(normId);
1861
+ if (cached) {
1862
+ return cached.slice();
1863
+ }
1864
+ const leaf = this._agentsByID.get(normId);
1865
+ if (!leaf) {
1866
+ return [];
1867
+ }
1868
+ const chainFromLeaf = [leaf];
1869
+ const visited = new UUIDSet([leaf.ID]);
1870
+ let currentBaseId = leaf.BaseAgentID;
1871
+ let hops = 0;
1872
+ while (currentBaseId && hops < MAX_AGENT_INHERITANCE_DEPTH) {
1873
+ if (visited.Has(currentBaseId)) {
1874
+ break;
1875
+ }
1876
+ visited.Add(currentBaseId);
1877
+ const baseAgent = this._agentsByID.get(NormalizeUUID(currentBaseId));
1878
+ if (!baseAgent) {
1879
+ break;
1880
+ }
1881
+ chainFromLeaf.push(baseAgent);
1882
+ currentBaseId = baseAgent.BaseAgentID;
1883
+ hops++;
1884
+ }
1885
+ const ordered = chainFromLeaf.reverse();
1886
+ this._agentInheritanceChainCache.set(normId, ordered);
1887
+ return ordered.slice();
1888
+ }
1889
+ /**
1890
+ * Returns the top-level prototype root agent (`BaseAgentID == null`) for `agentId`,
1891
+ * or the agent itself if it is already a root agent.
1892
+ */
1893
+ GetRootAgent(agentId) {
1894
+ const chain = this.GetAgentInheritanceChain(agentId);
1895
+ return chain.length > 0 ? chain[0] : void 0;
1896
+ }
1897
+ /**
1898
+ * Builds the root-to-leaf inheritance chain for an already-provided `MJAIAgentEntityExtended`
1899
+ * instance, keeping `agent` itself as the leaf so caller-supplied in-memory field overrides
1900
+ * (such as tests cloning a cached agent with different `AcceptsSkills` / `SkillActivationMode`)
1901
+ * are never shadowed by the cached copy in `_agents`.
1902
+ */
1903
+ resolveInheritanceNodesForAgent(agent) {
1904
+ if (!agent.BaseAgentID) {
1905
+ return [agent];
1906
+ }
1907
+ const ancestors = this.GetAgentInheritanceChain(agent.BaseAgentID).filter((a) => !UUIDsEqual(a.ID, agent.ID));
1908
+ return [...ancestors, agent];
1909
+ }
1910
+ /**
1911
+ * Walks up the `AIAgentCategory.ParentID` hierarchy cycle-safely and returns
1912
+ * `[rootCategory, ..., directCategory]` so defaults can merge root -> leaf.
1913
+ */
1914
+ resolveCategoryChain(categoryId) {
1915
+ if (!categoryId) {
1916
+ return [];
1917
+ }
1918
+ const categoriesById = IndexByUUID(this.AgentCategories);
1919
+ const chain = [];
1920
+ const visited = new UUIDSet();
1921
+ let currentId = categoryId;
1922
+ while (currentId && !visited.Has(currentId)) {
1923
+ visited.Add(currentId);
1924
+ const cat = categoriesById.Get(currentId);
1925
+ if (!cat) {
1926
+ break;
1927
+ }
1928
+ chain.push(cat);
1929
+ currentId = cat.ParentID ?? null;
1930
+ }
1931
+ return chain.reverse();
1932
+ }
1933
+ /**
1934
+ * Resolves effective scalar properties, 3-table `IAgentConfiguration` cascade
1935
+ * (`Instance -> BaseAgent Chain -> Category -> Parent Categories -> AgentType -> System Default`),
1936
+ * and deep-merged `TypeConfiguration` / `AgentTypePromptParams`.
1937
+ *
1938
+ * Dual-reads `Configuration` JSON with seamless fallback to deprecated legacy columns,
1939
+ * and enforces narrow-only security invariants monotonically down the chain.
1940
+ */
1941
+ ResolveEffectiveAgentProperties(agentOrId) {
1942
+ const leaf = typeof agentOrId === "string" ? this.GetAgentByID(agentOrId) : agentOrId;
1943
+ const nodes = leaf ? this.resolveInheritanceNodesForAgent(leaf) : [];
1944
+ const root = nodes[0];
1945
+ const nodeConfigs = nodes.map((n) => ParseAgentConfiguration(n.Configuration));
1946
+ const nearestNonNull = (picker) => {
1947
+ for (let i = nodes.length - 1; i >= 0; i--) {
1948
+ const v = picker(nodes[i], nodeConfigs[i]);
1949
+ if (v !== null && v !== void 0 && (typeof v !== "string" || v.trim().length > 0)) {
1950
+ return v;
1951
+ }
1952
+ }
1953
+ return null;
1954
+ };
1955
+ const effectiveTypeId = nearestNonNull((a) => a.TypeID);
1956
+ const agentType = effectiveTypeId ? this.AgentTypes.find((at) => UUIDsEqual(at.ID, effectiveTypeId)) : void 0;
1957
+ const orderedDefaultLayers = [];
1958
+ let defaultsLayer = {};
1959
+ if (agentType) {
1960
+ const typeLegacy = BuildAgentTypeConfigurationFromLegacyFields(agentType);
1961
+ const typeJson = ParseAgentConfiguration(agentType.DefaultAgentConfiguration);
1962
+ const typeLayer = DeepMergeAgentConfigurations(typeLegacy, typeJson);
1963
+ if (Object.keys(typeLayer).length > 0) {
1964
+ orderedDefaultLayers.push(typeLayer);
1965
+ defaultsLayer = DeepMergeAgentConfigurations(defaultsLayer, typeLayer);
1966
+ }
1967
+ }
1968
+ const orderedCatEntries = [];
1969
+ for (const node of nodes) {
1970
+ if (!node.CategoryID) {
1318
1971
  continue;
1319
- const agent = this._agentsByID.get(NormalizeUUID(ar.SubAgentID));
1320
- if (agent && (!status || agent.Status === status)) {
1321
- const normId = NormalizeUUID(agent.ID);
1322
- if (!uniqueAgentIDs.has(normId)) {
1323
- uniqueAgentIDs.add(normId);
1324
- allSubAgents.push(agent);
1972
+ }
1973
+ const nodeCategoryChain = this.resolveCategoryChain(node.CategoryID);
1974
+ for (const cat of nodeCategoryChain) {
1975
+ const catJson = ParseAgentConfiguration(cat.DefaultConfiguration);
1976
+ if (catJson) {
1977
+ orderedCatEntries.push({ id: cat.ID, json: catJson });
1978
+ }
1979
+ }
1980
+ }
1981
+ const seenForNarrow = new UUIDSet();
1982
+ for (const entry of orderedCatEntries) {
1983
+ if (!seenForNarrow.Has(entry.id)) {
1984
+ seenForNarrow.Add(entry.id);
1985
+ orderedDefaultLayers.push(entry.json);
1986
+ }
1987
+ }
1988
+ const lastIndexByCatId = /* @__PURE__ */ new Map();
1989
+ for (let i = 0; i < orderedCatEntries.length; i++) {
1990
+ lastIndexByCatId.set(NormalizeUUID(orderedCatEntries[i].id), i);
1991
+ }
1992
+ for (let i = 0; i < orderedCatEntries.length; i++) {
1993
+ if (lastIndexByCatId.get(NormalizeUUID(orderedCatEntries[i].id)) === i) {
1994
+ defaultsLayer = DeepMergeAgentConfigurations(defaultsLayer, orderedCatEntries[i].json);
1995
+ }
1996
+ }
1997
+ const nearestOrDefault = (nodePicker, defaultValue) => {
1998
+ const fromNodes = nearestNonNull(nodePicker);
1999
+ if (fromNodes !== null) {
2000
+ return fromNodes;
2001
+ }
2002
+ if (defaultValue !== null && defaultValue !== void 0 && (typeof defaultValue !== "string" || defaultValue.trim().length > 0)) {
2003
+ return defaultValue;
2004
+ }
2005
+ return null;
2006
+ };
2007
+ let effectiveIsolation = "InProcess";
2008
+ for (const node of nodes) {
2009
+ const iso = node.Isolation ?? "InProcess";
2010
+ if ((AGENT_ISOLATION_RANK[iso] ?? 0) > (AGENT_ISOLATION_RANK[effectiveIsolation] ?? 0)) {
2011
+ effectiveIsolation = iso;
2012
+ }
2013
+ }
2014
+ const canWidenAt = (index) => index > 0 && nodeConfigs[index]?.allowWidenFromBase === true;
2015
+ const effectiveAcceptsSkills = FoldRebaseAwareChain({
2016
+ Nodes: nodes,
2017
+ NodeConfigs: nodeConfigs,
2018
+ Seed: root?.AcceptsSkills ?? "None",
2019
+ GetNodeValue: (node) => node.AcceptsSkills ?? void 0,
2020
+ Narrow: (acc, next) => (AGENT_ACCEPTS_SKILLS_RANK[next] ?? 0) < (AGENT_ACCEPTS_SKILLS_RANK[acc] ?? 0) ? next : acc
2021
+ });
2022
+ let seedSkillMode = null;
2023
+ const narrowSkillMode = (acc, val) => {
2024
+ if (val == null)
2025
+ return acc;
2026
+ if (acc === null || (AGENT_SKILL_ACTIVATION_RANK[val] ?? 0) < (AGENT_SKILL_ACTIVATION_RANK[acc] ?? 0)) {
2027
+ return val;
2028
+ }
2029
+ return acc;
2030
+ };
2031
+ for (const layer of orderedDefaultLayers) {
2032
+ seedSkillMode = narrowSkillMode(seedSkillMode, layer.skills?.activationMode);
2033
+ }
2034
+ if (nodes.length > 0) {
2035
+ seedSkillMode = narrowSkillMode(seedSkillMode, nodeConfigs[0]?.skills?.activationMode);
2036
+ seedSkillMode = narrowSkillMode(seedSkillMode, nodes[0].SkillActivationMode);
2037
+ }
2038
+ const resolvedSkillActivationMode = FoldRebaseAwareChain({
2039
+ Nodes: nodes,
2040
+ NodeConfigs: nodeConfigs,
2041
+ Seed: seedSkillMode,
2042
+ GetNodeValue: (node, cfg, idx) => {
2043
+ const explicit = cfg?.skills?.activationMode ?? null;
2044
+ const legacy = node.SkillActivationMode ?? null;
2045
+ if (canWidenAt(idx)) {
2046
+ if (explicit != null)
2047
+ return explicit;
2048
+ return legacy != null && legacy !== "RequestedOnly" ? legacy : void 0;
2049
+ }
2050
+ if (explicit != null && legacy != null) {
2051
+ return (AGENT_SKILL_ACTIVATION_RANK[legacy] ?? 0) < (AGENT_SKILL_ACTIVATION_RANK[explicit] ?? 0) ? legacy : explicit;
2052
+ }
2053
+ if (explicit != null)
2054
+ return explicit;
2055
+ const isNonInstantiableDerived = Boolean(node.BaseAgentID) && (node.InstantiationMode ?? "None") === "None";
2056
+ if (legacy != null && (legacy !== "RequestedOnly" || !isNonInstantiableDerived)) {
2057
+ return legacy;
2058
+ }
2059
+ return void 0;
2060
+ },
2061
+ Narrow: (acc, next) => narrowSkillMode(acc, next)
2062
+ }) ?? "RequestedOnly";
2063
+ const activePromptAgentIds = new UUIDSet(this._agentPrompts.filter((ap) => ap.Status === "Active").map((ap) => ap.AgentID));
2064
+ const leafHasOwnPrompts = leaf ? activePromptAgentIds.Has(leaf.ID) : false;
2065
+ const leafModelMode = (nodes.length > 0 ? nodeConfigs[nodes.length - 1]?.execution?.modelSelectionMode : null) ?? leaf?.ModelSelectionMode;
2066
+ let effectiveModelSelectionMode = leafModelMode ?? defaultsLayer.execution?.modelSelectionMode ?? "Agent Type";
2067
+ if (!leafHasOwnPrompts && nodes.length > 1) {
2068
+ for (let i = nodes.length - 1; i >= 0; i--) {
2069
+ const candidate = nodes[i];
2070
+ if (activePromptAgentIds.Has(candidate.ID)) {
2071
+ effectiveModelSelectionMode = nodeConfigs[i]?.execution?.modelSelectionMode ?? candidate.ModelSelectionMode ?? defaultsLayer.execution?.modelSelectionMode ?? "Agent Type";
2072
+ break;
2073
+ }
2074
+ }
2075
+ }
2076
+ let mergedTypeConfig = null;
2077
+ for (const node of nodes) {
2078
+ const parsed = ParseAgentConfigJsonObject(node.TypeConfiguration);
2079
+ if (parsed) {
2080
+ mergedTypeConfig = mergedTypeConfig ? DeepMergeAgentConfigObjects(mergedTypeConfig, parsed) : { ...parsed };
2081
+ }
2082
+ }
2083
+ if (mergedTypeConfig && leaf && leaf.BaseAgentID && (leaf.InstantiationMode ?? "None") === "None") {
2084
+ delete mergedTypeConfig["instantiation"];
2085
+ }
2086
+ let mergedPromptParams = null;
2087
+ const lockedPromptGates = /* @__PURE__ */ new Map();
2088
+ const trackPromptGates = (obj, allowRebase) => {
2089
+ if (!obj)
2090
+ return;
2091
+ for (const gate of NARROW_ONLY_PROMPT_PARAM_GATES) {
2092
+ if (typeof obj[gate] === "boolean") {
2093
+ if (allowRebase) {
2094
+ lockedPromptGates.set(gate, obj[gate]);
2095
+ } else if (obj[gate] === false) {
2096
+ lockedPromptGates.set(gate, false);
2097
+ } else if (!lockedPromptGates.has(gate)) {
2098
+ lockedPromptGates.set(gate, true);
2099
+ }
2100
+ }
2101
+ }
2102
+ };
2103
+ if (defaultsLayer.promptDefaults && Object.keys(defaultsLayer.promptDefaults).length > 0) {
2104
+ mergedPromptParams = ParseAgentConfigJsonObject(JSON.stringify(defaultsLayer.promptDefaults));
2105
+ trackPromptGates(mergedPromptParams, false);
2106
+ }
2107
+ for (let i = 0; i < nodes.length; i++) {
2108
+ const parsed = ParseAgentConfigJsonObject(nodes[i].AgentTypePromptParams);
2109
+ if (parsed) {
2110
+ mergedPromptParams = mergedPromptParams ? DeepMergeAgentConfigObjects(mergedPromptParams, parsed) : { ...parsed };
2111
+ trackPromptGates(parsed, canWidenAt(i));
2112
+ }
2113
+ }
2114
+ if (mergedPromptParams) {
2115
+ for (const gate of NARROW_ONLY_PROMPT_PARAM_GATES) {
2116
+ if (lockedPromptGates.get(gate) === false) {
2117
+ mergedPromptParams[gate] = false;
2118
+ }
2119
+ }
2120
+ }
2121
+ const seedRequirePlanMode = orderedDefaultLayers.some((l) => l.execution?.requirePlanMode === true) || nodes.length > 0 && (nodeConfigs[0]?.execution?.requirePlanMode === true || nodes[0].RequirePlanMode === true);
2122
+ const effectiveRequirePlanMode = FoldRebaseAwareChain({
2123
+ Nodes: nodes,
2124
+ NodeConfigs: nodeConfigs,
2125
+ Seed: seedRequirePlanMode,
2126
+ GetNodeValue: (node, cfg, idx) => {
2127
+ const explicit = cfg?.execution?.requirePlanMode;
2128
+ const legacy = node.RequirePlanMode;
2129
+ if (canWidenAt(idx)) {
2130
+ if (typeof explicit === "boolean")
2131
+ return explicit;
2132
+ return legacy === true ? true : void 0;
2133
+ }
2134
+ if (explicit === true || legacy === true)
2135
+ return true;
2136
+ if (typeof explicit === "boolean")
2137
+ return explicit;
2138
+ return void 0;
2139
+ },
2140
+ Narrow: (acc, next) => acc || next
2141
+ });
2142
+ const seedSupportsPlanMode = orderedDefaultLayers.some((l) => l.execution?.supportsPlanMode === false) ? false : nodes.length > 0 ? nodeConfigs[0]?.execution?.supportsPlanMode !== false && nodes[0].SupportsPlanMode !== false : defaultsLayer.execution?.supportsPlanMode ?? true;
2143
+ const effectiveSupportsPlanMode = FoldRebaseAwareChain({
2144
+ Nodes: nodes,
2145
+ NodeConfigs: nodeConfigs,
2146
+ Seed: seedSupportsPlanMode,
2147
+ GetNodeValue: (node, cfg, idx) => {
2148
+ const explicit = cfg?.execution?.supportsPlanMode;
2149
+ const legacy = node.SupportsPlanMode;
2150
+ if (canWidenAt(idx)) {
2151
+ if (typeof explicit === "boolean")
2152
+ return explicit;
2153
+ return legacy === false ? false : void 0;
2154
+ }
2155
+ if (explicit === false || legacy === false)
2156
+ return false;
2157
+ if (typeof explicit === "boolean")
2158
+ return explicit;
2159
+ return void 0;
2160
+ },
2161
+ Narrow: (acc, next) => acc && next
2162
+ });
2163
+ let seedSearchAccess = null;
2164
+ const narrowSearchAccess = (acc, val) => {
2165
+ if (val == null)
2166
+ return acc;
2167
+ if (acc === null || AGENT_SEARCH_SCOPE_ACCESS_RANK[val] < AGENT_SEARCH_SCOPE_ACCESS_RANK[acc]) {
2168
+ return val;
2169
+ }
2170
+ return acc;
2171
+ };
2172
+ for (const layer of orderedDefaultLayers) {
2173
+ seedSearchAccess = narrowSearchAccess(seedSearchAccess, layer.scope?.searchScopeAccess);
2174
+ }
2175
+ if (nodes.length > 0) {
2176
+ const explicit0 = nodeConfigs[0]?.scope?.searchScopeAccess ?? null;
2177
+ const legacy0 = nodes[0].SearchScopeAccess ?? null;
2178
+ if (explicit0 != null && legacy0 != null) {
2179
+ const stricter = AGENT_SEARCH_SCOPE_ACCESS_RANK[legacy0] < AGENT_SEARCH_SCOPE_ACCESS_RANK[explicit0] ? legacy0 : explicit0;
2180
+ seedSearchAccess = narrowSearchAccess(seedSearchAccess, stricter);
2181
+ } else {
2182
+ const isNonInstantiableDerived0 = Boolean(nodes[0].BaseAgentID) && (nodes[0].InstantiationMode ?? "None") === "None";
2183
+ const cand0 = explicit0 ?? (legacy0 && (legacy0 !== "None" || !isNonInstantiableDerived0) ? legacy0 : null);
2184
+ seedSearchAccess = narrowSearchAccess(seedSearchAccess, cand0);
2185
+ }
2186
+ }
2187
+ const effectiveSearchScopeAccess = FoldRebaseAwareChain({
2188
+ Nodes: nodes,
2189
+ NodeConfigs: nodeConfigs,
2190
+ Seed: seedSearchAccess,
2191
+ GetNodeValue: (node, cfg, idx) => {
2192
+ const explicit = cfg?.scope?.searchScopeAccess ?? null;
2193
+ const legacy = node.SearchScopeAccess ?? null;
2194
+ if (canWidenAt(idx)) {
2195
+ if (explicit != null)
2196
+ return explicit;
2197
+ return legacy != null && legacy !== "None" ? legacy : void 0;
2198
+ }
2199
+ if (explicit != null && legacy != null) {
2200
+ return AGENT_SEARCH_SCOPE_ACCESS_RANK[legacy] < AGENT_SEARCH_SCOPE_ACCESS_RANK[explicit] ? legacy : explicit;
2201
+ }
2202
+ if (explicit != null)
2203
+ return explicit;
2204
+ const isNonInstantiableDerived = Boolean(node.BaseAgentID) && (node.InstantiationMode ?? "None") === "None";
2205
+ if (legacy != null && (legacy !== "None" || !isNonInstantiableDerived)) {
2206
+ return legacy;
2207
+ }
2208
+ return void 0;
2209
+ },
2210
+ Narrow: (acc, next) => narrowSearchAccess(acc, next)
2211
+ }) ?? "None";
2212
+ let seedArtifactCreationMode = null;
2213
+ const narrowArtifactMode = (acc, val) => {
2214
+ if (val == null)
2215
+ return acc;
2216
+ if (acc === null || AGENT_ARTIFACT_CREATION_MODE_RANK[val] < AGENT_ARTIFACT_CREATION_MODE_RANK[acc]) {
2217
+ return val;
2218
+ }
2219
+ return acc;
2220
+ };
2221
+ for (const layer of orderedDefaultLayers) {
2222
+ seedArtifactCreationMode = narrowArtifactMode(seedArtifactCreationMode, layer.artifacts?.creationMode);
2223
+ }
2224
+ if (nodes.length > 0) {
2225
+ const exp0 = nodeConfigs[0]?.artifacts?.creationMode ?? null;
2226
+ const leg0 = nodes[0].ArtifactCreationMode ?? null;
2227
+ if (exp0 != null && leg0 != null) {
2228
+ seedArtifactCreationMode = narrowArtifactMode(seedArtifactCreationMode, AGENT_ARTIFACT_CREATION_MODE_RANK[leg0] < AGENT_ARTIFACT_CREATION_MODE_RANK[exp0] ? leg0 : exp0);
2229
+ } else if (exp0 != null) {
2230
+ seedArtifactCreationMode = narrowArtifactMode(seedArtifactCreationMode, exp0);
2231
+ } else if (leg0 != null && leg0 !== "Always") {
2232
+ seedArtifactCreationMode = narrowArtifactMode(seedArtifactCreationMode, leg0);
2233
+ } else if (seedArtifactCreationMode === null && leg0 != null) {
2234
+ seedArtifactCreationMode = leg0;
2235
+ }
2236
+ }
2237
+ const effectiveArtifactCreationMode = FoldRebaseAwareChain({
2238
+ Nodes: nodes,
2239
+ NodeConfigs: nodeConfigs,
2240
+ Seed: seedArtifactCreationMode,
2241
+ GetNodeValue: (node, cfg, idx) => {
2242
+ const explicit = cfg?.artifacts?.creationMode ?? null;
2243
+ const legacy = node.ArtifactCreationMode ?? null;
2244
+ if (canWidenAt(idx)) {
2245
+ if (explicit != null)
2246
+ return explicit;
2247
+ return legacy != null && legacy !== "Always" ? legacy : void 0;
2248
+ }
2249
+ if (explicit != null && legacy != null) {
2250
+ return AGENT_ARTIFACT_CREATION_MODE_RANK[legacy] < AGENT_ARTIFACT_CREATION_MODE_RANK[explicit] ? legacy : explicit;
2251
+ }
2252
+ if (explicit != null)
2253
+ return explicit;
2254
+ return legacy != null && legacy !== "Always" ? legacy : void 0;
2255
+ },
2256
+ Narrow: (acc, next) => narrowArtifactMode(acc, next)
2257
+ }) ?? "Always";
2258
+ const resolveRebaseNarrowBoolean = (jsonPicker, legacyPicker, sqlDefault, fallback) => {
2259
+ let seed = null;
2260
+ const foldAnd = (acc, val) => {
2261
+ if (typeof val !== "boolean")
2262
+ return acc;
2263
+ return acc === null ? val : acc && val;
2264
+ };
2265
+ for (const layer of orderedDefaultLayers) {
2266
+ seed = foldAnd(seed, jsonPicker(layer));
2267
+ }
2268
+ if (nodes.length > 0) {
2269
+ const exp0 = jsonPicker(nodeConfigs[0]);
2270
+ const leg0 = legacyPicker(nodes[0]);
2271
+ if (typeof exp0 === "boolean" && typeof leg0 === "boolean") {
2272
+ seed = foldAnd(seed, exp0 && leg0);
2273
+ } else {
2274
+ seed = foldAnd(seed, exp0 ?? leg0);
2275
+ }
2276
+ }
2277
+ const resolved = FoldRebaseAwareChain({
2278
+ Nodes: nodes,
2279
+ NodeConfigs: nodeConfigs,
2280
+ Seed: seed,
2281
+ GetNodeValue: (node, cfg, idx) => {
2282
+ const explicit = jsonPicker(cfg);
2283
+ const legacy = legacyPicker(node);
2284
+ if (canWidenAt(idx)) {
2285
+ if (typeof explicit === "boolean")
2286
+ return explicit;
2287
+ return typeof legacy === "boolean" && legacy !== sqlDefault ? legacy : void 0;
2288
+ }
2289
+ if (typeof explicit === "boolean" && typeof legacy === "boolean") {
2290
+ return explicit && legacy;
2291
+ }
2292
+ if (typeof explicit === "boolean")
2293
+ return explicit;
2294
+ if (typeof legacy === "boolean") {
2295
+ if (sqlDefault === false && legacy === false) {
2296
+ const isNonInstantiableDerived = Boolean(node.BaseAgentID) && (node.InstantiationMode ?? "None") === "None";
2297
+ return isNonInstantiableDerived ? void 0 : false;
2298
+ }
2299
+ return legacy !== sqlDefault ? legacy : void 0;
2300
+ }
2301
+ return void 0;
2302
+ },
2303
+ Narrow: (acc, next) => foldAnd(acc, next)
2304
+ });
2305
+ return resolved ?? fallback;
2306
+ };
2307
+ const effectiveAllowEphemeralClientTools = resolveRebaseNarrowBoolean((cfg) => cfg?.clientTools?.allowEphemeral, (a) => a.AllowEphemeralClientTools, true, false);
2308
+ const effectiveAcceptUnregisteredFiles = resolveRebaseNarrowBoolean((cfg) => cfg?.attachments?.acceptUnregisteredFiles, (a) => a.AcceptUnregisteredFiles, false, false);
2309
+ const resolveRebaseMinCeiling = (jsonPicker, legacyPicker, sqlDefault, seedUsesLayerFallbackWhenRootAtSqlDefault = false) => {
2310
+ const minFinite = (a, b) => {
2311
+ if (typeof b !== "number" || !Number.isFinite(b))
2312
+ return a;
2313
+ return a === null ? b : Math.min(a, b);
2314
+ };
2315
+ let seed = null;
2316
+ for (const layer of orderedDefaultLayers) {
2317
+ seed = minFinite(seed, jsonPicker(layer));
2318
+ }
2319
+ if (nodes.length > 0) {
2320
+ const exp0 = jsonPicker(nodeConfigs[0]);
2321
+ const leg0 = legacyPicker(nodes[0]);
2322
+ const leg0Effective = seedUsesLayerFallbackWhenRootAtSqlDefault && exp0 === void 0 && sqlDefault !== null && leg0 === sqlDefault && seed !== null ? null : leg0;
2323
+ seed = minFinite(seed, exp0);
2324
+ seed = minFinite(seed, leg0Effective);
2325
+ }
2326
+ return FoldRebaseAwareChain({
2327
+ Nodes: nodes,
2328
+ NodeConfigs: nodeConfigs,
2329
+ Seed: seed,
2330
+ GetNodeValue: (node, cfg, idx) => {
2331
+ const explicit = jsonPicker(cfg);
2332
+ const legacy = legacyPicker(node);
2333
+ if (canWidenAt(idx)) {
2334
+ if (explicit === null)
2335
+ return null;
2336
+ if (typeof explicit === "number" && Number.isFinite(explicit))
2337
+ return explicit;
2338
+ if (typeof legacy === "number" && Number.isFinite(legacy) && legacy !== sqlDefault) {
2339
+ return legacy;
2340
+ }
2341
+ return void 0;
2342
+ }
2343
+ if (typeof explicit === "number" && Number.isFinite(explicit)) {
2344
+ if (typeof legacy === "number" && Number.isFinite(legacy) && legacy !== sqlDefault) {
2345
+ return Math.min(explicit, legacy);
2346
+ }
2347
+ return explicit;
2348
+ }
2349
+ if (typeof legacy === "number" && Number.isFinite(legacy) && legacy !== sqlDefault) {
2350
+ return legacy;
2351
+ }
2352
+ return void 0;
2353
+ },
2354
+ Narrow: (acc, next) => minFinite(acc, next)
2355
+ });
2356
+ };
2357
+ const effectiveMaxExecutionsPerRun = resolveRebaseMinCeiling((cfg) => cfg?.subAgentExecution?.maxExecutionsPerRun, (a) => a.MaxExecutionsPerRun, null);
2358
+ const effectiveMaxSubAgentConsultRounds = resolveRebaseMinCeiling((cfg) => cfg?.subAgentExecution?.maxConsultRounds, (a) => a.MaxSubAgentConsultRounds, null);
2359
+ const effectiveContextWindowMaxTokens = resolveRebaseMinCeiling((cfg) => cfg?.contextWindow?.maxTokens, (a) => a.ContextWindowMaxTokens, null);
2360
+ const effectiveMaxNotesToInject = resolveRebaseMinCeiling(
2361
+ (cfg) => cfg?.memory?.maxNotesToInject,
2362
+ (a) => a.MaxNotesToInject,
2363
+ 5,
2364
+ // SQL schema default DF_AIAgent_MaxNotesToInject
2365
+ true
2366
+ );
2367
+ const effectiveMaxExamplesToInject = resolveRebaseMinCeiling(
2368
+ (cfg) => cfg?.memory?.maxExamplesToInject,
2369
+ (a) => a.MaxExamplesToInject,
2370
+ 3,
2371
+ // SQL schema default DF_AIAgent_MaxExamplesToInject
2372
+ true
2373
+ );
2374
+ const effectiveNoteRetentionDays = resolveRebaseMinCeiling(
2375
+ (cfg) => cfg?.memory?.noteRetentionDays,
2376
+ (a) => a.NoteRetentionDays,
2377
+ 90,
2378
+ // SQL schema default DF_AIAgent_NoteRetentionDays
2379
+ true
2380
+ );
2381
+ const effectiveExampleRetentionDays = resolveRebaseMinCeiling(
2382
+ (cfg) => cfg?.memory?.exampleRetentionDays,
2383
+ (a) => a.ExampleRetentionDays,
2384
+ 180,
2385
+ // SQL schema default DF_AIAgent_ExampleRetentionDays
2386
+ true
2387
+ );
2388
+ const effectiveMaxMessages = resolveRebaseMinCeiling((cfg) => cfg?.attachments?.maxMessages, (a) => a.MaxMessages, null);
2389
+ const effectiveInlineStorageThresholdBytes = resolveRebaseMinCeiling((cfg) => cfg?.attachments?.inlineStorageThresholdBytes, (a) => a.InlineStorageThresholdBytes, null);
2390
+ const effectiveFinalValidationMaxRetries = resolveRebaseMinCeiling(
2391
+ (cfg) => cfg?.payload?.finalValidationMaxRetries,
2392
+ (a) => a.FinalPayloadValidationMaxRetries,
2393
+ 3,
2394
+ // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
2395
+ true
2396
+ ) ?? 3;
2397
+ let mergedConfiguration = DeepMergeAgentConfigurations({}, defaultsLayer);
2398
+ for (const cfg of nodeConfigs) {
2399
+ if (cfg) {
2400
+ mergedConfiguration = DeepMergeAgentConfigurations(mergedConfiguration, cfg);
2401
+ }
2402
+ }
2403
+ const sanitizePositiveInt = (v) => typeof v === "number" && Number.isFinite(v) && Math.floor(v) >= 1 ? Math.floor(v) : null;
2404
+ let seedMaxInstances = null;
2405
+ const minInst = (a, b) => b === null ? a : a === null ? b : Math.min(a, b);
2406
+ for (const layer of orderedDefaultLayers) {
2407
+ seedMaxInstances = minInst(seedMaxInstances, sanitizePositiveInt(layer.instantiation?.maxInstancesPerUser));
2408
+ }
2409
+ if (nodes.length > 0) {
2410
+ seedMaxInstances = minInst(seedMaxInstances, sanitizePositiveInt(nodeConfigs[0]?.instantiation?.maxInstancesPerUser));
2411
+ seedMaxInstances = minInst(seedMaxInstances, sanitizePositiveInt(ParseAgentInstantiationConfig(nodes[0].TypeConfiguration)?.maxInstancesPerUser));
2412
+ }
2413
+ const effectiveMaxInstancesPerUser = FoldRebaseAwareChain({
2414
+ Nodes: nodes,
2415
+ NodeConfigs: nodeConfigs,
2416
+ Seed: seedMaxInstances,
2417
+ GetNodeValue: (node, cfg, idx) => {
2418
+ const fromJson = sanitizePositiveInt(cfg?.instantiation?.maxInstancesPerUser);
2419
+ const fromTypeCfg = sanitizePositiveInt(ParseAgentInstantiationConfig(node.TypeConfiguration)?.maxInstancesPerUser);
2420
+ if (canWidenAt(idx)) {
2421
+ if (fromJson !== null)
2422
+ return fromJson;
2423
+ return fromTypeCfg !== null ? fromTypeCfg : void 0;
2424
+ }
2425
+ const combined = minInst(fromJson, fromTypeCfg);
2426
+ return combined !== null ? combined : void 0;
2427
+ },
2428
+ Narrow: (acc, next) => minInst(acc, next)
2429
+ });
2430
+ if (effectiveMaxInstancesPerUser !== null && effectiveMaxInstancesPerUser >= 1) {
2431
+ mergedConfiguration = {
2432
+ ...mergedConfiguration,
2433
+ instantiation: {
2434
+ ...mergedConfiguration.instantiation ?? {},
2435
+ maxInstancesPerUser: effectiveMaxInstancesPerUser
2436
+ }
2437
+ };
2438
+ }
2439
+ if (leaf && leaf.BaseAgentID && (leaf.InstantiationMode ?? "None") === "None" && mergedConfiguration.instantiation) {
2440
+ delete mergedConfiguration.instantiation;
2441
+ }
2442
+ const helperPlugins = [];
2443
+ for (const layer of orderedDefaultLayers) {
2444
+ if (Array.isArray(layer.helperPlugins) && layer.helperPlugins.length > 0) {
2445
+ helperPlugins.push(...ParseAgentHelperPlugins(JSON.stringify({ helperPlugins: layer.helperPlugins })));
2446
+ }
2447
+ }
2448
+ for (const node of nodes) {
2449
+ helperPlugins.push(...ParseAgentHelperPlugins(node.Configuration));
2450
+ helperPlugins.push(...ParseAgentHelperPlugins(node.TypeConfiguration));
2451
+ }
2452
+ const effectiveReranker = nearestOrDefault((a, cfg) => cfg?.memory?.reranker ? JSON.stringify(cfg.memory.reranker) : a.RerankerConfiguration, defaultsLayer.memory?.reranker ? JSON.stringify(defaultsLayer.memory.reranker) : null);
2453
+ const parsePlainScopeObj = (raw) => {
2454
+ if (!raw || raw.trim().length === 0)
2455
+ return null;
2456
+ const parsed = ParseAgentConfigJsonObject(raw);
2457
+ return parsed ? { ...parsed } : null;
2458
+ };
2459
+ let seedScopeObj = null;
2460
+ for (const layer of orderedDefaultLayers) {
2461
+ if (layer.scope?.secondaryScopeConfig) {
2462
+ seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, layer.scope.secondaryScopeConfig);
2463
+ }
2464
+ }
2465
+ if (nodes.length > 0) {
2466
+ const rootScope = nodeConfigs[0]?.scope?.secondaryScopeConfig ?? parsePlainScopeObj(nodes[0].ScopeConfig);
2467
+ if (rootScope) {
2468
+ seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, rootScope);
2469
+ }
2470
+ }
2471
+ const effectiveScopeObj = FoldRebaseAwareChain({
2472
+ Nodes: nodes,
2473
+ NodeConfigs: nodeConfigs,
2474
+ Seed: seedScopeObj,
2475
+ GetNodeValue: (node, cfg, idx) => {
2476
+ if (canWidenAt(idx) && cfg?.scope?.secondaryScopeConfig === null) {
2477
+ return null;
2478
+ }
2479
+ const fromJson = cfg?.scope?.secondaryScopeConfig;
2480
+ if (fromJson && typeof fromJson === "object" && !Array.isArray(fromJson)) {
2481
+ return fromJson;
2482
+ }
2483
+ const fromLegacy = parsePlainScopeObj(node.ScopeConfig);
2484
+ return fromLegacy ?? void 0;
2485
+ },
2486
+ Narrow: (acc, next) => NarrowScopeConfigObjects(acc, next),
2487
+ Rebase: (_acc, next) => next ? { ...next } : null
2488
+ });
2489
+ const effectiveScopeConfig = effectiveScopeObj && Object.keys(effectiveScopeObj).length > 0 ? JSON.stringify(effectiveScopeObj) : null;
2490
+ const resolveOverridableBoolean = (jsonPicker, legacyPicker, dbDefault) => {
2491
+ for (let i = nodes.length - 1; i >= 0; i--) {
2492
+ const explicit = jsonPicker(nodeConfigs[i]);
2493
+ if (typeof explicit === "boolean") {
2494
+ return explicit;
2495
+ }
2496
+ const legacy = legacyPicker(nodes[i]);
2497
+ if (typeof legacy === "boolean" && legacy !== dbDefault) {
2498
+ return legacy;
2499
+ }
2500
+ }
2501
+ const layerVal = jsonPicker(defaultsLayer);
2502
+ if (typeof layerVal === "boolean") {
2503
+ return layerVal;
2504
+ }
2505
+ return dbDefault;
2506
+ };
2507
+ const resolveOverridableWithDbDefault = (jsonPicker, legacyPicker, layerDefault, dbDefault) => {
2508
+ for (let i = nodes.length - 1; i >= 0; i--) {
2509
+ const explicit = jsonPicker(nodeConfigs[i]);
2510
+ if (explicit !== null && explicit !== void 0 && (typeof explicit !== "string" || explicit.trim().length > 0)) {
2511
+ return explicit;
2512
+ }
2513
+ const legacy = legacyPicker(nodes[i]);
2514
+ if (legacy !== null && legacy !== void 0 && (typeof legacy !== "string" || legacy.trim().length > 0) && legacy !== dbDefault) {
2515
+ return legacy;
2516
+ }
2517
+ }
2518
+ if (layerDefault !== null && layerDefault !== void 0 && (typeof layerDefault !== "string" || layerDefault.trim().length > 0)) {
2519
+ return layerDefault;
2520
+ }
2521
+ return nearestNonNull((a) => legacyPicker(a));
2522
+ };
2523
+ const effectiveEnableCompression = resolveOverridableBoolean((cfg) => cfg?.contextWindow?.enableCompression, (a) => a.EnableContextCompression, false);
2524
+ const effectiveDeclareNativeTools = resolveOverridableBoolean((cfg) => cfg?.execution?.declareActionsAsNativeTools, (a) => a.DeclareActionsAsNativeTools, true);
2525
+ const effectiveAllowMemoryWrite = resolveRebaseNarrowBoolean((cfg) => cfg?.memory?.allowMemoryWrite, (a) => a.AllowMemoryWrite, true, true);
2526
+ const effectiveInjectNotes = resolveOverridableBoolean((cfg) => cfg?.memory?.injectNotes, (a) => a.InjectNotes, true);
2527
+ const effectiveInjectExamples = resolveOverridableBoolean((cfg) => cfg?.memory?.injectExamples, (a) => a.InjectExamples, false);
2528
+ const seedAutoArchive = (() => {
2529
+ if (nodes.length > 0) {
2530
+ const exp0 = nodeConfigs[0]?.memory?.autoArchiveEnabled;
2531
+ if (typeof exp0 === "boolean")
2532
+ return exp0;
2533
+ const leg0 = nodes[0].AutoArchiveEnabled;
2534
+ if (typeof leg0 === "boolean" && leg0 !== true)
2535
+ return leg0;
2536
+ }
2537
+ if (typeof defaultsLayer.memory?.autoArchiveEnabled === "boolean") {
2538
+ return defaultsLayer.memory.autoArchiveEnabled;
2539
+ }
2540
+ return true;
2541
+ })();
2542
+ const hasFiniteRetention = effectiveNoteRetentionDays !== null || effectiveExampleRetentionDays !== null;
2543
+ const effectiveAutoArchive = FoldRebaseAwareChain({
2544
+ Nodes: nodes,
2545
+ NodeConfigs: nodeConfigs,
2546
+ Seed: seedAutoArchive,
2547
+ GetNodeValue: (node, cfg) => {
2548
+ const explicit = cfg?.memory?.autoArchiveEnabled;
2549
+ if (typeof explicit === "boolean")
2550
+ return explicit;
2551
+ const legacy = node.AutoArchiveEnabled;
2552
+ return typeof legacy === "boolean" && legacy !== true ? legacy : void 0;
2553
+ },
2554
+ Narrow: (acc, next) => acc === true && hasFiniteRetention && next === false ? true : next
2555
+ });
2556
+ const parseStringArrayColumn = (raw) => {
2557
+ if (!raw || raw.trim().length === 0) {
2558
+ return null;
2559
+ }
2560
+ try {
2561
+ const parsed = JSON.parse(raw);
2562
+ if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
2563
+ return parsed;
2564
+ }
2565
+ } catch {
2566
+ }
2567
+ return null;
2568
+ };
2569
+ const resolveRebasePayloadPaths = (jsonPicker, legacyPicker, treatWildcardAsDbDefault) => {
2570
+ let seed = null;
2571
+ for (const layer of orderedDefaultLayers) {
2572
+ const layerPaths = jsonPicker(layer);
2573
+ if (Array.isArray(layerPaths)) {
2574
+ seed = IntersectPayloadPathSets(seed, layerPaths);
2575
+ }
2576
+ }
2577
+ if (nodes.length > 0) {
2578
+ const exp0 = jsonPicker(nodeConfigs[0]);
2579
+ if (Array.isArray(exp0)) {
2580
+ seed = IntersectPayloadPathSets(seed, exp0);
2581
+ } else {
2582
+ const leg0 = parseStringArrayColumn(legacyPicker(nodes[0]));
2583
+ if (leg0 !== null) {
2584
+ const isDbWildcard = treatWildcardAsDbDefault && leg0.length === 1 && leg0[0] === "*";
2585
+ if (!isDbWildcard) {
2586
+ seed = IntersectPayloadPathSets(seed, leg0);
2587
+ } else if (seed === null) {
2588
+ seed = leg0;
2589
+ }
2590
+ }
2591
+ }
2592
+ }
2593
+ return FoldRebaseAwareChain({
2594
+ Nodes: nodes,
2595
+ NodeConfigs: nodeConfigs,
2596
+ Seed: seed,
2597
+ GetNodeValue: (node, cfg, idx) => {
2598
+ const explicit = jsonPicker(cfg);
2599
+ if (canWidenAt(idx) && explicit === null) {
2600
+ return null;
2601
+ }
2602
+ if (Array.isArray(explicit)) {
2603
+ return [...explicit];
2604
+ }
2605
+ const legacy = parseStringArrayColumn(legacyPicker(node));
2606
+ if (legacy !== null) {
2607
+ const isDbWildcard = treatWildcardAsDbDefault && legacy.length === 1 && legacy[0] === "*";
2608
+ if (!isDbWildcard) {
2609
+ return legacy;
2610
+ }
2611
+ }
2612
+ return void 0;
2613
+ },
2614
+ Narrow: (acc, next) => IntersectPayloadPathSets(acc, next),
2615
+ Rebase: (_acc, next) => next === null ? null : [...next]
2616
+ });
2617
+ };
2618
+ const effectivePayloadDownstreamPaths = resolveRebasePayloadPaths((cfg) => cfg?.payload?.downstreamPaths, (a) => a.PayloadDownstreamPaths, true) ?? ["*"];
2619
+ const effectivePayloadUpstreamPaths = resolveRebasePayloadPaths((cfg) => cfg?.payload?.upstreamPaths, (a) => a.PayloadUpstreamPaths, true) ?? ["*"];
2620
+ const effectivePayloadSelfReadPaths = resolveRebasePayloadPaths((cfg) => cfg?.payload?.selfReadPaths, (a) => a.PayloadSelfReadPaths, false);
2621
+ const effectivePayloadSelfWritePaths = resolveRebasePayloadPaths((cfg) => cfg?.payload?.selfWritePaths, (a) => a.PayloadSelfWritePaths, false);
2622
+ let seedPayloadScope = null;
2623
+ for (const layer of orderedDefaultLayers) {
2624
+ if (typeof layer.payload?.scope === "string" && layer.payload.scope.trim().length > 0) {
2625
+ seedPayloadScope = NarrowPayloadScope(seedPayloadScope, layer.payload.scope);
2626
+ }
2627
+ }
2628
+ if (nodes.length > 0) {
2629
+ const rootScope = nodeConfigs[0]?.payload?.scope ?? nodes[0].PayloadScope ?? null;
2630
+ if (typeof rootScope === "string" && rootScope.trim().length > 0) {
2631
+ seedPayloadScope = NarrowPayloadScope(seedPayloadScope, rootScope);
2632
+ }
2633
+ }
2634
+ const effectivePayloadScope = FoldRebaseAwareChain({
2635
+ Nodes: nodes,
2636
+ NodeConfigs: nodeConfigs,
2637
+ Seed: seedPayloadScope,
2638
+ GetNodeValue: (node, cfg, idx) => {
2639
+ const explicit = cfg?.payload?.scope;
2640
+ if (canWidenAt(idx) && explicit === null) {
2641
+ return null;
2642
+ }
2643
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
2644
+ return explicit.trim();
2645
+ }
2646
+ const legacy = node.PayloadScope?.trim();
2647
+ return legacy && legacy.length > 0 ? legacy : void 0;
2648
+ },
2649
+ Narrow: (acc, next) => NarrowPayloadScope(acc, next),
2650
+ Rebase: (acc, next) => next === null ? null : HasPathTraversalSegment(next) ? acc : next
2651
+ });
2652
+ const resolveValidationSchemas = (jsonPicker, legacyPicker) => {
2653
+ const seedSchemas = [];
2654
+ const pushUnique = (list, schema) => {
2655
+ if (typeof schema === "string" && schema.trim().length > 0 && !list.includes(schema)) {
2656
+ list.push(schema);
2657
+ }
2658
+ };
2659
+ for (const layer of orderedDefaultLayers) {
2660
+ pushUnique(seedSchemas, jsonPicker(layer));
2661
+ }
2662
+ if (nodes.length > 0) {
2663
+ pushUnique(seedSchemas, jsonPicker(nodeConfigs[0]) ?? legacyPicker(nodes[0]));
2664
+ }
2665
+ return FoldRebaseAwareChain({
2666
+ Nodes: nodes,
2667
+ NodeConfigs: nodeConfigs,
2668
+ Seed: seedSchemas,
2669
+ GetNodeValue: (node, cfg, idx) => {
2670
+ const explicit = jsonPicker(cfg);
2671
+ if (canWidenAt(idx) && explicit === null) {
2672
+ return [];
2673
+ }
2674
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
2675
+ return [explicit];
2676
+ }
2677
+ const legacy = legacyPicker(node);
2678
+ if (typeof legacy === "string" && legacy.trim().length > 0) {
2679
+ return [legacy];
2680
+ }
2681
+ return void 0;
2682
+ },
2683
+ Narrow: (acc, next) => {
2684
+ const out = [...acc];
2685
+ for (const s of next) {
2686
+ pushUnique(out, s);
2687
+ }
2688
+ return out;
2689
+ },
2690
+ Rebase: (_acc, next) => [...next]
2691
+ });
2692
+ };
2693
+ const effectiveStartingValidationSchemas = resolveValidationSchemas((cfg) => cfg?.payload?.startingValidationSchema, (a) => a.StartingPayloadValidation);
2694
+ const effectiveFinalValidationSchemas = resolveValidationSchemas((cfg) => cfg?.payload?.finalValidationSchema, (a) => a.FinalPayloadValidation);
2695
+ let seedStartingValMode = null;
2696
+ const narrowStartingValMode = (acc, val) => {
2697
+ if (val == null)
2698
+ return acc;
2699
+ if (acc === null || AGENT_STARTING_VALIDATION_MODE_RANK[val] < AGENT_STARTING_VALIDATION_MODE_RANK[acc]) {
2700
+ return val;
2701
+ }
2702
+ return acc;
2703
+ };
2704
+ for (const layer of orderedDefaultLayers) {
2705
+ seedStartingValMode = narrowStartingValMode(seedStartingValMode, layer.payload?.startingValidationMode);
2706
+ }
2707
+ if (nodes.length > 0) {
2708
+ const exp0 = nodeConfigs[0]?.payload?.startingValidationMode ?? null;
2709
+ const leg0 = nodes[0].StartingPayloadValidationMode ?? null;
2710
+ if (exp0 != null) {
2711
+ seedStartingValMode = narrowStartingValMode(seedStartingValMode, exp0);
2712
+ } else if (leg0 != null && leg0 !== "Fail") {
2713
+ seedStartingValMode = narrowStartingValMode(seedStartingValMode, leg0);
2714
+ } else if (seedStartingValMode === null && leg0 != null) {
2715
+ seedStartingValMode = leg0;
2716
+ }
2717
+ }
2718
+ const effectiveStartingValidationMode = FoldRebaseAwareChain({
2719
+ Nodes: nodes,
2720
+ NodeConfigs: nodeConfigs,
2721
+ Seed: seedStartingValMode,
2722
+ GetNodeValue: (node, cfg) => {
2723
+ const explicit = cfg?.payload?.startingValidationMode ?? null;
2724
+ if (explicit != null)
2725
+ return explicit;
2726
+ const legacy = node.StartingPayloadValidationMode ?? null;
2727
+ return legacy != null && legacy !== "Fail" ? legacy : void 0;
2728
+ },
2729
+ Narrow: (acc, next) => narrowStartingValMode(acc, next)
2730
+ }) ?? "Fail";
2731
+ let seedFinalValMode = null;
2732
+ const narrowFinalValMode = (acc, val) => {
2733
+ if (val == null)
2734
+ return acc;
2735
+ if (acc === null || AGENT_FINAL_VALIDATION_MODE_RANK[val] < AGENT_FINAL_VALIDATION_MODE_RANK[acc]) {
2736
+ return val;
2737
+ }
2738
+ return acc;
2739
+ };
2740
+ for (const layer of orderedDefaultLayers) {
2741
+ seedFinalValMode = narrowFinalValMode(seedFinalValMode, layer.payload?.finalValidationMode);
2742
+ }
2743
+ if (nodes.length > 0) {
2744
+ const exp0 = nodeConfigs[0]?.payload?.finalValidationMode ?? null;
2745
+ const leg0 = nodes[0].FinalPayloadValidationMode ?? null;
2746
+ if (exp0 != null) {
2747
+ seedFinalValMode = narrowFinalValMode(seedFinalValMode, exp0);
2748
+ } else if (leg0 != null && leg0 !== "Retry") {
2749
+ seedFinalValMode = narrowFinalValMode(seedFinalValMode, leg0);
2750
+ } else if (seedFinalValMode === null && leg0 != null) {
2751
+ seedFinalValMode = leg0;
2752
+ }
2753
+ }
2754
+ const effectiveFinalValidationMode = FoldRebaseAwareChain({
2755
+ Nodes: nodes,
2756
+ NodeConfigs: nodeConfigs,
2757
+ Seed: seedFinalValMode,
2758
+ GetNodeValue: (node, cfg) => {
2759
+ const explicit = cfg?.payload?.finalValidationMode ?? null;
2760
+ if (explicit != null)
2761
+ return explicit;
2762
+ const legacy = node.FinalPayloadValidationMode ?? null;
2763
+ return legacy != null && legacy !== "Retry" ? legacy : void 0;
2764
+ },
2765
+ Narrow: (acc, next) => narrowFinalValMode(acc, next)
2766
+ }) ?? "Retry";
2767
+ let seedMessageMode = null;
2768
+ const narrowMessageMode = (acc, val) => {
2769
+ if (val == null)
2770
+ return acc;
2771
+ if (acc === null || AGENT_MESSAGE_MODE_RANK[val] < AGENT_MESSAGE_MODE_RANK[acc]) {
2772
+ return val;
2773
+ }
2774
+ return acc;
2775
+ };
2776
+ for (const layer of orderedDefaultLayers) {
2777
+ seedMessageMode = narrowMessageMode(seedMessageMode, layer.attachments?.messageMode);
2778
+ }
2779
+ if (nodes.length > 0) {
2780
+ const exp0 = nodeConfigs[0]?.attachments?.messageMode ?? null;
2781
+ const leg0 = nodes[0].MessageMode ?? null;
2782
+ if (exp0 != null) {
2783
+ seedMessageMode = narrowMessageMode(seedMessageMode, exp0);
2784
+ } else if (leg0 != null && leg0 !== "None") {
2785
+ seedMessageMode = narrowMessageMode(seedMessageMode, leg0);
2786
+ } else if (seedMessageMode === null && leg0 != null) {
2787
+ seedMessageMode = leg0;
2788
+ }
2789
+ }
2790
+ const effectiveMessageMode = FoldRebaseAwareChain({
2791
+ Nodes: nodes,
2792
+ NodeConfigs: nodeConfigs,
2793
+ Seed: seedMessageMode,
2794
+ GetNodeValue: (node, cfg) => {
2795
+ const explicit = cfg?.attachments?.messageMode ?? null;
2796
+ if (explicit != null)
2797
+ return explicit;
2798
+ const legacy = node.MessageMode ?? null;
2799
+ return legacy != null && legacy !== "None" ? legacy : void 0;
2800
+ },
2801
+ Narrow: (acc, next) => narrowMessageMode(acc, next)
2802
+ }) ?? "All";
2803
+ let seedAttachmentRootPath = null;
2804
+ for (const layer of orderedDefaultLayers) {
2805
+ if (typeof layer.attachments?.rootPath === "string" && layer.attachments.rootPath.trim().length > 0) {
2806
+ seedAttachmentRootPath = NarrowAttachmentRootPath(seedAttachmentRootPath, layer.attachments.rootPath);
2807
+ }
2808
+ }
2809
+ if (nodes.length > 0) {
2810
+ const rootPath0 = nodeConfigs[0]?.attachments?.rootPath ?? nodes[0].AttachmentRootPath ?? null;
2811
+ if (typeof rootPath0 === "string" && rootPath0.trim().length > 0) {
2812
+ seedAttachmentRootPath = NarrowAttachmentRootPath(seedAttachmentRootPath, rootPath0);
2813
+ }
2814
+ }
2815
+ const effectiveAttachmentRootPath = FoldRebaseAwareChain({
2816
+ Nodes: nodes,
2817
+ NodeConfigs: nodeConfigs,
2818
+ Seed: seedAttachmentRootPath,
2819
+ GetNodeValue: (node, cfg, idx) => {
2820
+ const explicit = cfg?.attachments?.rootPath;
2821
+ if (canWidenAt(idx) && explicit === null) {
2822
+ return null;
2823
+ }
2824
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
2825
+ return explicit.trim();
2826
+ }
2827
+ const legacy = node.AttachmentRootPath?.trim();
2828
+ return legacy && legacy.length > 0 ? legacy : void 0;
2829
+ },
2830
+ Narrow: (acc, next) => NarrowAttachmentRootPath(acc, next),
2831
+ Rebase: (acc, next) => next === null ? null : HasPathTraversalSegment(next) ? acc : next
2832
+ });
2833
+ return {
2834
+ TypeID: effectiveTypeId,
2835
+ DriverClass: nearestNonNull((a) => a.DriverClass),
2836
+ ModelSelectionMode: effectiveModelSelectionMode,
2837
+ Isolation: effectiveIsolation,
2838
+ ContextWindowMaxTokens: effectiveContextWindowMaxTokens,
2839
+ CompactionTriggerPercent: nearestOrDefault((a, cfg) => cfg?.contextWindow?.compactionTriggerPercent ?? a.CompactionTriggerPercent, defaultsLayer.contextWindow?.compactionTriggerPercent),
2840
+ CompactionTargetPercent: nearestOrDefault((a, cfg) => cfg?.contextWindow?.compactionTargetPercent ?? a.CompactionTargetPercent, defaultsLayer.contextWindow?.compactionTargetPercent),
2841
+ ConversationSummaryPromptID: nearestOrDefault((a, cfg) => cfg?.contextWindow?.summaryPromptID ?? a.ConversationSummaryPromptID, defaultsLayer.contextWindow?.summaryPromptID),
2842
+ EnableContextCompression: effectiveEnableCompression,
2843
+ ContextCompressionMessageThreshold: nearestOrDefault((a, cfg) => cfg?.contextWindow?.compressionMessageThreshold ?? a.ContextCompressionMessageThreshold, defaultsLayer.contextWindow?.compressionMessageThreshold),
2844
+ ContextCompressionPromptID: nearestOrDefault((a, cfg) => cfg?.contextWindow?.compressionPromptID ?? a.ContextCompressionPromptID, defaultsLayer.contextWindow?.compressionPromptID),
2845
+ ContextCompressionMessageRetentionCount: nearestOrDefault((a, cfg) => cfg?.contextWindow?.compressionMessageRetentionCount ?? a.ContextCompressionMessageRetentionCount, defaultsLayer.contextWindow?.compressionMessageRetentionCount),
2846
+ RerankerConfiguration: effectiveReranker,
2847
+ ScopeConfig: effectiveScopeConfig,
2848
+ DefaultPromptEffortLevel: nearestOrDefault((a, cfg) => cfg?.execution?.defaultPromptEffortLevel ?? a.DefaultPromptEffortLevel, defaultsLayer.execution?.defaultPromptEffortLevel),
2849
+ ChatHandlingOption: nearestOrDefault((a, cfg) => cfg?.execution?.chatHandlingOption ?? a.ChatHandlingOption, defaultsLayer.execution?.chatHandlingOption),
2850
+ DefaultArtifactTypeID: nearestOrDefault((a, cfg) => cfg?.artifacts?.defaultArtifactTypeID ?? a.DefaultArtifactTypeID, defaultsLayer.artifacts?.defaultArtifactTypeID),
2851
+ ArtifactCreationMode: effectiveArtifactCreationMode,
2852
+ DeclareActionsAsNativeTools: effectiveDeclareNativeTools,
2853
+ SupportsPlanMode: effectiveSupportsPlanMode,
2854
+ RequirePlanMode: effectiveRequirePlanMode,
2855
+ AcceptsSkills: effectiveAcceptsSkills,
2856
+ SkillActivationMode: resolvedSkillActivationMode,
2857
+ SearchScopeAccess: effectiveSearchScopeAccess,
2858
+ AllowMemoryWrite: effectiveAllowMemoryWrite,
2859
+ InjectNotes: effectiveInjectNotes,
2860
+ MaxNotesToInject: effectiveMaxNotesToInject,
2861
+ NoteInjectionStrategy: resolveOverridableWithDbDefault((cfg) => cfg?.memory?.noteInjectionStrategy, (a) => a.NoteInjectionStrategy, defaultsLayer.memory?.noteInjectionStrategy, "Relevant") ?? "Relevant",
2862
+ InjectExamples: effectiveInjectExamples,
2863
+ MaxExamplesToInject: effectiveMaxExamplesToInject,
2864
+ ExampleInjectionStrategy: resolveOverridableWithDbDefault((cfg) => cfg?.memory?.exampleInjectionStrategy, (a) => a.ExampleInjectionStrategy, defaultsLayer.memory?.exampleInjectionStrategy, "Semantic") ?? "Semantic",
2865
+ NoteRetentionDays: effectiveNoteRetentionDays,
2866
+ ExampleRetentionDays: effectiveExampleRetentionDays,
2867
+ AutoArchiveEnabled: effectiveAutoArchive,
2868
+ PayloadDownstreamPaths: effectivePayloadDownstreamPaths,
2869
+ PayloadUpstreamPaths: effectivePayloadUpstreamPaths,
2870
+ PayloadSelfReadPaths: effectivePayloadSelfReadPaths,
2871
+ PayloadSelfWritePaths: effectivePayloadSelfWritePaths,
2872
+ PayloadScope: effectivePayloadScope,
2873
+ StartingPayloadValidation: effectiveStartingValidationSchemas.length > 0 ? effectiveStartingValidationSchemas[effectiveStartingValidationSchemas.length - 1] : null,
2874
+ StartingPayloadValidationSchemas: effectiveStartingValidationSchemas,
2875
+ StartingPayloadValidationMode: effectiveStartingValidationMode,
2876
+ FinalPayloadValidation: effectiveFinalValidationSchemas.length > 0 ? effectiveFinalValidationSchemas[effectiveFinalValidationSchemas.length - 1] : null,
2877
+ FinalPayloadValidationSchemas: effectiveFinalValidationSchemas,
2878
+ FinalPayloadValidationMode: effectiveFinalValidationMode,
2879
+ FinalPayloadValidationMaxRetries: effectiveFinalValidationMaxRetries,
2880
+ ExecutionMode: resolveOverridableWithDbDefault((cfg) => cfg?.subAgentExecution?.mode, (a) => a.ExecutionMode, defaultsLayer.subAgentExecution?.mode, "Sequential") ?? "Sequential",
2881
+ MinExecutionsPerRun: nearestOrDefault((a, cfg) => cfg?.subAgentExecution?.minExecutionsPerRun ?? a.MinExecutionsPerRun, defaultsLayer.subAgentExecution?.minExecutionsPerRun),
2882
+ MaxExecutionsPerRun: effectiveMaxExecutionsPerRun,
2883
+ MaxSubAgentConsultRounds: effectiveMaxSubAgentConsultRounds,
2884
+ MessageMode: effectiveMessageMode,
2885
+ MaxMessages: effectiveMaxMessages,
2886
+ AttachmentRootPath: effectiveAttachmentRootPath,
2887
+ InlineStorageThresholdBytes: effectiveInlineStorageThresholdBytes,
2888
+ AcceptUnregisteredFiles: effectiveAcceptUnregisteredFiles,
2889
+ AllowEphemeralClientTools: effectiveAllowEphemeralClientTools,
2890
+ RecordingDefault: nearestOrDefault((a, cfg) => cfg?.recording?.defaultMode ?? a.RecordingDefault, defaultsLayer.recording?.defaultMode),
2891
+ LogoURL: nearestNonNull((a) => a.LogoURL),
2892
+ IconClass: nearestNonNull((a) => a.IconClass),
2893
+ TypeConfiguration: mergedTypeConfig && Object.keys(mergedTypeConfig).length > 0 ? JSON.stringify(mergedTypeConfig) : null,
2894
+ AgentTypePromptParams: mergedPromptParams && Object.keys(mergedPromptParams).length > 0 ? JSON.stringify(mergedPromptParams) : null,
2895
+ Configuration: mergedConfiguration,
2896
+ HelperPlugins: helperPlugins
2897
+ };
2898
+ }
2899
+ /**
2900
+ * Resolves effective `AIAgentPrompt` rows for `agentId` along its `BaseAgentID` chain:
2901
+ * if the agent defines its own matching prompts, those are returned; otherwise walks up
2902
+ * `BaseAgentID` to the nearest ancestor with matching prompts.
2903
+ */
2904
+ GetEffectiveAgentPrompts(agentId, status = "Active") {
2905
+ const chain = this.GetAgentInheritanceChain(agentId);
2906
+ const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : agentId ? [agentId] : [];
2907
+ const chainIdSet = new UUIDSet(idsLeafToRoot);
2908
+ const promptsByAgentId = /* @__PURE__ */ new Map();
2909
+ for (const ap of this._agentPrompts) {
2910
+ if (ap.Status === status && chainIdSet.Has(ap.AgentID)) {
2911
+ const key = NormalizeUUID(ap.AgentID);
2912
+ const list = promptsByAgentId.get(key) ?? [];
2913
+ list.push(ap);
2914
+ promptsByAgentId.set(key, list);
2915
+ }
2916
+ }
2917
+ for (const id of idsLeafToRoot) {
2918
+ const matches = promptsByAgentId.get(NormalizeUUID(id));
2919
+ if (matches && matches.length > 0) {
2920
+ return matches.sort((a, b) => a.ExecutionOrder - b.ExecutionOrder);
2921
+ }
2922
+ }
2923
+ return [];
2924
+ }
2925
+ /**
2926
+ * Resolves effective `AIAgentAction` rows for `agentId` across its `BaseAgentID` chain
2927
+ * (root -> leaf, keyed by `ActionID`).
2928
+ * - A descendant row with `Status !== 'Active'` (e.g. `'Disabled'` or `'Revoked'`) vetoes an
2929
+ * inherited action.
2930
+ * - On derived hops without `allowWidenFromBase: true`, active rows can only narrow per-item
2931
+ * bounds (`MaxExecutionsPerRun` via `Math.min`, `ResultExpirationTurns` via `Math.min`,
2932
+ * `MinExecutionsPerRun` via `Math.max`) on already-inherited `ActionID`s; net-new `ActionID`s
2933
+ * are ignored.
2934
+ * - On derived hops with `allowWidenFromBase: true`, active rows may add net-new `ActionID`s
2935
+ * and rebase per-item bounds.
2936
+ */
2937
+ GetEffectiveAgentActions(agentId) {
2938
+ const chain = this.GetAgentInheritanceChain(agentId);
2939
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
2940
+ id: a.ID,
2941
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
2942
+ })) : agentId ? [{ id: agentId, canWiden: false }] : [];
2943
+ const chainIdSet = new UUIDSet(nodes.map((n) => n.id));
2944
+ const actionsByAgentId = /* @__PURE__ */ new Map();
2945
+ for (const aa of this._agentActions) {
2946
+ if (chainIdSet.Has(aa.AgentID)) {
2947
+ const key = NormalizeUUID(aa.AgentID);
2948
+ const list = actionsByAgentId.get(key) ?? [];
2949
+ list.push(aa);
2950
+ actionsByAgentId.set(key, list);
2951
+ }
2952
+ }
2953
+ const minNullable = (a, b) => {
2954
+ if (typeof a === "number" && typeof b === "number")
2955
+ return Math.min(a, b);
2956
+ if (typeof b === "number")
2957
+ return b;
2958
+ return typeof a === "number" ? a : null;
2959
+ };
2960
+ const maxNullable = (a, b) => {
2961
+ if (typeof a === "number" && typeof b === "number")
2962
+ return Math.max(a, b);
2963
+ if (typeof b === "number")
2964
+ return b;
2965
+ return typeof a === "number" ? a : null;
2966
+ };
2967
+ const effectiveByActionId = /* @__PURE__ */ new Map();
2968
+ for (let idx = 0; idx < nodes.length; idx++) {
2969
+ const { id, canWiden } = nodes[idx];
2970
+ const isRoot = idx === 0;
2971
+ const rows = actionsByAgentId.get(NormalizeUUID(id)) ?? [];
2972
+ for (const row of rows) {
2973
+ if (!row.ActionID)
2974
+ continue;
2975
+ const normActionId = NormalizeUUID(row.ActionID);
2976
+ if (row.Status !== "Active") {
2977
+ effectiveByActionId.delete(normActionId);
2978
+ continue;
2979
+ }
2980
+ const prev = effectiveByActionId.get(normActionId);
2981
+ if (!prev) {
2982
+ if (isRoot || canWiden) {
2983
+ effectiveByActionId.set(normActionId, row);
2984
+ }
2985
+ continue;
2986
+ }
2987
+ if (canWiden) {
2988
+ effectiveByActionId.set(normActionId, row);
2989
+ continue;
1325
2990
  }
2991
+ const narrowedMaxExec = minNullable(prev.MaxExecutionsPerRun, row.MaxExecutionsPerRun);
2992
+ const narrowedExpTurns = minNullable(prev.ResultExpirationTurns, row.ResultExpirationTurns);
2993
+ const narrowedMinExec = maxNullable(prev.MinExecutionsPerRun, row.MinExecutionsPerRun);
2994
+ const narrowed = Object.create(row);
2995
+ Object.defineProperty(narrowed, "MaxExecutionsPerRun", {
2996
+ value: narrowedMaxExec,
2997
+ enumerable: true,
2998
+ configurable: true
2999
+ });
3000
+ Object.defineProperty(narrowed, "ResultExpirationTurns", {
3001
+ value: narrowedExpTurns,
3002
+ enumerable: true,
3003
+ configurable: true
3004
+ });
3005
+ Object.defineProperty(narrowed, "MinExecutionsPerRun", {
3006
+ value: narrowedMinExec,
3007
+ enumerable: true,
3008
+ configurable: true
3009
+ });
3010
+ effectiveByActionId.set(normActionId, narrowed);
3011
+ }
3012
+ }
3013
+ return Array.from(effectiveByActionId.values());
3014
+ }
3015
+ /**
3016
+ * Collects non-empty `AdditionalInstructions` stacked down the `BaseAgentID` chain from
3017
+ * root template to leaf instance.
3018
+ */
3019
+ GetStackedAdditionalInstructions(agentId) {
3020
+ const chain = this.GetAgentInheritanceChain(agentId);
3021
+ const stacked = [];
3022
+ for (const node of chain) {
3023
+ const text = node.AdditionalInstructions?.trim();
3024
+ if (text && text.length > 0) {
3025
+ stacked.push({
3026
+ AgentID: node.ID,
3027
+ AgentName: node.Name ?? node.ID,
3028
+ IsRootOrTemplate: !node.BaseAgentID || node.InstantiationMode !== "None",
3029
+ Instructions: text
3030
+ });
1326
3031
  }
1327
3032
  }
1328
- return allSubAgents;
3033
+ return stacked;
1329
3034
  }
1330
3035
  get AgentTypes() {
1331
3036
  return this.GetConfigData("_agentTypes");
1332
3037
  }
3038
+ /**
3039
+ * Built-in and OpenApp-registered AI agent step types (`MJ: AI Agent Step Types`),
3040
+ * cached conditionally during Config() and consumed by `AgentStepTypeRegistry`.
3041
+ */
3042
+ get AgentStepTypes() {
3043
+ return this.GetConfigData("_agentStepTypes");
3044
+ }
3045
+ /**
3046
+ * Finds a registered AI agent step type by its canonical `Name` (trimmed, case-insensitive).
3047
+ */
3048
+ GetAgentStepTypeByName(name) {
3049
+ const normalized = name?.trim().toLowerCase();
3050
+ if (!normalized) {
3051
+ return void 0;
3052
+ }
3053
+ return this.AgentStepTypes.find((t) => t.Name.trim().toLowerCase() === normalized);
3054
+ }
1333
3055
  /**
1334
3056
  * The `MJ: AI Agent Request Types` rows (Approval, Information, ...), cached during Config().
1335
3057
  * Resolve a type with {@link GetAgentRequestTypeByName} instead of hardcoding its ID.
@@ -1524,19 +3246,158 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1524
3246
  }
1525
3247
  }
1526
3248
  /**
1527
- * Synchronous permission check using already-loaded `_agentPermissions` metadata.
1528
- * Mirrors `AIAgentPermissionHelper.GetEffectivePermissions` without async `Config()` overhead.
3249
+ * Synchronous check for whether `user` has `CanView` permission on `agent` under the
3250
+ * 2x2 RBAC matrix.
1529
3251
  */
1530
- canUserRunAgentSync(agent, allPermissions, user, userRoleIds) {
1531
- if (UUIDsEqual(agent.OwnerUserID, user.ID)) {
1532
- return true;
3252
+ CanUserViewAgentSync(agent, user) {
3253
+ if (!agent || !user) {
3254
+ return false;
3255
+ }
3256
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, this._agentPermissions, user).canView;
3257
+ }
3258
+ /**
3259
+ * Synchronous check for whether `user` has `CanRun` permission on `agent` under the
3260
+ * 2x2 RBAC matrix AND the Ancestor `CanRun` Invariant across `BaseAgentID`.
3261
+ */
3262
+ CanUserRunAgentSync(agent, user) {
3263
+ if (!agent || !user) {
3264
+ return false;
1533
3265
  }
1534
- const agentPerms = allPermissions.filter((p) => UUIDsEqual(p.AgentID, agent.ID));
1535
- if (agentPerms.length === 0) {
3266
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, this._agentPermissions, user).canRun;
3267
+ }
3268
+ /**
3269
+ * Returns active agents that can be instantiated as templates (`InstantiationMode` is
3270
+ * `'Required'` or `'Optional'`) and that `user` is permitted to run.
3271
+ */
3272
+ GetInstantiableAgents(user) {
3273
+ if (!user) {
3274
+ return [];
3275
+ }
3276
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
3277
+ 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 ?? ""));
3278
+ }
3279
+ /**
3280
+ * Returns active derived agents (`BaseAgentID != null`) owned by or shared with `user`.
3281
+ * Optionally filters to instances descending from `rootOrBaseAgentId` (matching either
3282
+ * direct `BaseAgentID` or top-level `GetRootAgent(a.ID)`).
3283
+ *
3284
+ * Ordered: owned instances first, `IsPrimaryInstance` first, then alphabetically by `Name`.
3285
+ */
3286
+ GetUserDerivedAgents(user, rootOrBaseAgentId) {
3287
+ if (!user) {
3288
+ return [];
3289
+ }
3290
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
3291
+ const filtered = this._agents.filter((a) => {
3292
+ if (a.Status !== "Active" || !a.BaseAgentID) {
3293
+ return false;
3294
+ }
3295
+ const perms = AIAgentPermissionHelper.ComputeEffectivePermissionsSync(a, this._agents, this._agentPermissions, user, userRoleIds);
3296
+ if (!perms.canView) {
3297
+ return false;
3298
+ }
3299
+ if (rootOrBaseAgentId) {
3300
+ const root = this.GetRootAgent(a.ID);
3301
+ const matchesDirect = UUIDsEqual(a.BaseAgentID, rootOrBaseAgentId);
3302
+ const matchesRoot = root ? UUIDsEqual(root.ID, rootOrBaseAgentId) : false;
3303
+ if (!matchesDirect && !matchesRoot) {
3304
+ return false;
3305
+ }
3306
+ }
1536
3307
  return true;
3308
+ });
3309
+ return filtered.sort((a, b) => {
3310
+ const aOwned = UUIDsEqual(a.OwnerUserID, user.ID) ? 1 : 0;
3311
+ const bOwned = UUIDsEqual(b.OwnerUserID, user.ID) ? 1 : 0;
3312
+ if (aOwned !== bOwned)
3313
+ return bOwned - aOwned;
3314
+ const aPrimary = a.IsPrimaryInstance ? 1 : 0;
3315
+ const bPrimary = b.IsPrimaryInstance ? 1 : 0;
3316
+ if (aPrimary !== bPrimary)
3317
+ return bPrimary - aPrimary;
3318
+ return (a.Name ?? "").localeCompare(b.Name ?? "");
3319
+ });
3320
+ }
3321
+ /**
3322
+ * User-scoped agent resolution by UUID or display name so multiple users naming their
3323
+ * personal bots `"Pepper"`, `"Jarvis"`, or `"Sage"` never collide or shadow system agents.
3324
+ *
3325
+ * Resolution precedence:
3326
+ * 1. Exact UUID match (visible to `user`, or any agent if `user` is omitted)
3327
+ * 2. User's owned active derived agents (`BaseAgentID != null && OwnerUserID === user.ID`)
3328
+ * 3. Shared active derived agents visible to `user`
3329
+ * 4. Root catalog agents (`BaseAgentID == null`) visible to `user`
3330
+ */
3331
+ ResolveAgentForUser(nameOrId, user) {
3332
+ const trimmed = nameOrId?.trim();
3333
+ if (!trimmed) {
3334
+ return void 0;
3335
+ }
3336
+ this.ensureAgentsIndex();
3337
+ const byId = this._agentsByID.get(NormalizeUUID(trimmed));
3338
+ if (byId) {
3339
+ if (!user || this.CanUserViewAgentSync(byId, user)) {
3340
+ return byId;
3341
+ }
3342
+ return void 0;
1537
3343
  }
1538
- const matching = agentPerms.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID != null && userRoleIds.Has(p.RoleID));
1539
- return matching.some((p) => p.CanDelete === true || p.CanEdit === true || p.CanRun === true);
3344
+ const normName = trimmed.toLowerCase();
3345
+ if (!user) {
3346
+ return this._agentsByName.get(normName);
3347
+ }
3348
+ const userRoleIds = new UUIDSet(user.UserRoles?.map((ur) => ur.RoleID) ?? []);
3349
+ const ownedDerived = this._agents.find((a) => a.Status === "Active" && a.BaseAgentID != null && UUIDsEqual(a.OwnerUserID, user.ID) && (a.Name ?? "").trim().toLowerCase() === normName);
3350
+ if (ownedDerived) {
3351
+ return ownedDerived;
3352
+ }
3353
+ 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);
3354
+ if (sharedDerived) {
3355
+ return sharedDerived;
3356
+ }
3357
+ const rootMatch = this._agents.find((a) => !a.BaseAgentID && (a.Name ?? "").trim().toLowerCase() === normName && AIAgentPermissionHelper.ComputeEffectivePermissionsSync(a, this._agents, this._agentPermissions, user, userRoleIds).canView);
3358
+ return rootMatch;
3359
+ }
3360
+ /**
3361
+ * Deterministically resolves a user's primary active derived instance descending from
3362
+ * `rootAgentIdOrName` (for example, resolving *"Alice's Chief of Staff"* to Alice's
3363
+ * `IsPrimaryInstance = true` *Pepper* agent for inbound email wakes, inter-agent requests,
3364
+ * and Agent Channels).
3365
+ *
3366
+ * Preference order among `userId`'s active owned instances under the root:
3367
+ * 1. Instance with `IsPrimaryInstance === true`
3368
+ * 2. Earliest-created active instance (fallback when no primary flag is set)
3369
+ * 3. `undefined` when the user has not instantiated an instance under that root yet.
3370
+ */
3371
+ ResolvePrimaryUserAgentInstance(rootAgentIdOrName, userId) {
3372
+ if (!rootAgentIdOrName || !userId) {
3373
+ return void 0;
3374
+ }
3375
+ this.ensureAgentsIndex();
3376
+ const rootAgent = this._agentsByID.get(NormalizeUUID(rootAgentIdOrName)) ?? this._agentsByName.get(rootAgentIdOrName.trim().toLowerCase());
3377
+ const targetRootId = rootAgent?.ID ?? rootAgentIdOrName;
3378
+ const candidates = this._agents.filter((a) => {
3379
+ if (a.Status !== "Active" || !a.BaseAgentID || !UUIDsEqual(a.OwnerUserID, userId)) {
3380
+ return false;
3381
+ }
3382
+ const chainRoot = this.GetRootAgent(a.ID);
3383
+ return UUIDsEqual(a.BaseAgentID, targetRootId) || chainRoot != null && UUIDsEqual(chainRoot.ID, targetRootId);
3384
+ });
3385
+ if (candidates.length === 0) {
3386
+ return void 0;
3387
+ }
3388
+ const explicitPrimary = candidates.find((a) => a.IsPrimaryInstance === true);
3389
+ if (explicitPrimary) {
3390
+ return explicitPrimary;
3391
+ }
3392
+ return candidates.sort((a, b) => (a.Name ?? "").localeCompare(b.Name ?? ""))[0];
3393
+ }
3394
+ /**
3395
+ * Synchronous permission check using already-loaded `_agentPermissions` metadata.
3396
+ * Delegates to {@link AIAgentPermissionHelper.ComputeEffectivePermissionsSync} so
3397
+ * 2x2 RBAC and Ancestor `CanRun` semantics stay 100% consistent everywhere.
3398
+ */
3399
+ canUserRunAgentSync(agent, allPermissions, user, userRoleIds) {
3400
+ return AIAgentPermissionHelper.ComputeEffectivePermissionsSync(agent, this._agents, allPermissions, user, userRoleIds).canRun;
1540
3401
  }
1541
3402
  summarizeAgentDescription(rawDescription) {
1542
3403
  if (!rawDescription) {
@@ -1598,16 +3459,73 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1598
3459
  * @param user - Optional user; when present, filters to skills the user can Run.
1599
3460
  * @returns MJAISkillEntity[] - Active skills the agent may activate (empty if AcceptsSkills is 'None').
1600
3461
  */
3462
+ /**
3463
+ * Resolves the effective narrowed `AcceptsSkills` value down the agent's `BaseAgentID`
3464
+ * chain (`All` -> `Limited` -> `None`) without reading unrelated scalar columns.
3465
+ */
3466
+ resolveEffectiveAcceptsSkills(agent) {
3467
+ const nodes = this.resolveInheritanceNodesForAgent(agent);
3468
+ const acceptsRank = {
3469
+ None: 0,
3470
+ Limited: 1,
3471
+ All: 2
3472
+ };
3473
+ let effective = nodes[0]?.AcceptsSkills ?? "None";
3474
+ for (let i = 1; i < nodes.length; i++) {
3475
+ const nodeAccepts = nodes[i].AcceptsSkills;
3476
+ if (nodeAccepts != null && (acceptsRank[nodeAccepts] ?? 0) < (acceptsRank[effective] ?? 0)) {
3477
+ effective = nodeAccepts;
3478
+ }
3479
+ }
3480
+ return effective;
3481
+ }
3482
+ /**
3483
+ * Resolves the effective narrowed `SkillActivationMode` across all configuration tiers
3484
+ * (`AIAgentType` -> `AIAgentCategory` chain -> `BaseAgentID` chain -> leaf `AIAgent`,
3485
+ * `Auto` -> `RequestedOnly`) by delegating to {@link ResolveEffectiveAgentProperties} (R3-9).
3486
+ */
3487
+ resolveEffectiveSkillActivationMode(agent) {
3488
+ return this.ResolveEffectiveAgentProperties(agent).SkillActivationMode;
3489
+ }
1601
3490
  GetSkillsForAgent(agent, user) {
1602
- if (!agent || agent.AcceptsSkills === "None") {
3491
+ if (!agent) {
3492
+ return [];
3493
+ }
3494
+ const effectiveAcceptsSkills = this.resolveEffectiveAcceptsSkills(agent);
3495
+ if (effectiveAcceptsSkills === "None") {
1603
3496
  return [];
1604
3497
  }
1605
3498
  const activeSkills = this._skills.filter((s) => s.Status === "Active");
1606
3499
  let agentSkills;
1607
- if (agent.AcceptsSkills === "All") {
3500
+ if (effectiveAcceptsSkills === "All") {
1608
3501
  agentSkills = activeSkills;
1609
3502
  } else {
1610
- const grantedSkillIDs = new Set(this._agentSkills.filter((gs) => UUIDsEqual(gs.AgentID, agent.ID) && gs.Status === "Active").map((gs) => NormalizeUUID(gs.SkillID)));
3503
+ const nodes = this.resolveInheritanceNodesForAgent(agent);
3504
+ const chainIds = nodes.map((a) => a.ID);
3505
+ const chainIdSet = new UUIDSet(chainIds);
3506
+ const grantsByAgentId = /* @__PURE__ */ new Map();
3507
+ for (const gs of this._agentSkills) {
3508
+ if (chainIdSet.Has(gs.AgentID)) {
3509
+ const key = NormalizeUUID(gs.AgentID);
3510
+ const list = grantsByAgentId.get(key) ?? [];
3511
+ list.push(gs);
3512
+ grantsByAgentId.set(key, list);
3513
+ }
3514
+ }
3515
+ const grantedSkillIDs = /* @__PURE__ */ new Set();
3516
+ for (let idx = 0; idx < nodes.length; idx++) {
3517
+ const isRoot = idx === 0;
3518
+ const canWiden = idx > 0 && DoesAgentAllowWidenFromBase(nodes[idx].Configuration);
3519
+ const grants = grantsByAgentId.get(NormalizeUUID(nodes[idx].ID)) ?? [];
3520
+ for (const grant of grants) {
3521
+ const normSkillId = NormalizeUUID(grant.SkillID);
3522
+ if (grant.Status !== "Active") {
3523
+ grantedSkillIDs.delete(normSkillId);
3524
+ } else if (isRoot || canWiden) {
3525
+ grantedSkillIDs.add(normSkillId);
3526
+ }
3527
+ }
3528
+ }
1611
3529
  agentSkills = activeSkills.filter((s) => grantedSkillIDs.has(NormalizeUUID(s.ID)));
1612
3530
  }
1613
3531
  if (!user) {
@@ -1644,7 +3562,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1644
3562
  * gate is 'RequestedOnly', or when no availability gate passes).
1645
3563
  */
1646
3564
  GetAutoActivatableSkillsForAgent(agent, user) {
1647
- if (!agent || agent.SkillActivationMode !== "Auto") {
3565
+ if (!agent) {
3566
+ return [];
3567
+ }
3568
+ if (this.resolveEffectiveSkillActivationMode(agent) !== "Auto") {
1648
3569
  return [];
1649
3570
  }
1650
3571
  return this.GetSkillsForAgent(agent, user).filter((s) => s.ActivationMode === "Auto");
@@ -1669,6 +3590,33 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1669
3590
  GetSkillExposedActionIDs(skillID) {
1670
3591
  return this._skillActions.filter((sa) => UUIDsEqual(sa.SkillID, skillID) && sa.ExposeToModel !== false).map((sa) => sa.ActionID);
1671
3592
  }
3593
+ /**
3594
+ * The subset of {@link GetSkillActionIDs} marked as briefing contributors (`Role = 'Briefing' | 'Both'`).
3595
+ * Invoked in parallel by `Assemble My Briefing` so a Loop agent (such as Chief of Staff) collects
3596
+ * deterministic per-app briefing sections without relying on prompt memory or cluttering its tool list.
3597
+ */
3598
+ GetSkillBriefingActionIDs(skillID) {
3599
+ return this._skillActions.filter((sa) => UUIDsEqual(sa.SkillID, skillID) && (sa.Role === "Briefing" || sa.Role === "Both")).map((sa) => sa.ActionID);
3600
+ }
3601
+ /**
3602
+ * Returns every briefing contributor (`Role = 'Briefing' | 'Both'`) across all skills granted
3603
+ * to `agent` that `user` is permitted to use (via {@link GetSkillsForAgent}). Deduplicates by `ActionID`.
3604
+ */
3605
+ GetBriefingActionsForAgent(agent, user) {
3606
+ const skills = this.GetSkillsForAgent(agent, user);
3607
+ const seen = /* @__PURE__ */ new Set();
3608
+ const entries = [];
3609
+ for (const skill of skills) {
3610
+ for (const actionID of this.GetSkillBriefingActionIDs(skill.ID)) {
3611
+ const key = actionID.trim().toLowerCase();
3612
+ if (!seen.has(key)) {
3613
+ seen.add(key);
3614
+ entries.push({ skill, actionID });
3615
+ }
3616
+ }
3617
+ }
3618
+ return entries;
3619
+ }
1672
3620
  /**
1673
3621
  * Returns the sub-agent IDs bundled into a skill (via "MJ: AI Skill Sub Agents"). Callers
1674
3622
  * resolve the full `MJAIAgentEntityExtended` objects via `this.Agents` / `GetAgentByID`.
@@ -1694,9 +3642,21 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1694
3642
  */
1695
3643
  GetAgentConfigurationPresets(agentId, activeOnly = true) {
1696
3644
  this.ensureAgentConfigurationsIndex();
1697
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId)) ?? [];
1698
- const presets = activeOnly ? raw.filter((ac) => ac.Status === "Active") : raw.slice();
1699
- return presets.sort((a, b) => a.Priority - b.Priority);
3645
+ const chain = this.GetAgentInheritanceChain(agentId);
3646
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => NormalizeUUID(a.ID)) : [NormalizeUUID(agentId)];
3647
+ const byPresetName = /* @__PURE__ */ new Map();
3648
+ for (const id of idsRootToLeaf) {
3649
+ const raw = this._agentConfigurationsByAgentID.get(id) ?? [];
3650
+ for (const preset of raw) {
3651
+ const key = (preset.Name ?? preset.ID).trim().toLowerCase();
3652
+ if (activeOnly && preset.Status !== "Active") {
3653
+ byPresetName.delete(key);
3654
+ } else {
3655
+ byPresetName.set(key, preset);
3656
+ }
3657
+ }
3658
+ }
3659
+ return Array.from(byPresetName.values()).sort((a, b) => a.Priority - b.Priority);
1700
3660
  }
1701
3661
  /**
1702
3662
  * Gets the default configuration preset for an agent
@@ -1714,11 +3674,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1714
3674
  * @returns The configuration preset, or undefined if not found
1715
3675
  */
1716
3676
  GetAgentConfigurationPresetByName(agentId, presetName) {
1717
- this.ensureAgentConfigurationsIndex();
1718
- const raw = this._agentConfigurationsByAgentID.get(NormalizeUUID(agentId));
1719
- if (!raw)
1720
- return void 0;
1721
- return raw.find((ac) => ac.Name === presetName && ac.Status === "Active");
3677
+ const presets = this.GetAgentConfigurationPresets(agentId, true);
3678
+ return presets.find((ac) => ac.Name === presetName);
1722
3679
  }
1723
3680
  get AgentNoteTypes() {
1724
3681
  return this.GetConfigData("_agentNoteTypes");
@@ -1901,7 +3858,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1901
3858
  if (a.ID) {
1902
3859
  byId.set(NormalizeUUID(a.ID), a);
1903
3860
  }
1904
- if (a.Name) {
3861
+ if (a.Name && !a.BaseAgentID) {
1905
3862
  const normName = a.Name.trim().toLowerCase();
1906
3863
  if (!byName.has(normName)) {
1907
3864
  byName.set(normName, a);
@@ -1917,9 +3874,18 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1917
3874
  list.push(a);
1918
3875
  }
1919
3876
  }
3877
+ for (const a of this._agents) {
3878
+ if (a.Name && a.BaseAgentID) {
3879
+ const normName = a.Name.trim().toLowerCase();
3880
+ if (!byName.has(normName)) {
3881
+ byName.set(normName, a);
3882
+ }
3883
+ }
3884
+ }
1920
3885
  this._agentsByID = byId;
1921
3886
  this._agentsByName = byName;
1922
3887
  this._childAgentsByParentID = byParentId;
3888
+ this._agentInheritanceChainCache.clear();
1923
3889
  this._agentsIndexedRef = this._agents;
1924
3890
  this._agentsIndexedLen = this._agents.length;
1925
3891
  }
@@ -2478,7 +4444,36 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2478
4444
  * Joins through the junction table to return full tool definition entities.
2479
4445
  */
2480
4446
  GetClientToolsForAgent(agentId) {
2481
- const junctions = this._agentClientTools.filter((j) => UUIDsEqual(j.AgentID, agentId)).sort((a, b) => a.Priority - b.Priority);
4447
+ const chain = this.GetAgentInheritanceChain(agentId);
4448
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
4449
+ id: a.ID,
4450
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
4451
+ })) : [{ id: agentId, canWiden: false }];
4452
+ const chainIdSet = new UUIDSet(nodes.map((n) => n.id));
4453
+ const toolsByAgentId = /* @__PURE__ */ new Map();
4454
+ for (const j of this._agentClientTools) {
4455
+ if (chainIdSet.Has(j.AgentID)) {
4456
+ const key = NormalizeUUID(j.AgentID);
4457
+ const list = toolsByAgentId.get(key) ?? [];
4458
+ list.push(j);
4459
+ toolsByAgentId.set(key, list);
4460
+ }
4461
+ }
4462
+ const mergedByToolId = /* @__PURE__ */ new Map();
4463
+ for (let idx = 0; idx < nodes.length; idx++) {
4464
+ const { id, canWiden } = nodes[idx];
4465
+ const isRoot = idx === 0;
4466
+ const rows = toolsByAgentId.get(NormalizeUUID(id)) ?? [];
4467
+ for (const row of rows) {
4468
+ if (!row.ClientToolDefinitionID)
4469
+ continue;
4470
+ const normToolId = NormalizeUUID(row.ClientToolDefinitionID);
4471
+ if (isRoot || canWiden || mergedByToolId.has(normToolId)) {
4472
+ mergedByToolId.set(normToolId, row);
4473
+ }
4474
+ }
4475
+ }
4476
+ const junctions = Array.from(mergedByToolId.values()).sort((a, b) => a.Priority - b.Priority);
2482
4477
  const tools = [];
2483
4478
  for (const junction of junctions) {
2484
4479
  const tool = this._clientToolDefinitions.find((t) => UUIDsEqual(t.ID, junction.ClientToolDefinitionID));
@@ -2515,8 +4510,10 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2515
4510
  if (!agent) {
2516
4511
  return void 0;
2517
4512
  }
2518
- if (agent.ModelSelectionMode === "Agent") {
2519
- const agentPrompt = this._agentPrompts.filter((ap) => UUIDsEqual(ap.AgentID, agent.ID) && ap.Status === "Active").sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
4513
+ const effectiveProps = this.ResolveEffectiveAgentProperties(agent);
4514
+ const effectivePrompts = this.GetEffectiveAgentPrompts(agent.ID, "Active");
4515
+ if (effectiveProps.ModelSelectionMode === "Agent") {
4516
+ const agentPrompt = effectivePrompts[0];
2520
4517
  if (agentPrompt) {
2521
4518
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2522
4519
  if (promptModels && promptModels.length > 0) {
@@ -2524,8 +4521,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2524
4521
  }
2525
4522
  }
2526
4523
  }
2527
- if (agent.TypeID) {
2528
- const agentType = this._agentTypes.find((at) => UUIDsEqual(at.ID, agent.TypeID));
4524
+ if (effectiveProps.TypeID) {
4525
+ const agentType = this._agentTypes.find((at) => UUIDsEqual(at.ID, effectiveProps.TypeID));
2529
4526
  if (agentType?.SystemPromptID) {
2530
4527
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentType.SystemPromptID));
2531
4528
  if (promptModels && promptModels.length > 0) {
@@ -2533,8 +4530,8 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2533
4530
  }
2534
4531
  }
2535
4532
  }
2536
- if (agent.ModelSelectionMode !== "Agent") {
2537
- const agentPrompt = this._agentPrompts.filter((ap) => UUIDsEqual(ap.AgentID, agent.ID) && ap.Status === "Active").sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
4533
+ if (effectiveProps.ModelSelectionMode !== "Agent") {
4534
+ const agentPrompt = effectivePrompts[0];
2538
4535
  if (agentPrompt) {
2539
4536
  const promptModels = this.PromptModelsByPromptID.get(NormalizeUUID(agentPrompt.PromptID));
2540
4537
  if (promptModels && promptModels.length > 0) {
@@ -2546,13 +4543,9 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2546
4543
  }
2547
4544
  /**
2548
4545
  * Gets all modalities supported by an agent for a given direction.
2549
- * Follows precedence chain: Agent → Model → System → Default.
4546
+ * Follows precedence chain: Agent (walked BaseAgentID root -> leaf) → Model → System → Default.
2550
4547
  * If no explicit agent modality records exist, falls through to the agent's model's effective modalities.
2551
4548
  * Any explicit AIAgentModality records override: IsAllowed = 1 adds/retains, IsAllowed = 0 acts as a hard veto.
2552
- * @param agentId - The agent ID
2553
- * @param direction - 'Input' or 'Output'
2554
- * @param modelId - Optional model ID override
2555
- * @returns Array of modality entities the agent supports
2556
4549
  */
2557
4550
  GetAgentModalities(agentId, direction, modelId) {
2558
4551
  this.ensureModalitiesIndex();
@@ -2562,17 +4555,38 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2562
4555
  for (const m of baseModalities) {
2563
4556
  resultMap.set(NormalizeUUID(m.ID), m);
2564
4557
  }
2565
- const agentRecords = this._agentModalities.filter((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction);
2566
- for (const am of agentRecords) {
2567
- const normId = NormalizeUUID(am.ModalityID);
2568
- const isAllowed = am.IsAllowed !== false;
2569
- if (isAllowed) {
2570
- const modality = this._modalitiesByID.get(normId);
2571
- if (modality) {
2572
- resultMap.set(normId, modality);
4558
+ const chain = this.GetAgentInheritanceChain(agentId);
4559
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
4560
+ id: a.ID,
4561
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
4562
+ })) : [{ id: agentId, canWiden: false }];
4563
+ const chainIdSet = new UUIDSet(nodes.map((n) => n.id));
4564
+ const modalitiesByAgentId = /* @__PURE__ */ new Map();
4565
+ for (const am of this._agentModalities) {
4566
+ if (am.Direction === direction && chainIdSet.Has(am.AgentID)) {
4567
+ const key = NormalizeUUID(am.AgentID);
4568
+ const list = modalitiesByAgentId.get(key) ?? [];
4569
+ list.push(am);
4570
+ modalitiesByAgentId.set(key, list);
4571
+ }
4572
+ }
4573
+ for (let idx = 0; idx < nodes.length; idx++) {
4574
+ const { id, canWiden } = nodes[idx];
4575
+ const isRoot = idx === 0;
4576
+ const agentRecords = modalitiesByAgentId.get(NormalizeUUID(id)) ?? [];
4577
+ for (const am of agentRecords) {
4578
+ const normId = NormalizeUUID(am.ModalityID);
4579
+ const isAllowed = am.IsAllowed !== false;
4580
+ if (isAllowed) {
4581
+ if (isRoot || canWiden || resultMap.has(normId)) {
4582
+ const modality = this._modalitiesByID.get(normId);
4583
+ if (modality) {
4584
+ resultMap.set(normId, modality);
4585
+ }
4586
+ }
4587
+ } else {
4588
+ resultMap.delete(normId);
2573
4589
  }
2574
- } else {
2575
- resultMap.delete(normId);
2576
4590
  }
2577
4591
  }
2578
4592
  return Array.from(resultMap.values());
@@ -2633,17 +4647,39 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2633
4647
  AgentSupportsModality(agentId, modalityName, direction, modelId) {
2634
4648
  this.ensureModalitiesIndex();
2635
4649
  const targetModality = this._modalitiesByName.get(modalityName.toLowerCase());
4650
+ const resolvedModelId = this.resolveAgentModelId(agentId, modelId);
4651
+ let supported = resolvedModelId ? this.ModelSupportsModality(resolvedModelId, modalityName, direction) : modalityName.toLowerCase() === "text";
2636
4652
  if (targetModality) {
2637
- const agentRecord = this._agentModalities.find((am) => UUIDsEqual(am.AgentID, agentId) && am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID));
2638
- if (agentRecord) {
2639
- return agentRecord.IsAllowed !== false;
4653
+ const chain = this.GetAgentInheritanceChain(agentId);
4654
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
4655
+ id: a.ID,
4656
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
4657
+ })) : [{ id: agentId, canWiden: false }];
4658
+ const chainIdSet = new UUIDSet(nodes.map((n) => n.id));
4659
+ const recordByAgentId = /* @__PURE__ */ new Map();
4660
+ for (const am of this._agentModalities) {
4661
+ if (am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID) && chainIdSet.Has(am.AgentID)) {
4662
+ const key = NormalizeUUID(am.AgentID);
4663
+ if (!recordByAgentId.has(key)) {
4664
+ recordByAgentId.set(key, am);
4665
+ }
4666
+ }
4667
+ }
4668
+ for (let idx = 0; idx < nodes.length; idx++) {
4669
+ const { id, canWiden } = nodes[idx];
4670
+ const isRoot = idx === 0;
4671
+ const agentRecord = recordByAgentId.get(NormalizeUUID(id));
4672
+ if (!agentRecord) {
4673
+ continue;
4674
+ }
4675
+ if (agentRecord.IsAllowed === false) {
4676
+ supported = false;
4677
+ } else if (isRoot || canWiden) {
4678
+ supported = true;
4679
+ }
2640
4680
  }
2641
4681
  }
2642
- const resolvedModelId = this.resolveAgentModelId(agentId, modelId);
2643
- if (resolvedModelId) {
2644
- return this.ModelSupportsModality(resolvedModelId, modalityName, direction);
2645
- }
2646
- return modalityName.toLowerCase() === "text";
4682
+ return supported;
2647
4683
  }
2648
4684
  /**
2649
4685
  * Checks if a model supports a specific modality for a given direction.
@@ -2705,16 +4741,64 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2705
4741
  source: "Default"
2706
4742
  };
2707
4743
  }
2708
- const agentModality = this._agentModalities.find((am) => UUIDsEqual(am.AgentID, agentId) && UUIDsEqual(am.ModalityID, modality.ID) && am.Direction === "Input");
2709
- if (agentModality) {
4744
+ const chain = this.GetAgentInheritanceChain(agentId);
4745
+ const nodes = chain.length > 0 ? chain.map((a, idx) => ({
4746
+ id: a.ID,
4747
+ canWiden: idx > 0 && DoesAgentAllowWidenFromBase(a.Configuration)
4748
+ })) : [{ id: agentId, canWiden: false }];
4749
+ const chainIdSet = new UUIDSet(nodes.map((n) => n.id));
4750
+ const modalityByAgentId = /* @__PURE__ */ new Map();
4751
+ for (const am of this._agentModalities) {
4752
+ if (am.Direction === "Input" && UUIDsEqual(am.ModalityID, modality.ID) && chainIdSet.Has(am.AgentID)) {
4753
+ const key = NormalizeUUID(am.AgentID);
4754
+ if (!modalityByAgentId.has(key)) {
4755
+ modalityByAgentId.set(key, am);
4756
+ }
4757
+ }
4758
+ }
4759
+ const minNullable = (a, b) => {
4760
+ if (typeof b !== "number" || !Number.isFinite(b))
4761
+ return a;
4762
+ return a === null ? b : Math.min(a, b);
4763
+ };
4764
+ let matchedAnyAgentRow = false;
4765
+ let resolvedMaxSizeBytes = null;
4766
+ let resolvedMaxCount = null;
4767
+ let resolvedIsAllowed = true;
4768
+ for (let idx = 0; idx < nodes.length; idx++) {
4769
+ const { id, canWiden } = nodes[idx];
4770
+ const found = modalityByAgentId.get(NormalizeUUID(id));
4771
+ if (!found)
4772
+ continue;
4773
+ if (!matchedAnyAgentRow) {
4774
+ matchedAnyAgentRow = true;
4775
+ resolvedMaxSizeBytes = found.MaxSizeBytes ?? null;
4776
+ resolvedMaxCount = found.MaxCountPerMessage ?? null;
4777
+ resolvedIsAllowed = found.IsAllowed !== false;
4778
+ continue;
4779
+ }
4780
+ if (canWiden) {
4781
+ resolvedIsAllowed = found.IsAllowed !== false;
4782
+ if (found.MaxSizeBytes != null)
4783
+ resolvedMaxSizeBytes = found.MaxSizeBytes;
4784
+ if (found.MaxCountPerMessage != null)
4785
+ resolvedMaxCount = found.MaxCountPerMessage;
4786
+ } else {
4787
+ if (found.IsAllowed === false)
4788
+ resolvedIsAllowed = false;
4789
+ resolvedMaxSizeBytes = minNullable(resolvedMaxSizeBytes, found.MaxSizeBytes);
4790
+ resolvedMaxCount = minNullable(resolvedMaxCount, found.MaxCountPerMessage);
4791
+ }
4792
+ }
4793
+ if (matchedAnyAgentRow) {
2710
4794
  return {
2711
- maxSizeBytes: agentModality.MaxSizeBytes,
2712
- maxCountPerMessage: agentModality.MaxCountPerMessage,
4795
+ maxSizeBytes: resolvedMaxSizeBytes,
4796
+ maxCountPerMessage: resolvedMaxCount,
2713
4797
  maxDimension: null,
2714
4798
  // Agent modality doesn't have MaxDimension
2715
4799
  supportedFormats: null,
2716
4800
  // Agent modality doesn't have SupportedFormats
2717
- isAllowed: agentModality.IsAllowed,
4801
+ isAllowed: resolvedIsAllowed,
2718
4802
  source: "Agent"
2719
4803
  };
2720
4804
  }
@@ -2978,16 +5062,56 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2978
5062
  return excludedApiNames;
2979
5063
  }
2980
5064
  /**
2981
- * Gets all personas configured for an agent, ordered by Sequence.
2982
- * Only returns personas where IsAllowed is true and the persona record is active.
5065
+ * Gets all personas configured for an agent across its `BaseAgentID` inheritance chain
5066
+ * (root -> leaf), ordered by `Sequence`. Descendant rows override ancestor rows for the
5067
+ * same `PersonaID`, and descendant `IsAllowed === false` vetoes an inherited persona.
2983
5068
  *
2984
5069
  * @param agentId - The agent ID
2985
5070
  * @returns Array of resolved agent personas
2986
5071
  */
2987
5072
  GetAgentPersonas(agentId) {
2988
- const agentRecords = this._agentPersonas.filter((ap) => UUIDsEqual(ap.AgentID, agentId) && ap.IsAllowed).sort((a, b) => (a.Sequence ?? 0) - (b.Sequence ?? 0));
5073
+ const chain = this.GetAgentInheritanceChain(agentId);
5074
+ const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
5075
+ const chainIdSet = new UUIDSet(idsRootToLeaf);
5076
+ const personasByAgentId = /* @__PURE__ */ new Map();
5077
+ for (const ap of this._agentPersonas) {
5078
+ if (chainIdSet.Has(ap.AgentID)) {
5079
+ const key = NormalizeUUID(ap.AgentID);
5080
+ const list = personasByAgentId.get(key) ?? [];
5081
+ list.push(ap);
5082
+ personasByAgentId.set(key, list);
5083
+ }
5084
+ }
5085
+ const mergedByPersonaId = /* @__PURE__ */ new Map();
5086
+ const depthByPersonaId = /* @__PURE__ */ new Map();
5087
+ idsRootToLeaf.forEach((id, depth) => {
5088
+ const rows = personasByAgentId.get(NormalizeUUID(id)) ?? [];
5089
+ for (const ap of rows) {
5090
+ if (!ap.PersonaID)
5091
+ continue;
5092
+ const normPersonaId = NormalizeUUID(ap.PersonaID);
5093
+ if (ap.IsAllowed === false) {
5094
+ mergedByPersonaId.delete(normPersonaId);
5095
+ depthByPersonaId.delete(normPersonaId);
5096
+ } else {
5097
+ mergedByPersonaId.set(normPersonaId, ap);
5098
+ depthByPersonaId.set(normPersonaId, depth);
5099
+ }
5100
+ }
5101
+ });
5102
+ const sortedRecords = Array.from(mergedByPersonaId.entries()).sort(([idA, a], [idB, b]) => {
5103
+ const aDef = a.IsDefault ? 1 : 0;
5104
+ const bDef = b.IsDefault ? 1 : 0;
5105
+ if (aDef !== bDef)
5106
+ return bDef - aDef;
5107
+ const depthA = depthByPersonaId.get(idA) ?? 0;
5108
+ const depthB = depthByPersonaId.get(idB) ?? 0;
5109
+ if (aDef === 1 && depthA !== depthB)
5110
+ return depthB - depthA;
5111
+ return (a.Sequence ?? 0) - (b.Sequence ?? 0);
5112
+ }).map(([, ap]) => ap);
2989
5113
  const result = [];
2990
- for (const ap of agentRecords) {
5114
+ for (const ap of sortedRecords) {
2991
5115
  const persona = this._personas.find((p) => UUIDsEqual(p.ID, ap.PersonaID) && p.IsActive);
2992
5116
  if (persona) {
2993
5117
  result.push({
@@ -3000,28 +5124,42 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3000
5124
  }
3001
5125
  /**
3002
5126
  * Resolves the effective persona for an agent using the precedence chain:
3003
- * 1. Agent's default persona (AIAgentPersona where IsDefault = 1 and IsAllowed = 1)
3004
- * 2. First allowed agent persona (by Sequence)
3005
- * 3. Model/vendor default persona (from GetModelPersonas)
5127
+ * 1. Explicit `options.preferredPersonaId` (e.g. from `AIAgentUserPolicy.PreferredPersonaID`)
5128
+ * 2. Agent's default persona across its `BaseAgentID` chain (`AIAgentPersona` where `IsDefault = 1`, leaf wins)
5129
+ * 3. First allowed agent persona (by Sequence)
5130
+ * 4. Model/vendor default persona (from GetModelPersonas)
3006
5131
  *
3007
5132
  * In all cases, merges agent-level StyleOverride (Tone, SpeakingStyle) over the persona's defaults.
3008
5133
  *
3009
5134
  * @param agentId - The agent ID
3010
- * @param options - Optional overrides for modelId, vendorId, modalityName
5135
+ * @param options - Optional overrides for modelId, vendorId, modalityName, preferredPersonaId, and allowModelFallback (defaults to true)
3011
5136
  */
3012
5137
  ResolveAgentPersona(agentId, options) {
3013
5138
  const modalityName = options?.modalityName ?? "Audio";
3014
5139
  const agentPersonas = this.GetAgentPersonas(agentId);
3015
5140
  let chosenPersona = null;
3016
5141
  let chosenAgentPersona = void 0;
3017
- if (agentPersonas.length > 0) {
5142
+ if (options?.preferredPersonaId) {
5143
+ const matchedAgentPersona = agentPersonas.find((ap) => UUIDsEqual(ap.Persona.ID, options.preferredPersonaId));
5144
+ if (matchedAgentPersona) {
5145
+ chosenPersona = matchedAgentPersona.Persona;
5146
+ chosenAgentPersona = matchedAgentPersona.AgentPersona;
5147
+ } else {
5148
+ const catalogPersona = this._personas.find((p) => UUIDsEqual(p.ID, options.preferredPersonaId) && p.IsActive);
5149
+ if (catalogPersona) {
5150
+ chosenPersona = catalogPersona;
5151
+ chosenAgentPersona = agentPersonas.find((ap) => ap.AgentPersona.IsDefault)?.AgentPersona ?? agentPersonas[0]?.AgentPersona;
5152
+ }
5153
+ }
5154
+ }
5155
+ if (!chosenPersona && agentPersonas.length > 0) {
3018
5156
  const defaultAP = agentPersonas.find((ap) => ap.AgentPersona.IsDefault);
3019
5157
  const selected = defaultAP ?? agentPersonas[0];
3020
5158
  chosenPersona = selected.Persona;
3021
5159
  chosenAgentPersona = selected.AgentPersona;
3022
5160
  }
3023
5161
  const resolvedModelId = this.resolveAgentModelId(agentId, options?.modelId);
3024
- if (!chosenPersona && resolvedModelId) {
5162
+ if (!chosenPersona && resolvedModelId && options?.allowModelFallback !== false) {
3025
5163
  const modelPersonas = this.GetModelPersonas(resolvedModelId, modalityName, options?.vendorId);
3026
5164
  if (modelPersonas.length > 0) {
3027
5165
  chosenPersona = modelPersonas[0].Persona;
@@ -3715,7 +5853,7 @@ var AgentClientSession = class {
3715
5853
  if (!provider) {
3716
5854
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3717
5855
  }
3718
- const aiClient = new tt(provider);
5856
+ const aiClient = new rt(provider);
3719
5857
  try {
3720
5858
  const agentShim = { ID: params.AgentId };
3721
5859
  const messages = params.Messages.map((m) => ({
@@ -3773,7 +5911,7 @@ var AgentClientSession = class {
3773
5911
  if (!provider) {
3774
5912
  return { Success: false, ErrorMessage: "GraphQL provider not available" };
3775
5913
  }
3776
- const aiClient = new tt(provider);
5914
+ const aiClient = new rt(provider);
3777
5915
  try {
3778
5916
  const gqlParams = {
3779
5917
  userMessageId: params.UserMessageId,
@@ -4214,6 +6352,24 @@ function IntersectAcceptedSkills(runnable, accepted) {
4214
6352
  }
4215
6353
 
4216
6354
  // ../../ConversationsRuntime/dist/mentions/MentionAutocomplete.js
6355
+ var GROUP_LABELS = {
6356
+ frequent: "Frequent & Recent",
6357
+ "my-agents": "My Agents",
6358
+ shared: "Shared",
6359
+ people: "People",
6360
+ results: "Results"
6361
+ };
6362
+ var FRECENCY_SETTING_KEY = "chat.mentionFrecency";
6363
+ var MAX_FRECENCY_ENTRIES = 100;
6364
+ var FRECENCY_DECAY_HOURS = 72;
6365
+ var FRECENCY_USE_WEIGHT = 6;
6366
+ var BOOST_IN_THREAD = 25;
6367
+ var BOOST_DEFAULT_CHAT_AGENT = 18;
6368
+ var BOOST_MY_AGENT = 12;
6369
+ var MAX_FREQUENT_ITEMS = 3;
6370
+ var AUTO_SYNC_DEBOUNCE_MS = 50;
6371
+ var AGENT_WATCHED_ENTITIES = /* @__PURE__ */ new Set(["mj: ai agents", "mj: ai agent permissions"]);
6372
+ var SKILL_WATCHED_ENTITIES = /* @__PURE__ */ new Set(["mj: ai skills"]);
4217
6373
  var MentionAutocomplete = class extends BaseSingleton {
4218
6374
  constructor() {
4219
6375
  super();
@@ -4226,53 +6382,309 @@ var MentionAutocomplete = class extends BaseSingleton {
4226
6382
  this.queriesEntityIcon = "fa-solid fa-database";
4227
6383
  this.isInitialized = false;
4228
6384
  this.initializationPromise = null;
6385
+ this.frecencyMap = /* @__PURE__ */ new Map();
6386
+ this.lastSyncedFrecencyRaw = null;
6387
+ this.entityEventSubscription = null;
6388
+ this.syncDebounceTimer = null;
6389
+ this.pendingAgentSync = false;
6390
+ this.pendingSkillSync = false;
4229
6391
  }
4230
6392
  /** The process-wide shared instance (Global Object Store backed). */
4231
6393
  static get Instance() {
4232
6394
  return super.getInstance();
4233
6395
  }
4234
- /** True once the caches have loaded (agents/users/entities/queries/skills). */
4235
- get IsInitialized() {
4236
- return this.isInitialized;
6396
+ /** True once the caches have loaded (agents/users/entities/queries/skills). */
6397
+ get IsInitialized() {
6398
+ return this.isInitialized;
6399
+ }
6400
+ /**
6401
+ * Initialize the service by loading agents and users
6402
+ * Prevents concurrent initialization with promise lock
6403
+ */
6404
+ async initialize(currentUser, provider) {
6405
+ if (this.isInitialized) {
6406
+ return;
6407
+ }
6408
+ if (this.initializationPromise) {
6409
+ return this.initializationPromise;
6410
+ }
6411
+ this.initializationPromise = this._initializeInternal(currentUser, provider);
6412
+ try {
6413
+ await this.initializationPromise;
6414
+ } finally {
6415
+ this.initializationPromise = null;
6416
+ }
6417
+ }
6418
+ /**
6419
+ * Internal initialization logic
6420
+ */
6421
+ async _initializeInternal(currentUser, provider) {
6422
+ try {
6423
+ this.currentUser = currentUser;
6424
+ this.provider = provider;
6425
+ const aiEngine = this.aiEngineFor(provider);
6426
+ await aiEngine.Config(false);
6427
+ this.agentsCache = await this.loadRunnableAgents(currentUser, provider);
6428
+ this.usersCache = [currentUser];
6429
+ this.entitiesCache = this.loadReadableEntities(currentUser, provider);
6430
+ this.queriesCache = await this.loadRunnableQueries(currentUser, provider);
6431
+ this.queriesEntityIcon = this.resolveQueriesEntityIcon(provider);
6432
+ this.skillsCache = await this.filterSkillsByRunPermission(currentUser);
6433
+ this.syncFrecencyFromUserSettings();
6434
+ this.ensureEntityEventSubscription();
6435
+ this.isInitialized = true;
6436
+ } catch (error) {
6437
+ console.error("Failed to initialize MentionAutocomplete:", error);
6438
+ throw error;
6439
+ }
6440
+ }
6441
+ /**
6442
+ * Returns the AIEngineBase for the given provider, or the global singleton when none is given.
6443
+ */
6444
+ aiEngineFor(provider) {
6445
+ if (provider && typeof AIEngineBase.GetProviderInstance === "function") {
6446
+ return AIEngineBase.GetProviderInstance(provider, AIEngineBase);
6447
+ }
6448
+ return AIEngineBase.Instance;
6449
+ }
6450
+ /**
6451
+ * Reads `AIEngineBase.ReadableAgents`, applies eligibility filters, and filters by run permission.
6452
+ */
6453
+ async loadRunnableAgents(currentUser, provider) {
6454
+ const aiEngine = this.aiEngineFor(provider);
6455
+ const allAgents = aiEngine.ReadableAgents;
6456
+ const candidateAgents = allAgents.filter((a) => !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent" && !a.IsRestricted && a.InstantiationMode !== "Required");
6457
+ return this.filterAgentsByRunPermission(candidateAgents, currentUser);
6458
+ }
6459
+ /**
6460
+ * Subscribe once to MJGlobal `BaseEntity` events (`save`, `delete`, `remote-invalidate`) for
6461
+ * `'MJ: AI Agents'`, `'MJ: AI Agent Permissions'`, and `'MJ: AI Skills'`, debouncing cache
6462
+ * re-syncs (~50ms) so callers never need manual `Refresh()` calls.
6463
+ */
6464
+ ensureEntityEventSubscription() {
6465
+ if (this.entityEventSubscription) {
6466
+ return;
6467
+ }
6468
+ if (!MJGlobal?.Instance || typeof MJGlobal.Instance.GetEventListener !== "function") {
6469
+ return;
6470
+ }
6471
+ const listener = MJGlobal.Instance.GetEventListener(false);
6472
+ if (!listener || typeof listener.subscribe !== "function") {
6473
+ return;
6474
+ }
6475
+ this.entityEventSubscription = listener.subscribe((event) => {
6476
+ this.handleGlobalEvent(event);
6477
+ });
6478
+ }
6479
+ /**
6480
+ * Filters MJGlobal events down to relevant BaseEntity mutations and schedules a debounced sync.
6481
+ */
6482
+ handleGlobalEvent(event) {
6483
+ const baseEventCode = BaseEntity?.BaseEventCode ?? "BaseEntityEvent";
6484
+ if (event.event !== MJEventType.ComponentEvent || event.eventCode !== baseEventCode) {
6485
+ return;
6486
+ }
6487
+ const entityEvent = this.extractBaseEntityEvent(event.args);
6488
+ if (!entityEvent) {
6489
+ return;
6490
+ }
6491
+ if (entityEvent.type !== "save" && entityEvent.type !== "delete" && entityEvent.type !== "remote-invalidate") {
6492
+ return;
6493
+ }
6494
+ const rawName = entityEvent.baseEntity?.EntityInfo?.Name || entityEvent.entityName || "";
6495
+ const entityName = rawName.trim().toLowerCase();
6496
+ if (!entityName) {
6497
+ return;
6498
+ }
6499
+ let shouldSchedule = false;
6500
+ if (AGENT_WATCHED_ENTITIES.has(entityName)) {
6501
+ this.pendingAgentSync = true;
6502
+ shouldSchedule = true;
6503
+ }
6504
+ if (SKILL_WATCHED_ENTITIES.has(entityName)) {
6505
+ this.pendingSkillSync = true;
6506
+ shouldSchedule = true;
6507
+ }
6508
+ if (shouldSchedule) {
6509
+ this.scheduleAutoSync();
6510
+ }
6511
+ }
6512
+ /**
6513
+ * Type guard narrowing an `MJEvent.args` payload into a `BaseEntityEvent` shape.
6514
+ */
6515
+ extractBaseEntityEvent(args) {
6516
+ if (typeof args !== "object" || args === null) {
6517
+ return null;
6518
+ }
6519
+ const candidate = args;
6520
+ if (typeof candidate.type !== "string") {
6521
+ return null;
6522
+ }
6523
+ return candidate;
6524
+ }
6525
+ /**
6526
+ * Debounces cache re-sync so bursts of entity events coalesce into a single re-sync after ~50ms.
6527
+ */
6528
+ scheduleAutoSync() {
6529
+ if (this.syncDebounceTimer) {
6530
+ clearTimeout(this.syncDebounceTimer);
6531
+ }
6532
+ this.syncDebounceTimer = setTimeout(() => {
6533
+ this.syncDebounceTimer = null;
6534
+ this.flushAutoSync().catch((err) => {
6535
+ console.error("MentionAutocomplete: auto-sync failed:", err);
6536
+ });
6537
+ }, AUTO_SYNC_DEBOUNCE_MS);
4237
6538
  }
4238
6539
  /**
4239
- * Initialize the service by loading agents and users
4240
- * Prevents concurrent initialization with promise lock
6540
+ * Re-syncs `agentsCache` and/or `skillsCache` from `AIEngineBase` without forcing a server reload.
4241
6541
  */
4242
- async initialize(currentUser, provider) {
4243
- if (this.isInitialized) {
6542
+ async flushAutoSync() {
6543
+ const syncAgents = this.pendingAgentSync;
6544
+ const syncSkills = this.pendingSkillSync;
6545
+ this.pendingAgentSync = false;
6546
+ this.pendingSkillSync = false;
6547
+ const user = this.currentUser ?? this.usersCache[0];
6548
+ if (!user) {
4244
6549
  return;
4245
6550
  }
4246
- if (this.initializationPromise) {
4247
- return this.initializationPromise;
6551
+ if (syncAgents) {
6552
+ this.agentsCache = await this.loadRunnableAgents(user, this.provider);
4248
6553
  }
4249
- this.initializationPromise = this._initializeInternal(currentUser, provider);
6554
+ if (syncSkills) {
6555
+ this.skillsCache = await this.filterSkillsByRunPermission(user);
6556
+ }
6557
+ }
6558
+ /**
6559
+ * Record that the user selected a mention suggestion so future suggestions boost it via
6560
+ * exponentially decayed frecency (`uses * 6 * exp(-hours / 72)`).
6561
+ *
6562
+ * Persists to `UserInfoEngine.Instance` under `'chat.mentionFrecency'` (capped at top 100 entries)
6563
+ * when user/setting context is available, while always updating the in-memory map immediately.
6564
+ */
6565
+ RecordMentionUse(id, type, currentUser) {
6566
+ const normalizedId = id?.trim().toLowerCase();
6567
+ if (!normalizedId || !type) {
6568
+ return;
6569
+ }
6570
+ this.syncFrecencyFromUserSettings();
6571
+ const nowMs = Date.now();
6572
+ const existing = this.frecencyMap.get(normalizedId);
6573
+ const updatedEntry = {
6574
+ uses: (existing?.uses ?? 0) + 1,
6575
+ lastUsedAt: new Date(nowMs).toISOString()
6576
+ };
6577
+ this.frecencyMap.set(normalizedId, updatedEntry);
6578
+ this.pruneFrecencyMap(nowMs);
6579
+ const serialized = this.serializeFrecencyMap();
6580
+ this.lastSyncedFrecencyRaw = serialized;
6581
+ this.persistFrecencySetting(serialized, currentUser);
6582
+ }
6583
+ /**
6584
+ * Reads `chat.mentionFrecency` from `UserInfoEngine.Instance` if it changed since last sync.
6585
+ * Safe no-op in mocked or uninitialized test environments.
6586
+ */
6587
+ syncFrecencyFromUserSettings() {
6588
+ const raw = this.readUserSetting(FRECENCY_SETTING_KEY);
6589
+ if (raw == null || raw === this.lastSyncedFrecencyRaw) {
6590
+ return;
6591
+ }
6592
+ this.lastSyncedFrecencyRaw = raw;
6593
+ this.frecencyMap.clear();
4250
6594
  try {
4251
- await this.initializationPromise;
4252
- } finally {
4253
- this.initializationPromise = null;
6595
+ const parsed = JSON.parse(raw);
6596
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
6597
+ return;
6598
+ }
6599
+ for (const [key, candidate] of Object.entries(parsed)) {
6600
+ if (typeof candidate === "object" && candidate !== null && !Array.isArray(candidate)) {
6601
+ if (typeof candidate.uses === "number" && Number.isFinite(candidate.uses) && candidate.uses > 0 && typeof candidate.lastUsedAt === "string" && candidate.lastUsedAt.length > 0) {
6602
+ this.frecencyMap.set(key.trim().toLowerCase(), {
6603
+ uses: candidate.uses,
6604
+ lastUsedAt: candidate.lastUsedAt
6605
+ });
6606
+ }
6607
+ }
6608
+ }
6609
+ } catch {
4254
6610
  }
4255
6611
  }
4256
6612
  /**
4257
- * Internal initialization logic
6613
+ * Caps `frecencyMap` at {@link MAX_FRECENCY_ENTRIES} entries ranked by current frecency score.
4258
6614
  */
4259
- async _initializeInternal(currentUser, provider) {
6615
+ pruneFrecencyMap(nowMs) {
6616
+ if (this.frecencyMap.size <= MAX_FRECENCY_ENTRIES) {
6617
+ return;
6618
+ }
6619
+ const ranked = Array.from(this.frecencyMap.entries()).sort((a, b) => {
6620
+ const scoreDiff = this.calculateFrecencyValue(b[1], nowMs) - this.calculateFrecencyValue(a[1], nowMs);
6621
+ if (scoreDiff !== 0) {
6622
+ return scoreDiff;
6623
+ }
6624
+ return b[1].lastUsedAt.localeCompare(a[1].lastUsedAt);
6625
+ });
6626
+ this.frecencyMap = new Map(ranked.slice(0, MAX_FRECENCY_ENTRIES));
6627
+ }
6628
+ serializeFrecencyMap() {
6629
+ const record = {};
6630
+ for (const [key, entry] of this.frecencyMap.entries()) {
6631
+ record[key] = entry;
6632
+ }
6633
+ return JSON.stringify(record);
6634
+ }
6635
+ readUserSetting(settingKey) {
4260
6636
  try {
4261
- await AIEngineBase.Instance.Config(false);
4262
- const allAgents = AIEngineBase.Instance.ReadableAgents;
4263
- const candidateAgents = allAgents.filter((a) => !a.ParentID && a.Status === "Active" && a.InvocationMode !== "Sub-Agent" && !a.IsRestricted);
4264
- this.agentsCache = await this.filterAgentsByRunPermission(candidateAgents, currentUser);
4265
- this.usersCache = [currentUser];
4266
- this.entitiesCache = this.loadReadableEntities(currentUser, provider);
4267
- this.queriesCache = await this.loadRunnableQueries(currentUser, provider);
4268
- this.queriesEntityIcon = this.resolveQueriesEntityIcon(provider);
4269
- this.skillsCache = await this.filterSkillsByRunPermission(currentUser);
4270
- this.provider = provider;
4271
- this.isInitialized = true;
4272
- } catch (error) {
4273
- console.error("Failed to initialize MentionAutocomplete:", error);
4274
- throw error;
6637
+ if (!UserInfoEngine?.Instance || typeof UserInfoEngine.Instance.GetSetting !== "function") {
6638
+ return void 0;
6639
+ }
6640
+ return UserInfoEngine.Instance.GetSetting(settingKey);
6641
+ } catch {
6642
+ return void 0;
6643
+ }
6644
+ }
6645
+ persistFrecencySetting(serialized, currentUser) {
6646
+ try {
6647
+ if (!UserInfoEngine?.Instance || typeof UserInfoEngine.Instance.SetSettingDebounced !== "function") {
6648
+ return;
6649
+ }
6650
+ const engine = UserInfoEngine.Instance;
6651
+ const userForSetting = currentUser ?? this.currentUser ?? this.getMetadataCurrentUser();
6652
+ const hasUserContext = Boolean(userForSetting?.ID);
6653
+ if (engine.Loaded === false || !hasUserContext && engine.Loaded !== true) {
6654
+ return;
6655
+ }
6656
+ engine.SetSettingDebounced(FRECENCY_SETTING_KEY, serialized, userForSetting);
6657
+ } catch {
6658
+ }
6659
+ }
6660
+ getMetadataCurrentUser() {
6661
+ try {
6662
+ const md = this.provider ?? Metadata?.Provider;
6663
+ return md?.CurrentUser;
6664
+ } catch {
6665
+ return void 0;
6666
+ }
6667
+ }
6668
+ calculateFrecencyValue(entry, nowMs) {
6669
+ if (!entry || entry.uses <= 0) {
6670
+ return 0;
6671
+ }
6672
+ const lastUsedMs = Date.parse(entry.lastUsedAt);
6673
+ if (!Number.isFinite(lastUsedMs)) {
6674
+ return 0;
6675
+ }
6676
+ const hoursSinceLastUse = Math.max(0, (nowMs - lastUsedMs) / 36e5);
6677
+ return entry.uses * FRECENCY_USE_WEIGHT * Math.exp(-hoursSinceLastUse / FRECENCY_DECAY_HOURS);
6678
+ }
6679
+ getFrecencyForId(id, nowMs) {
6680
+ const entry = this.frecencyMap.get(id.trim().toLowerCase());
6681
+ if (!entry) {
6682
+ return { uses: 0, score: 0 };
4275
6683
  }
6684
+ return {
6685
+ uses: entry.uses,
6686
+ score: this.calculateFrecencyValue(entry, nowMs)
6687
+ };
4276
6688
  }
4277
6689
  /**
4278
6690
  * Filter agents to only those the current user has 'run' permission for.
@@ -4325,16 +6737,17 @@ var MentionAutocomplete = class extends BaseSingleton {
4325
6737
  }
4326
6738
  }
4327
6739
  /**
4328
- * Load queries the current user can run, from the provider's QueryEngine (loaded here if it
4329
- * has not loaded yet). A query is runnable when the user holds its run permission and, for a
4330
- * query without explicit permission rows, can read every entity it references.
4331
- * These are the candidates surfaced for #query mentions.
6740
+ * Load Approved queries the current user can run, from the provider's QueryEngine (loaded here
6741
+ * if it has not loaded yet). A query is runnable when the user holds its run permission and, for
6742
+ * a query without explicit permission rows, can read every entity it references. Pending queries
6743
+ * are drafts (for example one saved from a conversation so a list can refresh from it) and are
6744
+ * not offered. These are the candidates surfaced for #query mentions.
4332
6745
  */
4333
6746
  async loadRunnableQueries(user, provider) {
4334
6747
  try {
4335
6748
  const engine = this.queryEngineFor(provider);
4336
6749
  await engine.Config(false, user, provider);
4337
- return engine.Queries.filter((query) => this.userCanRunQuery(query, user));
6750
+ return engine.Queries.filter((query) => query.Status === "Approved" && this.userCanRunQuery(query, user));
4338
6751
  } catch (error) {
4339
6752
  console.error("Failed to load queries for mention autocomplete:", error);
4340
6753
  return [];
@@ -4373,10 +6786,10 @@ var MentionAutocomplete = class extends BaseSingleton {
4373
6786
  * `MJ: AI Agent Skills` grants — via {@link AIEngineBase.GetSkillsForAgent}. Without it (or for an
4374
6787
  * agent not in the user's runnable set) the user's full runnable catalog is shown, as before, and
4375
6788
  * the server's `RequestedSkills` guard is the backstop.
4376
- * @param scope Narrows the '@' list for one composer: the agents it may offer and the people it
4377
- * offers. Passed per call, never stored, because this engine is shared by every composer on the
4378
- * page. Omitted keeps today's list: every agent the user can run, and the current user.
4379
- * @returns Filtered and ranked suggestions
6789
+ * @param scope Narrows the '@' list for one composer: the agents it may offer, the people it
6790
+ * offers, population/field filters, and thread/default-agent context boosts. Passed per call,
6791
+ * never stored, because this engine is shared by every composer on the page.
6792
+ * @returns Filtered, ranked, and grouped suggestions
4380
6793
  */
4381
6794
  GetSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4382
6795
  if (trigger === "#") {
@@ -4385,57 +6798,337 @@ var MentionAutocomplete = class extends BaseSingleton {
4385
6798
  if (trigger === "/") {
4386
6799
  return this.getSkillSuggestions(query, targetAgentId);
4387
6800
  }
6801
+ this.syncFrecencyFromUserSettings();
4388
6802
  const lowerQuery = query.toLowerCase().trim();
4389
- const suggestions = [
4390
- ...this.getAgentSuggestions(lowerQuery, scope?.AllowedAgentIDs ?? null),
4391
- ...includeUsers ? this.getPeopleSuggestions(lowerQuery, scope?.People ?? null) : []
6803
+ const populationFilter = scope?.PopulationFilter ?? "all";
6804
+ const searchField = scope?.SearchField ?? "all";
6805
+ const nowMs = Date.now();
6806
+ const includeAgents = populationFilter !== "people";
6807
+ const includePeople = includeUsers && (populationFilter === "all" || populationFilter === "people");
6808
+ const rankedItems = [
6809
+ ...includeAgents ? this.getRankedAgentSuggestions(lowerQuery, scope, populationFilter, searchField, nowMs) : [],
6810
+ ...includePeople ? this.getRankedPeopleSuggestions(lowerQuery, scope?.People ?? null, searchField, nowMs) : []
4392
6811
  ];
4393
- return suggestions.sort((a, b) => {
4394
- const scoreA = this.calculateMatchScore(a.name, lowerQuery);
4395
- const scoreB = this.calculateMatchScore(b.name, lowerQuery);
4396
- if (scoreB !== scoreA)
4397
- return scoreB - scoreA;
4398
- if (a.type !== b.type)
4399
- return a.type === "agent" ? -1 : 1;
4400
- return a.name.localeCompare(b.name);
4401
- });
6812
+ if (!lowerQuery && populationFilter === "all") {
6813
+ return this.groupEmptyAllSuggestions(rankedItems);
6814
+ }
6815
+ rankedItems.sort((a, b) => this.compareRankedItems(a, b));
6816
+ const groupKey = lowerQuery ? "results" : populationFilter === "my-agents" ? "my-agents" : populationFilter === "shared" ? "shared" : "people";
6817
+ const groupLabel = GROUP_LABELS[groupKey];
6818
+ return rankedItems.map((item) => ({
6819
+ ...item.suggestion,
6820
+ group: groupKey,
6821
+ groupLabel
6822
+ }));
4402
6823
  }
4403
6824
  /** @deprecated Use {@link GetSuggestions}. */
4404
6825
  getSuggestions(query, includeUsers = true, trigger = "@", targetAgentId = null, scope = null) {
4405
6826
  return this.GetSuggestions(query, includeUsers, trigger, targetAgentId, scope);
4406
6827
  }
4407
6828
  /**
4408
- * Agent suggestions for '@': the user's runnable agents that match the query, narrowed to
4409
- * `allowedAgentIDs` when one is given (null offers every runnable agent).
4410
- */
4411
- getAgentSuggestions(lowerQuery, allowedAgentIDs) {
4412
- return this.agentsCache.filter((agent) => allowedAgentIDs == null || allowedAgentIDs.some((id) => UUIDsEqual(id, agent.ID))).filter((agent) => !lowerQuery || this.calculateMatchScore(agent.Name || "", lowerQuery) > 0).map((agent) => ({
4413
- type: "agent",
4414
- id: agent.ID,
4415
- name: agent.Name || "Unknown",
4416
- displayName: agent.Name || "Unknown",
4417
- description: agent.Description || void 0,
4418
- imageUrl: agent.LogoURL || void 0,
4419
- // Agent logo/avatar image
4420
- icon: this.getAgentIcon(agent),
4421
- // Configuration presets ride on the suggestion — the (AI-blind) composer
4422
- // renders a preset picker on the inserted chip when there are 2+.
4423
- presets: this.getAgentPresets(agent.ID)
4424
- }));
6829
+ * Groups empty-query `'all'` suggestions into:
6830
+ * 1. `'frequent'` (top up-to-3 items with `uses >= 1 || isInCurrentThread || isDefaultChatAgent`)
6831
+ * 2. `'my-agents'` (remaining personal derived instances)
6832
+ * 3. `'shared'` (remaining shared agents)
6833
+ * 4. `'people'` (remaining users)
6834
+ * ordered by group sequence and by `totalScore` descending within each group.
6835
+ */
6836
+ groupEmptyAllSuggestions(items) {
6837
+ const sorted = [...items].sort((a, b) => this.compareRankedItems(a, b));
6838
+ const frequentItems = [];
6839
+ const frequentIds = /* @__PURE__ */ new Set();
6840
+ for (const item of sorted) {
6841
+ if (frequentItems.length >= MAX_FREQUENT_ITEMS) {
6842
+ break;
6843
+ }
6844
+ const isFrequentCandidate = item.uses >= 1 || Boolean(item.suggestion.isInCurrentThread) || Boolean(item.suggestion.isDefaultChatAgent);
6845
+ if (isFrequentCandidate) {
6846
+ frequentItems.push(item);
6847
+ frequentIds.add(`${item.suggestion.type}:${item.suggestion.id.toLowerCase()}`);
6848
+ }
6849
+ }
6850
+ const myAgentItems = [];
6851
+ const sharedItems = [];
6852
+ const peopleItems = [];
6853
+ for (const item of sorted) {
6854
+ const compositeKey = `${item.suggestion.type}:${item.suggestion.id.toLowerCase()}`;
6855
+ if (frequentIds.has(compositeKey)) {
6856
+ continue;
6857
+ }
6858
+ if (item.suggestion.type === "agent") {
6859
+ if (item.suggestion.isMyAgent) {
6860
+ myAgentItems.push(item);
6861
+ } else {
6862
+ sharedItems.push(item);
6863
+ }
6864
+ } else {
6865
+ peopleItems.push(item);
6866
+ }
6867
+ }
6868
+ const assignGroup = (list, group) => {
6869
+ const groupLabel = GROUP_LABELS[group];
6870
+ return list.map((item) => ({
6871
+ ...item.suggestion,
6872
+ group,
6873
+ groupLabel
6874
+ }));
6875
+ };
6876
+ return [
6877
+ ...assignGroup(frequentItems, "frequent"),
6878
+ ...assignGroup(myAgentItems, "my-agents"),
6879
+ ...assignGroup(sharedItems, "shared"),
6880
+ ...assignGroup(peopleItems, "people")
6881
+ ];
6882
+ }
6883
+ compareRankedItems(a, b) {
6884
+ if (b.totalScore !== a.totalScore) {
6885
+ return b.totalScore - a.totalScore;
6886
+ }
6887
+ if (a.suggestion.type !== b.suggestion.type) {
6888
+ return a.suggestion.type === "agent" ? -1 : 1;
6889
+ }
6890
+ return a.suggestion.name.localeCompare(b.suggestion.name);
6891
+ }
6892
+ /**
6893
+ * Resolves the current user ID for personal-agent ownership checks (`isMyAgent`).
6894
+ */
6895
+ resolveCurrentUserId() {
6896
+ return this.currentUser?.ID ?? this.usersCache[0]?.ID ?? this.getMetadataCurrentUser()?.ID ?? null;
6897
+ }
6898
+ /**
6899
+ * Resolves the human-readable base agent name for a derived agent instance.
6900
+ */
6901
+ resolveBaseAgentName(agent) {
6902
+ if (!agent.BaseAgentID) {
6903
+ return null;
6904
+ }
6905
+ if (typeof agent.BaseAgent === "string" && agent.BaseAgent.trim().length > 0) {
6906
+ return agent.BaseAgent.trim();
6907
+ }
6908
+ try {
6909
+ const aiEngine = this.aiEngineFor(this.provider);
6910
+ if (typeof aiEngine.GetAgentByID === "function") {
6911
+ const base = aiEngine.GetAgentByID(agent.BaseAgentID);
6912
+ if (base?.Name) {
6913
+ return base.Name;
6914
+ }
6915
+ }
6916
+ const readable = aiEngine.ReadableAgents;
6917
+ if (Array.isArray(readable)) {
6918
+ const base = readable.find((a) => UUIDsEqual(a.ID, agent.BaseAgentID));
6919
+ if (base?.Name) {
6920
+ return base.Name;
6921
+ }
6922
+ }
6923
+ } catch {
6924
+ }
6925
+ const fromCache = this.agentsCache.find((a) => UUIDsEqual(a.ID, agent.BaseAgentID));
6926
+ return fromCache?.Name ?? null;
6927
+ }
6928
+ /**
6929
+ * Builds the provenance/lineage badge text for an agent.
6930
+ */
6931
+ formatAgentLineage(isMyAgent, baseAgentName) {
6932
+ if (isMyAgent) {
6933
+ return baseAgentName ? `${baseAgentName} \xB7 My Agent` : "My Agent";
6934
+ }
6935
+ return baseAgentName ? `Shared \xB7 ${baseAgentName}` : "Shared";
6936
+ }
6937
+ /**
6938
+ * Ranked agent suggestions for '@' with frecency, context boosts, lineage, and multi-field matching.
6939
+ */
6940
+ getRankedAgentSuggestions(lowerQuery, scope, populationFilter, searchField, nowMs) {
6941
+ const allowedAgentIDs = scope?.AllowedAgentIDs ?? null;
6942
+ const inThreadIDs = scope?.InThreadAgentIDs ?? null;
6943
+ const inThreadAgentSet = inThreadIDs ? new UUIDSet(inThreadIDs) : null;
6944
+ const defaultChatAgentID = scope?.DefaultChatAgentID ?? null;
6945
+ const currentUserId = this.resolveCurrentUserId();
6946
+ const results = [];
6947
+ for (const agent of this.agentsCache) {
6948
+ if (allowedAgentIDs != null && !allowedAgentIDs.some((id) => UUIDsEqual(id, agent.ID))) {
6949
+ continue;
6950
+ }
6951
+ const isMyAgent = Boolean(agent.BaseAgentID != null && currentUserId != null && agent.OwnerUserID != null && UUIDsEqual(agent.OwnerUserID, currentUserId));
6952
+ if (populationFilter === "my-agents" && !isMyAgent) {
6953
+ continue;
6954
+ }
6955
+ if (populationFilter === "shared" && isMyAgent) {
6956
+ continue;
6957
+ }
6958
+ const name = agent.Name || "Unknown";
6959
+ const description = agent.Description || void 0;
6960
+ const baseAgentName = this.resolveBaseAgentName(agent);
6961
+ const lineage = this.formatAgentLineage(isMyAgent, baseAgentName);
6962
+ const queryScore = lowerQuery ? this.scoreAgentQuery(name, description, baseAgentName, lineage, lowerQuery, searchField) : 0;
6963
+ if (lowerQuery && queryScore <= 0) {
6964
+ continue;
6965
+ }
6966
+ const isInCurrentThread = Boolean(inThreadAgentSet?.Has(agent.ID));
6967
+ const isDefaultChatAgent = Boolean(defaultChatAgentID && UUIDsEqual(defaultChatAgentID, agent.ID));
6968
+ const { uses, score: frecencyScore } = this.getFrecencyForId(agent.ID, nowMs);
6969
+ const contextBoost = (isInCurrentThread ? BOOST_IN_THREAD : 0) + (isDefaultChatAgent ? BOOST_DEFAULT_CHAT_AGENT : 0) + (isMyAgent ? BOOST_MY_AGENT : 0);
6970
+ const suggestion = {
6971
+ type: "agent",
6972
+ id: agent.ID,
6973
+ name,
6974
+ displayName: name,
6975
+ description,
6976
+ imageUrl: agent.LogoURL || void 0,
6977
+ icon: this.getAgentIcon(agent),
6978
+ // Configuration presets ride on the suggestion — the (AI-blind) composer
6979
+ // renders a preset picker on the inserted chip when there are 2+.
6980
+ presets: this.getAgentPresets(agent.ID),
6981
+ lineage,
6982
+ isMyAgent,
6983
+ isDefaultChatAgent,
6984
+ isInCurrentThread,
6985
+ frecencyScore
6986
+ };
6987
+ results.push({
6988
+ suggestion,
6989
+ queryScore,
6990
+ totalScore: queryScore + frecencyScore + contextBoost,
6991
+ uses
6992
+ });
6993
+ }
6994
+ return results;
4425
6995
  }
4426
6996
  /**
4427
- * People suggestions for '@': the host's list when a composer supplies one, otherwise the
6997
+ * Ranked people suggestions for '@': the host's list when a composer supplies one, otherwise the
4428
6998
  * engine's own (which holds only the current user).
4429
6999
  */
4430
- getPeopleSuggestions(lowerQuery, people) {
7000
+ getRankedPeopleSuggestions(lowerQuery, people, searchField, nowMs) {
4431
7001
  const candidates = people ?? this.usersCache.map((user) => ({ ID: user.ID, Name: user.Name, Email: user.Email }));
4432
- return candidates.filter((person) => !lowerQuery || this.calculateMatchScore(person.Name, lowerQuery) > 0).map((person) => ({
4433
- type: "user",
4434
- id: person.ID,
4435
- name: person.Name,
4436
- displayName: person.Name,
4437
- description: person.Email || void 0
4438
- }));
7002
+ const results = [];
7003
+ for (const person of candidates) {
7004
+ const name = person.Name || "Unknown";
7005
+ const email = person.Email || void 0;
7006
+ const queryScore = lowerQuery ? this.scorePersonQuery(name, email, lowerQuery, searchField) : 0;
7007
+ if (lowerQuery && queryScore <= 0) {
7008
+ continue;
7009
+ }
7010
+ const { uses, score: frecencyScore } = this.getFrecencyForId(person.ID, nowMs);
7011
+ const suggestion = {
7012
+ type: "user",
7013
+ id: person.ID,
7014
+ name,
7015
+ displayName: name,
7016
+ description: email,
7017
+ isMyAgent: false,
7018
+ isDefaultChatAgent: false,
7019
+ isInCurrentThread: false,
7020
+ frecencyScore
7021
+ };
7022
+ results.push({
7023
+ suggestion,
7024
+ queryScore,
7025
+ totalScore: queryScore + frecencyScore,
7026
+ uses
7027
+ });
7028
+ }
7029
+ return results;
7030
+ }
7031
+ /**
7032
+ * Multi-field + acronym query scorer for agents:
7033
+ * - Exact name: 140
7034
+ * - Prefix name: 105
7035
+ * - Multi-word acronym prefix (len >= 2, e.g. `fcs` -> `FDA Clinical Scout`): 88
7036
+ * - Substring name: 70
7037
+ * - Base-agent lineage match: 58
7038
+ * - Token-AND match across name + description + lineage (e.g. `sql` -> `Query Builder`): 48
7039
+ */
7040
+ scoreAgentQuery(name, description, baseAgentName, lineage, lowerQuery, searchField) {
7041
+ let best = 0;
7042
+ if (searchField === "all" || searchField === "name") {
7043
+ best = Math.max(best, this.calculateNameMatchScore(name, lowerQuery));
7044
+ }
7045
+ if (searchField === "all" || searchField === "lineage") {
7046
+ best = Math.max(best, this.calculateLineageMatchScore(baseAgentName, lineage, lowerQuery));
7047
+ }
7048
+ if (searchField === "capabilities") {
7049
+ best = Math.max(best, this.calculateTokenAndScore(description ?? "", lowerQuery));
7050
+ } else if (searchField === "all") {
7051
+ const combined = `${name} ${description ?? ""} ${baseAgentName ?? ""} ${lineage}`;
7052
+ best = Math.max(best, this.calculateTokenAndScore(combined, lowerQuery));
7053
+ }
7054
+ return best;
7055
+ }
7056
+ /**
7057
+ * Multi-field + acronym query scorer for people.
7058
+ */
7059
+ scorePersonQuery(name, email, lowerQuery, searchField) {
7060
+ if (searchField === "lineage") {
7061
+ return 0;
7062
+ }
7063
+ if (searchField === "capabilities") {
7064
+ return this.calculateTokenAndScore(email ?? "", lowerQuery);
7065
+ }
7066
+ const nameScore = this.calculateNameMatchScore(name, lowerQuery);
7067
+ if (searchField === "name") {
7068
+ return nameScore;
7069
+ }
7070
+ return Math.max(nameScore, this.calculateTokenAndScore(`${name} ${email ?? ""}`, lowerQuery));
7071
+ }
7072
+ /**
7073
+ * Name scorer supporting exact (140), prefix (105), multi-word acronym prefix length >= 2 (88),
7074
+ * and substring (70).
7075
+ */
7076
+ calculateNameMatchScore(name, lowerQuery) {
7077
+ const lowerName = name.toLowerCase().trim();
7078
+ if (!lowerName || !lowerQuery) {
7079
+ return 0;
7080
+ }
7081
+ if (lowerName === lowerQuery) {
7082
+ return 140;
7083
+ }
7084
+ if (lowerName.startsWith(lowerQuery)) {
7085
+ return 105;
7086
+ }
7087
+ if (lowerQuery.length >= 2 && !/\s/.test(lowerQuery)) {
7088
+ const words = lowerName.split(/[\s\-_/.]+/).filter(Boolean);
7089
+ if (words.length >= 2) {
7090
+ const acronym = words.map((w) => w[0]).join("");
7091
+ if (acronym.startsWith(lowerQuery)) {
7092
+ return 88;
7093
+ }
7094
+ }
7095
+ }
7096
+ if (lowerName.includes(lowerQuery)) {
7097
+ return 70;
7098
+ }
7099
+ return 0;
7100
+ }
7101
+ /**
7102
+ * Base-agent / lineage scorer (58).
7103
+ */
7104
+ calculateLineageMatchScore(baseAgentName, lineage, lowerQuery) {
7105
+ if (!lowerQuery) {
7106
+ return 0;
7107
+ }
7108
+ const lowerBase = baseAgentName?.toLowerCase() ?? "";
7109
+ const lowerLineage = lineage.toLowerCase();
7110
+ if (lowerBase.includes(lowerQuery) || lowerLineage.includes(lowerQuery)) {
7111
+ return 58;
7112
+ }
7113
+ const tokens = lowerQuery.split(/\s+/).filter(Boolean);
7114
+ if (tokens.length > 0 && tokens.every((t) => lowerBase.includes(t) || lowerLineage.includes(t))) {
7115
+ return 58;
7116
+ }
7117
+ return 0;
7118
+ }
7119
+ /**
7120
+ * Token-AND matcher across a combined text haystack (48).
7121
+ */
7122
+ calculateTokenAndScore(haystack, lowerQuery) {
7123
+ if (!haystack || !lowerQuery) {
7124
+ return 0;
7125
+ }
7126
+ const lowerHaystack = haystack.toLowerCase();
7127
+ const tokens = lowerQuery.split(/\s+/).filter(Boolean);
7128
+ if (tokens.length === 0) {
7129
+ return 0;
7130
+ }
7131
+ return tokens.every((token) => lowerHaystack.includes(token)) ? 48 : 0;
4439
7132
  }
4440
7133
  /**
4441
7134
  * Get entity + query suggestions for #mentions, ranked by query match.
@@ -4490,7 +7183,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4490
7183
  if (!agent) {
4491
7184
  return this.skillsCache;
4492
7185
  }
4493
- const engine = this.provider ? AIEngineBase.GetProviderInstance(this.provider, AIEngineBase) : AIEngineBase.Instance;
7186
+ const engine = this.aiEngineFor(this.provider);
4494
7187
  return IntersectAcceptedSkills(this.skillsCache, engine.GetSkillsForAgent(agent));
4495
7188
  }
4496
7189
  /**
@@ -4518,8 +7211,8 @@ var MentionAutocomplete = class extends BaseSingleton {
4518
7211
  }).slice(0, MAX_SUGGESTIONS).map((x) => x.suggestion);
4519
7212
  }
4520
7213
  /**
4521
- * Calculate match score for ranking
4522
- * Higher score = better match
7214
+ * Calculate match score for ranking `#` (entities/queries) and `/` (skills) triggers.
7215
+ * Higher score = better match.
4523
7216
  */
4524
7217
  calculateMatchScore(name, query) {
4525
7218
  if (!query)
@@ -4549,7 +7242,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4549
7242
  */
4550
7243
  getAgentPresets(agentId) {
4551
7244
  try {
4552
- const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agentId, true);
7245
+ const presets = this.aiEngineFor(this.provider).GetAgentConfigurationPresets(agentId, true);
4553
7246
  if (!presets || presets.length === 0) {
4554
7247
  return void 0;
4555
7248
  }
@@ -4640,7 +7333,7 @@ var MentionAutocomplete = class extends BaseSingleton {
4640
7333
  async Refresh(currentUser) {
4641
7334
  this.isInitialized = false;
4642
7335
  this.initializationPromise = null;
4643
- await this.initialize(currentUser);
7336
+ await this.initialize(currentUser, this.provider);
4644
7337
  }
4645
7338
  /** @deprecated Use {@link Refresh}. */
4646
7339
  async refresh(currentUser) {
@@ -4725,68 +7418,223 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4725
7418
  static {
4726
7419
  this.SETTING_NAME = "Conversations.DefaultAgentID";
4727
7420
  }
7421
+ static {
7422
+ this.LEGACY_USER_SETTING_NAME = "chat.defaultAgentId";
7423
+ }
4728
7424
  static {
4729
7425
  this.FALLBACK_AGENT_NAME = "Sage";
4730
7426
  }
4731
7427
  /**
4732
- * Resolve the default agent for this turn. Walks the 4-step chain; throws a descriptive
4733
- * error if every step misses (vs. the previous code path's silent `null` return, which
4734
- * made misconfigurations hard to spot at the call site).
4735
- *
4736
- * @example
4737
- * ```typescript
4738
- * const agent = await runtime.DefaultAgent.resolve({
4739
- * explicitAgentId: widgetInput.DefaultAgentId, // wins if non-null and matches
4740
- * applicationId: currentAppId, // scopes the settings lookup
4741
- * contextUser: this.ProviderToUse.CurrentUser,
4742
- * provider: this.ProviderToUse,
4743
- * });
4744
- * ```
7428
+ * Resolve the default agent for this turn. Walks the full resolution chain; throws a descriptive
7429
+ * error if every step misses.
4745
7430
  */
4746
7431
  async Resolve(options = {}) {
4747
- const { explicitAgentId, applicationId, contextUser, provider } = options;
4748
- await AIEngineBase.Instance.Config(false, contextUser, provider);
4749
- await ApplicationSettingEngine.Instance.Config(false, contextUser, provider);
7432
+ const result = await this.ResolveWithDetails(options);
7433
+ return result.agent;
7434
+ }
7435
+ /**
7436
+ * Resolve the default agent along with provenance and any user-default fallback details
7437
+ * (so UI surfaces can display a one-time non-blocking notice if the user's saved default
7438
+ * was deactivated or revoked).
7439
+ */
7440
+ async ResolveWithDetails(options = {}) {
7441
+ const { explicitAgentId, applicationId, contextUser, provider, ignoreUserDefault } = options;
7442
+ const aiEngine = this.getAIEngine(provider);
7443
+ const appSettingEngine = this.getApplicationSettingEngine(provider);
7444
+ const userInfoEngine = this.getUserInfoEngine(provider);
7445
+ await aiEngine.Config(false, contextUser, provider);
7446
+ await appSettingEngine.Config(false, contextUser, provider);
7447
+ if (userInfoEngine && !ignoreUserDefault) {
7448
+ try {
7449
+ await userInfoEngine.Config(false, contextUser, provider);
7450
+ } catch (e) {
7451
+ console.warn(`DefaultAgentResolver: UserInfoEngine.Config failed \u2014 continuing without user preference: ${e instanceof Error ? e.message : String(e)}`);
7452
+ }
7453
+ }
4750
7454
  if (explicitAgentId) {
4751
- const explicit = this.findAgentById(explicitAgentId);
4752
- if (explicit)
4753
- return explicit;
4754
- console.warn(`DefaultAgentResolver: explicitAgentId "${explicitAgentId}" did not match any known agent \u2014 falling through to settings chain.`);
7455
+ const explicit = this.findAgentById(aiEngine, explicitAgentId);
7456
+ if (explicit && this.isAgentActive(explicit)) {
7457
+ return { agent: explicit, source: "explicit" };
7458
+ }
7459
+ console.warn(`DefaultAgentResolver: explicitAgentId "${explicitAgentId}" did not match any active known agent \u2014 falling through to user/org default chain.`);
7460
+ }
7461
+ let unavailableInfo = null;
7462
+ if (!ignoreUserDefault && userInfoEngine) {
7463
+ const rawUserDefault = this.readUserDefaultSetting(userInfoEngine);
7464
+ if (rawUserDefault) {
7465
+ const validation = this.validateCandidateAgent(aiEngine, rawUserDefault, contextUser);
7466
+ if (validation.valid) {
7467
+ return { agent: validation.agent, source: "user-setting" };
7468
+ }
7469
+ unavailableInfo = {
7470
+ userDefaultUnavailable: true,
7471
+ userDefaultUnavailableReason: validation.reason,
7472
+ unavailableUserDefaultAgentId: rawUserDefault
7473
+ };
7474
+ console.warn(`DefaultAgentResolver: user default "${rawUserDefault}" is unavailable (${validation.reason}) \u2014 falling through to org default.`);
7475
+ }
4755
7476
  }
7477
+ let orgDefault;
7478
+ let orgDefaultSource = "app-or-global-setting";
7479
+ let settingValue;
4756
7480
  if (applicationId) {
4757
7481
  const fromAppSettings = await this.getAppDefaultAgentId(applicationId, contextUser, provider);
4758
7482
  if (fromAppSettings) {
4759
- const resolved = this.findAgentById(fromAppSettings);
4760
- if (resolved)
4761
- return resolved;
4762
- console.warn(`DefaultAgentResolver: Application.AgentSettings.DefaultAgentID = "${fromAppSettings}" but no matching agent was found \u2014 falling through to the settings chain.`);
7483
+ const resolved = this.findAgentById(aiEngine, fromAppSettings);
7484
+ if (resolved && this.isAgentActive(resolved)) {
7485
+ orgDefault = resolved;
7486
+ orgDefaultSource = "app-agent-settings";
7487
+ } else {
7488
+ console.warn(`DefaultAgentResolver: Application.AgentSettings.DefaultAgentID = "${fromAppSettings}" did not resolve to an active agent \u2014 falling through to the settings chain.`);
7489
+ }
7490
+ }
7491
+ }
7492
+ if (!orgDefault) {
7493
+ settingValue = appSettingEngine.GetSetting(_DefaultAgentResolver.SETTING_NAME, applicationId ?? void 0);
7494
+ if (settingValue) {
7495
+ const fromSetting = this.findAgentById(aiEngine, settingValue);
7496
+ if (fromSetting && this.isAgentActive(fromSetting)) {
7497
+ orgDefault = fromSetting;
7498
+ orgDefaultSource = "app-or-global-setting";
7499
+ } else {
7500
+ 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.`);
7501
+ }
7502
+ }
7503
+ }
7504
+ if (orgDefault) {
7505
+ const primaryInstance = this.findUserPrimaryInstance(aiEngine, orgDefault, contextUser);
7506
+ if (primaryInstance) {
7507
+ return {
7508
+ agent: primaryInstance,
7509
+ source: "user-primary-instance",
7510
+ ...unavailableInfo ?? {}
7511
+ };
4763
7512
  }
7513
+ return {
7514
+ agent: orgDefault,
7515
+ source: orgDefaultSource,
7516
+ ...unavailableInfo ?? {}
7517
+ };
4764
7518
  }
4765
- const settingValue = ApplicationSettingEngine.Instance.GetSetting(_DefaultAgentResolver.SETTING_NAME, applicationId ?? void 0);
4766
- if (settingValue) {
4767
- const fromSetting = this.findAgentById(settingValue);
4768
- if (fromSetting)
4769
- return fromSetting;
4770
- console.warn(`DefaultAgentResolver: Application Setting "${_DefaultAgentResolver.SETTING_NAME}" resolved to "${settingValue}" but no matching agent was found \u2014 falling through to code-const fallback.`);
7519
+ const fallback = this.getSearchableAgents(aiEngine).find((a) => a.Name === _DefaultAgentResolver.FALLBACK_AGENT_NAME && this.isAgentActive(a));
7520
+ if (fallback) {
7521
+ return {
7522
+ agent: fallback,
7523
+ source: "code-fallback",
7524
+ ...unavailableInfo ?? {}
7525
+ };
4771
7526
  }
4772
- const fallback = AIEngineBase.Instance.ReadableAgents.find((a) => a.Name === _DefaultAgentResolver.FALLBACK_AGENT_NAME);
4773
- if (fallback)
4774
- return fallback;
4775
- throw new Error(`DefaultAgentResolver: could not resolve a default conversation manager agent. Tried (1) explicitAgentId=${explicitAgentId ?? "null"}, (2) Application.AgentSettings.DefaultAgentID (applicationId=${applicationId ?? "null"}), (3)+(4) Application Setting "${_DefaultAgentResolver.SETTING_NAME}" = "${settingValue ?? "undefined"}", (5) code-const fallback agent name = "${_DefaultAgentResolver.FALLBACK_AGENT_NAME}". Configure Application.AgentSettings, the Application Setting, or seed the fallback agent.`);
7527
+ throw new Error(`DefaultAgentResolver: could not resolve a default conversation manager agent. Tried (1) explicitAgentId=${explicitAgentId ?? "null"}, (2) UserInfoEngine "${_DefaultAgentResolver.SETTING_NAME}"=${unavailableInfo?.unavailableUserDefaultAgentId ?? "null"}, (3) user primary instance of org default template, (4a) Application.AgentSettings.DefaultAgentID (applicationId=${applicationId ?? "null"}), (4b) Application Setting "${_DefaultAgentResolver.SETTING_NAME}" = "${settingValue ?? "undefined"}", (5) code-const fallback agent name = "${_DefaultAgentResolver.FALLBACK_AGENT_NAME}". Configure Application.AgentSettings, the Application Setting, or seed the fallback agent.`);
4776
7528
  }
4777
7529
  /** @deprecated Use {@link Resolve}. */
4778
7530
  async resolve(options = {}) {
4779
7531
  return this.Resolve(options);
4780
7532
  }
7533
+ getAIEngine(provider) {
7534
+ if (provider && typeof AIEngineBase.GetProviderInstance === "function") {
7535
+ return AIEngineBase.GetProviderInstance(provider, AIEngineBase);
7536
+ }
7537
+ return AIEngineBase.Instance;
7538
+ }
7539
+ getApplicationSettingEngine(provider) {
7540
+ if (provider && typeof ApplicationSettingEngine.GetProviderInstance === "function") {
7541
+ return ApplicationSettingEngine.GetProviderInstance(provider, ApplicationSettingEngine);
7542
+ }
7543
+ return ApplicationSettingEngine.Instance;
7544
+ }
7545
+ getUserInfoEngine(provider) {
7546
+ if (!UserInfoEngine) {
7547
+ return null;
7548
+ }
7549
+ if (provider && typeof UserInfoEngine.GetProviderInstance === "function") {
7550
+ return UserInfoEngine.GetProviderInstance(provider, UserInfoEngine);
7551
+ }
7552
+ return UserInfoEngine.Instance ?? null;
7553
+ }
7554
+ readUserDefaultSetting(userInfoEngine) {
7555
+ if (typeof userInfoEngine.GetSetting !== "function") {
7556
+ return null;
7557
+ }
7558
+ const primary = userInfoEngine.GetSetting(_DefaultAgentResolver.SETTING_NAME)?.trim();
7559
+ if (primary) {
7560
+ return primary;
7561
+ }
7562
+ const legacy = userInfoEngine.GetSetting(_DefaultAgentResolver.LEGACY_USER_SETTING_NAME)?.trim();
7563
+ return legacy || null;
7564
+ }
7565
+ validateCandidateAgent(aiEngine, agentId, contextUser) {
7566
+ const agent = this.findAgentById(aiEngine, agentId);
7567
+ if (!agent) {
7568
+ return { valid: false, reason: "agent no longer exists or is not visible" };
7569
+ }
7570
+ if (!this.isAgentActive(agent)) {
7571
+ return { valid: false, reason: `agent "${agent.Name}" is inactive (${agent.Status})` };
7572
+ }
7573
+ if (agent.InstantiationMode === "Required") {
7574
+ return {
7575
+ valid: false,
7576
+ reason: `agent "${agent.Name}" is a template that requires a personal instance`
7577
+ };
7578
+ }
7579
+ if (contextUser && !this.canUserRunAgent(aiEngine, agent, contextUser)) {
7580
+ return {
7581
+ valid: false,
7582
+ reason: `you no longer have run permission for "${agent.Name}"`
7583
+ };
7584
+ }
7585
+ return { valid: true, agent };
7586
+ }
7587
+ /**
7588
+ * Finds the user's active primary instance (`IsPrimaryInstance = true`) descending from
7589
+ * `templateAgent` when `templateAgent` is an instantiable template (`Required` or `Optional`).
7590
+ * Validates that the primary instance is `Active` and the user holds `CanRun` across its
7591
+ * `BaseAgentID` ancestor chain.
7592
+ */
7593
+ findUserPrimaryInstance(aiEngine, templateAgent, contextUser) {
7594
+ if (!contextUser) {
7595
+ return null;
7596
+ }
7597
+ const mode = templateAgent.InstantiationMode;
7598
+ if (mode !== "Required" && mode !== "Optional") {
7599
+ return null;
7600
+ }
7601
+ const candidates = this.getUserDerivedAgentsForTemplate(aiEngine, templateAgent.ID, contextUser);
7602
+ const primary = candidates.find((a) => a.IsPrimaryInstance === true && this.isAgentActive(a) && UUIDsEqual(a.OwnerUserID, contextUser.ID) && this.canUserRunAgent(aiEngine, a, contextUser));
7603
+ return primary ?? null;
7604
+ }
7605
+ getUserDerivedAgentsForTemplate(aiEngine, templateId, contextUser) {
7606
+ if (typeof aiEngine.GetUserDerivedAgents === "function") {
7607
+ return aiEngine.GetUserDerivedAgents(contextUser, templateId);
7608
+ }
7609
+ const all = this.getSearchableAgents(aiEngine);
7610
+ return all.filter((a) => {
7611
+ if (!a.BaseAgentID || !this.isAgentActive(a)) {
7612
+ return false;
7613
+ }
7614
+ if (UUIDsEqual(a.BaseAgentID, templateId)) {
7615
+ return true;
7616
+ }
7617
+ if (typeof aiEngine.GetRootAgent === "function") {
7618
+ const root = aiEngine.GetRootAgent(a.ID);
7619
+ return root ? UUIDsEqual(root.ID, templateId) : false;
7620
+ }
7621
+ return false;
7622
+ });
7623
+ }
7624
+ isAgentActive(agent) {
7625
+ return agent.Status === void 0 || agent.Status === "Active";
7626
+ }
7627
+ canUserRunAgent(aiEngine, agent, contextUser) {
7628
+ if (typeof aiEngine.CanUserRunAgentSync === "function") {
7629
+ return aiEngine.CanUserRunAgentSync(agent, contextUser);
7630
+ }
7631
+ return true;
7632
+ }
4781
7633
  /**
4782
7634
  * Read `Application.AgentSettings.DefaultAgentID` for the given app via a targeted
4783
7635
  * `RunView` (single row by ID, `entity_object` so the typed `AgentSettingsObject`
4784
7636
  * accessor is available). Returns `undefined` when the app, the column, or the field
4785
7637
  * is absent.
4786
- *
4787
- * Kept query-light: one tiny by-ID read, served from the provider's RunView cache on
4788
- * repeat calls (server trusts its cache; the client caches too), and only reached when
4789
- * no explicit agent was supplied — i.e. at most once per conversation-turn start.
4790
7638
  */
4791
7639
  async getAppDefaultAgentId(applicationId, contextUser, provider) {
4792
7640
  try {
@@ -4817,13 +7665,24 @@ var DefaultAgentResolver = class _DefaultAgentResolver {
4817
7665
  const candidate = provider;
4818
7666
  return candidate && typeof candidate.RunView === "function" ? provider : void 0;
4819
7667
  }
7668
+ getSearchableAgents(aiEngine) {
7669
+ return aiEngine.ReadableAgents ?? aiEngine.Agents ?? [];
7670
+ }
4820
7671
  /**
4821
7672
  * Find an agent by ID from the AIEngineBase cache. Returns `undefined` if not found.
4822
7673
  * Uses {@link UUIDsEqual} per the standing rule about comparing UUIDs across
4823
7674
  * SQL Server / Postgres (case differences would silently miss).
4824
7675
  */
4825
- findAgentById(id) {
4826
- return AIEngineBase.Instance.ReadableAgents.find((a) => UUIDsEqual(a.ID, id));
7676
+ findAgentById(aiEngine, id) {
7677
+ const searchable = this.getSearchableAgents(aiEngine);
7678
+ const fromReadable = searchable.find((a) => UUIDsEqual(a.ID, id));
7679
+ if (fromReadable) {
7680
+ return fromReadable;
7681
+ }
7682
+ if (typeof aiEngine.GetAgentByID === "function") {
7683
+ return aiEngine.GetAgentByID(id);
7684
+ }
7685
+ return void 0;
4827
7686
  }
4828
7687
  };
4829
7688
 
@@ -5571,7 +8430,7 @@ var ConversationTail = class {
5571
8430
  if (!provider) {
5572
8431
  return void 0;
5573
8432
  }
5574
- this.client = new ns(provider);
8433
+ this.client = new as(provider);
5575
8434
  return this.client;
5576
8435
  } catch {
5577
8436
  return void 0;
@@ -5607,6 +8466,7 @@ var ConversationAgentRunner = class {
5607
8466
  this._activeRunCount = 0;
5608
8467
  this._provider = null;
5609
8468
  this.IsProcessing$ = this._isProcessing$.asObservable();
8469
+ this._notifiedUnavailableDefaultIds = /* @__PURE__ */ new Set();
5610
8470
  this.session = new AgentClientSession(toolRegistry);
5611
8471
  }
5612
8472
  /**
@@ -5707,19 +8567,29 @@ var ConversationAgentRunner = class {
5707
8567
  return this.ProcessMessage(input);
5708
8568
  }
5709
8569
  /**
5710
- * Resolve the agent that should handle this turn — explicit ID wins, then the
5711
- * Application Settings chain, then the Sage code-const fallback. Surfaces a
5712
- * notification on failure rather than throwing, so the caller (UI thread)
5713
- * sees a friendly message.
8570
+ * Resolve the agent that should handle this turn — explicit ID wins, then the user's
8571
+ * default / primary instance, then Application Settings, then the code-const fallback.
8572
+ * Surfaces a one-time non-blocking warning if the user's saved default is unavailable,
8573
+ * and notifies on total resolution failure rather than throwing.
5714
8574
  */
5715
8575
  async resolveAgent(input) {
5716
8576
  try {
5717
- return await this.resolver.resolve({
8577
+ const resolveOpts = {
5718
8578
  explicitAgentId: input.explicitAgentId,
5719
8579
  applicationId: input.applicationId,
5720
8580
  contextUser: this.Provider.CurrentUser ?? void 0,
5721
8581
  provider: this.Provider
5722
- });
8582
+ };
8583
+ const result = typeof this.resolver.ResolveWithDetails === "function" ? await this.resolver.ResolveWithDetails(resolveOpts) : { agent: await this.resolver.resolve(resolveOpts), source: "code-fallback" };
8584
+ if (result.userDefaultUnavailable && result.unavailableUserDefaultAgentId) {
8585
+ const key = result.unavailableUserDefaultAgentId.toLowerCase();
8586
+ if (!this._notifiedUnavailableDefaultIds.has(key)) {
8587
+ this._notifiedUnavailableDefaultIds.add(key);
8588
+ const detail = result.userDefaultUnavailableReason ? ` (${result.userDefaultUnavailableReason})` : "";
8589
+ this.context.Notification.Notify("warning", `Your default agent is currently unavailable${detail}. Using ${result.agent.Name} instead.`, 6e3);
8590
+ }
8591
+ }
8592
+ return result.agent;
5723
8593
  } catch (error) {
5724
8594
  const errorMsg = "Could not resolve a default conversation manager agent: " + (error instanceof Error ? error.message : String(error));
5725
8595
  console.error("[ConversationAgentRunner] Agent resolution failed:", error);