@memberjunction/realtime-widget 6.3.0-edge.2 → 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,15 +1,38 @@
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,
6
17
  DeepMergeAgentConfigObjects,
18
+ DeepMergeAgentConfigurations,
19
+ DoesAgentAllowWidenFromBase,
7
20
  EDGE_PRE_DISCOVERY_DATA_KEY,
8
21
  FileStorageEngineBase,
22
+ FoldRebaseAwareChain,
23
+ HasPathTraversalSegment,
24
+ IntersectPayloadPathSets,
9
25
  MAX_AGENT_INHERITANCE_DEPTH,
10
26
  MJAICredentialBindingEntity,
11
27
  MJAIModelPriceUnitTypeEntity,
28
+ NARROW_ONLY_PROMPT_PARAM_GATES,
29
+ NarrowAttachmentRootPath,
30
+ NarrowPayloadScope,
31
+ NarrowScopeConfigObjects,
12
32
  ParseAgentConfigJsonObject,
33
+ ParseAgentConfiguration,
34
+ ParseAgentHelperPlugins,
35
+ ParseAgentInstantiationConfig,
13
36
  QueryEngine,
14
37
  SanitizeEdgePreDiscoveryHint,
15
38
  TemplateEngineBase,
@@ -18,7 +41,7 @@ import {
18
41
  coerceFailedExecuteAgentResult,
19
42
  g,
20
43
  rt
21
- } from "./chunk-3U2F5LA6.js";
44
+ } from "./chunk-P3UR75T6.js";
22
45
  import {
23
46
  BaseEngine,
24
47
  BaseEntity,
@@ -29,13 +52,13 @@ import {
29
52
  PermissionConstrainedError,
30
53
  RegisterForStartup,
31
54
  RunView
32
- } from "./chunk-KJ4DC2CQ.js";
55
+ } from "./chunk-VCGHPATD.js";
33
56
  import {
34
57
  ApplyPlattCalibration,
35
58
  ParseModelConfiguration,
36
59
  ParseVendorConfiguration,
37
60
  ResolveEffectiveModelConfiguration
38
- } from "./chunk-CIZSPKQR.js";
61
+ } from "./chunk-IHM3SRNY.js";
39
62
  import {
40
63
  BaseSingleton,
41
64
  BehaviorSubject,
@@ -54,7 +77,7 @@ import {
54
77
  ValidationErrorInfo,
55
78
  ValidationErrorType,
56
79
  throttleTime
57
- } from "./chunk-KHEWGJIZ.js";
80
+ } from "./chunk-CUZ32HGY.js";
58
81
 
59
82
  // ../../AI/BaseAIEngine/dist/PriceUnitTypes.js
60
83
  var __decorate = function(decorators, target, key, desc) {
@@ -304,56 +327,12 @@ var MAX_INHERITANCE_DEPTH = 5;
304
327
  var AIAgentPermissionHelper = class {
305
328
  /**
306
329
  * Pure synchronous computation of effective permissions for a single agent row WITHOUT
307
- * walking `BaseAgentID` ancestors. Applies the 2x2 zero-ACL rule and hierarchical
308
- * permission implication (`Delete -> Edit -> Run -> View`).
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).
309
333
  */
310
334
  static computeDirectPermissions(agent, allPermissions, user, userRoleIds) {
311
- const isOwner = UUIDsEqual(agent.OwnerUserID, user.ID);
312
- if (isOwner) {
313
- return {
314
- canView: true,
315
- canRun: true,
316
- canEdit: true,
317
- canDelete: true,
318
- isOwner: true
319
- };
320
- }
321
- const agentPermissions = allPermissions.filter((p) => UUIDsEqual(p.AgentID, agent.ID));
322
- if (agentPermissions.length === 0) {
323
- const isDerived = agent.BaseAgentID != null && String(agent.BaseAgentID).trim().length > 0;
324
- if (isDerived) {
325
- return {
326
- canView: false,
327
- canRun: false,
328
- canEdit: false,
329
- canDelete: false,
330
- isOwner: false
331
- };
332
- }
333
- return {
334
- canView: true,
335
- canRun: true,
336
- canEdit: false,
337
- canDelete: false,
338
- isOwner: false
339
- };
340
- }
341
- const matchingPermissions = agentPermissions.filter((p) => UUIDsEqual(p.UserID, user.ID) || p.RoleID != null && userRoleIds.Has(p.RoleID));
342
- const hasDelete = matchingPermissions.some((p) => p.CanDelete === true);
343
- const hasEdit = matchingPermissions.some((p) => p.CanEdit === true);
344
- const hasRun = matchingPermissions.some((p) => p.CanRun === true);
345
- const hasView = matchingPermissions.some((p) => p.CanView === true);
346
- const canDelete = hasDelete;
347
- const canEdit = hasDelete || hasEdit;
348
- const canRun = hasDelete || hasEdit || hasRun;
349
- const canView = hasDelete || hasEdit || hasRun || hasView;
350
- return {
351
- canView,
352
- canRun,
353
- canEdit,
354
- canDelete,
355
- isOwner: false
356
- };
335
+ return ComputeDirectAIAgentPermissions(agent, allPermissions, user, userRoleIds);
357
336
  }
358
337
  /**
359
338
  * Pure synchronous computation of effective permissions including the 2x2 RBAC matrix
@@ -559,34 +538,15 @@ var AISkillPermissionHelper = class {
559
538
  }
560
539
  /**
561
540
  * Synchronous core of the permission calculation, operating on already-loaded cache arrays.
562
- * Exposed so hot-path callers (e.g. `AIEngineBase.GetSkillsForAgent(agent, user)`) can filter
563
- * 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).
564
543
  *
565
544
  * @param skill - The skill entity (owner is `CreatedByUserID`).
566
545
  * @param allPermissions - The full `SkillPermissions` cache (filtered internally by skill).
567
546
  * @param user - The user to evaluate for.
568
547
  */
569
548
  static ComputeEffectivePermissions(skill, allPermissions, user) {
570
- if (UUIDsEqual(skill.CreatedByUserID, user.ID)) {
571
- return { canView: true, canRun: true, canEdit: true, canDelete: true, isOwner: true };
572
- }
573
- const skillPermissions = allPermissions.filter((p) => UUIDsEqual(p.SkillID, skill.ID));
574
- if (skillPermissions.length === 0) {
575
- return { canView: true, canRun: true, canEdit: false, canDelete: false, isOwner: false };
576
- }
577
- const userRoleIds = user.UserRoles?.map((ur) => ur.RoleID) ?? [];
578
- const matching = skillPermissions.filter((p) => p.UserID && UUIDsEqual(p.UserID, user.ID) || p.RoleID && userRoleIds.some((rid) => UUIDsEqual(rid, p.RoleID)));
579
- const hasDelete = matching.some((p) => p.CanDelete === true);
580
- const hasEdit = matching.some((p) => p.CanEdit === true);
581
- const hasRun = matching.some((p) => p.CanRun === true);
582
- const hasView = matching.some((p) => p.CanView === true);
583
- return {
584
- canDelete: hasDelete,
585
- canEdit: hasDelete || hasEdit,
586
- canRun: hasDelete || hasEdit || hasRun,
587
- canView: hasDelete || hasEdit || hasRun || hasView,
588
- isOwner: false
589
- };
549
+ return ComputeDirectAISkillPermissions(skill, allPermissions, user);
590
550
  }
591
551
  /**
592
552
  * Gets all skills a user can access with at least the given permission level, from cache.
@@ -659,6 +619,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
659
619
  this._agents = [];
660
620
  this._agentRelationships = [];
661
621
  this._agentTypes = [];
622
+ this._agentStepTypes = [];
662
623
  this._agentRequestTypes = [];
663
624
  this._vendorTypeDefinitions = [];
664
625
  this._vendors = [];
@@ -796,6 +757,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
796
757
  PropertyName: "_agentNotes",
797
758
  EntityName: "MJ: AI Agent Notes",
798
759
  CacheLocal: true,
760
+ Filter: AIEngineBase_1.INJECTABLE_NOTE_FILTER,
799
761
  // Binary vector column: loaded server-side (the AIEngine reads it), skipped over the wire.
800
762
  IncludeBinaryFields: "DatabaseProviderOnly"
801
763
  },
@@ -1028,6 +990,11 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1028
990
  PropertyName: "_agentPersonas",
1029
991
  EntityName: "MJ: AI Agent Personas",
1030
992
  CacheLocal: true
993
+ },
994
+ {
995
+ PropertyName: "_agentStepTypes",
996
+ EntityName: "MJ: AI Agent Step Types",
997
+ CacheLocal: true
1031
998
  }
1032
999
  ];
1033
1000
  for (const config of conditional) {
@@ -1038,17 +1005,71 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1038
1005
  }
1039
1006
  }
1040
1007
  }
1008
+ static {
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
+ }
1041
1024
  static {
1042
1025
  this.IMMEDIATE_MUTATION_PROPERTIES = /* @__PURE__ */ new Set([
1043
1026
  "_vectorIndexes",
1044
1027
  "_agentPersonas",
1045
- "_agentPermissions"
1028
+ "_agentPermissions",
1029
+ "_agentNotes"
1046
1030
  ]);
1047
1031
  }
1048
1032
  canUseImmediateMutation(config, skipAdditionalLoadingCheck = false) {
1049
1033
  const independent = AIEngineBase_1.IMMEDIATE_MUTATION_PROPERTIES.has(config.PropertyName);
1050
1034
  return super.canUseImmediateMutation(config, skipAdditionalLoadingCheck || independent);
1051
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
+ }
1052
1073
  /**
1053
1074
  * Intercepts `MJ: AI Agents`, `MJ: AI Agent Personas`, and `MJ: AI Agent Permissions` events so
1054
1075
  * in-memory caches (`_agents`, `_agentsByID`, `_userRunnableAgentDirectoryCache`, and sibling
@@ -1274,7 +1295,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1274
1295
  };
1275
1296
  const keyFor = (id) => id ? id.toUpperCase() : "";
1276
1297
  const replaceContents = (target, next) => {
1277
- if (next.length <= 3e4) {
1298
+ if (next.length <= AIEngineBase_1.MAX_SPREAD_SPLICE_LENGTH) {
1278
1299
  target.splice(0, target.length, ...next);
1279
1300
  return;
1280
1301
  }
@@ -1704,20 +1725,103 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1704
1725
  * @returns MJAIAgentEntityExtended[] - Array of sub-agent entities matching the criteria (deduplicated by ID).
1705
1726
  * @memberof
1706
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
+ }
1707
1804
  GetSubAgents(agentID, status, relationshipStatus) {
1708
1805
  this.ensureAgentsIndex();
1709
1806
  this.ensureAgentRelationshipsIndex();
1710
1807
  const chain = this.GetAgentInheritanceChain(agentID);
1711
- const chainIds = chain.length > 0 ? chain.map((a) => NormalizeUUID(a.ID)) : [NormalizeUUID(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 }];
1712
1812
  const relStatus = relationshipStatus ?? "Active";
1713
1813
  const subAgentsById = /* @__PURE__ */ new Map();
1714
- for (const normChainAgentId of chainIds) {
1715
- const rawChildAgents = this._childAgentsByParentID.get(normChainAgentId) ?? [];
1716
- const childAgents = status ? rawChildAgents.filter((a) => a.Status === status) : rawChildAgents;
1717
- for (const child of childAgents) {
1718
- const normChildId = NormalizeUUID(child.ID);
1719
- if (!subAgentsById.has(normChildId)) {
1720
- subAgentsById.set(normChildId, child);
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
+ }
1721
1825
  }
1722
1826
  }
1723
1827
  const rawRelationships = this._agentRelationshipsByAgentID.get(normChainAgentId) ?? [];
@@ -1729,6 +1833,9 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1729
1833
  subAgentsById.delete(normSubId);
1730
1834
  continue;
1731
1835
  }
1836
+ if (!isRoot && !canWiden && !subAgentsById.has(normSubId)) {
1837
+ continue;
1838
+ }
1732
1839
  const subAgent = this._agentsByID.get(normSubId);
1733
1840
  if (subAgent && (!status || subAgent.Status === status)) {
1734
1841
  subAgentsById.set(normSubId, subAgent);
@@ -1801,67 +1908,167 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1801
1908
  return [...ancestors, agent];
1802
1909
  }
1803
1910
  /**
1804
- * Resolves effective scalar properties and deep-merged `TypeConfiguration` /
1805
- * `AgentTypePromptParams` across the agent's `BaseAgentID` prototype inheritance chain
1806
- * (`[rootAgent, ..., leafAgent]`).
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.
1807
1940
  */
1808
1941
  ResolveEffectiveAgentProperties(agentOrId) {
1809
1942
  const leaf = typeof agentOrId === "string" ? this.GetAgentByID(agentOrId) : agentOrId;
1810
1943
  const nodes = leaf ? this.resolveInheritanceNodesForAgent(leaf) : [];
1811
1944
  const root = nodes[0];
1945
+ const nodeConfigs = nodes.map((n) => ParseAgentConfiguration(n.Configuration));
1812
1946
  const nearestNonNull = (picker) => {
1813
1947
  for (let i = nodes.length - 1; i >= 0; i--) {
1814
- const v = picker(nodes[i]);
1948
+ const v = picker(nodes[i], nodeConfigs[i]);
1815
1949
  if (v !== null && v !== void 0 && (typeof v !== "string" || v.trim().length > 0)) {
1816
1950
  return v;
1817
1951
  }
1818
1952
  }
1819
1953
  return null;
1820
1954
  };
1821
- const isolationRank = {
1822
- InProcess: 0,
1823
- Worker: 1,
1824
- Process: 2,
1825
- Container: 3
1826
- };
1827
- let effectiveIsolation = "InProcess";
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 = [];
1828
1969
  for (const node of nodes) {
1829
- const iso = node.Isolation ?? "InProcess";
1830
- if ((isolationRank[iso] ?? 0) > (isolationRank[effectiveIsolation] ?? 0)) {
1831
- effectiveIsolation = iso;
1970
+ if (!node.CategoryID) {
1971
+ continue;
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
+ }
1832
1979
  }
1833
1980
  }
1834
- const acceptsRank = {
1835
- None: 0,
1836
- Limited: 1,
1837
- All: 2
1838
- };
1839
- let effectiveAcceptsSkills = root?.AcceptsSkills ?? "None";
1840
- for (let i = 1; i < nodes.length; i++) {
1841
- const nodeAccepts = nodes[i].AcceptsSkills;
1842
- if (nodeAccepts != null && (acceptsRank[nodeAccepts] ?? 0) < (acceptsRank[effectiveAcceptsSkills] ?? 0)) {
1843
- effectiveAcceptsSkills = nodeAccepts;
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);
1844
1986
  }
1845
1987
  }
1846
- const skillModeRank = {
1847
- RequestedOnly: 0,
1848
- Auto: 1
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;
1849
2006
  };
1850
- let effectiveSkillActivationMode = root?.SkillActivationMode ?? "RequestedOnly";
1851
- for (let i = 1; i < nodes.length; i++) {
1852
- const nodeMode = nodes[i].SkillActivationMode;
1853
- if (nodeMode != null && (skillModeRank[nodeMode] ?? 0) < (skillModeRank[effectiveSkillActivationMode] ?? 0)) {
1854
- effectiveSkillActivationMode = nodeMode;
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;
1855
2012
  }
1856
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";
1857
2063
  const activePromptAgentIds = new UUIDSet(this._agentPrompts.filter((ap) => ap.Status === "Active").map((ap) => ap.AgentID));
1858
2064
  const leafHasOwnPrompts = leaf ? activePromptAgentIds.Has(leaf.ID) : false;
1859
- let effectiveModelSelectionMode = leaf?.ModelSelectionMode ?? "Agent Type";
2065
+ const leafModelMode = (nodes.length > 0 ? nodeConfigs[nodes.length - 1]?.execution?.modelSelectionMode : null) ?? leaf?.ModelSelectionMode;
2066
+ let effectiveModelSelectionMode = leafModelMode ?? defaultsLayer.execution?.modelSelectionMode ?? "Agent Type";
1860
2067
  if (!leafHasOwnPrompts && nodes.length > 1) {
1861
2068
  for (let i = nodes.length - 1; i >= 0; i--) {
1862
2069
  const candidate = nodes[i];
1863
2070
  if (activePromptAgentIds.Has(candidate.ID)) {
1864
- effectiveModelSelectionMode = candidate.ModelSelectionMode ?? "Agent Type";
2071
+ effectiveModelSelectionMode = nodeConfigs[i]?.execution?.modelSelectionMode ?? candidate.ModelSelectionMode ?? defaultsLayer.execution?.modelSelectionMode ?? "Agent Type";
1865
2072
  break;
1866
2073
  }
1867
2074
  }
@@ -1877,52 +2084,816 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1877
2084
  delete mergedTypeConfig["instantiation"];
1878
2085
  }
1879
2086
  let mergedPromptParams = null;
1880
- for (const node of nodes) {
1881
- const parsed = ParseAgentConfigJsonObject(node.AgentTypePromptParams);
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);
1882
2109
  if (parsed) {
1883
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
+ }
1884
2119
  }
1885
2120
  }
1886
- const effectiveRequirePlanMode = nodes.some((n) => n.RequirePlanMode === true);
1887
- const effectiveSupportsPlanMode = nodes.length > 0 ? nodes.every((n) => n.SupportsPlanMode !== false) : true;
1888
- const effectiveSearchScopeAccess = leaf?.SearchScopeAccess && leaf.SearchScopeAccess !== "None" ? leaf.SearchScopeAccess : nearestNonNull((a) => a.SearchScopeAccess && a.SearchScopeAccess !== "None" ? a.SearchScopeAccess : null) ?? leaf?.SearchScopeAccess ?? "None";
1889
- const effectiveArtifactCreationMode = leaf?.ArtifactCreationMode && leaf.ArtifactCreationMode !== "Never" ? leaf.ArtifactCreationMode : nearestNonNull((a) => a.ArtifactCreationMode && a.ArtifactCreationMode !== "Never" ? a.ArtifactCreationMode : null) ?? leaf?.ArtifactCreationMode ?? "Never";
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
+ });
1890
2833
  return {
1891
- TypeID: nearestNonNull((a) => a.TypeID),
2834
+ TypeID: effectiveTypeId,
1892
2835
  DriverClass: nearestNonNull((a) => a.DriverClass),
1893
2836
  ModelSelectionMode: effectiveModelSelectionMode,
1894
2837
  Isolation: effectiveIsolation,
1895
- ContextWindowMaxTokens: nearestNonNull((a) => a.ContextWindowMaxTokens),
1896
- CompactionTriggerPercent: nearestNonNull((a) => a.CompactionTriggerPercent),
1897
- CompactionTargetPercent: nearestNonNull((a) => a.CompactionTargetPercent),
1898
- ConversationSummaryPromptID: nearestNonNull((a) => a.ConversationSummaryPromptID),
1899
- EnableContextCompression: nodes.some((n) => n.EnableContextCompression === true),
1900
- ContextCompressionMessageThreshold: nearestNonNull((a) => a.ContextCompressionMessageThreshold),
1901
- ContextCompressionPromptID: nearestNonNull((a) => a.ContextCompressionPromptID),
1902
- ContextCompressionMessageRetentionCount: nearestNonNull((a) => a.ContextCompressionMessageRetentionCount),
1903
- RerankerConfiguration: nearestNonNull((a) => a.RerankerConfiguration),
1904
- ScopeConfig: nearestNonNull((a) => a.ScopeConfig),
1905
- DefaultPromptEffortLevel: nearestNonNull((a) => a.DefaultPromptEffortLevel),
1906
- ChatHandlingOption: nearestNonNull((a) => a.ChatHandlingOption),
1907
- DefaultArtifactTypeID: nearestNonNull((a) => a.DefaultArtifactTypeID),
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),
1908
2851
  ArtifactCreationMode: effectiveArtifactCreationMode,
1909
- DeclareActionsAsNativeTools: nodes.some((n) => n.DeclareActionsAsNativeTools === true),
2852
+ DeclareActionsAsNativeTools: effectiveDeclareNativeTools,
1910
2853
  SupportsPlanMode: effectiveSupportsPlanMode,
1911
2854
  RequirePlanMode: effectiveRequirePlanMode,
1912
2855
  AcceptsSkills: effectiveAcceptsSkills,
1913
- SkillActivationMode: effectiveSkillActivationMode,
2856
+ SkillActivationMode: resolvedSkillActivationMode,
1914
2857
  SearchScopeAccess: effectiveSearchScopeAccess,
1915
- AllowMemoryWrite: nodes.some((n) => n.AllowMemoryWrite === true),
1916
- InjectNotes: nodes.some((n) => n.InjectNotes === true),
1917
- MaxNotesToInject: nearestNonNull((a) => a.MaxNotesToInject),
1918
- NoteInjectionStrategy: nearestNonNull((a) => a.NoteInjectionStrategy) ?? "Relevant",
1919
- InjectExamples: nodes.some((n) => n.InjectExamples === true),
1920
- MaxExamplesToInject: nearestNonNull((a) => a.MaxExamplesToInject),
1921
- ExampleInjectionStrategy: nearestNonNull((a) => a.ExampleInjectionStrategy) ?? "Semantic",
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),
1922
2891
  LogoURL: nearestNonNull((a) => a.LogoURL),
1923
2892
  IconClass: nearestNonNull((a) => a.IconClass),
1924
2893
  TypeConfiguration: mergedTypeConfig && Object.keys(mergedTypeConfig).length > 0 ? JSON.stringify(mergedTypeConfig) : null,
1925
- AgentTypePromptParams: mergedPromptParams && Object.keys(mergedPromptParams).length > 0 ? JSON.stringify(mergedPromptParams) : null
2894
+ AgentTypePromptParams: mergedPromptParams && Object.keys(mergedPromptParams).length > 0 ? JSON.stringify(mergedPromptParams) : null,
2895
+ Configuration: mergedConfiguration,
2896
+ HelperPlugins: helperPlugins
1926
2897
  };
1927
2898
  }
1928
2899
  /**
@@ -1953,13 +2924,23 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1953
2924
  }
1954
2925
  /**
1955
2926
  * Resolves effective `AIAgentAction` rows for `agentId` across its `BaseAgentID` chain
1956
- * (root -> leaf, keyed by `ActionID`). A descendant row with `Status !== 'Active'`
1957
- * (e.g. `'Disabled'` or `'Revoked'`) vetoes an inherited action.
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.
1958
2936
  */
1959
2937
  GetEffectiveAgentActions(agentId) {
1960
2938
  const chain = this.GetAgentInheritanceChain(agentId);
1961
- const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : agentId ? [agentId] : [];
1962
- const chainIdSet = new UUIDSet(idsRootToLeaf);
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));
1963
2944
  const actionsByAgentId = /* @__PURE__ */ new Map();
1964
2945
  for (const aa of this._agentActions) {
1965
2946
  if (chainIdSet.Has(aa.AgentID)) {
@@ -1969,18 +2950,64 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
1969
2950
  actionsByAgentId.set(key, list);
1970
2951
  }
1971
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
+ };
1972
2967
  const effectiveByActionId = /* @__PURE__ */ new Map();
1973
- for (const id of idsRootToLeaf) {
2968
+ for (let idx = 0; idx < nodes.length; idx++) {
2969
+ const { id, canWiden } = nodes[idx];
2970
+ const isRoot = idx === 0;
1974
2971
  const rows = actionsByAgentId.get(NormalizeUUID(id)) ?? [];
1975
2972
  for (const row of rows) {
1976
2973
  if (!row.ActionID)
1977
2974
  continue;
1978
2975
  const normActionId = NormalizeUUID(row.ActionID);
1979
- if (row.Status === "Active") {
1980
- effectiveByActionId.set(normActionId, row);
1981
- } else {
2976
+ if (row.Status !== "Active") {
1982
2977
  effectiveByActionId.delete(normActionId);
2978
+ continue;
1983
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;
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);
1984
3011
  }
1985
3012
  }
1986
3013
  return Array.from(effectiveByActionId.values());
@@ -2008,6 +3035,23 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2008
3035
  get AgentTypes() {
2009
3036
  return this.GetConfigData("_agentTypes");
2010
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
+ }
2011
3055
  /**
2012
3056
  * The `MJ: AI Agent Request Types` rows (Approval, Information, ...), cached during Config().
2013
3057
  * Resolve a type with {@link GetAgentRequestTypeByName} instead of hardcoding its ID.
@@ -2436,23 +3480,12 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2436
3480
  return effective;
2437
3481
  }
2438
3482
  /**
2439
- * Resolves the effective narrowed `SkillActivationMode` value down the agent's `BaseAgentID`
2440
- * chain (`Auto` -> `RequestedOnly`).
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).
2441
3486
  */
2442
3487
  resolveEffectiveSkillActivationMode(agent) {
2443
- const nodes = this.resolveInheritanceNodesForAgent(agent);
2444
- const skillModeRank = {
2445
- RequestedOnly: 0,
2446
- Auto: 1
2447
- };
2448
- let effective = nodes[0]?.SkillActivationMode ?? "RequestedOnly";
2449
- for (let i = 1; i < nodes.length; i++) {
2450
- const nodeMode = nodes[i].SkillActivationMode;
2451
- if (nodeMode != null && (skillModeRank[nodeMode] ?? 0) < (skillModeRank[effective] ?? 0)) {
2452
- effective = nodeMode;
2453
- }
2454
- }
2455
- return effective;
3488
+ return this.ResolveEffectiveAgentProperties(agent).SkillActivationMode;
2456
3489
  }
2457
3490
  GetSkillsForAgent(agent, user) {
2458
3491
  if (!agent) {
@@ -2480,14 +3513,16 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
2480
3513
  }
2481
3514
  }
2482
3515
  const grantedSkillIDs = /* @__PURE__ */ new Set();
2483
- for (const chainAgentId of chainIds) {
2484
- const grants = grantsByAgentId.get(NormalizeUUID(chainAgentId)) ?? [];
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)) ?? [];
2485
3520
  for (const grant of grants) {
2486
3521
  const normSkillId = NormalizeUUID(grant.SkillID);
2487
- if (grant.Status === "Active") {
2488
- grantedSkillIDs.add(normSkillId);
2489
- } else {
3522
+ if (grant.Status !== "Active") {
2490
3523
  grantedSkillIDs.delete(normSkillId);
3524
+ } else if (isRoot || canWiden) {
3525
+ grantedSkillIDs.add(normSkillId);
2491
3526
  }
2492
3527
  }
2493
3528
  }
@@ -3410,8 +4445,11 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3410
4445
  */
3411
4446
  GetClientToolsForAgent(agentId) {
3412
4447
  const chain = this.GetAgentInheritanceChain(agentId);
3413
- const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
3414
- const chainIdSet = new UUIDSet(idsRootToLeaf);
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));
3415
4453
  const toolsByAgentId = /* @__PURE__ */ new Map();
3416
4454
  for (const j of this._agentClientTools) {
3417
4455
  if (chainIdSet.Has(j.AgentID)) {
@@ -3422,12 +4460,17 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3422
4460
  }
3423
4461
  }
3424
4462
  const mergedByToolId = /* @__PURE__ */ new Map();
3425
- for (const id of idsRootToLeaf) {
4463
+ for (let idx = 0; idx < nodes.length; idx++) {
4464
+ const { id, canWiden } = nodes[idx];
4465
+ const isRoot = idx === 0;
3426
4466
  const rows = toolsByAgentId.get(NormalizeUUID(id)) ?? [];
3427
4467
  for (const row of rows) {
3428
4468
  if (!row.ClientToolDefinitionID)
3429
4469
  continue;
3430
- mergedByToolId.set(NormalizeUUID(row.ClientToolDefinitionID), row);
4470
+ const normToolId = NormalizeUUID(row.ClientToolDefinitionID);
4471
+ if (isRoot || canWiden || mergedByToolId.has(normToolId)) {
4472
+ mergedByToolId.set(normToolId, row);
4473
+ }
3431
4474
  }
3432
4475
  }
3433
4476
  const junctions = Array.from(mergedByToolId.values()).sort((a, b) => a.Priority - b.Priority);
@@ -3513,8 +4556,11 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3513
4556
  resultMap.set(NormalizeUUID(m.ID), m);
3514
4557
  }
3515
4558
  const chain = this.GetAgentInheritanceChain(agentId);
3516
- const idsRootToLeaf = chain.length > 0 ? chain.map((a) => a.ID) : [agentId];
3517
- const chainIdSet = new UUIDSet(idsRootToLeaf);
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));
3518
4564
  const modalitiesByAgentId = /* @__PURE__ */ new Map();
3519
4565
  for (const am of this._agentModalities) {
3520
4566
  if (am.Direction === direction && chainIdSet.Has(am.AgentID)) {
@@ -3524,15 +4570,19 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3524
4570
  modalitiesByAgentId.set(key, list);
3525
4571
  }
3526
4572
  }
3527
- for (const id of idsRootToLeaf) {
4573
+ for (let idx = 0; idx < nodes.length; idx++) {
4574
+ const { id, canWiden } = nodes[idx];
4575
+ const isRoot = idx === 0;
3528
4576
  const agentRecords = modalitiesByAgentId.get(NormalizeUUID(id)) ?? [];
3529
4577
  for (const am of agentRecords) {
3530
4578
  const normId = NormalizeUUID(am.ModalityID);
3531
4579
  const isAllowed = am.IsAllowed !== false;
3532
4580
  if (isAllowed) {
3533
- const modality = this._modalitiesByID.get(normId);
3534
- if (modality) {
3535
- resultMap.set(normId, modality);
4581
+ if (isRoot || canWiden || resultMap.has(normId)) {
4582
+ const modality = this._modalitiesByID.get(normId);
4583
+ if (modality) {
4584
+ resultMap.set(normId, modality);
4585
+ }
3536
4586
  }
3537
4587
  } else {
3538
4588
  resultMap.delete(normId);
@@ -3597,10 +4647,15 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3597
4647
  AgentSupportsModality(agentId, modalityName, direction, modelId) {
3598
4648
  this.ensureModalitiesIndex();
3599
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";
3600
4652
  if (targetModality) {
3601
4653
  const chain = this.GetAgentInheritanceChain(agentId);
3602
- const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : [agentId];
3603
- const chainIdSet = new UUIDSet(idsLeafToRoot);
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));
3604
4659
  const recordByAgentId = /* @__PURE__ */ new Map();
3605
4660
  for (const am of this._agentModalities) {
3606
4661
  if (am.Direction === direction && UUIDsEqual(am.ModalityID, targetModality.ID) && chainIdSet.Has(am.AgentID)) {
@@ -3610,18 +4665,21 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3610
4665
  }
3611
4666
  }
3612
4667
  }
3613
- for (const id of idsLeafToRoot) {
4668
+ for (let idx = 0; idx < nodes.length; idx++) {
4669
+ const { id, canWiden } = nodes[idx];
4670
+ const isRoot = idx === 0;
3614
4671
  const agentRecord = recordByAgentId.get(NormalizeUUID(id));
3615
- if (agentRecord) {
3616
- return agentRecord.IsAllowed !== false;
4672
+ if (!agentRecord) {
4673
+ continue;
4674
+ }
4675
+ if (agentRecord.IsAllowed === false) {
4676
+ supported = false;
4677
+ } else if (isRoot || canWiden) {
4678
+ supported = true;
3617
4679
  }
3618
4680
  }
3619
4681
  }
3620
- const resolvedModelId = this.resolveAgentModelId(agentId, modelId);
3621
- if (resolvedModelId) {
3622
- return this.ModelSupportsModality(resolvedModelId, modalityName, direction);
3623
- }
3624
- return modalityName.toLowerCase() === "text";
4682
+ return supported;
3625
4683
  }
3626
4684
  /**
3627
4685
  * Checks if a model supports a specific modality for a given direction.
@@ -3684,8 +4742,11 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3684
4742
  };
3685
4743
  }
3686
4744
  const chain = this.GetAgentInheritanceChain(agentId);
3687
- const idsLeafToRoot = chain.length > 0 ? chain.map((a) => a.ID).reverse() : [agentId];
3688
- const chainIdSet = new UUIDSet(idsLeafToRoot);
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));
3689
4750
  const modalityByAgentId = /* @__PURE__ */ new Map();
3690
4751
  for (const am of this._agentModalities) {
3691
4752
  if (am.Direction === "Input" && UUIDsEqual(am.ModalityID, modality.ID) && chainIdSet.Has(am.AgentID)) {
@@ -3695,23 +4756,49 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
3695
4756
  }
3696
4757
  }
3697
4758
  }
3698
- let agentModality;
3699
- for (const id of idsLeafToRoot) {
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];
3700
4770
  const found = modalityByAgentId.get(NormalizeUUID(id));
3701
- if (found) {
3702
- agentModality = found;
3703
- break;
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);
3704
4791
  }
3705
4792
  }
3706
- if (agentModality) {
4793
+ if (matchedAnyAgentRow) {
3707
4794
  return {
3708
- maxSizeBytes: agentModality.MaxSizeBytes,
3709
- maxCountPerMessage: agentModality.MaxCountPerMessage,
4795
+ maxSizeBytes: resolvedMaxSizeBytes,
4796
+ maxCountPerMessage: resolvedMaxCount,
3710
4797
  maxDimension: null,
3711
4798
  // Agent modality doesn't have MaxDimension
3712
4799
  supportedFormats: null,
3713
4800
  // Agent modality doesn't have SupportedFormats
3714
- isAllowed: agentModality.IsAllowed,
4801
+ isAllowed: resolvedIsAllowed,
3715
4802
  source: "Agent"
3716
4803
  };
3717
4804
  }
@@ -4045,7 +5132,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
4045
5132
  * In all cases, merges agent-level StyleOverride (Tone, SpeakingStyle) over the persona's defaults.
4046
5133
  *
4047
5134
  * @param agentId - The agent ID
4048
- * @param options - Optional overrides for modelId, vendorId, modalityName, preferredPersonaId
5135
+ * @param options - Optional overrides for modelId, vendorId, modalityName, preferredPersonaId, and allowModelFallback (defaults to true)
4049
5136
  */
4050
5137
  ResolveAgentPersona(agentId, options) {
4051
5138
  const modalityName = options?.modalityName ?? "Audio";
@@ -4072,7 +5159,7 @@ var AIEngineBase = class AIEngineBase2 extends BaseEngine {
4072
5159
  chosenAgentPersona = selected.AgentPersona;
4073
5160
  }
4074
5161
  const resolvedModelId = this.resolveAgentModelId(agentId, options?.modelId);
4075
- if (!chosenPersona && resolvedModelId) {
5162
+ if (!chosenPersona && resolvedModelId && options?.allowModelFallback !== false) {
4076
5163
  const modelPersonas = this.GetModelPersonas(resolvedModelId, modalityName, options?.vendorId);
4077
5164
  if (modelPersonas.length > 0) {
4078
5165
  chosenPersona = modelPersonas[0].Persona;