@memberjunction/core-entities-server 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.
- package/README.md +13 -0
- package/dist/custom/AgentChannelConversationDriver.server.d.ts +87 -0
- package/dist/custom/AgentChannelConversationDriver.server.d.ts.map +1 -0
- package/dist/custom/AgentChannelConversationDriver.server.js +216 -0
- package/dist/custom/AgentChannelConversationDriver.server.js.map +1 -0
- package/dist/custom/ArtifactSecurityHookHelpers.d.ts.map +1 -1
- package/dist/custom/ArtifactSecurityHookHelpers.js +50 -0
- package/dist/custom/ArtifactSecurityHookHelpers.js.map +1 -1
- package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts +25 -0
- package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts.map +1 -0
- package/dist/custom/AudienceNamedPersonAgentRequestService.js +304 -0
- package/dist/custom/AudienceNamedPersonAgentRequestService.js.map +1 -0
- package/dist/custom/ConversationDetailWritePermissionProvider.d.ts +113 -0
- package/dist/custom/ConversationDetailWritePermissionProvider.d.ts.map +1 -0
- package/dist/custom/ConversationDetailWritePermissionProvider.js +200 -0
- package/dist/custom/ConversationDetailWritePermissionProvider.js.map +1 -0
- package/dist/custom/ConversationReadSecurityHook.d.ts +61 -0
- package/dist/custom/ConversationReadSecurityHook.d.ts.map +1 -0
- package/dist/custom/ConversationReadSecurityHook.js +587 -0
- package/dist/custom/ConversationReadSecurityHook.js.map +1 -0
- package/dist/custom/GraphConceptReadSecurityHook.d.ts +75 -0
- package/dist/custom/GraphConceptReadSecurityHook.d.ts.map +1 -0
- package/dist/custom/GraphConceptReadSecurityHook.js +574 -0
- package/dist/custom/GraphConceptReadSecurityHook.js.map +1 -0
- package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts +45 -0
- package/dist/custom/GraphRecordChangesReadSecurityHook.d.ts.map +1 -0
- package/dist/custom/GraphRecordChangesReadSecurityHook.js +744 -0
- package/dist/custom/GraphRecordChangesReadSecurityHook.js.map +1 -0
- package/dist/custom/MJAIAgentActionEntityServer.server.d.ts +13 -0
- package/dist/custom/MJAIAgentActionEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentActionEntityServer.server.js +52 -0
- package/dist/custom/MJAIAgentActionEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts +30 -0
- package/dist/custom/MJAIAgentCategoryEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentCategoryEntityServer.server.js +127 -0
- package/dist/custom/MJAIAgentCategoryEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts +12 -0
- package/dist/custom/MJAIAgentClientToolEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentClientToolEntityServer.server.js +46 -0
- package/dist/custom/MJAIAgentClientToolEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentEntityServer.server.d.ts +185 -33
- package/dist/custom/MJAIAgentEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJAIAgentEntityServer.server.js +2232 -42
- package/dist/custom/MJAIAgentEntityServer.server.js.map +1 -1
- package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts +13 -0
- package/dist/custom/MJAIAgentModalityEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentModalityEntityServer.server.js +52 -0
- package/dist/custom/MJAIAgentModalityEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts +64 -8
- package/dist/custom/MJAIAgentNoteEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJAIAgentNoteEntityServer.server.js +263 -9
- package/dist/custom/MJAIAgentNoteEntityServer.server.js.map +1 -1
- package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts +23 -0
- package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentPersonaEntityServer.server.js +95 -0
- package/dist/custom/MJAIAgentPersonaEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts +5 -2
- package/dist/custom/MJAIAgentRelationshipEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJAIAgentRelationshipEntityServer.server.js +25 -2
- package/dist/custom/MJAIAgentRelationshipEntityServer.server.js.map +1 -1
- package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts +12 -0
- package/dist/custom/MJAIAgentSkillEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentSkillEntityServer.server.js +46 -0
- package/dist/custom/MJAIAgentSkillEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts +28 -0
- package/dist/custom/MJAIAgentStepTypeEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentStepTypeEntityServer.server.js +117 -0
- package/dist/custom/MJAIAgentStepTypeEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts +34 -0
- package/dist/custom/MJAIAgentTypeEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJAIAgentTypeEntityServer.server.js +231 -0
- package/dist/custom/MJAIAgentTypeEntityServer.server.js.map +1 -0
- package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts +24 -13
- package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js +167 -24
- package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js.map +1 -1
- package/dist/custom/MJActionEntityServer.server.d.ts +37 -0
- package/dist/custom/MJActionEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJActionEntityServer.server.js +208 -3
- package/dist/custom/MJActionEntityServer.server.js.map +1 -1
- package/dist/custom/MJComponentEntityServer.server.d.ts +6 -0
- package/dist/custom/MJComponentEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJComponentEntityServer.server.js +20 -2
- package/dist/custom/MJComponentEntityServer.server.js.map +1 -1
- package/dist/custom/MJContentSourceEntityServer.server.d.ts +28 -0
- package/dist/custom/MJContentSourceEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJContentSourceEntityServer.server.js +73 -0
- package/dist/custom/MJContentSourceEntityServer.server.js.map +1 -0
- package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts +25 -0
- package/dist/custom/MJContentSourceTypeEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJContentSourceTypeEntityServer.server.js +73 -0
- package/dist/custom/MJContentSourceTypeEntityServer.server.js.map +1 -0
- package/dist/custom/MJConversationDetailEntityServer.server.d.ts +27 -2
- package/dist/custom/MJConversationDetailEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJConversationDetailEntityServer.server.js +300 -4
- package/dist/custom/MJConversationDetailEntityServer.server.js.map +1 -1
- package/dist/custom/MJConversationEntityServer.server.d.ts +5 -26
- package/dist/custom/MJConversationEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJConversationEntityServer.server.js +236 -8
- package/dist/custom/MJConversationEntityServer.server.js.map +1 -1
- package/dist/custom/MJDashboardEntityServer.server.d.ts +6 -0
- package/dist/custom/MJDashboardEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJDashboardEntityServer.server.js +24 -2
- package/dist/custom/MJDashboardEntityServer.server.js.map +1 -1
- package/dist/custom/MJGraphConceptEntityServer.server.d.ts +244 -0
- package/dist/custom/MJGraphConceptEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJGraphConceptEntityServer.server.js +746 -0
- package/dist/custom/MJGraphConceptEntityServer.server.js.map +1 -0
- package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +52 -11
- package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJGraphEdgeEntityServer.server.js +269 -37
- package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -1
- package/dist/custom/MJGraphEntityServer.server.d.ts +58 -0
- package/dist/custom/MJGraphEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJGraphEntityServer.server.js +357 -0
- package/dist/custom/MJGraphEntityServer.server.js.map +1 -0
- package/dist/custom/MJGraphLinkEntityServer.server.d.ts +98 -0
- package/dist/custom/MJGraphLinkEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJGraphLinkEntityServer.server.js +375 -0
- package/dist/custom/MJGraphLinkEntityServer.server.js.map +1 -0
- package/dist/custom/MJGraphPermissionEntityServer.server.d.ts +29 -0
- package/dist/custom/MJGraphPermissionEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJGraphPermissionEntityServer.server.js +141 -0
- package/dist/custom/MJGraphPermissionEntityServer.server.js.map +1 -0
- package/dist/custom/MJListDetailEntityServer.server.d.ts +4 -4
- package/dist/custom/MJListDetailEntityServer.server.js +4 -4
- package/dist/custom/MJListEntityServer.server.d.ts +2 -1
- package/dist/custom/MJListEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJListEntityServer.server.js +5 -2
- package/dist/custom/MJListEntityServer.server.js.map +1 -1
- package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts +31 -0
- package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJMLModelPublishRecordEntityServer.server.js +68 -0
- package/dist/custom/MJMLModelPublishRecordEntityServer.server.js.map +1 -0
- package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts +78 -0
- package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJMLModelScoringBindingEntityServer.server.js +273 -0
- package/dist/custom/MJMLModelScoringBindingEntityServer.server.js.map +1 -0
- package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts +18 -0
- package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJMLOutputBindingEntityServer.server.js +61 -0
- package/dist/custom/MJMLOutputBindingEntityServer.server.js.map +1 -0
- package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts +3 -3
- package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJMLPredictionUnitEntityServer.server.js +4 -4
- package/dist/custom/MJMLPredictionUnitEntityServer.server.js.map +1 -1
- package/dist/custom/MJQueryEntityServer.server.d.ts +81 -0
- package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJQueryEntityServer.server.js +194 -4
- package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
- package/dist/custom/MJQueryParameterEntityServer.server.d.ts +37 -0
- package/dist/custom/MJQueryParameterEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJQueryParameterEntityServer.server.js +160 -0
- package/dist/custom/MJQueryParameterEntityServer.server.js.map +1 -0
- package/dist/custom/MJQuerySQLEntityServer.server.d.ts +36 -1
- package/dist/custom/MJQuerySQLEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJQuerySQLEntityServer.server.js +138 -7
- package/dist/custom/MJQuerySQLEntityServer.server.js.map +1 -1
- package/dist/custom/MJResourcePermissionEntityServer.server.d.ts +28 -0
- package/dist/custom/MJResourcePermissionEntityServer.server.d.ts.map +1 -0
- package/dist/custom/MJResourcePermissionEntityServer.server.js +206 -0
- package/dist/custom/MJResourcePermissionEntityServer.server.js.map +1 -0
- package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts +1 -1
- package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js +8 -5
- package/dist/custom/MJRowLevelSecurityFilterEntityServer.server.js.map +1 -1
- package/dist/custom/MJUserRoleEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJUserRoleEntityServer.server.js +9 -0
- package/dist/custom/MJUserRoleEntityServer.server.js.map +1 -1
- package/dist/custom/MJUserRoutineEntityServer.server.d.ts +23 -0
- package/dist/custom/MJUserRoutineEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJUserRoutineEntityServer.server.js +320 -3
- package/dist/custom/MJUserRoutineEntityServer.server.js.map +1 -1
- package/dist/custom/MJUserViewEntityServer.server.d.ts +9 -0
- package/dist/custom/MJUserViewEntityServer.server.d.ts.map +1 -1
- package/dist/custom/MJUserViewEntityServer.server.js +59 -3
- package/dist/custom/MJUserViewEntityServer.server.js.map +1 -1
- package/dist/custom/agentRelationalGrantGuard.d.ts +73 -0
- package/dist/custom/agentRelationalGrantGuard.d.ts.map +1 -0
- package/dist/custom/agentRelationalGrantGuard.js +375 -0
- package/dist/custom/agentRelationalGrantGuard.js.map +1 -0
- package/dist/custom/approvalStamp.d.ts +86 -6
- package/dist/custom/approvalStamp.d.ts.map +1 -1
- package/dist/custom/approvalStamp.js +119 -15
- package/dist/custom/approvalStamp.js.map +1 -1
- package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts +20 -0
- package/dist/custom/canon/CanonFingerprintRecorderServer.d.ts.map +1 -0
- package/dist/custom/canon/CanonFingerprintRecorderServer.js +148 -0
- package/dist/custom/canon/CanonFingerprintRecorderServer.js.map +1 -0
- package/dist/custom/canon/index.d.ts +2 -0
- package/dist/custom/canon/index.d.ts.map +1 -0
- package/dist/custom/canon/index.js +2 -0
- package/dist/custom/canon/index.js.map +1 -0
- package/dist/custom/graph/GraphFindPathServerOperation.d.ts +26 -0
- package/dist/custom/graph/GraphFindPathServerOperation.d.ts.map +1 -0
- package/dist/custom/graph/GraphFindPathServerOperation.js +117 -0
- package/dist/custom/graph/GraphFindPathServerOperation.js.map +1 -0
- package/dist/custom/graph/index.d.ts +2 -0
- package/dist/custom/graph/index.d.ts.map +1 -0
- package/dist/custom/graph/index.js +2 -0
- package/dist/custom/graph/index.js.map +1 -0
- package/dist/custom/graphPermissionGuard.d.ts +69 -0
- package/dist/custom/graphPermissionGuard.d.ts.map +1 -0
- package/dist/custom/graphPermissionGuard.js +229 -0
- package/dist/custom/graphPermissionGuard.js.map +1 -0
- package/dist/custom/graphRlsCacheInvalidation.d.ts +38 -0
- package/dist/custom/graphRlsCacheInvalidation.d.ts.map +1 -0
- package/dist/custom/graphRlsCacheInvalidation.js +111 -0
- package/dist/custom/graphRlsCacheInvalidation.js.map +1 -0
- package/dist/custom/queryParentFingerprint.d.ts +36 -0
- package/dist/custom/queryParentFingerprint.d.ts.map +1 -0
- package/dist/custom/queryParentFingerprint.js +159 -0
- package/dist/custom/queryParentFingerprint.js.map +1 -0
- package/dist/custom/queryParentSaveChain.d.ts +5 -0
- package/dist/custom/queryParentSaveChain.d.ts.map +1 -0
- package/dist/custom/queryParentSaveChain.js +25 -0
- package/dist/custom/queryParentSaveChain.js.map +1 -0
- package/dist/custom/seededMetadataPush.d.ts +7 -0
- package/dist/custom/seededMetadataPush.d.ts.map +1 -0
- package/dist/custom/seededMetadataPush.js +23 -0
- package/dist/custom/seededMetadataPush.js.map +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +31 -31
|
@@ -4,70 +4,2270 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
4
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
-
import { BaseEntity, ValidationErrorInfo, ValidationErrorType } from '@memberjunction/core';
|
|
8
|
-
import { RegisterClass } from '@memberjunction/global';
|
|
9
|
-
import { MJAIAgentEntityExtended } from '@memberjunction/ai-core-plus';
|
|
7
|
+
import { AuthorizationEvaluator, BaseEntity, BaseEntityResult, EntityPermissionType, Metadata, RunView, ValidationErrorInfo, ValidationErrorType, WellKnownUserSource, } from '@memberjunction/core';
|
|
8
|
+
import { EscapeSQLString, IndexByUUID, RegisterClass, UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
9
|
+
import { AGENT_ACCEPTS_SKILLS_RANK, AGENT_ARTIFACT_CREATION_MODE_RANK, AGENT_FINAL_VALIDATION_MODE_RANK, AGENT_ISOLATION_RANK, AGENT_MESSAGE_MODE_RANK, AGENT_SEARCH_SCOPE_ACCESS_RANK, AGENT_SKILL_ACTIVATION_RANK, AGENT_STARTING_VALIDATION_MODE_RANK, BuildAgentTypeConfigurationFromLegacyFields, DeepMergeAgentConfigurations, FindScopeConfigWideningViolations, FoldRebaseAwareChain, HasPathTraversalSegment, IntersectPayloadPathSets, IsAttachmentRootPathWithinAncestor, IsForbiddenMetadataHelperSeam, IsLegacyAIAgentConfigSqlDefault, IsPayloadPathSetWithinAncestor, IsPayloadScopeWithinAncestor, JsonHasAllowWidenFromBaseKey, LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, MAX_AGENT_INHERITANCE_DEPTH, MJAIAgentEntityExtended, NARROW_ONLY_PROMPT_PARAM_GATES, NarrowAttachmentRootPath, NarrowPayloadScope, NarrowScopeConfigObjects, ParseAgentConfigJsonObject, ParseAgentConfiguration, ParseAgentHelperPlugins, ParseAgentInstantiationConfig, SyncAgentLegacyColumnsAndConfiguration, VALID_AGENT_HELPER_SEAMS, ValidateAgentConfigurationJson, ValidateLegacyAgentConfigFields, } from '@memberjunction/ai-core-plus';
|
|
10
|
+
import { AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';
|
|
10
11
|
import { ValidateJsonAgainstSchemaLite } from './json-schema-lite.js';
|
|
11
12
|
/**
|
|
12
|
-
*
|
|
13
|
+
* Canonical `MJ: Authorizations` capability name granting full administrative authority over
|
|
14
|
+
* AI Agents, Categories, Types, Step Types, and Personas. Evaluated with ancestors via
|
|
15
|
+
* `AuthorizationEvaluator` alongside the legacy administrative role fallback.
|
|
16
|
+
*/
|
|
17
|
+
export const AI_AGENT_ADMINISTRATION_AUTHORIZATION = 'AI: Agent Administration';
|
|
18
|
+
const ADMIN_ROLE_NAMES = new Set([
|
|
19
|
+
'system administrator',
|
|
20
|
+
'administrator',
|
|
21
|
+
'admin',
|
|
22
|
+
'administration',
|
|
23
|
+
'agent administrator',
|
|
24
|
+
]);
|
|
25
|
+
const ISOLATION_RANK = AGENT_ISOLATION_RANK;
|
|
26
|
+
const SEARCH_ACCESS_RANK = AGENT_SEARCH_SCOPE_ACCESS_RANK;
|
|
27
|
+
const ACCEPTS_SKILLS_RANK = AGENT_ACCEPTS_SKILLS_RANK;
|
|
28
|
+
const SKILL_ACTIVATION_RANK = AGENT_SKILL_ACTIVATION_RANK;
|
|
29
|
+
/**
|
|
30
|
+
* Type guard narrowing an `IEntityDataProvider` to `IMetadataProvider` when the provider
|
|
31
|
+
* implements metadata/entity-instantiation methods (e.g., `SQLServerDataProvider`, `PostgreSQLDataProvider`).
|
|
32
|
+
*/
|
|
33
|
+
export function IsMetadataProvider(provider) {
|
|
34
|
+
return Boolean(provider && 'GetEntityObject' in provider && 'Entities' in provider);
|
|
35
|
+
}
|
|
36
|
+
function authorizationsForAdminCheck(provider) {
|
|
37
|
+
const mdProvider = provider && 'Authorizations' in provider && Array.isArray(provider.Authorizations)
|
|
38
|
+
? provider
|
|
39
|
+
: undefined;
|
|
40
|
+
try {
|
|
41
|
+
const md = mdProvider ?? new Metadata();
|
|
42
|
+
return Array.isArray(md.Authorizations) ? md.Authorizations : [];
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Returns true when `user` is the server system user, an Owner-type user, holds the
|
|
50
|
+
* `AI: Agent Administration` authorization (direct or via an ancestor authorization), or holds
|
|
51
|
+
* an administrative / `Agent Administrator` role.
|
|
52
|
+
*/
|
|
53
|
+
export function IsAgentAdminOrOwnerUser(user, provider) {
|
|
54
|
+
if (!user) {
|
|
55
|
+
return true; // System / unauthenticated internal context
|
|
56
|
+
}
|
|
57
|
+
if (user.Type?.trim().toLowerCase() === 'owner' || WellKnownUserSource.Instance.IsSystemUser(user)) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
const authorizations = authorizationsForAdminCheck(provider);
|
|
61
|
+
if (authorizations.length > 0) {
|
|
62
|
+
const auth = authorizations.find((a) => a.Name?.trim().toLowerCase() === AI_AGENT_ADMINISTRATION_AUTHORIZATION.toLowerCase());
|
|
63
|
+
if (auth) {
|
|
64
|
+
const evaluator = new AuthorizationEvaluator();
|
|
65
|
+
if (evaluator.UserCanExecuteWithAncestors(auth, user, authorizations)) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const roles = user.UserRoles ?? [];
|
|
71
|
+
return roles.some((ur) => ADMIN_ROLE_NAMES.has((ur.Role ?? '').trim().toLowerCase()));
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Shared `CheckPermissions` helper for admin-governed AI Agent definition entities
|
|
75
|
+
* (`MJ: AI Agent Categories`, `MJ: AI Agent Types`, `MJ: AI Agent Step Types`).
|
|
13
76
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
|
|
77
|
+
* Baseline `Developer` and `Integration` role grants on these entities are read-only
|
|
78
|
+
* (`CanRead: true`, `CanCreate/Update/Delete: false`), while `User: System` (and other `Owner`
|
|
79
|
+
* users or holders of the `AI: Agent Administration` authorization / admin roles) may not carry
|
|
80
|
+
* the dedicated `Agent Administrator` role in `UserRoles`. This helper authorizes those admin /
|
|
81
|
+
* owner / system callers for Create/Update/Delete once entity-level API flags allow the operation,
|
|
82
|
+
* while delegating reads and non-admin callers to `super.CheckPermissions`.
|
|
83
|
+
*/
|
|
84
|
+
export function CheckAgentAdminEntityPermissions(context, type, throwError, superCheck) {
|
|
85
|
+
if (type === EntityPermissionType.Read) {
|
|
86
|
+
return superCheck(type, throwError);
|
|
87
|
+
}
|
|
88
|
+
const user = context.ActiveUser;
|
|
89
|
+
if (!user) {
|
|
90
|
+
return superCheck(type, throwError);
|
|
91
|
+
}
|
|
92
|
+
const info = context.EntityInfo;
|
|
93
|
+
if (!info || info.VirtualEntity) {
|
|
94
|
+
return superCheck(type, throwError);
|
|
95
|
+
}
|
|
96
|
+
const apiAllowed = (type === EntityPermissionType.Create && info.AllowCreateAPI) ||
|
|
97
|
+
(type === EntityPermissionType.Update && info.AllowUpdateAPI) ||
|
|
98
|
+
(type === EntityPermissionType.Delete && info.AllowDeleteAPI);
|
|
99
|
+
if (!apiAllowed) {
|
|
100
|
+
return superCheck(type, throwError);
|
|
101
|
+
}
|
|
102
|
+
if (IsAgentAdminOrOwnerUser(user, context.ProviderToUse)) {
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
return superCheck(type, throwError);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Resolves ordered narrow-only default policy layers (`AgentType -> Category Parent Chains`)
|
|
109
|
+
* for an agent chain `[...ancestors, target]`, mirroring `BaseAIEngine.ResolveEffectiveAgentProperties`.
|
|
110
|
+
*/
|
|
111
|
+
function collectDefaultPolicyLayers(chain, allCategories, allAgentTypes) {
|
|
112
|
+
const layers = [];
|
|
113
|
+
let effectiveTypeId = null;
|
|
114
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
115
|
+
if (chain[i].TypeID) {
|
|
116
|
+
effectiveTypeId = chain[i].TypeID ?? null;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (effectiveTypeId && allAgentTypes && allAgentTypes.length > 0) {
|
|
121
|
+
const agentType = allAgentTypes.find((at) => UUIDsEqual(at.ID, effectiveTypeId));
|
|
122
|
+
if (agentType) {
|
|
123
|
+
const typeLegacy = BuildAgentTypeConfigurationFromLegacyFields(agentType);
|
|
124
|
+
const typeJson = ParseAgentConfiguration(agentType.DefaultAgentConfiguration);
|
|
125
|
+
const typeLayer = DeepMergeAgentConfigurations(typeLegacy, typeJson);
|
|
126
|
+
if (Object.keys(typeLayer).length > 0) {
|
|
127
|
+
layers.push(typeLayer);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (allCategories && allCategories.length > 0) {
|
|
132
|
+
const catsById = IndexByUUID(allCategories);
|
|
133
|
+
const seenCatIds = new UUIDSet();
|
|
134
|
+
for (const node of chain) {
|
|
135
|
+
if (!node.CategoryID) {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const catChain = [];
|
|
139
|
+
const walkVisited = new UUIDSet();
|
|
140
|
+
let curId = node.CategoryID;
|
|
141
|
+
while (curId && !walkVisited.Has(curId)) {
|
|
142
|
+
walkVisited.Add(curId);
|
|
143
|
+
const cat = catsById.Get(curId);
|
|
144
|
+
if (!cat) {
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
catChain.push(cat);
|
|
148
|
+
curId = cat.ParentID ?? null;
|
|
149
|
+
}
|
|
150
|
+
catChain.reverse();
|
|
151
|
+
for (const cat of catChain) {
|
|
152
|
+
if (seenCatIds.Has(cat.ID)) {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
seenCatIds.Add(cat.ID);
|
|
156
|
+
const catJson = ParseAgentConfiguration(cat.DefaultConfiguration);
|
|
157
|
+
if (catJson) {
|
|
158
|
+
layers.push(catJson);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return layers;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Computes the effective monotonic `SearchScopeAccess` ceiling across Category/Type default policy
|
|
167
|
+
* layers and the ancestor agent chain using the exact `R5-6` node-property rule shared with
|
|
168
|
+
* `BaseAIEngine.ResolveAgentConfiguration`:
|
|
169
|
+
* - Only treat an untouched legacy `'None'` (with no explicit JSON value) as unset on a
|
|
170
|
+
* non-instantiable derived row (`BaseAgentID != null && InstantiationMode === 'None'`).
|
|
171
|
+
* - Roots and instantiable templates (`InstantiationMode !== 'None'`) enforce `'None'` as an
|
|
172
|
+
* active ceiling.
|
|
173
|
+
*/
|
|
174
|
+
function computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs) {
|
|
175
|
+
const narrow = (acc, val) => {
|
|
176
|
+
if (val == null)
|
|
177
|
+
return acc;
|
|
178
|
+
if (acc === null || SEARCH_ACCESS_RANK[val] < SEARCH_ACCESS_RANK[acc]) {
|
|
179
|
+
return val;
|
|
180
|
+
}
|
|
181
|
+
return acc;
|
|
182
|
+
};
|
|
183
|
+
let seed = null;
|
|
184
|
+
for (const layer of defaultPolicyLayers) {
|
|
185
|
+
seed = narrow(seed, layer.scope?.searchScopeAccess);
|
|
186
|
+
}
|
|
187
|
+
if (ancestors.length === 0) {
|
|
188
|
+
return seed;
|
|
189
|
+
}
|
|
190
|
+
const exp0 = ancestorConfigs[0]?.scope?.searchScopeAccess ?? null;
|
|
191
|
+
const leg0 = ancestors[0].SearchScopeAccess ?? null;
|
|
192
|
+
if (exp0 != null && leg0 != null) {
|
|
193
|
+
seed = narrow(seed, SEARCH_ACCESS_RANK[leg0] < SEARCH_ACCESS_RANK[exp0] ? leg0 : exp0);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
const isNonInst0 = Boolean(ancestors[0].BaseAgentID) && (ancestors[0].InstantiationMode ?? 'None') === 'None';
|
|
197
|
+
seed = narrow(seed, exp0 ?? (leg0 && (leg0 !== 'None' || !isNonInst0) ? leg0 : null));
|
|
198
|
+
}
|
|
199
|
+
return FoldRebaseAwareChain({
|
|
200
|
+
Nodes: ancestors,
|
|
201
|
+
NodeConfigs: ancestorConfigs,
|
|
202
|
+
Seed: seed,
|
|
203
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
204
|
+
const explicit = cfg?.scope?.searchScopeAccess ?? null;
|
|
205
|
+
const legacy = anc.SearchScopeAccess ?? null;
|
|
206
|
+
const canWiden = idx > 0 && cfg?.allowWidenFromBase === true;
|
|
207
|
+
if (canWiden) {
|
|
208
|
+
if (explicit != null)
|
|
209
|
+
return explicit;
|
|
210
|
+
return legacy != null && legacy !== 'None' ? legacy : undefined;
|
|
211
|
+
}
|
|
212
|
+
if (explicit != null && legacy != null) {
|
|
213
|
+
return SEARCH_ACCESS_RANK[legacy] < SEARCH_ACCESS_RANK[explicit] ? legacy : explicit;
|
|
214
|
+
}
|
|
215
|
+
if (explicit != null)
|
|
216
|
+
return explicit;
|
|
217
|
+
const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
|
|
218
|
+
if (legacy != null && (legacy !== 'None' || !isNonInst)) {
|
|
219
|
+
return legacy;
|
|
220
|
+
}
|
|
221
|
+
return undefined;
|
|
222
|
+
},
|
|
223
|
+
Narrow: (acc, next) => narrow(acc, next),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* PURE validation core for `BaseAgentID` prototype inheritance integrity and non-Owner (`UI` role)
|
|
228
|
+
* sandboxing (exported for unit tests and called by {@link MJAIAgentEntityServer.ValidateAsync}):
|
|
21
229
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
230
|
+
* 1. **Chain integrity (all users)**:
|
|
231
|
+
* - `BaseAgentID` must reference an existing agent, cannot point to itself or form a cycle,
|
|
232
|
+
* and total inheritance depth must not exceed `MAX_AGENT_INHERITANCE_DEPTH` (5).
|
|
233
|
+
* 2. **Instantiation policy on create**:
|
|
234
|
+
* - Non-admin users can only instantiate from a base agent whose `InstantiationMode !== 'None'`.
|
|
235
|
+
* - Enforces `TypeConfiguration.instantiation.maxInstancesPerUser` when configured.
|
|
236
|
+
* 3. **Non-Owner (`UI` role) sandbox**:
|
|
237
|
+
* - May only create/update derived agents (`BaseAgentID != null`), owned by `User.ID`
|
|
238
|
+
* (checked against pre-save `OldValue` on update), with `InstantiationMode === 'None'`.
|
|
239
|
+
* - Must hold effective `CanRun` on `BaseAgentID`.
|
|
240
|
+
* - Cannot set custom `DriverClass`, loosen `Isolation`, set `ExposeAsAction = true`, or raise
|
|
241
|
+
* finite `MaxCostPerRun` / `MaxTokensPerRun` / `MaxTimePerRun` / `MaxIterationsPerRun` above
|
|
242
|
+
* the base agent's bounds.
|
|
243
|
+
*/
|
|
244
|
+
export function ValidateAgentInheritanceAndSandbox(ctx) {
|
|
245
|
+
const errors = [];
|
|
246
|
+
const { Target, User, AllAgents, AllPermissions } = ctx;
|
|
247
|
+
const isAdmin = IsAgentAdminOrOwnerUser(User, ctx.Provider);
|
|
248
|
+
// 0. Per-agent helperPlugins security guard (Extension Point #3):
|
|
249
|
+
// - Code-only security seams (limits, actionPolicy, policy, permissions) are forbidden in
|
|
250
|
+
// metadata for ALL users (including administrators).
|
|
251
|
+
// - Non-administrator users cannot configure ANY helperPlugins on personal agent instances.
|
|
252
|
+
const declaredHelperPlugins = [
|
|
253
|
+
...ParseAgentHelperPlugins(Target.Configuration),
|
|
254
|
+
...ParseAgentHelperPlugins(Target.TypeConfiguration),
|
|
255
|
+
];
|
|
256
|
+
const jsonHasHelperPluginsKey = (raw) => {
|
|
257
|
+
if (!raw || raw.trim().length === 0)
|
|
258
|
+
return false;
|
|
259
|
+
try {
|
|
260
|
+
const parsed = JSON.parse(raw);
|
|
261
|
+
return Boolean(parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'helperPlugins'));
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
const hasHelperPluginsKey = jsonHasHelperPluginsKey(Target.Configuration) || jsonHasHelperPluginsKey(Target.TypeConfiguration);
|
|
268
|
+
for (const plugin of declaredHelperPlugins) {
|
|
269
|
+
if (IsForbiddenMetadataHelperSeam(plugin.seam)) {
|
|
270
|
+
errors.push(new ValidationErrorInfo('Configuration', `Helper seam '${plugin.seam}' is code-only and cannot be overridden via agent metadata helperPlugins (driverClass '${plugin.driverClass}'). Use @RegisterClass in server code instead.`, plugin.seam, ValidationErrorType.Failure));
|
|
271
|
+
}
|
|
272
|
+
else if (!VALID_AGENT_HELPER_SEAMS.has(plugin.seam.trim())) {
|
|
273
|
+
errors.push(new ValidationErrorInfo('Configuration', `Helper seam '${plugin.seam}' is not a valid helper seam (driverClass '${plugin.driverClass}'). Valid seams: ${Array.from(VALID_AGENT_HELPER_SEAMS).join(', ')}.`, plugin.seam, ValidationErrorType.Failure));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const helperConfigDirty = !Target.IsSaved ||
|
|
277
|
+
!Target.DirtyFields ||
|
|
278
|
+
Target.DirtyFields.has('Configuration') ||
|
|
279
|
+
Target.DirtyFields.has('TypeConfiguration');
|
|
280
|
+
if (!isAdmin && User && helperConfigDirty && (declaredHelperPlugins.length > 0 || hasHelperPluginsKey)) {
|
|
281
|
+
errors.push(new ValidationErrorInfo('Configuration', 'Only administrators may configure helperPlugins (including clearing/modifying the key) on an AI Agent.', declaredHelperPlugins.map((p) => `${p.seam}:${p.driverClass}`).join(', '), ValidationErrorType.Failure));
|
|
282
|
+
}
|
|
283
|
+
// 0b. Admin-only Configuration.allowWidenFromBase guard:
|
|
284
|
+
// Non-administrator users cannot set, modify, or clear `allowWidenFromBase` on save.
|
|
285
|
+
const configDirty = !Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('Configuration');
|
|
286
|
+
if (!isAdmin &&
|
|
287
|
+
User &&
|
|
288
|
+
configDirty &&
|
|
289
|
+
(JsonHasAllowWidenFromBaseKey(Target.Configuration) ||
|
|
290
|
+
JsonHasAllowWidenFromBaseKey(Target.PreSaveConfiguration))) {
|
|
291
|
+
errors.push(new ValidationErrorInfo('Configuration', 'Only administrators may set, modify, or clear Configuration.allowWidenFromBase on an AI Agent.', Target.Configuration, ValidationErrorType.Failure));
|
|
292
|
+
}
|
|
293
|
+
// 0c. Path-traversal guard on PayloadScope and AttachmentRootPath (ALL users, root or derived,
|
|
294
|
+
// even when allowWidenFromBase === true).
|
|
295
|
+
const preParsedTargetConfig = ParseAgentConfiguration(Target.Configuration);
|
|
296
|
+
const rawTargetPayloadScope = preParsedTargetConfig?.payload?.scope !== undefined
|
|
297
|
+
? preParsedTargetConfig.payload.scope
|
|
298
|
+
: Target.PayloadScope;
|
|
299
|
+
if (HasPathTraversalSegment(rawTargetPayloadScope)) {
|
|
300
|
+
errors.push(new ValidationErrorInfo('PayloadScope', `PayloadScope ('${rawTargetPayloadScope}') cannot contain '..' path traversal segments.`, rawTargetPayloadScope, ValidationErrorType.Failure));
|
|
301
|
+
}
|
|
302
|
+
const rawTargetAttachRoot = preParsedTargetConfig?.attachments?.rootPath !== undefined
|
|
303
|
+
? preParsedTargetConfig.attachments.rootPath
|
|
304
|
+
: Target.AttachmentRootPath;
|
|
305
|
+
if (HasPathTraversalSegment(rawTargetAttachRoot)) {
|
|
306
|
+
errors.push(new ValidationErrorInfo('AttachmentRootPath', `AttachmentRootPath ('${rawTargetAttachRoot}') cannot contain '..' path traversal segments.`, rawTargetAttachRoot, ValidationErrorType.Failure));
|
|
307
|
+
}
|
|
308
|
+
// 1. Non-admin sandbox on root vs derived + ownership + InstantiationMode
|
|
309
|
+
if (!isAdmin && User) {
|
|
310
|
+
const effectiveBaseId = Target.BaseAgentID;
|
|
311
|
+
if (!effectiveBaseId) {
|
|
312
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', 'Non-administrator users can only create or modify derived agent instances with BaseAgentID set.', null, ValidationErrorType.Failure));
|
|
313
|
+
return errors;
|
|
314
|
+
}
|
|
315
|
+
if (Target.IsSaved && Target.PreSaveBaseAgentID && !UUIDsEqual(Target.PreSaveBaseAgentID, effectiveBaseId)) {
|
|
316
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', 'Cannot re-parent BaseAgentID on an existing derived agent instance.', effectiveBaseId, ValidationErrorType.Failure));
|
|
317
|
+
}
|
|
318
|
+
const preSaveOwner = Target.IsSaved ? (Target.PreSaveOwnerUserID ?? Target.OwnerUserID) : Target.OwnerUserID;
|
|
319
|
+
if (preSaveOwner && !UUIDsEqual(preSaveOwner, User.ID)) {
|
|
320
|
+
errors.push(new ValidationErrorInfo('OwnerUserID', 'You can only create or modify your own personal agent instances.', Target.OwnerUserID, ValidationErrorType.Failure));
|
|
321
|
+
}
|
|
322
|
+
if (Target.OwnerUserID && !UUIDsEqual(Target.OwnerUserID, User.ID)) {
|
|
323
|
+
errors.push(new ValidationErrorInfo('OwnerUserID', 'Cannot reassign OwnerUserID to another user.', Target.OwnerUserID, ValidationErrorType.Failure));
|
|
324
|
+
}
|
|
325
|
+
if ((Target.InstantiationMode ?? 'None') !== 'None') {
|
|
326
|
+
errors.push(new ValidationErrorInfo('InstantiationMode', 'Only administrators may publish instantiable agent templates (InstantiationMode must be None for personal instances).', Target.InstantiationMode, ValidationErrorType.Failure));
|
|
327
|
+
}
|
|
328
|
+
if (Target.ExposeAsAction) {
|
|
329
|
+
errors.push(new ValidationErrorInfo('ExposeAsAction', 'Personal agent instances cannot set ExposeAsAction = true.', true, ValidationErrorType.Failure));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// 2. BaseAgentID chain integrity (existence, no cycle, depth <= MAX_AGENT_INHERITANCE_DEPTH)
|
|
333
|
+
if (!Target.BaseAgentID) {
|
|
334
|
+
return errors;
|
|
335
|
+
}
|
|
336
|
+
if (Target.ID && UUIDsEqual(Target.ID, Target.BaseAgentID)) {
|
|
337
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', 'An agent cannot set BaseAgentID to itself.', Target.BaseAgentID, ValidationErrorType.Failure));
|
|
338
|
+
return errors;
|
|
339
|
+
}
|
|
340
|
+
const agentsById = IndexByUUID(AllAgents);
|
|
341
|
+
const baseAgent = agentsById.Get(Target.BaseAgentID);
|
|
342
|
+
if (!baseAgent) {
|
|
343
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', `BaseAgentID '${Target.BaseAgentID}' does not reference an existing AI Agent.`, Target.BaseAgentID, ValidationErrorType.Failure));
|
|
344
|
+
return errors;
|
|
345
|
+
}
|
|
346
|
+
// Walk up BaseAgentID chain to detect cycles, enforce max depth (5 hops), and collect full
|
|
347
|
+
// ancestor chain (`ancestors[0]` = root, `ancestors[ancestors.length - 1]` = immediate baseAgent)
|
|
348
|
+
// so multi-hop capability and limit ceilings are enforced across every ancestor.
|
|
349
|
+
const visited = new UUIDSet(Target.ID ? [Target.ID] : []);
|
|
350
|
+
const ancestorsBottomUp = [];
|
|
351
|
+
let cursor = baseAgent;
|
|
352
|
+
let hops = 1; // Target -> baseAgent is hop 1
|
|
353
|
+
while (cursor) {
|
|
354
|
+
if (visited.Has(cursor.ID)) {
|
|
355
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', 'BaseAgentID inheritance cycle detected.', Target.BaseAgentID, ValidationErrorType.Failure));
|
|
356
|
+
return errors;
|
|
357
|
+
}
|
|
358
|
+
visited.Add(cursor.ID);
|
|
359
|
+
ancestorsBottomUp.push(cursor);
|
|
360
|
+
if (hops > MAX_AGENT_INHERITANCE_DEPTH) {
|
|
361
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', `Agent prototype inheritance depth exceeds maximum allowed depth of ${MAX_AGENT_INHERITANCE_DEPTH}.`, Target.BaseAgentID, ValidationErrorType.Failure));
|
|
362
|
+
return errors;
|
|
363
|
+
}
|
|
364
|
+
if (!cursor.BaseAgentID) {
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
const nextParent = agentsById.Get(cursor.BaseAgentID);
|
|
368
|
+
if (!nextParent) {
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
cursor = nextParent;
|
|
372
|
+
hops++;
|
|
373
|
+
}
|
|
374
|
+
const ancestors = [...ancestorsBottomUp].reverse(); // root -> ... -> baseAgent
|
|
375
|
+
const defaultPolicyLayers = collectDefaultPolicyLayers([...ancestors, Target], ctx.AllCategories, ctx.AllAgentTypes);
|
|
376
|
+
// 3. InstantiationMode & maxInstancesPerUser check on create (R5-7: monotonic Math.min across
|
|
377
|
+
// AgentType -> Categories -> root..baseAgent, counted per root base agent matching
|
|
378
|
+
// ManageMyAgentInstanceAction and BaseAIEngine.ResolveEffectiveAgentProperties)
|
|
379
|
+
if (!Target.IsSaved) {
|
|
380
|
+
if (!isAdmin && (baseAgent.InstantiationMode ?? 'None') === 'None') {
|
|
381
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', `Agent '${baseAgent.Name ?? baseAgent.ID}' does not allow creating derived instances (InstantiationMode is 'None').`, Target.BaseAgentID, ValidationErrorType.Failure));
|
|
382
|
+
}
|
|
383
|
+
const ancestorConfigsForInst = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
|
|
384
|
+
const sanitizePosInt = (v) => typeof v === 'number' && Number.isFinite(v) && Math.floor(v) >= 1 ? Math.floor(v) : null;
|
|
385
|
+
const minInstVal = (a, b) => b === null ? a : a === null ? b : Math.min(a, b);
|
|
386
|
+
let seedMaxPerUser = null;
|
|
387
|
+
for (const layer of defaultPolicyLayers) {
|
|
388
|
+
seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(layer.instantiation?.maxInstancesPerUser));
|
|
389
|
+
}
|
|
390
|
+
if (ancestors.length > 0) {
|
|
391
|
+
seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(ancestorConfigsForInst[0]?.instantiation?.maxInstancesPerUser));
|
|
392
|
+
seedMaxPerUser = minInstVal(seedMaxPerUser, sanitizePosInt(ParseAgentInstantiationConfig(ancestors[0].TypeConfiguration)?.maxInstancesPerUser));
|
|
393
|
+
}
|
|
394
|
+
const effectiveMaxPerUser = FoldRebaseAwareChain({
|
|
395
|
+
Nodes: ancestors,
|
|
396
|
+
NodeConfigs: ancestorConfigsForInst,
|
|
397
|
+
Seed: seedMaxPerUser,
|
|
398
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
399
|
+
const fromJson = sanitizePosInt(cfg?.instantiation?.maxInstancesPerUser);
|
|
400
|
+
const fromTypeCfg = sanitizePosInt(ParseAgentInstantiationConfig(anc.TypeConfiguration)?.maxInstancesPerUser);
|
|
401
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
402
|
+
if (fromJson !== null)
|
|
403
|
+
return fromJson;
|
|
404
|
+
return fromTypeCfg !== null ? fromTypeCfg : undefined;
|
|
405
|
+
}
|
|
406
|
+
const combined = minInstVal(fromJson, fromTypeCfg);
|
|
407
|
+
return combined !== null ? combined : undefined;
|
|
408
|
+
},
|
|
409
|
+
Narrow: (acc, next) => minInstVal(acc, next),
|
|
410
|
+
});
|
|
411
|
+
const ownerId = Target.OwnerUserID ?? User?.ID ?? null;
|
|
412
|
+
const isCreatingPersonalInstance = (Target.InstantiationMode ?? 'None') === 'None';
|
|
413
|
+
if (effectiveMaxPerUser !== null && ownerId && isCreatingPersonalInstance) {
|
|
414
|
+
const resolveRootId = (agent) => {
|
|
415
|
+
const seen = new UUIDSet([agent.ID]);
|
|
416
|
+
let cur = agent;
|
|
417
|
+
let depth = 0;
|
|
418
|
+
while (cur.BaseAgentID && depth < MAX_AGENT_INHERITANCE_DEPTH) {
|
|
419
|
+
if (seen.Has(cur.BaseAgentID))
|
|
420
|
+
break;
|
|
421
|
+
seen.Add(cur.BaseAgentID);
|
|
422
|
+
const p = agentsById.Get(cur.BaseAgentID);
|
|
423
|
+
if (!p)
|
|
424
|
+
return cur.BaseAgentID;
|
|
425
|
+
cur = p;
|
|
426
|
+
depth++;
|
|
427
|
+
}
|
|
428
|
+
return cur.ID;
|
|
429
|
+
};
|
|
430
|
+
const rootBaseId = resolveRootId(baseAgent);
|
|
431
|
+
const existingCount = AllAgents.filter((a) => a.Status === 'Active' &&
|
|
432
|
+
a.BaseAgentID != null &&
|
|
433
|
+
(a.InstantiationMode ?? 'None') === 'None' &&
|
|
434
|
+
UUIDsEqual(a.OwnerUserID, ownerId) &&
|
|
435
|
+
UUIDsEqual(resolveRootId(a), rootBaseId)).length;
|
|
436
|
+
if (existingCount >= effectiveMaxPerUser) {
|
|
437
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', `Maximum of ${effectiveMaxPerUser} active instance(s) of '${baseAgent.Name ?? baseAgent.ID}' per user reached.`, Target.BaseAgentID, ValidationErrorType.Failure));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const ancestorConfigs = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
|
|
442
|
+
const targetConfig = preParsedTargetConfig;
|
|
443
|
+
const targetAllowsWiden = targetConfig?.allowWidenFromBase === true;
|
|
444
|
+
const baseAgentLabel = baseAgent.Name ?? baseAgent.ID;
|
|
445
|
+
// Helper for R2-3 & R3-5: on existing saved instances where DirtyFields is tracked, only
|
|
446
|
+
// re-check narrow-only columns and numeric ceilings that were actually modified (or when
|
|
447
|
+
// Configuration or BaseAgentID itself was modified) so an admin tightening a base agent
|
|
448
|
+
// never breaks unrelated edits (rename/persona) on pre-existing derived instances while
|
|
449
|
+
// attaching/re-parenting BaseAgentID enforces every invariant.
|
|
450
|
+
const shouldEnforceField = (fieldName) => {
|
|
451
|
+
if (!Target.IsSaved || !Target.DirtyFields) {
|
|
452
|
+
return true;
|
|
453
|
+
}
|
|
454
|
+
return (Target.DirtyFields.has(fieldName) ||
|
|
455
|
+
Target.DirtyFields.has('Configuration') ||
|
|
456
|
+
Target.DirtyFields.has('BaseAgentID'));
|
|
457
|
+
};
|
|
458
|
+
const widenHint = (fieldName, detail) => `Derived agent cannot widen ${fieldName} ${detail} beyond base agent '${baseAgentLabel}'. Set Configuration.allowWidenFromBase = true (Admin only) if intentional.`;
|
|
459
|
+
// 4A. Non-admin-only sandbox checks (CanRun, DriverClass, CategoryID, TypeID)
|
|
460
|
+
if (!isAdmin && User) {
|
|
461
|
+
const basePerms = AIAgentPermissionHelper.ComputeEffectivePermissionsSync(baseAgent, AllAgents, AllPermissions, User);
|
|
462
|
+
if (!basePerms.canRun) {
|
|
463
|
+
errors.push(new ValidationErrorInfo('BaseAgentID', `You do not have permission to run base agent '${baseAgentLabel}'.`, Target.BaseAgentID, ValidationErrorType.Failure));
|
|
464
|
+
}
|
|
465
|
+
// DriverClass: compare unconditionally against nearest non-null ancestor DriverClass
|
|
466
|
+
let effectiveAncestorDriver = null;
|
|
467
|
+
for (let i = ancestors.length - 1; i >= 0; i--) {
|
|
468
|
+
const d = ancestors[i].DriverClass?.trim();
|
|
469
|
+
if (d) {
|
|
470
|
+
effectiveAncestorDriver = d;
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const targetDriver = Target.DriverClass?.trim() || null;
|
|
475
|
+
if (targetDriver !== null && targetDriver !== effectiveAncestorDriver) {
|
|
476
|
+
errors.push(new ValidationErrorInfo('DriverClass', 'Non-administrator users cannot set a custom DriverClass on a derived agent instance.', Target.DriverClass, ValidationErrorType.Failure));
|
|
477
|
+
}
|
|
478
|
+
// CategoryID / TypeID sandbox (S2, R2-4): non-admins cannot re-point or assign a derived
|
|
479
|
+
// instance's CategoryID or TypeID away from its base agent chain (or assign a loose category
|
|
480
|
+
// when the pre-save value was null).
|
|
481
|
+
let effectiveAncestorCategoryId = null;
|
|
482
|
+
let effectiveAncestorTypeId = null;
|
|
483
|
+
for (let i = ancestors.length - 1; i >= 0; i--) {
|
|
484
|
+
if (!effectiveAncestorCategoryId && ancestors[i].CategoryID) {
|
|
485
|
+
effectiveAncestorCategoryId = ancestors[i].CategoryID ?? null;
|
|
486
|
+
}
|
|
487
|
+
if (!effectiveAncestorTypeId && ancestors[i].TypeID) {
|
|
488
|
+
effectiveAncestorTypeId = ancestors[i].TypeID ?? null;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (Target.CategoryID !== undefined) {
|
|
492
|
+
const expectedCat = Target.IsSaved ? (Target.PreSaveCategoryID ?? effectiveAncestorCategoryId) : effectiveAncestorCategoryId;
|
|
493
|
+
if (expectedCat && Target.CategoryID && !UUIDsEqual(Target.CategoryID, expectedCat)) {
|
|
494
|
+
errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot reassign CategoryID on a derived agent instance.', Target.CategoryID, ValidationErrorType.Failure));
|
|
495
|
+
}
|
|
496
|
+
else if (!expectedCat && Target.CategoryID && (!Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('CategoryID'))) {
|
|
497
|
+
errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot assign CategoryID on a derived agent instance.', Target.CategoryID, ValidationErrorType.Failure));
|
|
498
|
+
}
|
|
499
|
+
else if (expectedCat && Target.CategoryID === null && Target.DirtyFields?.has('CategoryID')) {
|
|
500
|
+
errors.push(new ValidationErrorInfo('CategoryID', 'Non-administrator users cannot clear CategoryID on a derived agent instance.', null, ValidationErrorType.Failure));
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (Target.TypeID !== undefined) {
|
|
504
|
+
const expectedType = Target.IsSaved ? (Target.PreSaveTypeID ?? effectiveAncestorTypeId) : effectiveAncestorTypeId;
|
|
505
|
+
if (expectedType && Target.TypeID && !UUIDsEqual(Target.TypeID, expectedType)) {
|
|
506
|
+
errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot reassign TypeID on a derived agent instance.', Target.TypeID, ValidationErrorType.Failure));
|
|
507
|
+
}
|
|
508
|
+
else if (!expectedType && Target.TypeID && (!Target.IsSaved || !Target.DirtyFields || Target.DirtyFields.has('TypeID'))) {
|
|
509
|
+
errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot assign TypeID on a derived agent instance.', Target.TypeID, ValidationErrorType.Failure));
|
|
510
|
+
}
|
|
511
|
+
else if (expectedType && Target.TypeID === null && Target.DirtyFields?.has('TypeID')) {
|
|
512
|
+
errors.push(new ValidationErrorInfo('TypeID', 'Non-administrator users cannot clear TypeID on a derived agent instance.', null, ValidationErrorType.Failure));
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
// 4B. Unconditional derived invariants (ALL users, including Admins AND even with allowWidenFromBase === true)
|
|
517
|
+
// - Isolation minimum (InProcess < Worker < Process < Container)
|
|
518
|
+
// - Cross-cascade effectiveMinExecutionsPerRun <= effectiveMaxExecutionsPerRun
|
|
519
|
+
let strictestAncestorIsolation = 'InProcess';
|
|
520
|
+
for (const anc of ancestors) {
|
|
521
|
+
const ancIso = anc.Isolation ?? 'InProcess';
|
|
522
|
+
if ((ISOLATION_RANK[ancIso] ?? 0) > (ISOLATION_RANK[strictestAncestorIsolation] ?? 0)) {
|
|
523
|
+
strictestAncestorIsolation = ancIso;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const targetIsoRank = ISOLATION_RANK[Target.Isolation ?? 'InProcess'] ?? 0;
|
|
527
|
+
if (shouldEnforceField('Isolation') && targetIsoRank < (ISOLATION_RANK[strictestAncestorIsolation] ?? 0)) {
|
|
528
|
+
errors.push(new ValidationErrorInfo('Isolation', `Derived agent Isolation ('${Target.Isolation}') cannot be less strict than ancestor Isolation ('${strictestAncestorIsolation}').`, Target.Isolation, ValidationErrorType.Failure));
|
|
529
|
+
}
|
|
530
|
+
const computeRebaseAncestorMin = (layerPicker, nodeJsonPicker, nodeLegacyPicker, sqlDefault = null) => {
|
|
531
|
+
const minFin = (a, b) => {
|
|
532
|
+
if (typeof b !== 'number' || !Number.isFinite(b))
|
|
533
|
+
return a;
|
|
534
|
+
return a === null ? b : Math.min(a, b);
|
|
535
|
+
};
|
|
536
|
+
let seed = null;
|
|
537
|
+
for (const layer of defaultPolicyLayers) {
|
|
538
|
+
seed = minFin(seed, layerPicker(layer));
|
|
539
|
+
}
|
|
540
|
+
if (ancestors.length > 0) {
|
|
541
|
+
const exp0 = nodeJsonPicker(ancestorConfigs[0]);
|
|
542
|
+
const leg0 = nodeLegacyPicker(ancestors[0]);
|
|
543
|
+
const leg0Eff = exp0 === undefined && sqlDefault !== null && leg0 === sqlDefault && seed !== null ? null : leg0;
|
|
544
|
+
seed = minFin(seed, exp0);
|
|
545
|
+
seed = minFin(seed, leg0Eff);
|
|
546
|
+
}
|
|
547
|
+
return FoldRebaseAwareChain({
|
|
548
|
+
Nodes: ancestors,
|
|
549
|
+
NodeConfigs: ancestorConfigs,
|
|
550
|
+
Seed: seed,
|
|
551
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
552
|
+
const explicit = nodeJsonPicker(cfg);
|
|
553
|
+
const legacy = nodeLegacyPicker(anc);
|
|
554
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
555
|
+
if (explicit === null)
|
|
556
|
+
return null;
|
|
557
|
+
if (typeof explicit === 'number' && Number.isFinite(explicit))
|
|
558
|
+
return explicit;
|
|
559
|
+
if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault)
|
|
560
|
+
return legacy;
|
|
561
|
+
return undefined;
|
|
562
|
+
}
|
|
563
|
+
if (typeof explicit === 'number' && Number.isFinite(explicit)) {
|
|
564
|
+
if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault) {
|
|
565
|
+
return Math.min(explicit, legacy);
|
|
566
|
+
}
|
|
567
|
+
return explicit;
|
|
568
|
+
}
|
|
569
|
+
if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy !== sqlDefault) {
|
|
570
|
+
return legacy;
|
|
571
|
+
}
|
|
572
|
+
return undefined;
|
|
573
|
+
},
|
|
574
|
+
Narrow: (acc, next) => minFin(acc, next),
|
|
575
|
+
});
|
|
576
|
+
};
|
|
577
|
+
// Cross-cascade effectiveMinExecutionsPerRun <= effectiveMaxExecutionsPerRun
|
|
578
|
+
const ancestorMaxExecutions = computeRebaseAncestorMin((l) => l.subAgentExecution?.maxExecutionsPerRun, (cfg) => cfg?.subAgentExecution?.maxExecutionsPerRun, (a) => a.MaxExecutionsPerRun);
|
|
579
|
+
const targetMaxExecutions = targetConfig?.subAgentExecution?.maxExecutionsPerRun !== undefined
|
|
580
|
+
? targetConfig.subAgentExecution.maxExecutionsPerRun
|
|
581
|
+
: Target.MaxExecutionsPerRun;
|
|
582
|
+
const effectiveMaxExecAcrossCascade = targetAllowsWiden
|
|
583
|
+
? targetMaxExecutions !== undefined
|
|
584
|
+
? targetMaxExecutions
|
|
585
|
+
: ancestorMaxExecutions
|
|
586
|
+
: typeof targetMaxExecutions === 'number' && Number.isFinite(targetMaxExecutions)
|
|
587
|
+
? ancestorMaxExecutions !== null
|
|
588
|
+
? Math.min(ancestorMaxExecutions, targetMaxExecutions)
|
|
589
|
+
: targetMaxExecutions
|
|
590
|
+
: ancestorMaxExecutions;
|
|
591
|
+
let effectiveMinExecAcrossCascade = null;
|
|
592
|
+
for (const layer of defaultPolicyLayers) {
|
|
593
|
+
if (typeof layer.subAgentExecution?.minExecutionsPerRun === 'number') {
|
|
594
|
+
effectiveMinExecAcrossCascade = layer.subAgentExecution.minExecutionsPerRun;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
for (let i = 0; i < ancestors.length; i++) {
|
|
598
|
+
const v = ancestorConfigs[i]?.subAgentExecution?.minExecutionsPerRun ?? ancestors[i].MinExecutionsPerRun;
|
|
599
|
+
if (typeof v === 'number' && Number.isFinite(v)) {
|
|
600
|
+
effectiveMinExecAcrossCascade = v;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const targetMinExec = targetConfig?.subAgentExecution?.minExecutionsPerRun !== undefined
|
|
604
|
+
? targetConfig.subAgentExecution.minExecutionsPerRun
|
|
605
|
+
: Target.MinExecutionsPerRun;
|
|
606
|
+
if (typeof targetMinExec === 'number' && Number.isFinite(targetMinExec)) {
|
|
607
|
+
effectiveMinExecAcrossCascade = targetMinExec;
|
|
608
|
+
}
|
|
609
|
+
else if (targetMinExec === null && targetConfig?.subAgentExecution?.minExecutionsPerRun === null) {
|
|
610
|
+
effectiveMinExecAcrossCascade = null;
|
|
611
|
+
}
|
|
612
|
+
if ((shouldEnforceField('MinExecutionsPerRun') || shouldEnforceField('MaxExecutionsPerRun')) &&
|
|
613
|
+
effectiveMinExecAcrossCascade !== null &&
|
|
614
|
+
effectiveMaxExecAcrossCascade !== null &&
|
|
615
|
+
effectiveMinExecAcrossCascade > effectiveMaxExecAcrossCascade) {
|
|
616
|
+
errors.push(new ValidationErrorInfo('MinExecutionsPerRun', `Effective MinExecutionsPerRun (${effectiveMinExecAcrossCascade}) across the BaseAgentID cascade cannot exceed effective MaxExecutionsPerRun (${effectiveMaxExecAcrossCascade}).`, effectiveMinExecAcrossCascade, ValidationErrorType.Failure));
|
|
617
|
+
}
|
|
618
|
+
// 4C. Non-widening ceiling & capability enforcement for ALL users (including Admins!) unless
|
|
619
|
+
// Configuration.allowWidenFromBase === true (eliminates save-time vs runtime split-brain).
|
|
620
|
+
if (!targetAllowsWiden) {
|
|
621
|
+
const checkMultiHopUpperBound = (fieldName, effectiveCeiling, childLimit, explicitJsonVal, sqlDefault = null) => {
|
|
622
|
+
if (!shouldEnforceField(fieldName)) {
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
if (effectiveCeiling === null) {
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
// Ignore untouched SQL default values when JSON didn't set the key and the field wasn't dirtied
|
|
629
|
+
if (sqlDefault !== null &&
|
|
630
|
+
explicitJsonVal === undefined &&
|
|
631
|
+
childLimit === sqlDefault &&
|
|
632
|
+
Target.DirtyFields &&
|
|
633
|
+
!Target.DirtyFields.has(fieldName)) {
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
if (childLimit === null) {
|
|
637
|
+
const isExplicitClear = (Target.IsSaved &&
|
|
638
|
+
Target.DirtyFields?.has(fieldName) === true &&
|
|
639
|
+
typeof Target.PreSaveLimits?.[fieldName] === 'number') ||
|
|
640
|
+
explicitJsonVal === null;
|
|
641
|
+
if (isExplicitClear) {
|
|
642
|
+
errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(cleared to null vs ceiling ${effectiveCeiling})`), null, ValidationErrorType.Failure));
|
|
643
|
+
}
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
if (typeof childLimit === 'number' && childLimit > effectiveCeiling) {
|
|
647
|
+
errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(${childLimit} > ceiling ${effectiveCeiling})`), childLimit, ValidationErrorType.Failure));
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
checkMultiHopUpperBound('MaxCostPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxCostPerRun), Target.MaxCostPerRun, undefined);
|
|
651
|
+
checkMultiHopUpperBound('MaxTokensPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxTokensPerRun), Target.MaxTokensPerRun, undefined);
|
|
652
|
+
checkMultiHopUpperBound('MaxTimePerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxTimePerRun), Target.MaxTimePerRun, undefined);
|
|
653
|
+
checkMultiHopUpperBound('MaxIterationsPerRun', computeRebaseAncestorMin(() => undefined, () => undefined, (a) => a.MaxIterationsPerRun), Target.MaxIterationsPerRun, undefined);
|
|
654
|
+
checkMultiHopUpperBound('MaxExecutionsPerRun', ancestorMaxExecutions, targetMaxExecutions, targetConfig?.subAgentExecution?.maxExecutionsPerRun);
|
|
655
|
+
checkMultiHopUpperBound('MaxSubAgentConsultRounds', computeRebaseAncestorMin((l) => l.subAgentExecution?.maxConsultRounds, (cfg) => cfg?.subAgentExecution?.maxConsultRounds, (a) => a.MaxSubAgentConsultRounds), targetConfig?.subAgentExecution?.maxConsultRounds !== undefined
|
|
656
|
+
? targetConfig.subAgentExecution.maxConsultRounds
|
|
657
|
+
: Target.MaxSubAgentConsultRounds, targetConfig?.subAgentExecution?.maxConsultRounds);
|
|
658
|
+
checkMultiHopUpperBound('ContextWindowMaxTokens', computeRebaseAncestorMin((l) => l.contextWindow?.maxTokens, (cfg) => cfg?.contextWindow?.maxTokens, (a) => a.ContextWindowMaxTokens), targetConfig?.contextWindow?.maxTokens !== undefined
|
|
659
|
+
? targetConfig.contextWindow.maxTokens
|
|
660
|
+
: Target.ContextWindowMaxTokens, targetConfig?.contextWindow?.maxTokens);
|
|
661
|
+
checkMultiHopUpperBound('MaxNotesToInject', computeRebaseAncestorMin((l) => l.memory?.maxNotesToInject, (cfg) => cfg?.memory?.maxNotesToInject, (a) => a.MaxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
|
|
662
|
+
), targetConfig?.memory?.maxNotesToInject !== undefined
|
|
663
|
+
? targetConfig.memory.maxNotesToInject
|
|
664
|
+
: Target.MaxNotesToInject, targetConfig?.memory?.maxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
|
|
665
|
+
);
|
|
666
|
+
checkMultiHopUpperBound('MaxExamplesToInject', computeRebaseAncestorMin((l) => l.memory?.maxExamplesToInject, (cfg) => cfg?.memory?.maxExamplesToInject, (a) => a.MaxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
|
|
667
|
+
), targetConfig?.memory?.maxExamplesToInject !== undefined
|
|
668
|
+
? targetConfig.memory.maxExamplesToInject
|
|
669
|
+
: Target.MaxExamplesToInject, targetConfig?.memory?.maxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
|
|
670
|
+
);
|
|
671
|
+
const ancestorNoteRetentionDays = computeRebaseAncestorMin((l) => l.memory?.noteRetentionDays, (cfg) => cfg?.memory?.noteRetentionDays, (a) => a.NoteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
|
|
672
|
+
);
|
|
673
|
+
checkMultiHopUpperBound('NoteRetentionDays', ancestorNoteRetentionDays, targetConfig?.memory?.noteRetentionDays !== undefined
|
|
674
|
+
? targetConfig.memory.noteRetentionDays
|
|
675
|
+
: Target.NoteRetentionDays, targetConfig?.memory?.noteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
|
|
676
|
+
);
|
|
677
|
+
const ancestorExampleRetentionDays = computeRebaseAncestorMin((l) => l.memory?.exampleRetentionDays, (cfg) => cfg?.memory?.exampleRetentionDays, (a) => a.ExampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
|
|
678
|
+
);
|
|
679
|
+
checkMultiHopUpperBound('ExampleRetentionDays', ancestorExampleRetentionDays, targetConfig?.memory?.exampleRetentionDays !== undefined
|
|
680
|
+
? targetConfig.memory.exampleRetentionDays
|
|
681
|
+
: Target.ExampleRetentionDays, targetConfig?.memory?.exampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
|
|
682
|
+
);
|
|
683
|
+
checkMultiHopUpperBound('MaxMessages', computeRebaseAncestorMin((l) => l.attachments?.maxMessages, (cfg) => cfg?.attachments?.maxMessages, (a) => a.MaxMessages), targetConfig?.attachments?.maxMessages !== undefined
|
|
684
|
+
? targetConfig.attachments.maxMessages
|
|
685
|
+
: Target.MaxMessages, targetConfig?.attachments?.maxMessages);
|
|
686
|
+
checkMultiHopUpperBound('InlineStorageThresholdBytes', computeRebaseAncestorMin((l) => l.attachments?.inlineStorageThresholdBytes, (cfg) => cfg?.attachments?.inlineStorageThresholdBytes, (a) => a.InlineStorageThresholdBytes), targetConfig?.attachments?.inlineStorageThresholdBytes !== undefined
|
|
687
|
+
? targetConfig.attachments.inlineStorageThresholdBytes
|
|
688
|
+
: Target.InlineStorageThresholdBytes, targetConfig?.attachments?.inlineStorageThresholdBytes);
|
|
689
|
+
checkMultiHopUpperBound('FinalPayloadValidationMaxRetries', computeRebaseAncestorMin((l) => l.payload?.finalValidationMaxRetries, (cfg) => cfg?.payload?.finalValidationMaxRetries, (a) => a.FinalPayloadValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
|
|
690
|
+
), targetConfig?.payload?.finalValidationMaxRetries !== undefined
|
|
691
|
+
? targetConfig.payload.finalValidationMaxRetries
|
|
692
|
+
: Target.FinalPayloadValidationMaxRetries, targetConfig?.payload?.finalValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
|
|
693
|
+
);
|
|
694
|
+
// instantiation.maxInstancesPerUser ceiling (cannot raise above ancestor ceiling)
|
|
695
|
+
const ancestorMaxInstances = computeRebaseAncestorMin((l) => l.instantiation?.maxInstancesPerUser, (cfg) => cfg?.instantiation?.maxInstancesPerUser, (a) => ParseAgentInstantiationConfig(a.TypeConfiguration)?.maxInstancesPerUser);
|
|
696
|
+
const targetMaxInstances = targetConfig?.instantiation?.maxInstancesPerUser ??
|
|
697
|
+
ParseAgentInstantiationConfig(Target.TypeConfiguration)?.maxInstancesPerUser;
|
|
698
|
+
if (shouldEnforceField('Configuration') &&
|
|
699
|
+
ancestorMaxInstances !== null &&
|
|
700
|
+
typeof targetMaxInstances === 'number' &&
|
|
701
|
+
targetMaxInstances > ancestorMaxInstances) {
|
|
702
|
+
errors.push(new ValidationErrorInfo('Configuration', widenHint('instantiation.maxInstancesPerUser', `(${targetMaxInstances} > ceiling ${ancestorMaxInstances})`), targetMaxInstances, ValidationErrorType.Failure));
|
|
703
|
+
}
|
|
704
|
+
// Narrow-only capabilities validated across BOTH Configuration JSON and legacy columns
|
|
705
|
+
// as well as Category/AgentType default policy layers (rebase-aware across ancestors):
|
|
706
|
+
// 4a. SearchScopeAccess (None: 0 < Assigned: 1 < All: 2)
|
|
707
|
+
const ancestorSearchAccess = computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs);
|
|
708
|
+
const targetSearchAccess = targetConfig?.scope?.searchScopeAccess ?? Target.SearchScopeAccess ?? null;
|
|
709
|
+
if (shouldEnforceField('SearchScopeAccess') &&
|
|
710
|
+
ancestorSearchAccess !== null &&
|
|
711
|
+
targetSearchAccess !== null &&
|
|
712
|
+
SEARCH_ACCESS_RANK[targetSearchAccess] > SEARCH_ACCESS_RANK[ancestorSearchAccess]) {
|
|
713
|
+
errors.push(new ValidationErrorInfo('SearchScopeAccess', widenHint('SearchScopeAccess', `('${targetSearchAccess}' > '${ancestorSearchAccess}')`), targetSearchAccess, ValidationErrorType.Failure));
|
|
714
|
+
}
|
|
715
|
+
// 4b. AcceptsSkills (None: 0 < Limited: 1 < All: 2)
|
|
716
|
+
const ancestorAcceptsSkills = FoldRebaseAwareChain({
|
|
717
|
+
Nodes: ancestors,
|
|
718
|
+
NodeConfigs: ancestorConfigs,
|
|
719
|
+
Seed: ancestors[0]?.AcceptsSkills ?? null,
|
|
720
|
+
GetNodeValue: (anc) => anc.AcceptsSkills ?? undefined,
|
|
721
|
+
Narrow: (acc, next) => {
|
|
722
|
+
if (next == null)
|
|
723
|
+
return acc;
|
|
724
|
+
return acc === null || ACCEPTS_SKILLS_RANK[next] < ACCEPTS_SKILLS_RANK[acc] ? next : acc;
|
|
725
|
+
},
|
|
726
|
+
});
|
|
727
|
+
if (shouldEnforceField('AcceptsSkills') &&
|
|
728
|
+
ancestorAcceptsSkills !== null &&
|
|
729
|
+
Target.AcceptsSkills != null &&
|
|
730
|
+
ACCEPTS_SKILLS_RANK[Target.AcceptsSkills] > ACCEPTS_SKILLS_RANK[ancestorAcceptsSkills]) {
|
|
731
|
+
errors.push(new ValidationErrorInfo('AcceptsSkills', widenHint('AcceptsSkills', `('${Target.AcceptsSkills}' > '${ancestorAcceptsSkills}')`), Target.AcceptsSkills, ValidationErrorType.Failure));
|
|
732
|
+
}
|
|
733
|
+
// 4c. SkillActivationMode (RequestedOnly: 0 < Auto: 1)
|
|
734
|
+
const narrowSkill = (acc, v) => {
|
|
735
|
+
if (v == null)
|
|
736
|
+
return acc;
|
|
737
|
+
return acc === null || SKILL_ACTIVATION_RANK[v] < SKILL_ACTIVATION_RANK[acc] ? v : acc;
|
|
738
|
+
};
|
|
739
|
+
let seedAncSkill = null;
|
|
740
|
+
for (const layer of defaultPolicyLayers) {
|
|
741
|
+
seedAncSkill = narrowSkill(seedAncSkill, layer.skills?.activationMode);
|
|
742
|
+
}
|
|
743
|
+
if (ancestors.length > 0) {
|
|
744
|
+
seedAncSkill = narrowSkill(seedAncSkill, ancestorConfigs[0]?.skills?.activationMode);
|
|
745
|
+
seedAncSkill = narrowSkill(seedAncSkill, ancestors[0].SkillActivationMode);
|
|
746
|
+
}
|
|
747
|
+
const ancestorSkillMode = FoldRebaseAwareChain({
|
|
748
|
+
Nodes: ancestors,
|
|
749
|
+
NodeConfigs: ancestorConfigs,
|
|
750
|
+
Seed: seedAncSkill,
|
|
751
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
752
|
+
const exp = cfg?.skills?.activationMode ?? null;
|
|
753
|
+
const leg = anc.SkillActivationMode ?? null;
|
|
754
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
755
|
+
if (exp != null)
|
|
756
|
+
return exp;
|
|
757
|
+
return leg != null && leg !== 'RequestedOnly' ? leg : undefined;
|
|
758
|
+
}
|
|
759
|
+
if (exp != null && leg != null) {
|
|
760
|
+
return SKILL_ACTIVATION_RANK[leg] < SKILL_ACTIVATION_RANK[exp] ? leg : exp;
|
|
761
|
+
}
|
|
762
|
+
if (exp != null)
|
|
763
|
+
return exp;
|
|
764
|
+
const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
|
|
765
|
+
return leg != null && (leg !== 'RequestedOnly' || !isNonInst) ? leg : undefined;
|
|
766
|
+
},
|
|
767
|
+
Narrow: (acc, next) => narrowSkill(acc, next),
|
|
768
|
+
});
|
|
769
|
+
const targetSkillMode = targetConfig?.skills?.activationMode ?? Target.SkillActivationMode ?? null;
|
|
770
|
+
if (shouldEnforceField('SkillActivationMode') &&
|
|
771
|
+
ancestorSkillMode !== null &&
|
|
772
|
+
targetSkillMode !== null &&
|
|
773
|
+
SKILL_ACTIVATION_RANK[targetSkillMode] > SKILL_ACTIVATION_RANK[ancestorSkillMode]) {
|
|
774
|
+
errors.push(new ValidationErrorInfo('SkillActivationMode', widenHint('SkillActivationMode', `('${targetSkillMode}' > '${ancestorSkillMode}')`), targetSkillMode, ValidationErrorType.Failure));
|
|
775
|
+
}
|
|
776
|
+
// 4d. RequirePlanMode (rebase-aware monotonic OR)
|
|
777
|
+
const seedAncRequirePlan = defaultPolicyLayers.some((l) => l.execution?.requirePlanMode === true) ||
|
|
778
|
+
(ancestors.length > 0 &&
|
|
779
|
+
(ancestorConfigs[0]?.execution?.requirePlanMode === true || ancestors[0].RequirePlanMode === true));
|
|
780
|
+
const ancestorRequiresPlan = FoldRebaseAwareChain({
|
|
781
|
+
Nodes: ancestors,
|
|
782
|
+
NodeConfigs: ancestorConfigs,
|
|
783
|
+
Seed: seedAncRequirePlan,
|
|
784
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
785
|
+
const exp = cfg?.execution?.requirePlanMode;
|
|
786
|
+
const leg = anc.RequirePlanMode;
|
|
787
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
788
|
+
if (typeof exp === 'boolean')
|
|
789
|
+
return exp;
|
|
790
|
+
return leg === true ? true : undefined;
|
|
791
|
+
}
|
|
792
|
+
if (exp === true || leg === true)
|
|
793
|
+
return true;
|
|
794
|
+
return typeof exp === 'boolean' ? exp : undefined;
|
|
795
|
+
},
|
|
796
|
+
Narrow: (acc, next) => acc || next,
|
|
797
|
+
});
|
|
798
|
+
const targetRequirePlan = targetConfig?.execution?.requirePlanMode ?? Target.RequirePlanMode;
|
|
799
|
+
if (shouldEnforceField('RequirePlanMode') && ancestorRequiresPlan && targetRequirePlan === false) {
|
|
800
|
+
errors.push(new ValidationErrorInfo('RequirePlanMode', widenHint('RequirePlanMode', `(false vs required true)`), false, ValidationErrorType.Failure));
|
|
801
|
+
}
|
|
802
|
+
// 4e. Narrow-only booleans (rebase-aware monotonic AND)
|
|
803
|
+
const computeRebaseAncestorBoolAnd = (layerPicker, nodeJsonPicker, nodeLegacyPicker, sqlDefault) => {
|
|
804
|
+
const foldAnd = (acc, v) => {
|
|
805
|
+
if (typeof v !== 'boolean')
|
|
806
|
+
return acc;
|
|
807
|
+
return acc === null ? v : acc && v;
|
|
808
|
+
};
|
|
809
|
+
let seed = null;
|
|
810
|
+
for (const layer of defaultPolicyLayers) {
|
|
811
|
+
seed = foldAnd(seed, layerPicker(layer));
|
|
812
|
+
}
|
|
813
|
+
if (ancestors.length > 0) {
|
|
814
|
+
const exp0 = nodeJsonPicker(ancestorConfigs[0]);
|
|
815
|
+
const leg0 = nodeLegacyPicker(ancestors[0]);
|
|
816
|
+
seed =
|
|
817
|
+
typeof exp0 === 'boolean' && typeof leg0 === 'boolean'
|
|
818
|
+
? foldAnd(seed, exp0 && leg0)
|
|
819
|
+
: foldAnd(seed, exp0 ?? leg0);
|
|
820
|
+
}
|
|
821
|
+
return FoldRebaseAwareChain({
|
|
822
|
+
Nodes: ancestors,
|
|
823
|
+
NodeConfigs: ancestorConfigs,
|
|
824
|
+
Seed: seed,
|
|
825
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
826
|
+
const exp = nodeJsonPicker(cfg);
|
|
827
|
+
const leg = nodeLegacyPicker(anc);
|
|
828
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
829
|
+
if (typeof exp === 'boolean')
|
|
830
|
+
return exp;
|
|
831
|
+
return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
|
|
832
|
+
}
|
|
833
|
+
if (typeof exp === 'boolean' && typeof leg === 'boolean')
|
|
834
|
+
return exp && leg;
|
|
835
|
+
if (typeof exp === 'boolean')
|
|
836
|
+
return exp;
|
|
837
|
+
if (typeof leg === 'boolean') {
|
|
838
|
+
if (sqlDefault === false && leg === false) {
|
|
839
|
+
const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
|
|
840
|
+
return isNonInst ? undefined : false;
|
|
841
|
+
}
|
|
842
|
+
return leg !== sqlDefault ? leg : undefined;
|
|
843
|
+
}
|
|
844
|
+
return undefined;
|
|
845
|
+
},
|
|
846
|
+
Narrow: (acc, next) => foldAnd(acc, next),
|
|
847
|
+
});
|
|
848
|
+
};
|
|
849
|
+
const checkRebaseNarrowBoolean = (fieldName, ancestorEffective, targetVal) => {
|
|
850
|
+
if (shouldEnforceField(fieldName) && ancestorEffective === false && targetVal === true) {
|
|
851
|
+
errors.push(new ValidationErrorInfo(fieldName, widenHint(fieldName, `(true vs disabled false)`), true, ValidationErrorType.Failure));
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
checkRebaseNarrowBoolean('SupportsPlanMode', computeRebaseAncestorBoolAnd((l) => l.execution?.supportsPlanMode, (cfg) => cfg?.execution?.supportsPlanMode, (a) => a.SupportsPlanMode, true), targetConfig?.execution?.supportsPlanMode ?? Target.SupportsPlanMode);
|
|
855
|
+
checkRebaseNarrowBoolean('AcceptUnregisteredFiles', computeRebaseAncestorBoolAnd((l) => l.attachments?.acceptUnregisteredFiles, (cfg) => cfg?.attachments?.acceptUnregisteredFiles, (a) => a.AcceptUnregisteredFiles, false), targetConfig?.attachments?.acceptUnregisteredFiles ?? Target.AcceptUnregisteredFiles);
|
|
856
|
+
checkRebaseNarrowBoolean('AllowEphemeralClientTools', computeRebaseAncestorBoolAnd((l) => l.clientTools?.allowEphemeral, (cfg) => cfg?.clientTools?.allowEphemeral, (a) => a.AllowEphemeralClientTools, true), targetConfig?.clientTools?.allowEphemeral ?? Target.AllowEphemeralClientTools);
|
|
857
|
+
checkRebaseNarrowBoolean('AllowMemoryWrite', computeRebaseAncestorBoolAnd((l) => l.memory?.allowMemoryWrite, (cfg) => cfg?.memory?.allowMemoryWrite, (a) => a.AllowMemoryWrite, true), targetConfig?.memory?.allowMemoryWrite ?? Target.AllowMemoryWrite);
|
|
858
|
+
// 4f. Ranked enum surfaces: ArtifactCreationMode, MessageMode, StartingPayloadValidationMode, FinalPayloadValidationMode
|
|
859
|
+
const checkRankedEnumSurface = (args) => {
|
|
860
|
+
if (!shouldEnforceField(args.fieldName))
|
|
861
|
+
return;
|
|
862
|
+
const narrowEnum = (acc, v) => {
|
|
863
|
+
if (v == null)
|
|
864
|
+
return acc;
|
|
865
|
+
return acc === null || args.ranks[v] < args.ranks[acc] ? v : acc;
|
|
866
|
+
};
|
|
867
|
+
let seed = null;
|
|
868
|
+
for (const layer of defaultPolicyLayers) {
|
|
869
|
+
seed = narrowEnum(seed, args.layerPicker(layer));
|
|
870
|
+
}
|
|
871
|
+
if (ancestors.length > 0) {
|
|
872
|
+
const exp0 = args.jsonPicker(ancestorConfigs[0]);
|
|
873
|
+
const leg0 = args.legacyPicker(ancestors[0]);
|
|
874
|
+
if (exp0 != null && leg0 != null) {
|
|
875
|
+
seed = narrowEnum(seed, args.ranks[leg0] < args.ranks[exp0] ? leg0 : exp0);
|
|
876
|
+
}
|
|
877
|
+
else if (exp0 != null) {
|
|
878
|
+
seed = narrowEnum(seed, exp0);
|
|
879
|
+
}
|
|
880
|
+
else if (leg0 != null && leg0 !== args.sqlDefault) {
|
|
881
|
+
seed = narrowEnum(seed, leg0);
|
|
882
|
+
}
|
|
883
|
+
else if (seed === null && leg0 != null) {
|
|
884
|
+
seed = leg0;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
const ancestorEffective = FoldRebaseAwareChain({
|
|
888
|
+
Nodes: ancestors,
|
|
889
|
+
NodeConfigs: ancestorConfigs,
|
|
890
|
+
Seed: seed,
|
|
891
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
892
|
+
const exp = args.jsonPicker(cfg) ?? null;
|
|
893
|
+
const leg = args.legacyPicker(anc) ?? null;
|
|
894
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
895
|
+
if (exp != null)
|
|
896
|
+
return exp;
|
|
897
|
+
return leg != null && leg !== args.sqlDefault ? leg : undefined;
|
|
898
|
+
}
|
|
899
|
+
if (exp != null && leg != null) {
|
|
900
|
+
return args.ranks[leg] < args.ranks[exp] ? leg : exp;
|
|
901
|
+
}
|
|
902
|
+
if (exp != null)
|
|
903
|
+
return exp;
|
|
904
|
+
return leg != null && leg !== args.sqlDefault ? leg : undefined;
|
|
905
|
+
},
|
|
906
|
+
Narrow: (acc, next) => narrowEnum(acc, next),
|
|
907
|
+
});
|
|
908
|
+
if (ancestorEffective === null)
|
|
909
|
+
return;
|
|
910
|
+
const expTarget = args.jsonPicker(targetConfig);
|
|
911
|
+
if (expTarget === undefined &&
|
|
912
|
+
args.targetLegacy === args.sqlDefault &&
|
|
913
|
+
Target.DirtyFields &&
|
|
914
|
+
!Target.DirtyFields.has(args.fieldName)) {
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
const targetVal = expTarget ?? args.targetLegacy ?? null;
|
|
918
|
+
if (targetVal != null && args.ranks[targetVal] > args.ranks[ancestorEffective]) {
|
|
919
|
+
errors.push(new ValidationErrorInfo(args.fieldName, widenHint(args.fieldName, `('${targetVal}' > '${ancestorEffective}')`), targetVal, ValidationErrorType.Failure));
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
checkRankedEnumSurface({
|
|
923
|
+
fieldName: 'ArtifactCreationMode',
|
|
924
|
+
ranks: AGENT_ARTIFACT_CREATION_MODE_RANK,
|
|
925
|
+
sqlDefault: 'Always',
|
|
926
|
+
layerPicker: (l) => l.artifacts?.creationMode,
|
|
927
|
+
jsonPicker: (cfg) => cfg?.artifacts?.creationMode,
|
|
928
|
+
legacyPicker: (a) => a.ArtifactCreationMode,
|
|
929
|
+
targetLegacy: Target.ArtifactCreationMode,
|
|
930
|
+
});
|
|
931
|
+
checkRankedEnumSurface({
|
|
932
|
+
fieldName: 'MessageMode',
|
|
933
|
+
ranks: AGENT_MESSAGE_MODE_RANK,
|
|
934
|
+
sqlDefault: 'None',
|
|
935
|
+
layerPicker: (l) => l.attachments?.messageMode,
|
|
936
|
+
jsonPicker: (cfg) => cfg?.attachments?.messageMode,
|
|
937
|
+
legacyPicker: (a) => a.MessageMode,
|
|
938
|
+
targetLegacy: Target.MessageMode,
|
|
939
|
+
});
|
|
940
|
+
checkRankedEnumSurface({
|
|
941
|
+
fieldName: 'StartingPayloadValidationMode',
|
|
942
|
+
ranks: AGENT_STARTING_VALIDATION_MODE_RANK,
|
|
943
|
+
sqlDefault: 'Fail',
|
|
944
|
+
layerPicker: (l) => l.payload?.startingValidationMode,
|
|
945
|
+
jsonPicker: (cfg) => cfg?.payload?.startingValidationMode,
|
|
946
|
+
legacyPicker: (a) => a.StartingPayloadValidationMode,
|
|
947
|
+
targetLegacy: Target.StartingPayloadValidationMode,
|
|
948
|
+
});
|
|
949
|
+
checkRankedEnumSurface({
|
|
950
|
+
fieldName: 'FinalPayloadValidationMode',
|
|
951
|
+
ranks: AGENT_FINAL_VALIDATION_MODE_RANK,
|
|
952
|
+
sqlDefault: 'Retry',
|
|
953
|
+
layerPicker: (l) => l.payload?.finalValidationMode,
|
|
954
|
+
jsonPicker: (cfg) => cfg?.payload?.finalValidationMode,
|
|
955
|
+
legacyPicker: (a) => a.FinalPayloadValidationMode,
|
|
956
|
+
targetLegacy: Target.FinalPayloadValidationMode,
|
|
957
|
+
});
|
|
958
|
+
// 4g. AutoArchiveEnabled: cannot flip true -> false when ancestor enforces finite retention
|
|
959
|
+
const ancestorHasFiniteRetention = ancestorNoteRetentionDays !== null || ancestorExampleRetentionDays !== null;
|
|
960
|
+
const seedAncAutoArchive = (() => {
|
|
961
|
+
if (ancestors.length > 0) {
|
|
962
|
+
const exp0 = ancestorConfigs[0]?.memory?.autoArchiveEnabled;
|
|
963
|
+
if (typeof exp0 === 'boolean')
|
|
964
|
+
return exp0;
|
|
965
|
+
const leg0 = ancestors[0].AutoArchiveEnabled;
|
|
966
|
+
if (typeof leg0 === 'boolean' && leg0 !== true)
|
|
967
|
+
return leg0;
|
|
968
|
+
}
|
|
969
|
+
for (let i = defaultPolicyLayers.length - 1; i >= 0; i--) {
|
|
970
|
+
if (typeof defaultPolicyLayers[i].memory?.autoArchiveEnabled === 'boolean') {
|
|
971
|
+
return defaultPolicyLayers[i].memory.autoArchiveEnabled;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return true;
|
|
975
|
+
})();
|
|
976
|
+
const ancestorAutoArchive = FoldRebaseAwareChain({
|
|
977
|
+
Nodes: ancestors,
|
|
978
|
+
NodeConfigs: ancestorConfigs,
|
|
979
|
+
Seed: seedAncAutoArchive,
|
|
980
|
+
GetNodeValue: (anc, cfg) => {
|
|
981
|
+
const exp = cfg?.memory?.autoArchiveEnabled;
|
|
982
|
+
if (typeof exp === 'boolean')
|
|
983
|
+
return exp;
|
|
984
|
+
const leg = anc.AutoArchiveEnabled;
|
|
985
|
+
return typeof leg === 'boolean' && leg !== true ? leg : undefined;
|
|
986
|
+
},
|
|
987
|
+
Narrow: (acc, next) => (acc === true && ancestorHasFiniteRetention && next === false ? true : next),
|
|
988
|
+
});
|
|
989
|
+
const targetAutoArchive = targetConfig?.memory?.autoArchiveEnabled ?? Target.AutoArchiveEnabled;
|
|
990
|
+
if (shouldEnforceField('AutoArchiveEnabled') &&
|
|
991
|
+
ancestorAutoArchive === true &&
|
|
992
|
+
ancestorHasFiniteRetention &&
|
|
993
|
+
targetAutoArchive === false) {
|
|
994
|
+
errors.push(new ValidationErrorInfo('AutoArchiveEnabled', widenHint('AutoArchiveEnabled', '(false while ancestor enforces finite retention)'), false, ValidationErrorType.Failure));
|
|
995
|
+
}
|
|
996
|
+
// 4h. Payload path glob-sets (Downstream, Upstream, SelfRead, SelfWrite)
|
|
997
|
+
const parsePathList = (raw) => {
|
|
998
|
+
if (!raw || raw.trim().length === 0)
|
|
999
|
+
return null;
|
|
1000
|
+
try {
|
|
1001
|
+
const p = JSON.parse(raw);
|
|
1002
|
+
if (Array.isArray(p) && p.every((item) => typeof item === 'string')) {
|
|
1003
|
+
return p;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
catch {
|
|
1007
|
+
return null;
|
|
1008
|
+
}
|
|
1009
|
+
return null;
|
|
1010
|
+
};
|
|
1011
|
+
const checkPayloadPathSurface = (args) => {
|
|
1012
|
+
if (!shouldEnforceField(args.fieldName))
|
|
1013
|
+
return;
|
|
1014
|
+
let seed = null;
|
|
1015
|
+
for (const layer of defaultPolicyLayers) {
|
|
1016
|
+
const lp = args.jsonPicker(layer);
|
|
1017
|
+
if (Array.isArray(lp)) {
|
|
1018
|
+
seed = IntersectPayloadPathSets(seed, lp);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (ancestors.length > 0) {
|
|
1022
|
+
const exp0 = args.jsonPicker(ancestorConfigs[0]);
|
|
1023
|
+
if (Array.isArray(exp0)) {
|
|
1024
|
+
seed = IntersectPayloadPathSets(seed, exp0);
|
|
1025
|
+
}
|
|
1026
|
+
else {
|
|
1027
|
+
const leg0 = parsePathList(args.legacyPicker(ancestors[0]));
|
|
1028
|
+
if (leg0 !== null) {
|
|
1029
|
+
const isDbWildcard = args.treatWildcardAsDbDefault && leg0.length === 1 && leg0[0] === '*';
|
|
1030
|
+
if (!isDbWildcard) {
|
|
1031
|
+
seed = IntersectPayloadPathSets(seed, leg0);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
const ancestorPaths = FoldRebaseAwareChain({
|
|
1037
|
+
Nodes: ancestors,
|
|
1038
|
+
NodeConfigs: ancestorConfigs,
|
|
1039
|
+
Seed: seed,
|
|
1040
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1041
|
+
const exp = args.jsonPicker(cfg);
|
|
1042
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null) {
|
|
1043
|
+
return null;
|
|
1044
|
+
}
|
|
1045
|
+
if (Array.isArray(exp))
|
|
1046
|
+
return [...exp];
|
|
1047
|
+
const leg = parsePathList(args.legacyPicker(anc));
|
|
1048
|
+
if (leg !== null) {
|
|
1049
|
+
const isDbWildcard = args.treatWildcardAsDbDefault && leg.length === 1 && leg[0] === '*';
|
|
1050
|
+
if (!isDbWildcard)
|
|
1051
|
+
return leg;
|
|
1052
|
+
}
|
|
1053
|
+
return undefined;
|
|
1054
|
+
},
|
|
1055
|
+
Narrow: (acc, next) => IntersectPayloadPathSets(acc, next),
|
|
1056
|
+
Rebase: (_acc, next) => (next === null ? null : [...next]),
|
|
1057
|
+
});
|
|
1058
|
+
const expTarget = args.jsonPicker(targetConfig);
|
|
1059
|
+
let targetPaths;
|
|
1060
|
+
if (expTarget !== undefined) {
|
|
1061
|
+
targetPaths = expTarget;
|
|
1062
|
+
}
|
|
1063
|
+
else {
|
|
1064
|
+
const legTarget = parsePathList(args.targetLegacy);
|
|
1065
|
+
if (legTarget !== null) {
|
|
1066
|
+
const isUntouchedWildcard = args.treatWildcardAsDbDefault &&
|
|
1067
|
+
legTarget.length === 1 &&
|
|
1068
|
+
legTarget[0] === '*' &&
|
|
1069
|
+
Target.DirtyFields &&
|
|
1070
|
+
!Target.DirtyFields.has(args.fieldName);
|
|
1071
|
+
if (!isUntouchedWildcard) {
|
|
1072
|
+
targetPaths = legTarget;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
if (targetPaths === undefined)
|
|
1077
|
+
return;
|
|
1078
|
+
if (!IsPayloadPathSetWithinAncestor(ancestorPaths, targetPaths)) {
|
|
1079
|
+
errors.push(new ValidationErrorInfo(args.fieldName, widenHint(args.fieldName, `(${JSON.stringify(targetPaths)} outside ${JSON.stringify(ancestorPaths)})`), targetPaths, ValidationErrorType.Failure));
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
checkPayloadPathSurface({
|
|
1083
|
+
fieldName: 'PayloadDownstreamPaths',
|
|
1084
|
+
jsonPicker: (cfg) => cfg?.payload?.downstreamPaths,
|
|
1085
|
+
legacyPicker: (a) => a.PayloadDownstreamPaths,
|
|
1086
|
+
targetLegacy: Target.PayloadDownstreamPaths,
|
|
1087
|
+
treatWildcardAsDbDefault: true,
|
|
1088
|
+
});
|
|
1089
|
+
checkPayloadPathSurface({
|
|
1090
|
+
fieldName: 'PayloadUpstreamPaths',
|
|
1091
|
+
jsonPicker: (cfg) => cfg?.payload?.upstreamPaths,
|
|
1092
|
+
legacyPicker: (a) => a.PayloadUpstreamPaths,
|
|
1093
|
+
targetLegacy: Target.PayloadUpstreamPaths,
|
|
1094
|
+
treatWildcardAsDbDefault: true,
|
|
1095
|
+
});
|
|
1096
|
+
checkPayloadPathSurface({
|
|
1097
|
+
fieldName: 'PayloadSelfReadPaths',
|
|
1098
|
+
jsonPicker: (cfg) => cfg?.payload?.selfReadPaths,
|
|
1099
|
+
legacyPicker: (a) => a.PayloadSelfReadPaths,
|
|
1100
|
+
targetLegacy: Target.PayloadSelfReadPaths,
|
|
1101
|
+
treatWildcardAsDbDefault: false,
|
|
1102
|
+
});
|
|
1103
|
+
checkPayloadPathSurface({
|
|
1104
|
+
fieldName: 'PayloadSelfWritePaths',
|
|
1105
|
+
jsonPicker: (cfg) => cfg?.payload?.selfWritePaths,
|
|
1106
|
+
legacyPicker: (a) => a.PayloadSelfWritePaths,
|
|
1107
|
+
targetLegacy: Target.PayloadSelfWritePaths,
|
|
1108
|
+
treatWildcardAsDbDefault: false,
|
|
1109
|
+
});
|
|
1110
|
+
// 4i. PayloadScope subtree prefix lock
|
|
1111
|
+
if (shouldEnforceField('PayloadScope')) {
|
|
1112
|
+
let seedScope = null;
|
|
1113
|
+
for (const layer of defaultPolicyLayers) {
|
|
1114
|
+
if (typeof layer.payload?.scope === 'string' && layer.payload.scope.trim().length > 0) {
|
|
1115
|
+
seedScope = NarrowPayloadScope(seedScope, layer.payload.scope);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
if (ancestors.length > 0) {
|
|
1119
|
+
const s0 = ancestorConfigs[0]?.payload?.scope ?? ancestors[0].PayloadScope ?? null;
|
|
1120
|
+
if (typeof s0 === 'string' && s0.trim().length > 0) {
|
|
1121
|
+
seedScope = NarrowPayloadScope(seedScope, s0);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
const ancestorPayloadScope = FoldRebaseAwareChain({
|
|
1125
|
+
Nodes: ancestors,
|
|
1126
|
+
NodeConfigs: ancestorConfigs,
|
|
1127
|
+
Seed: seedScope,
|
|
1128
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1129
|
+
const exp = cfg?.payload?.scope;
|
|
1130
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null)
|
|
1131
|
+
return null;
|
|
1132
|
+
if (typeof exp === 'string' && exp.trim().length > 0)
|
|
1133
|
+
return exp.trim();
|
|
1134
|
+
const leg = anc.PayloadScope?.trim();
|
|
1135
|
+
return leg && leg.length > 0 ? leg : undefined;
|
|
1136
|
+
},
|
|
1137
|
+
Narrow: (acc, next) => NarrowPayloadScope(acc, next),
|
|
1138
|
+
Rebase: (acc, next) => (next === null ? null : HasPathTraversalSegment(next) ? acc : next),
|
|
1139
|
+
});
|
|
1140
|
+
if (ancestorPayloadScope) {
|
|
1141
|
+
const expScope = targetConfig?.payload?.scope;
|
|
1142
|
+
const explicitNullClear = expScope === null || (Target.PayloadScope === null && Target.DirtyFields?.has('PayloadScope'));
|
|
1143
|
+
const candidateScope = expScope !== undefined ? expScope : Target.PayloadScope !== undefined ? Target.PayloadScope : undefined;
|
|
1144
|
+
if (explicitNullClear || (typeof candidateScope === 'string' && candidateScope.trim().length > 0)) {
|
|
1145
|
+
if (!IsPayloadScopeWithinAncestor(ancestorPayloadScope, candidateScope)) {
|
|
1146
|
+
errors.push(new ValidationErrorInfo('PayloadScope', widenHint('PayloadScope', `('${String(candidateScope)}' outside '${ancestorPayloadScope}')`), candidateScope, ValidationErrorType.Failure));
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
// 4j. AttachmentRootPath subtree prefix lock
|
|
1152
|
+
if (shouldEnforceField('AttachmentRootPath')) {
|
|
1153
|
+
let seedAttachPath = null;
|
|
1154
|
+
for (const layer of defaultPolicyLayers) {
|
|
1155
|
+
if (typeof layer.attachments?.rootPath === 'string' && layer.attachments.rootPath.trim().length > 0) {
|
|
1156
|
+
seedAttachPath = NarrowAttachmentRootPath(seedAttachPath, layer.attachments.rootPath);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (ancestors.length > 0) {
|
|
1160
|
+
const r0 = ancestorConfigs[0]?.attachments?.rootPath ?? ancestors[0].AttachmentRootPath ?? null;
|
|
1161
|
+
if (typeof r0 === 'string' && r0.trim().length > 0) {
|
|
1162
|
+
seedAttachPath = NarrowAttachmentRootPath(seedAttachPath, r0);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
const ancestorAttachRoot = FoldRebaseAwareChain({
|
|
1166
|
+
Nodes: ancestors,
|
|
1167
|
+
NodeConfigs: ancestorConfigs,
|
|
1168
|
+
Seed: seedAttachPath,
|
|
1169
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1170
|
+
const exp = cfg?.attachments?.rootPath;
|
|
1171
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true && exp === null)
|
|
1172
|
+
return null;
|
|
1173
|
+
if (typeof exp === 'string' && exp.trim().length > 0)
|
|
1174
|
+
return exp.trim();
|
|
1175
|
+
const leg = anc.AttachmentRootPath?.trim();
|
|
1176
|
+
return leg && leg.length > 0 ? leg : undefined;
|
|
1177
|
+
},
|
|
1178
|
+
Narrow: (acc, next) => NarrowAttachmentRootPath(acc, next),
|
|
1179
|
+
Rebase: (acc, next) => (next === null ? null : HasPathTraversalSegment(next) ? acc : next),
|
|
1180
|
+
});
|
|
1181
|
+
if (ancestorAttachRoot) {
|
|
1182
|
+
const expRoot = targetConfig?.attachments?.rootPath;
|
|
1183
|
+
const explicitNullClear = expRoot === null ||
|
|
1184
|
+
(Target.AttachmentRootPath === null && Target.DirtyFields?.has('AttachmentRootPath'));
|
|
1185
|
+
const candidateRoot = expRoot !== undefined
|
|
1186
|
+
? expRoot
|
|
1187
|
+
: Target.AttachmentRootPath !== undefined
|
|
1188
|
+
? Target.AttachmentRootPath
|
|
1189
|
+
: undefined;
|
|
1190
|
+
if (explicitNullClear || (typeof candidateRoot === 'string' && candidateRoot.trim().length > 0)) {
|
|
1191
|
+
if (!IsAttachmentRootPathWithinAncestor(ancestorAttachRoot, candidateRoot)) {
|
|
1192
|
+
errors.push(new ValidationErrorInfo('AttachmentRootPath', widenHint('AttachmentRootPath', `('${String(candidateRoot)}' outside '${ancestorAttachRoot}')`), candidateRoot, ValidationErrorType.Failure));
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
// 4k. ScopeConfig (`scope.secondaryScopeConfig`) per-key intersection
|
|
1198
|
+
if (shouldEnforceField('ScopeConfig')) {
|
|
1199
|
+
const parseScopeObj = (raw) => {
|
|
1200
|
+
if (!raw || raw.trim().length === 0)
|
|
1201
|
+
return null;
|
|
1202
|
+
const parsed = ParseAgentConfigJsonObject(raw);
|
|
1203
|
+
return parsed ? { ...parsed } : null;
|
|
1204
|
+
};
|
|
1205
|
+
let seedScopeObj = null;
|
|
1206
|
+
for (const layer of defaultPolicyLayers) {
|
|
1207
|
+
if (layer.scope?.secondaryScopeConfig) {
|
|
1208
|
+
seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, layer.scope.secondaryScopeConfig);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
if (ancestors.length > 0) {
|
|
1212
|
+
const s0 = ancestorConfigs[0]?.scope?.secondaryScopeConfig ?? parseScopeObj(ancestors[0].ScopeConfig);
|
|
1213
|
+
if (s0) {
|
|
1214
|
+
seedScopeObj = NarrowScopeConfigObjects(seedScopeObj, s0);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
const ancestorScopeObj = FoldRebaseAwareChain({
|
|
1218
|
+
Nodes: ancestors,
|
|
1219
|
+
NodeConfigs: ancestorConfigs,
|
|
1220
|
+
Seed: seedScopeObj,
|
|
1221
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1222
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true && cfg?.scope?.secondaryScopeConfig === null) {
|
|
1223
|
+
return null;
|
|
1224
|
+
}
|
|
1225
|
+
const exp = cfg?.scope?.secondaryScopeConfig;
|
|
1226
|
+
if (exp && typeof exp === 'object' && !Array.isArray(exp))
|
|
1227
|
+
return exp;
|
|
1228
|
+
return parseScopeObj(anc.ScopeConfig) ?? undefined;
|
|
1229
|
+
},
|
|
1230
|
+
Narrow: (acc, next) => NarrowScopeConfigObjects(acc, next),
|
|
1231
|
+
Rebase: (_acc, next) => (next ? { ...next } : null),
|
|
1232
|
+
});
|
|
1233
|
+
if (ancestorScopeObj && Object.keys(ancestorScopeObj).length > 0) {
|
|
1234
|
+
const expScopeObj = targetConfig?.scope?.secondaryScopeConfig;
|
|
1235
|
+
if (expScopeObj === null || (Target.ScopeConfig === null && Target.DirtyFields?.has('ScopeConfig'))) {
|
|
1236
|
+
errors.push(new ValidationErrorInfo('ScopeConfig', widenHint('ScopeConfig', '(cleared to null when ancestor enforces scope config)'), null, ValidationErrorType.Failure));
|
|
1237
|
+
}
|
|
1238
|
+
else {
|
|
1239
|
+
const targetScopeObj = expScopeObj ?? parseScopeObj(Target.ScopeConfig);
|
|
1240
|
+
if (targetScopeObj) {
|
|
1241
|
+
const scopeViolations = FindScopeConfigWideningViolations(ancestorScopeObj, targetScopeObj);
|
|
1242
|
+
for (const msg of scopeViolations) {
|
|
1243
|
+
errors.push(new ValidationErrorInfo('ScopeConfig', widenHint('ScopeConfig', `(${msg})`), targetScopeObj, ValidationErrorType.Failure));
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
// 4l. AgentTypePromptParams gates (`enableHandoff: false`, `enableTaskGraphs: false`)
|
|
1250
|
+
if (shouldEnforceField('AgentTypePromptParams')) {
|
|
1251
|
+
const ancestorLockedFalseGates = new Set();
|
|
1252
|
+
const applyGateMap = (obj, allowRebase) => {
|
|
1253
|
+
if (!obj)
|
|
1254
|
+
return;
|
|
1255
|
+
for (const gate of NARROW_ONLY_PROMPT_PARAM_GATES) {
|
|
1256
|
+
if (typeof obj[gate] === 'boolean') {
|
|
1257
|
+
if (obj[gate] === false) {
|
|
1258
|
+
ancestorLockedFalseGates.add(gate);
|
|
1259
|
+
}
|
|
1260
|
+
else if (allowRebase && obj[gate] === true) {
|
|
1261
|
+
ancestorLockedFalseGates.delete(gate);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
for (const layer of defaultPolicyLayers) {
|
|
1267
|
+
applyGateMap(layer.promptDefaults ?? null, false);
|
|
1268
|
+
}
|
|
1269
|
+
for (let i = 0; i < ancestors.length; i++) {
|
|
1270
|
+
const parsed = ParseAgentConfigJsonObject(ancestors[i].AgentTypePromptParams);
|
|
1271
|
+
applyGateMap(parsed, i > 0 && ancestorConfigs[i]?.allowWidenFromBase === true);
|
|
1272
|
+
}
|
|
1273
|
+
const targetPromptParams = ParseAgentConfigJsonObject(Target.AgentTypePromptParams);
|
|
1274
|
+
if (targetPromptParams && ancestorLockedFalseGates.size > 0) {
|
|
1275
|
+
for (const gate of ancestorLockedFalseGates) {
|
|
1276
|
+
if (targetPromptParams[gate] === true) {
|
|
1277
|
+
errors.push(new ValidationErrorInfo('AgentTypePromptParams', widenHint(`AgentTypePromptParams.${gate}`, '(true vs disabled false)'), true, ValidationErrorType.Failure));
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
return errors;
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Server-side AI Agent entity enforcing:
|
|
1287
|
+
* 1. `TypeConfiguration` ⊨ `ConfigSchema` validation.
|
|
1288
|
+
* 2. `BaseAgentID` prototype inheritance integrity (`MaxDepth = 5`, cycle detection, `InstantiationMode` & `maxInstancesPerUser`).
|
|
1289
|
+
* 3. Non-Owner (`UI` role) sandbox for creating/updating/deleting derived personal instances.
|
|
1290
|
+
* 4. Automatic `OwnerUserID` attribution, derived default capability inheritance on create, and
|
|
1291
|
+
* `IsPrimaryInstance` uniqueness per `(OwnerUserID, RootBaseAgentID)`.
|
|
26
1292
|
*/
|
|
27
1293
|
let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityExtended {
|
|
28
|
-
|
|
1294
|
+
constructor() {
|
|
1295
|
+
super(...arguments);
|
|
1296
|
+
/**
|
|
1297
|
+
* Captures whether the caller actually modified `Configuration` (or is creating a new record)
|
|
1298
|
+
* BEFORE `syncConfigurationWithLegacyColumns` runs in `Save()`, so unrelated legacy-column
|
|
1299
|
+
* edits on pre-existing rows do not trigger full-document JSON re-validation or spuriously
|
|
1300
|
+
* mark `Configuration` dirty for narrow-only checks (R3-10).
|
|
1301
|
+
*/
|
|
1302
|
+
this._configDirtyBeforeSync = null;
|
|
1303
|
+
this._dirtyLegacyPatchForValidation = null;
|
|
1304
|
+
this._saveGuardCache = null;
|
|
1305
|
+
}
|
|
1306
|
+
/** Enable async validation so TypeConfiguration, BaseAgentID chain, and sandbox checks run. */
|
|
29
1307
|
get DefaultSkipAsyncValidation() {
|
|
30
1308
|
return false;
|
|
31
1309
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
1310
|
+
async Save(options) {
|
|
1311
|
+
const isCreate = !this.IsSaved;
|
|
1312
|
+
let baseAgent = null;
|
|
1313
|
+
let resolvedRootBaseId = null;
|
|
1314
|
+
// Capture caller-dirty legacy fields BEFORE inheritDefaultsFromBaseAgent copies parent
|
|
1315
|
+
// defaults onto legacy columns so newly created derived instances do not freeze inherited
|
|
1316
|
+
// parent values into AIAgent.Configuration JSON.
|
|
1317
|
+
const callerDirtyLegacyFields = this.collectDirtyLegacyConfigFields(isCreate);
|
|
1318
|
+
const callerLegacyPatch = this.buildLegacyPatchFromSet(callerDirtyLegacyFields);
|
|
1319
|
+
this._dirtyLegacyPatchForValidation = Object.keys(callerLegacyPatch).length > 0 ? callerLegacyPatch : null;
|
|
1320
|
+
this._configDirtyBeforeSync = isCreate || (this.GetFieldByName('Configuration')?.Dirty ?? false);
|
|
1321
|
+
try {
|
|
1322
|
+
if (isCreate && !this.OwnerUserID && this.ContextCurrentUser) {
|
|
1323
|
+
this.OwnerUserID = this.ContextCurrentUser.ID;
|
|
1324
|
+
}
|
|
1325
|
+
if (this.BaseAgentID) {
|
|
1326
|
+
const guardBatch = await this.loadGuardMetadataBatch();
|
|
1327
|
+
this._saveGuardCache = guardBatch;
|
|
1328
|
+
const { AllAgents: allAgents, AllCategories: allCategories, AllAgentTypes: allAgentTypes } = guardBatch;
|
|
1329
|
+
baseAgent = allAgents.find((a) => UUIDsEqual(a.ID, this.BaseAgentID)) ?? null;
|
|
1330
|
+
if (baseAgent) {
|
|
1331
|
+
resolvedRootBaseId = this.findRootBaseAgentId(baseAgent, allAgents);
|
|
1332
|
+
if (isCreate) {
|
|
1333
|
+
const ancestorSearchCeiling = this.inheritDefaultsFromBaseAgent(baseAgent, allAgents, allCategories, allAgentTypes);
|
|
1334
|
+
// R5-1 + C-R3-1 + C-R3-2: If the caller explicitly wrote `SearchScopeAccess = 'None'`
|
|
1335
|
+
// (`NeverSet === false`) WITHOUT explicitly setting `Configuration.scope.searchScopeAccess`,
|
|
1336
|
+
// under a broader effective ancestor ceiling (`ancestorSearchCeiling !== 'None'`),
|
|
1337
|
+
// persist `scope.searchScopeAccess = 'None'` into `Configuration` so runtime resolution
|
|
1338
|
+
// honors the explicit restriction instead of treating the leaf column `'None'` as unset.
|
|
1339
|
+
const searchField = this.GetFieldByName('SearchScopeAccess');
|
|
1340
|
+
const explicitConfigSearchAccess = ParseAgentConfiguration(this.Configuration)?.scope?.searchScopeAccess;
|
|
1341
|
+
if (this.SearchScopeAccess === 'None' &&
|
|
1342
|
+
searchField &&
|
|
1343
|
+
searchField.NeverSet === false &&
|
|
1344
|
+
explicitConfigSearchAccess === undefined &&
|
|
1345
|
+
ancestorSearchCeiling !== null &&
|
|
1346
|
+
ancestorSearchCeiling !== 'None') {
|
|
1347
|
+
callerDirtyLegacyFields.add('SearchScopeAccess');
|
|
1348
|
+
}
|
|
1349
|
+
const primaryDirty = this.GetFieldByName('IsPrimaryInstance')?.Dirty ?? false;
|
|
1350
|
+
if (!primaryDirty && !this.IsPrimaryInstance && this.OwnerUserID) {
|
|
1351
|
+
const existingSiblings = this.findActiveSiblingsForOwnerAndRoot(allAgents, this.OwnerUserID, resolvedRootBaseId, this.ID);
|
|
1352
|
+
if (existingSiblings.length === 0) {
|
|
1353
|
+
this.IsPrimaryInstance = true;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
// Bidirectional v6.x sync between AIAgent.Configuration JSON and deprecated legacy columns
|
|
1360
|
+
this.syncConfigurationWithLegacyColumns(isCreate, callerDirtyLegacyFields);
|
|
1361
|
+
const saved = await super.Save(options);
|
|
1362
|
+
if (!saved) {
|
|
1363
|
+
return false;
|
|
1364
|
+
}
|
|
1365
|
+
// Maintain single IsPrimaryInstance per (OwnerUserID, RootBaseAgentID)
|
|
1366
|
+
if (this.BaseAgentID && this.OwnerUserID && this.IsPrimaryInstance === true) {
|
|
1367
|
+
const rootId = this.RootBaseAgentID ?? resolvedRootBaseId ?? this.BaseAgentID;
|
|
1368
|
+
await this.clearOtherPrimaryInstances(this.OwnerUserID, rootId, this.ID);
|
|
1369
|
+
}
|
|
1370
|
+
return true;
|
|
1371
|
+
}
|
|
1372
|
+
finally {
|
|
1373
|
+
this._configDirtyBeforeSync = null;
|
|
1374
|
+
this._dirtyLegacyPatchForValidation = null;
|
|
1375
|
+
this._saveGuardCache = null;
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
async Delete(options) {
|
|
1379
|
+
const user = this.ContextCurrentUser;
|
|
1380
|
+
if (!IsAgentAdminOrOwnerUser(user, this.ProviderToUse) && user) {
|
|
1381
|
+
const preSaveBase = this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID;
|
|
1382
|
+
const preSaveOwner = this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID;
|
|
1383
|
+
if (!preSaveBase || !preSaveOwner || !UUIDsEqual(preSaveOwner, user.ID)) {
|
|
1384
|
+
const err = new ValidationErrorInfo('OwnerUserID', 'Non-administrator users can only delete their own derived agent instances.', this.ID, ValidationErrorType.Failure);
|
|
1385
|
+
const deleteResult = new BaseEntityResult(false, '', 'delete');
|
|
1386
|
+
deleteResult.Errors = [err];
|
|
1387
|
+
this.RegisterResultHistoryEntry(deleteResult);
|
|
1388
|
+
return false;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
return super.Delete(options);
|
|
1392
|
+
}
|
|
37
1393
|
async ValidateAsync() {
|
|
38
1394
|
const result = await super.ValidateAsync();
|
|
39
1395
|
if (!result.Success)
|
|
40
1396
|
return result;
|
|
1397
|
+
// 0. Configuration JSON syntax & scalar-type validation (R2-2, R3-10, C-R1-7):
|
|
1398
|
+
// - On create or when caller directly modified Configuration, validate the full Configuration JSON
|
|
1399
|
+
// (plus any caller-dirty raw JSON legacy columns such as RerankerConfiguration/ScopeConfig).
|
|
1400
|
+
// - When caller only modified legacy columns on a saved row, validate ONLY the caller-dirty
|
|
1401
|
+
// legacy patch so invalid legacy edits are caught without breaking unrelated saves on
|
|
1402
|
+
// pre-existing rows with older backfilled Configuration payloads.
|
|
1403
|
+
const configDirtyForValidation = this._configDirtyBeforeSync ?? (!this.IsSaved || (this.GetFieldByName('Configuration')?.Dirty ?? false));
|
|
1404
|
+
const dirtyLegacyPatch = this._dirtyLegacyPatchForValidation ?? this.buildLegacyPatchFromSet(this.collectDirtyLegacyConfigFields(!this.IsSaved));
|
|
1405
|
+
if (configDirtyForValidation) {
|
|
1406
|
+
const configErrors = ValidateAgentConfigurationJson(this.Configuration, 'Configuration');
|
|
1407
|
+
if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'RerankerConfiguration') ||
|
|
1408
|
+
Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'ScopeConfig')) {
|
|
1409
|
+
const rawJsonSubset = {};
|
|
1410
|
+
if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'RerankerConfiguration')) {
|
|
1411
|
+
rawJsonSubset.RerankerConfiguration = dirtyLegacyPatch.RerankerConfiguration;
|
|
1412
|
+
}
|
|
1413
|
+
if (Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'ScopeConfig')) {
|
|
1414
|
+
rawJsonSubset.ScopeConfig = dirtyLegacyPatch.ScopeConfig;
|
|
1415
|
+
}
|
|
1416
|
+
configErrors.push(...ValidateLegacyAgentConfigFields(rawJsonSubset));
|
|
1417
|
+
}
|
|
1418
|
+
if (configErrors.length > 0) {
|
|
1419
|
+
for (const msg of configErrors) {
|
|
1420
|
+
result.Errors.push(new ValidationErrorInfo('Configuration', msg, this.Configuration, ValidationErrorType.Failure));
|
|
1421
|
+
}
|
|
1422
|
+
result.Success = false;
|
|
1423
|
+
return result;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
else if (Object.keys(dirtyLegacyPatch).length > 0) {
|
|
1427
|
+
const legacyErrors = ValidateLegacyAgentConfigFields(dirtyLegacyPatch);
|
|
1428
|
+
if (legacyErrors.length > 0) {
|
|
1429
|
+
for (const msg of legacyErrors) {
|
|
1430
|
+
result.Errors.push(new ValidationErrorInfo('Configuration', msg, this.Configuration, ValidationErrorType.Failure));
|
|
1431
|
+
}
|
|
1432
|
+
result.Success = false;
|
|
1433
|
+
return result;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
// C-R3-3: Always enforce SQL CHECK cross-field pair invariants against live post-sync
|
|
1437
|
+
// entity properties whenever Configuration or either column of the pair changed (covers
|
|
1438
|
+
// single-sided creates, JSON-only updates, and mixed legacy+JSON updates).
|
|
1439
|
+
const compactionTouched = configDirtyForValidation ||
|
|
1440
|
+
Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'CompactionTargetPercent') ||
|
|
1441
|
+
Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'CompactionTriggerPercent') ||
|
|
1442
|
+
(this.GetFieldByName('CompactionTargetPercent')?.Dirty ?? false) ||
|
|
1443
|
+
(this.GetFieldByName('CompactionTriggerPercent')?.Dirty ?? false);
|
|
1444
|
+
if (compactionTouched &&
|
|
1445
|
+
typeof this.CompactionTargetPercent === 'number' &&
|
|
1446
|
+
Number.isFinite(this.CompactionTargetPercent) &&
|
|
1447
|
+
typeof this.CompactionTriggerPercent === 'number' &&
|
|
1448
|
+
Number.isFinite(this.CompactionTriggerPercent) &&
|
|
1449
|
+
this.CompactionTargetPercent >= this.CompactionTriggerPercent) {
|
|
1450
|
+
result.Errors.push(new ValidationErrorInfo('CompactionTargetPercent', `CompactionTargetPercent (${this.CompactionTargetPercent}) must be less than CompactionTriggerPercent (${this.CompactionTriggerPercent}).`, this.CompactionTargetPercent, ValidationErrorType.Failure));
|
|
1451
|
+
result.Success = false;
|
|
1452
|
+
return result;
|
|
1453
|
+
}
|
|
1454
|
+
const execRangeTouched = configDirtyForValidation ||
|
|
1455
|
+
Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'MinExecutionsPerRun') ||
|
|
1456
|
+
Object.prototype.hasOwnProperty.call(dirtyLegacyPatch, 'MaxExecutionsPerRun') ||
|
|
1457
|
+
(this.GetFieldByName('MinExecutionsPerRun')?.Dirty ?? false) ||
|
|
1458
|
+
(this.GetFieldByName('MaxExecutionsPerRun')?.Dirty ?? false);
|
|
1459
|
+
if (execRangeTouched &&
|
|
1460
|
+
typeof this.MinExecutionsPerRun === 'number' &&
|
|
1461
|
+
Number.isFinite(this.MinExecutionsPerRun) &&
|
|
1462
|
+
typeof this.MaxExecutionsPerRun === 'number' &&
|
|
1463
|
+
Number.isFinite(this.MaxExecutionsPerRun) &&
|
|
1464
|
+
this.MinExecutionsPerRun > this.MaxExecutionsPerRun) {
|
|
1465
|
+
result.Errors.push(new ValidationErrorInfo('MinExecutionsPerRun', `MinExecutionsPerRun (${this.MinExecutionsPerRun}) cannot exceed MaxExecutionsPerRun (${this.MaxExecutionsPerRun}).`, this.MinExecutionsPerRun, ValidationErrorType.Failure));
|
|
1466
|
+
result.Success = false;
|
|
1467
|
+
return result;
|
|
1468
|
+
}
|
|
1469
|
+
// 1. BaseAgentID inheritance, helperPlugins & non-admin sandbox checks
|
|
1470
|
+
const user = this.ContextCurrentUser;
|
|
1471
|
+
const isAdmin = IsAgentAdminOrOwnerUser(user, this.ProviderToUse);
|
|
1472
|
+
const hasHelperPluginsKey = (raw) => {
|
|
1473
|
+
if (!raw || raw.trim().length === 0)
|
|
1474
|
+
return false;
|
|
1475
|
+
try {
|
|
1476
|
+
const parsed = JSON.parse(raw);
|
|
1477
|
+
return Boolean(parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'helperPlugins'));
|
|
1478
|
+
}
|
|
1479
|
+
catch {
|
|
1480
|
+
return false;
|
|
1481
|
+
}
|
|
1482
|
+
};
|
|
1483
|
+
const hasDeclaredHelperPlugins = ParseAgentHelperPlugins(this.Configuration).length > 0 ||
|
|
1484
|
+
ParseAgentHelperPlugins(this.TypeConfiguration).length > 0 ||
|
|
1485
|
+
hasHelperPluginsKey(this.Configuration) ||
|
|
1486
|
+
hasHelperPluginsKey(this.TypeConfiguration);
|
|
1487
|
+
const hasPathTraversal = HasPathTraversalSegment(this.PayloadScope) ||
|
|
1488
|
+
HasPathTraversalSegment(this.AttachmentRootPath) ||
|
|
1489
|
+
HasPathTraversalSegment(ParseAgentConfiguration(this.Configuration)?.payload?.scope) ||
|
|
1490
|
+
HasPathTraversalSegment(ParseAgentConfiguration(this.Configuration)?.attachments?.rootPath);
|
|
1491
|
+
const hasAllowWidenKey = JsonHasAllowWidenFromBaseKey(this.Configuration) ||
|
|
1492
|
+
JsonHasAllowWidenFromBaseKey(this.GetFieldByName('Configuration')?.OldValue ?? null);
|
|
1493
|
+
if (this.BaseAgentID || !isAdmin || hasDeclaredHelperPlugins || hasPathTraversal || hasAllowWidenKey) {
|
|
1494
|
+
const guardBatch = this._saveGuardCache ?? (await this.loadGuardMetadataBatch());
|
|
1495
|
+
if (guardBatch.ErrorMessage) {
|
|
1496
|
+
result.Errors.push(new ValidationErrorInfo('BaseAgentID', `Fail-closed: unable to verify agent inheritance and policy guardrails (${guardBatch.ErrorMessage}).`, this.BaseAgentID, ValidationErrorType.Failure));
|
|
1497
|
+
result.Success = false;
|
|
1498
|
+
return result;
|
|
1499
|
+
}
|
|
1500
|
+
const { AllAgents: allAgents, AllPermissions: allPermissions, AllCategories: allCategories, AllAgentTypes: allAgentTypes, } = guardBatch;
|
|
1501
|
+
const dirtyFieldNames = new Set();
|
|
1502
|
+
for (const f of this.Fields) {
|
|
1503
|
+
if (f.Dirty) {
|
|
1504
|
+
if (f.Name === 'Configuration' && this._configDirtyBeforeSync === false) {
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
dirtyFieldNames.add(f.Name);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
const oldNum = (name) => {
|
|
1511
|
+
const v = this.GetFieldByName(name)?.OldValue;
|
|
1512
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : null;
|
|
1513
|
+
};
|
|
1514
|
+
const sandboxErrors = ValidateAgentInheritanceAndSandbox({
|
|
1515
|
+
Target: {
|
|
1516
|
+
ID: this.ID,
|
|
1517
|
+
IsSaved: this.IsSaved,
|
|
1518
|
+
BaseAgentID: this.BaseAgentID,
|
|
1519
|
+
PreSaveBaseAgentID: this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID,
|
|
1520
|
+
OwnerUserID: this.OwnerUserID,
|
|
1521
|
+
PreSaveOwnerUserID: this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID,
|
|
1522
|
+
CategoryID: this.CategoryID,
|
|
1523
|
+
PreSaveCategoryID: this.GetFieldByName('CategoryID')?.OldValue ?? null,
|
|
1524
|
+
TypeID: this.TypeID,
|
|
1525
|
+
PreSaveTypeID: this.GetFieldByName('TypeID')?.OldValue ?? null,
|
|
1526
|
+
InstantiationMode: this.InstantiationMode,
|
|
1527
|
+
DriverClass: this.DriverClass,
|
|
1528
|
+
DriverClassDirty: this.GetFieldByName('DriverClass')?.Dirty ?? false,
|
|
1529
|
+
Isolation: this.Isolation,
|
|
1530
|
+
ExposeAsAction: this.ExposeAsAction,
|
|
1531
|
+
MaxCostPerRun: this.MaxCostPerRun,
|
|
1532
|
+
MaxTokensPerRun: this.MaxTokensPerRun,
|
|
1533
|
+
MaxTimePerRun: this.MaxTimePerRun,
|
|
1534
|
+
MaxIterationsPerRun: this.MaxIterationsPerRun,
|
|
1535
|
+
SearchScopeAccess: this.SearchScopeAccess,
|
|
1536
|
+
RequirePlanMode: this.RequirePlanMode,
|
|
1537
|
+
SupportsPlanMode: this.SupportsPlanMode,
|
|
1538
|
+
AcceptUnregisteredFiles: this.AcceptUnregisteredFiles,
|
|
1539
|
+
AllowEphemeralClientTools: this.AllowEphemeralClientTools,
|
|
1540
|
+
AcceptsSkills: this.AcceptsSkills,
|
|
1541
|
+
SkillActivationMode: this.SkillActivationMode,
|
|
1542
|
+
AllowMemoryWrite: this.AllowMemoryWrite,
|
|
1543
|
+
MinExecutionsPerRun: this.MinExecutionsPerRun,
|
|
1544
|
+
MaxExecutionsPerRun: this.MaxExecutionsPerRun,
|
|
1545
|
+
MaxSubAgentConsultRounds: this.MaxSubAgentConsultRounds,
|
|
1546
|
+
PayloadDownstreamPaths: this.PayloadDownstreamPaths,
|
|
1547
|
+
PayloadUpstreamPaths: this.PayloadUpstreamPaths,
|
|
1548
|
+
PayloadSelfReadPaths: this.PayloadSelfReadPaths,
|
|
1549
|
+
PayloadSelfWritePaths: this.PayloadSelfWritePaths,
|
|
1550
|
+
PayloadScope: this.PayloadScope,
|
|
1551
|
+
StartingPayloadValidationMode: this.StartingPayloadValidationMode,
|
|
1552
|
+
FinalPayloadValidationMode: this.FinalPayloadValidationMode,
|
|
1553
|
+
FinalPayloadValidationMaxRetries: this.FinalPayloadValidationMaxRetries,
|
|
1554
|
+
ArtifactCreationMode: this.ArtifactCreationMode,
|
|
1555
|
+
MessageMode: this.MessageMode,
|
|
1556
|
+
MaxMessages: this.MaxMessages,
|
|
1557
|
+
AttachmentRootPath: this.AttachmentRootPath,
|
|
1558
|
+
InlineStorageThresholdBytes: this.InlineStorageThresholdBytes,
|
|
1559
|
+
ContextWindowMaxTokens: this.ContextWindowMaxTokens,
|
|
1560
|
+
MaxNotesToInject: this.MaxNotesToInject,
|
|
1561
|
+
MaxExamplesToInject: this.MaxExamplesToInject,
|
|
1562
|
+
NoteRetentionDays: this.NoteRetentionDays,
|
|
1563
|
+
ExampleRetentionDays: this.ExampleRetentionDays,
|
|
1564
|
+
AutoArchiveEnabled: this.AutoArchiveEnabled,
|
|
1565
|
+
ScopeConfig: this.ScopeConfig,
|
|
1566
|
+
AgentTypePromptParams: this.AgentTypePromptParams,
|
|
1567
|
+
Configuration: this.Configuration,
|
|
1568
|
+
PreSaveConfiguration: this.GetFieldByName('Configuration')?.OldValue ?? null,
|
|
1569
|
+
TypeConfiguration: this.TypeConfiguration,
|
|
1570
|
+
DirtyFields: dirtyFieldNames,
|
|
1571
|
+
PreSaveLimits: {
|
|
1572
|
+
MaxCostPerRun: oldNum('MaxCostPerRun'),
|
|
1573
|
+
MaxTokensPerRun: oldNum('MaxTokensPerRun'),
|
|
1574
|
+
MaxTimePerRun: oldNum('MaxTimePerRun'),
|
|
1575
|
+
MaxIterationsPerRun: oldNum('MaxIterationsPerRun'),
|
|
1576
|
+
MaxExecutionsPerRun: oldNum('MaxExecutionsPerRun'),
|
|
1577
|
+
MaxSubAgentConsultRounds: oldNum('MaxSubAgentConsultRounds'),
|
|
1578
|
+
ContextWindowMaxTokens: oldNum('ContextWindowMaxTokens'),
|
|
1579
|
+
MaxNotesToInject: oldNum('MaxNotesToInject'),
|
|
1580
|
+
MaxExamplesToInject: oldNum('MaxExamplesToInject'),
|
|
1581
|
+
NoteRetentionDays: oldNum('NoteRetentionDays'),
|
|
1582
|
+
ExampleRetentionDays: oldNum('ExampleRetentionDays'),
|
|
1583
|
+
MaxMessages: oldNum('MaxMessages'),
|
|
1584
|
+
InlineStorageThresholdBytes: oldNum('InlineStorageThresholdBytes'),
|
|
1585
|
+
FinalPayloadValidationMaxRetries: oldNum('FinalPayloadValidationMaxRetries'),
|
|
1586
|
+
},
|
|
1587
|
+
},
|
|
1588
|
+
User: user,
|
|
1589
|
+
Provider: this.ProviderToUse,
|
|
1590
|
+
AllAgents: allAgents,
|
|
1591
|
+
AllPermissions: allPermissions,
|
|
1592
|
+
AllCategories: allCategories,
|
|
1593
|
+
AllAgentTypes: allAgentTypes,
|
|
1594
|
+
});
|
|
1595
|
+
if (sandboxErrors.length > 0) {
|
|
1596
|
+
result.Errors.push(...sandboxErrors);
|
|
1597
|
+
result.Success = result.Success && sandboxErrors.every((e) => e.Type !== ValidationErrorType.Failure);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
// 2. TypeConfiguration ⊨ ConfigSchema invariant
|
|
41
1601
|
const configJson = this.TypeConfiguration;
|
|
42
1602
|
if (!configJson || configJson.trim().length === 0) {
|
|
43
|
-
return result;
|
|
1603
|
+
return result;
|
|
44
1604
|
}
|
|
45
1605
|
const configDirty = this.GetFieldByName('TypeConfiguration')?.Dirty ?? false;
|
|
46
1606
|
const typeDirty = this.GetFieldByName('TypeID')?.Dirty ?? false;
|
|
47
1607
|
if (this.IsSaved && !configDirty && !typeDirty) {
|
|
48
|
-
return result;
|
|
1608
|
+
return result;
|
|
49
1609
|
}
|
|
50
1610
|
const schemaJson = await this.loadTypeConfigSchema();
|
|
51
1611
|
const errors = BuildTypeConfigurationValidationErrors(configJson, schemaJson);
|
|
52
1612
|
if (errors.length > 0) {
|
|
53
1613
|
result.Errors.push(...errors);
|
|
54
|
-
result.Success = errors.every((e) => e.Type !== ValidationErrorType.Failure);
|
|
1614
|
+
result.Success = result.Success && errors.every((e) => e.Type !== ValidationErrorType.Failure);
|
|
55
1615
|
}
|
|
56
1616
|
return result;
|
|
57
1617
|
}
|
|
58
1618
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
1619
|
+
* Copies core capability defaults from `baseAgent` onto a newly-created derived instance
|
|
1620
|
+
* ONLY for fields the caller left untouched (not dirty). This ensures newly minted instances
|
|
1621
|
+
* like *Pepper* immediately inherit `TypeID`, `AcceptsSkills`, `SkillActivationMode`,
|
|
1622
|
+
* `ModelSelectionMode`, `Isolation`, and memory settings without requiring every caller to
|
|
1623
|
+
* manually copy 20 columns.
|
|
1624
|
+
*
|
|
1625
|
+
* Note (C-R1-1 vs R5-1): On GraphQL creates (`NewRecord()` + `SetMany(input)`), untouched
|
|
1626
|
+
* columns arrive with `Dirty === false`, `NeverSet === false`, and their SQL default value.
|
|
1627
|
+
* For general overridable columns (e.g. `InjectNotes = true`), `!Dirty` + SQL default is
|
|
1628
|
+
* treated as untouched so parent values inherit cleanly (meaning an explicit create write equal
|
|
1629
|
+
* to the SQL default under a non-default base inherits the base value unless set via
|
|
1630
|
+
* `Configuration` or updated after create). For the 4 strict-default narrow-only columns
|
|
1631
|
+
* (`SearchScopeAccess`, `AcceptUnregisteredFiles`, `AcceptsSkills`, `SkillActivationMode`),
|
|
1632
|
+
* `NeverSet === true` is required so explicit strict restrictions are never loosened.
|
|
62
1633
|
*/
|
|
1634
|
+
inheritDefaultsFromBaseAgent(baseAgent, allAgents, allCategories, allAgentTypes) {
|
|
1635
|
+
const nonLegacySqlDefaults = {
|
|
1636
|
+
AcceptsSkills: 'None',
|
|
1637
|
+
Isolation: 'InProcess',
|
|
1638
|
+
MaxCostPerRun: null,
|
|
1639
|
+
MaxTokensPerRun: null,
|
|
1640
|
+
MaxTimePerRun: null,
|
|
1641
|
+
MaxIterationsPerRun: null,
|
|
1642
|
+
};
|
|
1643
|
+
const isFieldAtSqlDefault = (fieldName) => {
|
|
1644
|
+
const currentVal = this[fieldName];
|
|
1645
|
+
const keyStr = String(fieldName);
|
|
1646
|
+
if (Object.prototype.hasOwnProperty.call(LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, keyStr)) {
|
|
1647
|
+
const legacyKey = keyStr;
|
|
1648
|
+
return IsLegacyAIAgentConfigSqlDefault(legacyKey, currentVal);
|
|
1649
|
+
}
|
|
1650
|
+
if (Object.prototype.hasOwnProperty.call(nonLegacySqlDefaults, keyStr)) {
|
|
1651
|
+
return currentVal === nonLegacySqlDefaults[fieldName];
|
|
1652
|
+
}
|
|
1653
|
+
return false;
|
|
1654
|
+
};
|
|
1655
|
+
// R5-1: Never treat a written (`NeverSet === false`) strict SQL default as untouched on the
|
|
1656
|
+
// 4 narrow-only columns whose SQL default is the strict side (`SearchScopeAccess = 'None'`,
|
|
1657
|
+
// `AcceptUnregisteredFiles = false`, `AcceptsSkills = 'None'`, `SkillActivationMode = 'RequestedOnly'`),
|
|
1658
|
+
// otherwise an explicit caller restriction is silently loosened to the base agent's value!
|
|
1659
|
+
const STRICT_DEFAULT_NARROW_ONLY_FIELDS = new Set([
|
|
1660
|
+
'SearchScopeAccess',
|
|
1661
|
+
'AcceptUnregisteredFiles',
|
|
1662
|
+
'AcceptsSkills',
|
|
1663
|
+
'SkillActivationMode',
|
|
1664
|
+
]);
|
|
1665
|
+
const copyIfNotDirty = (fieldName, overrideVal, clampLooseDbDefault) => {
|
|
1666
|
+
const field = this.GetFieldByName(String(fieldName));
|
|
1667
|
+
if (!field)
|
|
1668
|
+
return;
|
|
1669
|
+
const val = overrideVal !== undefined ? overrideVal : baseAgent[fieldName];
|
|
1670
|
+
if (val === undefined)
|
|
1671
|
+
return;
|
|
1672
|
+
const preserveWrittenStrictDefault = STRICT_DEFAULT_NARROW_ONLY_FIELDS.has(String(fieldName));
|
|
1673
|
+
const isUntouched = preserveWrittenStrictDefault
|
|
1674
|
+
? !field.Dirty && field.NeverSet
|
|
1675
|
+
: !field.Dirty && (field.NeverSet || isFieldAtSqlDefault(fieldName));
|
|
1676
|
+
const isLooseDbDefault = clampLooseDbDefault !== undefined && this[fieldName] === clampLooseDbDefault;
|
|
1677
|
+
if (isUntouched || isLooseDbDefault) {
|
|
1678
|
+
this[fieldName] = val;
|
|
1679
|
+
}
|
|
1680
|
+
};
|
|
1681
|
+
// Walk full ancestor chain so newly-created derived instances inherit the strictest
|
|
1682
|
+
// ancestor limits and narrow-only capability booleans (prevents DB defaults like
|
|
1683
|
+
// AllowEphemeralClientTools=1 from colliding with a false ancestor in ValidateAsync).
|
|
1684
|
+
const ancestors = [baseAgent];
|
|
1685
|
+
if (allAgents && allAgents.length > 0) {
|
|
1686
|
+
const byId = IndexByUUID(allAgents);
|
|
1687
|
+
const seen = new UUIDSet([baseAgent.ID]);
|
|
1688
|
+
let cur = baseAgent;
|
|
1689
|
+
while (cur?.BaseAgentID && ancestors.length <= MAX_AGENT_INHERITANCE_DEPTH) {
|
|
1690
|
+
if (seen.Has(cur.BaseAgentID))
|
|
1691
|
+
break;
|
|
1692
|
+
seen.Add(cur.BaseAgentID);
|
|
1693
|
+
const parent = byId.Get(cur.BaseAgentID);
|
|
1694
|
+
if (!parent)
|
|
1695
|
+
break;
|
|
1696
|
+
ancestors.unshift(parent);
|
|
1697
|
+
cur = parent;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
const ancestorConfigs = ancestors.map((a) => ParseAgentConfiguration(a.Configuration));
|
|
1701
|
+
if (!this.TypeID && baseAgent.TypeID) {
|
|
1702
|
+
this.TypeID = baseAgent.TypeID;
|
|
1703
|
+
}
|
|
1704
|
+
if (!this.CategoryID && baseAgent.CategoryID) {
|
|
1705
|
+
this.CategoryID = baseAgent.CategoryID;
|
|
1706
|
+
}
|
|
1707
|
+
const defaultPolicyLayers = collectDefaultPolicyLayers([...ancestors, { CategoryID: this.CategoryID, TypeID: this.TypeID }], allCategories, allAgentTypes);
|
|
1708
|
+
const minFiniteRebase = (layerPicker, jsonPicker, legacyPicker, sqlDefault = null) => {
|
|
1709
|
+
const minVal = (a, b) => {
|
|
1710
|
+
if (typeof b !== 'number' || !Number.isFinite(b))
|
|
1711
|
+
return a;
|
|
1712
|
+
return a === null ? b : Math.min(a, b);
|
|
1713
|
+
};
|
|
1714
|
+
let seed = null;
|
|
1715
|
+
for (const layer of defaultPolicyLayers) {
|
|
1716
|
+
seed = minVal(seed, layerPicker(layer));
|
|
1717
|
+
}
|
|
1718
|
+
if (ancestors.length > 0) {
|
|
1719
|
+
const exp0 = jsonPicker(ancestorConfigs[0]);
|
|
1720
|
+
const leg0 = legacyPicker(ancestors[0]);
|
|
1721
|
+
const leg0Eff = exp0 === undefined && sqlDefault !== null && leg0 === sqlDefault && seed !== null ? null : leg0;
|
|
1722
|
+
seed = minVal(seed, exp0);
|
|
1723
|
+
seed = minVal(seed, leg0Eff);
|
|
1724
|
+
}
|
|
1725
|
+
return FoldRebaseAwareChain({
|
|
1726
|
+
Nodes: ancestors,
|
|
1727
|
+
NodeConfigs: ancestorConfigs,
|
|
1728
|
+
Seed: seed,
|
|
1729
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1730
|
+
const exp = jsonPicker(cfg);
|
|
1731
|
+
const leg = legacyPicker(anc);
|
|
1732
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
1733
|
+
if (exp === null)
|
|
1734
|
+
return null;
|
|
1735
|
+
if (typeof exp === 'number' && Number.isFinite(exp))
|
|
1736
|
+
return exp;
|
|
1737
|
+
if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault)
|
|
1738
|
+
return leg;
|
|
1739
|
+
return undefined;
|
|
1740
|
+
}
|
|
1741
|
+
if (typeof exp === 'number' && Number.isFinite(exp)) {
|
|
1742
|
+
if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault) {
|
|
1743
|
+
return Math.min(exp, leg);
|
|
1744
|
+
}
|
|
1745
|
+
return exp;
|
|
1746
|
+
}
|
|
1747
|
+
if (typeof leg === 'number' && Number.isFinite(leg) && leg !== sqlDefault)
|
|
1748
|
+
return leg;
|
|
1749
|
+
return undefined;
|
|
1750
|
+
},
|
|
1751
|
+
Narrow: (acc, next) => minVal(acc, next),
|
|
1752
|
+
});
|
|
1753
|
+
};
|
|
1754
|
+
const narrowSkillMode = (acc, v) => {
|
|
1755
|
+
if (v == null)
|
|
1756
|
+
return acc;
|
|
1757
|
+
return acc === null || SKILL_ACTIVATION_RANK[v] < SKILL_ACTIVATION_RANK[acc] ? v : acc;
|
|
1758
|
+
};
|
|
1759
|
+
let seedSkill = null;
|
|
1760
|
+
for (const layer of defaultPolicyLayers) {
|
|
1761
|
+
seedSkill = narrowSkillMode(seedSkill, layer.skills?.activationMode);
|
|
1762
|
+
}
|
|
1763
|
+
if (ancestors.length > 0) {
|
|
1764
|
+
seedSkill = narrowSkillMode(seedSkill, ancestorConfigs[0]?.skills?.activationMode);
|
|
1765
|
+
seedSkill = narrowSkillMode(seedSkill, ancestors[0].SkillActivationMode);
|
|
1766
|
+
}
|
|
1767
|
+
const strictestSkillMode = FoldRebaseAwareChain({
|
|
1768
|
+
Nodes: ancestors,
|
|
1769
|
+
NodeConfigs: ancestorConfigs,
|
|
1770
|
+
Seed: seedSkill,
|
|
1771
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1772
|
+
const exp = cfg?.skills?.activationMode ?? null;
|
|
1773
|
+
const leg = anc.SkillActivationMode ?? null;
|
|
1774
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
1775
|
+
if (exp != null)
|
|
1776
|
+
return exp;
|
|
1777
|
+
return leg != null && leg !== 'RequestedOnly' ? leg : undefined;
|
|
1778
|
+
}
|
|
1779
|
+
if (exp != null && leg != null) {
|
|
1780
|
+
return SKILL_ACTIVATION_RANK[leg] < SKILL_ACTIVATION_RANK[exp] ? leg : exp;
|
|
1781
|
+
}
|
|
1782
|
+
if (exp != null)
|
|
1783
|
+
return exp;
|
|
1784
|
+
const isNonInst = Boolean(anc.BaseAgentID) && (anc.InstantiationMode ?? 'None') === 'None';
|
|
1785
|
+
return leg != null && (leg !== 'RequestedOnly' || !isNonInst) ? leg : undefined;
|
|
1786
|
+
},
|
|
1787
|
+
Narrow: (acc, next) => narrowSkillMode(acc, next),
|
|
1788
|
+
}) ?? baseAgent.SkillActivationMode ?? 'RequestedOnly';
|
|
1789
|
+
const ancestorSearchCeiling = computeAncestorSearchScopeCeiling(defaultPolicyLayers, ancestors, ancestorConfigs);
|
|
1790
|
+
const strictestSearchAccess = ancestorSearchCeiling ?? 'None';
|
|
1791
|
+
const strictestAcceptsSkills = FoldRebaseAwareChain({
|
|
1792
|
+
Nodes: ancestors,
|
|
1793
|
+
NodeConfigs: ancestorConfigs,
|
|
1794
|
+
Seed: ancestors[0]?.AcceptsSkills ?? baseAgent.AcceptsSkills ?? 'None',
|
|
1795
|
+
GetNodeValue: (anc) => anc.AcceptsSkills ?? undefined,
|
|
1796
|
+
Narrow: (acc, next) => (ACCEPTS_SKILLS_RANK[next] < ACCEPTS_SKILLS_RANK[acc] ? next : acc),
|
|
1797
|
+
});
|
|
1798
|
+
const foldBoolAndRebase = (layerPicker, jsonPicker, legacyPicker, sqlDefault, fallback) => {
|
|
1799
|
+
const fAnd = (acc, v) => typeof v !== 'boolean' ? acc : acc === null ? v : acc && v;
|
|
1800
|
+
let seed = null;
|
|
1801
|
+
for (const layer of defaultPolicyLayers) {
|
|
1802
|
+
seed = fAnd(seed, layerPicker(layer));
|
|
1803
|
+
}
|
|
1804
|
+
if (ancestors.length > 0) {
|
|
1805
|
+
const exp0 = jsonPicker(ancestorConfigs[0]);
|
|
1806
|
+
const leg0 = legacyPicker(ancestors[0]);
|
|
1807
|
+
seed =
|
|
1808
|
+
typeof exp0 === 'boolean' && typeof leg0 === 'boolean'
|
|
1809
|
+
? fAnd(seed, exp0 && leg0)
|
|
1810
|
+
: fAnd(seed, exp0 ?? leg0);
|
|
1811
|
+
}
|
|
1812
|
+
return (FoldRebaseAwareChain({
|
|
1813
|
+
Nodes: ancestors,
|
|
1814
|
+
NodeConfigs: ancestorConfigs,
|
|
1815
|
+
Seed: seed,
|
|
1816
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1817
|
+
const exp = jsonPicker(cfg);
|
|
1818
|
+
const leg = legacyPicker(anc);
|
|
1819
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
1820
|
+
if (typeof exp === 'boolean')
|
|
1821
|
+
return exp;
|
|
1822
|
+
return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
|
|
1823
|
+
}
|
|
1824
|
+
if (typeof exp === 'boolean' && typeof leg === 'boolean')
|
|
1825
|
+
return exp && leg;
|
|
1826
|
+
if (typeof exp === 'boolean')
|
|
1827
|
+
return exp;
|
|
1828
|
+
return typeof leg === 'boolean' && leg !== sqlDefault ? leg : undefined;
|
|
1829
|
+
},
|
|
1830
|
+
Narrow: (acc, next) => fAnd(acc, next),
|
|
1831
|
+
}) ?? fallback);
|
|
1832
|
+
};
|
|
1833
|
+
const seedReqPlan = defaultPolicyLayers.some((l) => l.execution?.requirePlanMode === true) ||
|
|
1834
|
+
(ancestors.length > 0 &&
|
|
1835
|
+
(ancestorConfigs[0]?.execution?.requirePlanMode === true || ancestors[0].RequirePlanMode === true));
|
|
1836
|
+
const strictestRequirePlan = FoldRebaseAwareChain({
|
|
1837
|
+
Nodes: ancestors,
|
|
1838
|
+
NodeConfigs: ancestorConfigs,
|
|
1839
|
+
Seed: seedReqPlan,
|
|
1840
|
+
GetNodeValue: (anc, cfg, idx) => {
|
|
1841
|
+
const exp = cfg?.execution?.requirePlanMode;
|
|
1842
|
+
const leg = anc.RequirePlanMode;
|
|
1843
|
+
if (idx > 0 && cfg?.allowWidenFromBase === true) {
|
|
1844
|
+
if (typeof exp === 'boolean')
|
|
1845
|
+
return exp;
|
|
1846
|
+
return leg === true ? true : undefined;
|
|
1847
|
+
}
|
|
1848
|
+
if (exp === true || leg === true)
|
|
1849
|
+
return true;
|
|
1850
|
+
return typeof exp === 'boolean' ? exp : undefined;
|
|
1851
|
+
},
|
|
1852
|
+
Narrow: (acc, next) => acc || next,
|
|
1853
|
+
});
|
|
1854
|
+
copyIfNotDirty('ModelSelectionMode');
|
|
1855
|
+
copyIfNotDirty('AcceptsSkills', strictestAcceptsSkills);
|
|
1856
|
+
copyIfNotDirty('SkillActivationMode', strictestSkillMode);
|
|
1857
|
+
copyIfNotDirty('SearchScopeAccess', strictestSearchAccess);
|
|
1858
|
+
copyIfNotDirty('ArtifactCreationMode');
|
|
1859
|
+
copyIfNotDirty('DefaultArtifactTypeID');
|
|
1860
|
+
copyIfNotDirty('InjectNotes');
|
|
1861
|
+
copyIfNotDirty('MaxNotesToInject', minFiniteRebase((l) => l.memory?.maxNotesToInject, (cfg) => cfg?.memory?.maxNotesToInject, (a) => a.MaxNotesToInject, 5 // SQL schema default DF_AIAgent_MaxNotesToInject
|
|
1862
|
+
) ?? baseAgent.MaxNotesToInject);
|
|
1863
|
+
copyIfNotDirty('NoteInjectionStrategy');
|
|
1864
|
+
copyIfNotDirty('InjectExamples');
|
|
1865
|
+
copyIfNotDirty('MaxExamplesToInject', minFiniteRebase((l) => l.memory?.maxExamplesToInject, (cfg) => cfg?.memory?.maxExamplesToInject, (a) => a.MaxExamplesToInject, 3 // SQL schema default DF_AIAgent_MaxExamplesToInject
|
|
1866
|
+
) ?? baseAgent.MaxExamplesToInject);
|
|
1867
|
+
copyIfNotDirty('ExampleInjectionStrategy');
|
|
1868
|
+
copyIfNotDirty('NoteRetentionDays', minFiniteRebase((l) => l.memory?.noteRetentionDays, (cfg) => cfg?.memory?.noteRetentionDays, (a) => a.NoteRetentionDays, 90 // SQL schema default DF_AIAgent_NoteRetentionDays
|
|
1869
|
+
));
|
|
1870
|
+
copyIfNotDirty('ExampleRetentionDays', minFiniteRebase((l) => l.memory?.exampleRetentionDays, (cfg) => cfg?.memory?.exampleRetentionDays, (a) => a.ExampleRetentionDays, 180 // SQL schema default DF_AIAgent_ExampleRetentionDays
|
|
1871
|
+
));
|
|
1872
|
+
copyIfNotDirty('AutoArchiveEnabled');
|
|
1873
|
+
copyIfNotDirty('AllowMemoryWrite', foldBoolAndRebase((l) => l.memory?.allowMemoryWrite, (cfg) => cfg?.memory?.allowMemoryWrite, (a) => a.AllowMemoryWrite, true, baseAgent.AllowMemoryWrite), true);
|
|
1874
|
+
copyIfNotDirty('DeclareActionsAsNativeTools');
|
|
1875
|
+
let strictestIso = baseAgent.Isolation ?? 'InProcess';
|
|
1876
|
+
for (const a of ancestors) {
|
|
1877
|
+
const iso = a.Isolation ?? 'InProcess';
|
|
1878
|
+
if ((ISOLATION_RANK[iso] ?? 0) > (ISOLATION_RANK[strictestIso] ?? 0)) {
|
|
1879
|
+
strictestIso = iso;
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
copyIfNotDirty('Isolation', strictestIso, 'InProcess');
|
|
1883
|
+
copyIfNotDirty('SupportsPlanMode', foldBoolAndRebase((l) => l.execution?.supportsPlanMode, (cfg) => cfg?.execution?.supportsPlanMode, (a) => a.SupportsPlanMode, true, baseAgent.SupportsPlanMode), true);
|
|
1884
|
+
copyIfNotDirty('RequirePlanMode', strictestRequirePlan, false);
|
|
1885
|
+
copyIfNotDirty('AllowEphemeralClientTools', foldBoolAndRebase((l) => l.clientTools?.allowEphemeral, (cfg) => cfg?.clientTools?.allowEphemeral, (a) => a.AllowEphemeralClientTools, true, baseAgent.AllowEphemeralClientTools), true);
|
|
1886
|
+
copyIfNotDirty('AcceptUnregisteredFiles', foldBoolAndRebase((l) => l.attachments?.acceptUnregisteredFiles, (cfg) => cfg?.attachments?.acceptUnregisteredFiles, (a) => a.AcceptUnregisteredFiles, false, baseAgent.AcceptUnregisteredFiles));
|
|
1887
|
+
copyIfNotDirty('MaxCostPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxCostPerRun));
|
|
1888
|
+
copyIfNotDirty('MaxTokensPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxTokensPerRun));
|
|
1889
|
+
copyIfNotDirty('MaxTimePerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxTimePerRun));
|
|
1890
|
+
copyIfNotDirty('MaxIterationsPerRun', minFiniteRebase(() => undefined, () => undefined, (a) => a.MaxIterationsPerRun));
|
|
1891
|
+
copyIfNotDirty('MaxExecutionsPerRun', minFiniteRebase((l) => l.subAgentExecution?.maxExecutionsPerRun, (cfg) => cfg?.subAgentExecution?.maxExecutionsPerRun, (a) => a.MaxExecutionsPerRun));
|
|
1892
|
+
copyIfNotDirty('MaxSubAgentConsultRounds', minFiniteRebase((l) => l.subAgentExecution?.maxConsultRounds, (cfg) => cfg?.subAgentExecution?.maxConsultRounds, (a) => a.MaxSubAgentConsultRounds));
|
|
1893
|
+
copyIfNotDirty('MessageMode');
|
|
1894
|
+
copyIfNotDirty('MaxMessages', minFiniteRebase((l) => l.attachments?.maxMessages, (cfg) => cfg?.attachments?.maxMessages, (a) => a.MaxMessages));
|
|
1895
|
+
copyIfNotDirty('AttachmentRootPath');
|
|
1896
|
+
copyIfNotDirty('InlineStorageThresholdBytes', minFiniteRebase((l) => l.attachments?.inlineStorageThresholdBytes, (cfg) => cfg?.attachments?.inlineStorageThresholdBytes, (a) => a.InlineStorageThresholdBytes));
|
|
1897
|
+
copyIfNotDirty('PayloadDownstreamPaths');
|
|
1898
|
+
copyIfNotDirty('PayloadUpstreamPaths');
|
|
1899
|
+
copyIfNotDirty('PayloadSelfReadPaths');
|
|
1900
|
+
copyIfNotDirty('PayloadSelfWritePaths');
|
|
1901
|
+
copyIfNotDirty('PayloadScope');
|
|
1902
|
+
copyIfNotDirty('StartingPayloadValidationMode');
|
|
1903
|
+
copyIfNotDirty('FinalPayloadValidationMode');
|
|
1904
|
+
copyIfNotDirty('FinalPayloadValidationMaxRetries', minFiniteRebase((l) => l.payload?.finalValidationMaxRetries, (cfg) => cfg?.payload?.finalValidationMaxRetries, (a) => a.FinalPayloadValidationMaxRetries, 3 // SQL schema default DF_AIAgent_FinalPayloadValidationMaxRetries
|
|
1905
|
+
) ?? baseAgent.FinalPayloadValidationMaxRetries);
|
|
1906
|
+
copyIfNotDirty('ScopeConfig');
|
|
1907
|
+
copyIfNotDirty('EnableContextCompression');
|
|
1908
|
+
copyIfNotDirty('ContextCompressionMessageThreshold');
|
|
1909
|
+
copyIfNotDirty('ContextCompressionPromptID');
|
|
1910
|
+
copyIfNotDirty('ContextCompressionMessageRetentionCount');
|
|
1911
|
+
copyIfNotDirty('RerankerConfiguration');
|
|
1912
|
+
copyIfNotDirty('ContextWindowMaxTokens', minFiniteRebase((l) => l.contextWindow?.maxTokens, (cfg) => cfg?.contextWindow?.maxTokens, (a) => a.ContextWindowMaxTokens));
|
|
1913
|
+
copyIfNotDirty('CompactionTriggerPercent');
|
|
1914
|
+
copyIfNotDirty('CompactionTargetPercent');
|
|
1915
|
+
copyIfNotDirty('ConversationSummaryPromptID');
|
|
1916
|
+
return ancestorSearchCeiling;
|
|
1917
|
+
}
|
|
1918
|
+
findRootBaseAgentId(start, allAgents) {
|
|
1919
|
+
const agentsById = IndexByUUID(allAgents);
|
|
1920
|
+
const visited = new UUIDSet([start.ID]);
|
|
1921
|
+
let cursor = start;
|
|
1922
|
+
let hops = 0;
|
|
1923
|
+
while (cursor.BaseAgentID && hops < MAX_AGENT_INHERITANCE_DEPTH) {
|
|
1924
|
+
if (visited.Has(cursor.BaseAgentID)) {
|
|
1925
|
+
break;
|
|
1926
|
+
}
|
|
1927
|
+
visited.Add(cursor.BaseAgentID);
|
|
1928
|
+
const parent = agentsById.Get(cursor.BaseAgentID);
|
|
1929
|
+
if (!parent) {
|
|
1930
|
+
return cursor.BaseAgentID;
|
|
1931
|
+
}
|
|
1932
|
+
cursor = parent;
|
|
1933
|
+
hops++;
|
|
1934
|
+
}
|
|
1935
|
+
return cursor.ID;
|
|
1936
|
+
}
|
|
1937
|
+
findActiveSiblingsForOwnerAndRoot(allAgents, ownerUserId, rootBaseId, excludeAgentId) {
|
|
1938
|
+
return allAgents.filter((a) => {
|
|
1939
|
+
if (a.Status !== 'Active' || !a.BaseAgentID || !UUIDsEqual(a.OwnerUserID, ownerUserId)) {
|
|
1940
|
+
return false;
|
|
1941
|
+
}
|
|
1942
|
+
if (excludeAgentId && UUIDsEqual(a.ID, excludeAgentId)) {
|
|
1943
|
+
return false;
|
|
1944
|
+
}
|
|
1945
|
+
const aRoot = a.RootBaseAgentID ?? this.findRootBaseAgentId(a, allAgents);
|
|
1946
|
+
return UUIDsEqual(aRoot, rootBaseId);
|
|
1947
|
+
});
|
|
1948
|
+
}
|
|
1949
|
+
async clearOtherPrimaryInstances(ownerUserId, rootBaseId, currentAgentId) {
|
|
1950
|
+
const rv = new RunView(this.RunViewProviderToUse);
|
|
1951
|
+
const safeOwner = EscapeSQLString(ownerUserId);
|
|
1952
|
+
const res = await rv.RunView({
|
|
1953
|
+
EntityName: 'MJ: AI Agents',
|
|
1954
|
+
ExtraFilter: `OwnerUserID='${safeOwner}' AND BaseAgentID IS NOT NULL AND IsPrimaryInstance=1 AND Status='Active'`,
|
|
1955
|
+
ResultType: 'entity_object',
|
|
1956
|
+
}, this.ContextCurrentUser);
|
|
1957
|
+
if (!res.Success || res.Results.length === 0) {
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
const allAgents = await this.loadAllAgentsForGuard();
|
|
1961
|
+
for (const sibling of res.Results) {
|
|
1962
|
+
if (UUIDsEqual(sibling.ID, currentAgentId)) {
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
const sibRoot = sibling.RootBaseAgentID ?? this.findRootBaseAgentId(sibling, allAgents);
|
|
1966
|
+
if (UUIDsEqual(sibRoot, rootBaseId)) {
|
|
1967
|
+
sibling.IsPrimaryInstance = false;
|
|
1968
|
+
await sibling.Save();
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
async loadGuardMetadataBatch() {
|
|
1973
|
+
// R5 Follow-up #5 & C-R4-2: single batched RunViews with ResultType: 'simple' + minimal
|
|
1974
|
+
// explicit Fields (replaces 7 full-table entity_object queries on derived creates) and
|
|
1975
|
+
// fail-closed on read errors OR FLS-omitted requested guard columns.
|
|
1976
|
+
const AGENT_GUARD_FIELDS = [
|
|
1977
|
+
'ID', 'Name', 'BaseAgentID', 'RootBaseAgentID', 'OwnerUserID', 'Status',
|
|
1978
|
+
'CategoryID', 'TypeID', 'InstantiationMode', 'DriverClass', 'Isolation',
|
|
1979
|
+
'MaxCostPerRun', 'MaxTokensPerRun', 'MaxTimePerRun', 'MaxIterationsPerRun',
|
|
1980
|
+
'Configuration', 'TypeConfiguration', 'AgentTypePromptParams', 'ModelSelectionMode', 'AcceptsSkills',
|
|
1981
|
+
'SkillActivationMode', 'SearchScopeAccess', 'ScopeConfig', 'ArtifactCreationMode',
|
|
1982
|
+
'DefaultArtifactTypeID', 'InjectNotes', 'MaxNotesToInject', 'NoteInjectionStrategy',
|
|
1983
|
+
'InjectExamples', 'MaxExamplesToInject', 'ExampleInjectionStrategy',
|
|
1984
|
+
'NoteRetentionDays', 'ExampleRetentionDays', 'AutoArchiveEnabled',
|
|
1985
|
+
'AllowMemoryWrite', 'DeclareActionsAsNativeTools', 'SupportsPlanMode',
|
|
1986
|
+
'RequirePlanMode', 'AllowEphemeralClientTools', 'AcceptUnregisteredFiles',
|
|
1987
|
+
'MinExecutionsPerRun', 'MaxExecutionsPerRun', 'MaxSubAgentConsultRounds',
|
|
1988
|
+
'PayloadDownstreamPaths', 'PayloadUpstreamPaths', 'PayloadSelfReadPaths',
|
|
1989
|
+
'PayloadSelfWritePaths', 'PayloadScope', 'StartingPayloadValidationMode',
|
|
1990
|
+
'FinalPayloadValidationMode', 'FinalPayloadValidationMaxRetries',
|
|
1991
|
+
'MessageMode', 'MaxMessages', 'AttachmentRootPath', 'InlineStorageThresholdBytes',
|
|
1992
|
+
'EnableContextCompression', 'ContextCompressionMessageThreshold',
|
|
1993
|
+
'ContextCompressionPromptID', 'ContextCompressionMessageRetentionCount',
|
|
1994
|
+
'RerankerConfiguration', 'ContextWindowMaxTokens', 'CompactionTriggerPercent',
|
|
1995
|
+
'CompactionTargetPercent', 'ConversationSummaryPromptID',
|
|
1996
|
+
];
|
|
1997
|
+
const PERMISSION_GUARD_FIELDS = [
|
|
1998
|
+
'ID', 'AgentID', 'UserID', 'RoleID', 'CanView', 'CanRun', 'CanEdit', 'CanDelete',
|
|
1999
|
+
];
|
|
2000
|
+
const CATEGORY_GUARD_FIELDS = ['ID', 'ParentID', 'DefaultConfiguration'];
|
|
2001
|
+
const TYPE_GUARD_FIELDS = [
|
|
2002
|
+
'ID', 'DefaultAgentConfiguration', 'ContextCompressionMessageThreshold',
|
|
2003
|
+
'ContextCompressionPromptID', 'ContextCompressionMessageRetentionCount',
|
|
2004
|
+
'ContextWindowMaxTokens', 'CompactionTriggerPercent', 'CompactionTargetPercent',
|
|
2005
|
+
'ConversationSummaryPromptID',
|
|
2006
|
+
];
|
|
2007
|
+
// R7-1: Filter requested guard fields against the active provider's entity metadata so
|
|
2008
|
+
// hosts/databases whose schema has not yet received newly added columns (e.g. PostgreSQL
|
|
2009
|
+
// prior to the twin migration for AIAgent.Configuration) neither emit "not found in entity"
|
|
2010
|
+
// log noise nor misclassify schema-absent columns as field-level security denials.
|
|
2011
|
+
const hasEntityLookup = (p) => Boolean(p && 'EntityByName' in p && typeof p.EntityByName === 'function');
|
|
2012
|
+
const metadataProvider = IsMetadataProvider(this.ProviderToUse)
|
|
2013
|
+
? this.ProviderToUse
|
|
2014
|
+
: hasEntityLookup(this.RunViewProviderToUse)
|
|
2015
|
+
? this.RunViewProviderToUse
|
|
2016
|
+
: null;
|
|
2017
|
+
const filterExistingFields = (entityName, requested) => {
|
|
2018
|
+
const entityInfo = metadataProvider?.EntityByName(entityName);
|
|
2019
|
+
if (!entityInfo) {
|
|
2020
|
+
return [...requested];
|
|
2021
|
+
}
|
|
2022
|
+
return requested.filter((fieldName) => Boolean(entityInfo.FieldByName(fieldName)));
|
|
2023
|
+
};
|
|
2024
|
+
const agentFields = filterExistingFields('MJ: AI Agents', AGENT_GUARD_FIELDS);
|
|
2025
|
+
const permissionFields = filterExistingFields('MJ: AI Agent Permissions', PERMISSION_GUARD_FIELDS);
|
|
2026
|
+
const categoryFields = filterExistingFields('MJ: AI Agent Categories', CATEGORY_GUARD_FIELDS);
|
|
2027
|
+
const typeFields = filterExistingFields('MJ: AI Agent Types', TYPE_GUARD_FIELDS);
|
|
2028
|
+
const rv = new RunView(this.RunViewProviderToUse);
|
|
2029
|
+
const results = await rv.RunViews([
|
|
2030
|
+
{
|
|
2031
|
+
EntityName: 'MJ: AI Agents',
|
|
2032
|
+
ResultType: 'simple',
|
|
2033
|
+
Fields: agentFields,
|
|
2034
|
+
},
|
|
2035
|
+
{
|
|
2036
|
+
EntityName: 'MJ: AI Agent Permissions',
|
|
2037
|
+
ResultType: 'simple',
|
|
2038
|
+
Fields: permissionFields,
|
|
2039
|
+
},
|
|
2040
|
+
{
|
|
2041
|
+
EntityName: 'MJ: AI Agent Categories',
|
|
2042
|
+
ResultType: 'simple',
|
|
2043
|
+
Fields: categoryFields,
|
|
2044
|
+
},
|
|
2045
|
+
{
|
|
2046
|
+
EntityName: 'MJ: AI Agent Types',
|
|
2047
|
+
ResultType: 'simple',
|
|
2048
|
+
Fields: typeFields,
|
|
2049
|
+
},
|
|
2050
|
+
], this.ContextCurrentUser);
|
|
2051
|
+
const failed = results.find((r) => !r.Success);
|
|
2052
|
+
if (failed) {
|
|
2053
|
+
return {
|
|
2054
|
+
AllAgents: [],
|
|
2055
|
+
AllPermissions: [],
|
|
2056
|
+
AllCategories: [],
|
|
2057
|
+
AllAgentTypes: [],
|
|
2058
|
+
ErrorMessage: failed.ErrorMessage || 'Guard metadata RunViews query failed',
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
// R6 Follow-up #5, C-R4-2 & R7-1: Fail closed if field-level security silently omitted ANY
|
|
2062
|
+
// metadata-present requested guard column from a `'simple'` RunView projection (e.g. denied
|
|
2063
|
+
// `DefaultConfiguration`, `MaxCostPerRun`, `TypeConfiguration`, `RequirePlanMode`, etc.).
|
|
2064
|
+
const requiredGuardFieldsByResult = [
|
|
2065
|
+
{ Entity: 'MJ: AI Agents', Rows: results[0].Results, RequiredFields: agentFields },
|
|
2066
|
+
{ Entity: 'MJ: AI Agent Permissions', Rows: results[1].Results, RequiredFields: permissionFields },
|
|
2067
|
+
{ Entity: 'MJ: AI Agent Categories', Rows: results[2].Results, RequiredFields: categoryFields },
|
|
2068
|
+
{ Entity: 'MJ: AI Agent Types', Rows: results[3].Results, RequiredFields: typeFields },
|
|
2069
|
+
];
|
|
2070
|
+
for (const check of requiredGuardFieldsByResult) {
|
|
2071
|
+
if (check.Rows.length > 0) {
|
|
2072
|
+
const sample = check.Rows[0];
|
|
2073
|
+
const missingField = check.RequiredFields.find((f) => !sample || !Object.prototype.hasOwnProperty.call(sample, f));
|
|
2074
|
+
if (missingField) {
|
|
2075
|
+
return {
|
|
2076
|
+
AllAgents: [],
|
|
2077
|
+
AllPermissions: [],
|
|
2078
|
+
AllCategories: [],
|
|
2079
|
+
AllAgentTypes: [],
|
|
2080
|
+
ErrorMessage: `Required security guard field '${missingField}' was omitted from '${check.Entity}' query result (possible field-level security restriction).`,
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
return {
|
|
2086
|
+
AllAgents: results[0].Results,
|
|
2087
|
+
AllPermissions: results[1].Results,
|
|
2088
|
+
AllCategories: results[2].Results,
|
|
2089
|
+
AllAgentTypes: results[3].Results,
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
async loadAllAgentsForGuard() {
|
|
2093
|
+
const rv = new RunView(this.RunViewProviderToUse);
|
|
2094
|
+
const res = await rv.RunView({
|
|
2095
|
+
EntityName: 'MJ: AI Agents',
|
|
2096
|
+
ResultType: 'simple',
|
|
2097
|
+
Fields: ['ID', 'BaseAgentID', 'RootBaseAgentID'],
|
|
2098
|
+
}, this.ContextCurrentUser);
|
|
2099
|
+
return res.Success ? res.Results : [];
|
|
2100
|
+
}
|
|
2101
|
+
buildLegacyConfigValues() {
|
|
2102
|
+
return {
|
|
2103
|
+
ModelSelectionMode: this.ModelSelectionMode,
|
|
2104
|
+
DefaultPromptEffortLevel: this.DefaultPromptEffortLevel,
|
|
2105
|
+
ChatHandlingOption: this.ChatHandlingOption,
|
|
2106
|
+
SupportsPlanMode: this.SupportsPlanMode,
|
|
2107
|
+
RequirePlanMode: this.RequirePlanMode,
|
|
2108
|
+
DeclareActionsAsNativeTools: this.DeclareActionsAsNativeTools,
|
|
2109
|
+
EnableContextCompression: this.EnableContextCompression,
|
|
2110
|
+
ContextCompressionMessageThreshold: this.ContextCompressionMessageThreshold,
|
|
2111
|
+
ContextCompressionPromptID: this.ContextCompressionPromptID,
|
|
2112
|
+
ContextCompressionMessageRetentionCount: this.ContextCompressionMessageRetentionCount,
|
|
2113
|
+
ContextWindowMaxTokens: this.ContextWindowMaxTokens,
|
|
2114
|
+
CompactionTriggerPercent: this.CompactionTriggerPercent,
|
|
2115
|
+
CompactionTargetPercent: this.CompactionTargetPercent,
|
|
2116
|
+
ConversationSummaryPromptID: this.ConversationSummaryPromptID,
|
|
2117
|
+
InjectNotes: this.InjectNotes,
|
|
2118
|
+
MaxNotesToInject: this.MaxNotesToInject,
|
|
2119
|
+
NoteInjectionStrategy: this.NoteInjectionStrategy,
|
|
2120
|
+
InjectExamples: this.InjectExamples,
|
|
2121
|
+
MaxExamplesToInject: this.MaxExamplesToInject,
|
|
2122
|
+
ExampleInjectionStrategy: this.ExampleInjectionStrategy,
|
|
2123
|
+
NoteRetentionDays: this.NoteRetentionDays,
|
|
2124
|
+
ExampleRetentionDays: this.ExampleRetentionDays,
|
|
2125
|
+
AutoArchiveEnabled: this.AutoArchiveEnabled,
|
|
2126
|
+
AllowMemoryWrite: this.AllowMemoryWrite,
|
|
2127
|
+
RerankerConfiguration: this.RerankerConfiguration,
|
|
2128
|
+
PayloadDownstreamPaths: this.PayloadDownstreamPaths,
|
|
2129
|
+
PayloadUpstreamPaths: this.PayloadUpstreamPaths,
|
|
2130
|
+
PayloadSelfReadPaths: this.PayloadSelfReadPaths,
|
|
2131
|
+
PayloadSelfWritePaths: this.PayloadSelfWritePaths,
|
|
2132
|
+
PayloadScope: this.PayloadScope,
|
|
2133
|
+
StartingPayloadValidation: this.StartingPayloadValidation,
|
|
2134
|
+
StartingPayloadValidationMode: this.StartingPayloadValidationMode,
|
|
2135
|
+
FinalPayloadValidation: this.FinalPayloadValidation,
|
|
2136
|
+
FinalPayloadValidationMode: this.FinalPayloadValidationMode,
|
|
2137
|
+
FinalPayloadValidationMaxRetries: this.FinalPayloadValidationMaxRetries,
|
|
2138
|
+
ExecutionMode: this.ExecutionMode,
|
|
2139
|
+
MinExecutionsPerRun: this.MinExecutionsPerRun,
|
|
2140
|
+
MaxExecutionsPerRun: this.MaxExecutionsPerRun,
|
|
2141
|
+
MaxSubAgentConsultRounds: this.MaxSubAgentConsultRounds,
|
|
2142
|
+
MessageMode: this.MessageMode,
|
|
2143
|
+
MaxMessages: this.MaxMessages,
|
|
2144
|
+
AttachmentRootPath: this.AttachmentRootPath,
|
|
2145
|
+
InlineStorageThresholdBytes: this.InlineStorageThresholdBytes,
|
|
2146
|
+
AcceptUnregisteredFiles: this.AcceptUnregisteredFiles,
|
|
2147
|
+
ArtifactCreationMode: this.ArtifactCreationMode,
|
|
2148
|
+
DefaultArtifactTypeID: this.DefaultArtifactTypeID,
|
|
2149
|
+
SearchScopeAccess: this.SearchScopeAccess,
|
|
2150
|
+
ScopeConfig: this.ScopeConfig,
|
|
2151
|
+
SkillActivationMode: this.SkillActivationMode,
|
|
2152
|
+
AllowEphemeralClientTools: this.AllowEphemeralClientTools,
|
|
2153
|
+
RecordingDefault: this.RecordingDefault,
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
isFieldExplicitlyWritten(fieldName, isCreate) {
|
|
2157
|
+
const field = this.GetFieldByName(fieldName);
|
|
2158
|
+
if (!field) {
|
|
2159
|
+
return false;
|
|
2160
|
+
}
|
|
2161
|
+
if (!isCreate) {
|
|
2162
|
+
return field.Dirty === true;
|
|
2163
|
+
}
|
|
2164
|
+
if (field.Dirty === true) {
|
|
2165
|
+
return true;
|
|
2166
|
+
}
|
|
2167
|
+
if (field.NeverSet !== false) {
|
|
2168
|
+
return false;
|
|
2169
|
+
}
|
|
2170
|
+
// On GraphQL CreateRecord (`NewRecord()` + `SetMany(input)`), ResolverBase populates every
|
|
2171
|
+
// writable field with its SQL default, leaving `Dirty === false` while flipping `NeverSet`
|
|
2172
|
+
// to `false`. Treat `!Dirty` + SQL default value as untouched so defaults never freeze into
|
|
2173
|
+
// `AIAgent.Configuration` and clobber BaseAgent / Category / AgentType cascade (C-R1-1).
|
|
2174
|
+
if (fieldName === 'Configuration') {
|
|
2175
|
+
return this.Configuration !== null && this.Configuration !== undefined;
|
|
2176
|
+
}
|
|
2177
|
+
if (Object.prototype.hasOwnProperty.call(LEGACY_AI_AGENT_CONFIG_SQL_DEFAULTS, fieldName)) {
|
|
2178
|
+
const legacyKey = fieldName;
|
|
2179
|
+
const legacyValues = this.buildLegacyConfigValues();
|
|
2180
|
+
return !IsLegacyAIAgentConfigSqlDefault(legacyKey, legacyValues[legacyKey]);
|
|
2181
|
+
}
|
|
2182
|
+
return true;
|
|
2183
|
+
}
|
|
2184
|
+
collectDirtyLegacyConfigFields(isCreate) {
|
|
2185
|
+
const dirtyLegacyFields = new Set();
|
|
2186
|
+
const legacyValues = this.buildLegacyConfigValues();
|
|
2187
|
+
const keys = Object.keys(legacyValues);
|
|
2188
|
+
for (const key of keys) {
|
|
2189
|
+
const field = this.GetFieldByName(key);
|
|
2190
|
+
if (!field) {
|
|
2191
|
+
continue;
|
|
2192
|
+
}
|
|
2193
|
+
if (!isCreate) {
|
|
2194
|
+
if (field.Dirty === true) {
|
|
2195
|
+
dirtyLegacyFields.add(key);
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
else if (field.Dirty === true ||
|
|
2199
|
+
(field.NeverSet === false && !IsLegacyAIAgentConfigSqlDefault(key, legacyValues[key]))) {
|
|
2200
|
+
dirtyLegacyFields.add(key);
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
return dirtyLegacyFields;
|
|
2204
|
+
}
|
|
2205
|
+
buildLegacyPatchFromSet(dirtyFields) {
|
|
2206
|
+
const patch = {};
|
|
2207
|
+
if (dirtyFields.size === 0) {
|
|
2208
|
+
return patch;
|
|
2209
|
+
}
|
|
2210
|
+
const legacyValues = this.buildLegacyConfigValues();
|
|
2211
|
+
for (const key of dirtyFields) {
|
|
2212
|
+
if (legacyValues[key] !== undefined) {
|
|
2213
|
+
patch[key] = legacyValues[key];
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
// R5 Follow-up #6: include stored counterparts for cross-field pair constraints when only one side is dirty
|
|
2217
|
+
if (dirtyFields.has('CompactionTargetPercent') && !dirtyFields.has('CompactionTriggerPercent')) {
|
|
2218
|
+
patch.CompactionTriggerPercent = legacyValues.CompactionTriggerPercent;
|
|
2219
|
+
}
|
|
2220
|
+
else if (dirtyFields.has('CompactionTriggerPercent') && !dirtyFields.has('CompactionTargetPercent')) {
|
|
2221
|
+
patch.CompactionTargetPercent = legacyValues.CompactionTargetPercent;
|
|
2222
|
+
}
|
|
2223
|
+
if (dirtyFields.has('MinExecutionsPerRun') && !dirtyFields.has('MaxExecutionsPerRun')) {
|
|
2224
|
+
patch.MaxExecutionsPerRun = legacyValues.MaxExecutionsPerRun;
|
|
2225
|
+
}
|
|
2226
|
+
else if (dirtyFields.has('MaxExecutionsPerRun') && !dirtyFields.has('MinExecutionsPerRun')) {
|
|
2227
|
+
patch.MinExecutionsPerRun = legacyValues.MinExecutionsPerRun;
|
|
2228
|
+
}
|
|
2229
|
+
return patch;
|
|
2230
|
+
}
|
|
2231
|
+
syncConfigurationWithLegacyColumns(isCreate, dirtyLegacyFields) {
|
|
2232
|
+
const configField = this.GetFieldByName('Configuration');
|
|
2233
|
+
if (!configField) {
|
|
2234
|
+
// Database schema has not yet received the Configuration column (e.g., PostgreSQL prior to twin migration).
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
2237
|
+
const legacyValues = this.buildLegacyConfigValues();
|
|
2238
|
+
const configDirty = this.isFieldExplicitlyWritten('Configuration', isCreate);
|
|
2239
|
+
const previousConfigJson = !isCreate && typeof configField.OldValue === 'string' ? configField.OldValue : null;
|
|
2240
|
+
const syncResult = SyncAgentLegacyColumnsAndConfiguration({
|
|
2241
|
+
IsNewRecord: isCreate,
|
|
2242
|
+
ConfigurationJson: this.Configuration,
|
|
2243
|
+
PreviousConfigurationJson: previousConfigJson,
|
|
2244
|
+
ConfigurationDirty: configDirty,
|
|
2245
|
+
LegacyValues: legacyValues,
|
|
2246
|
+
DirtyLegacyFields: dirtyLegacyFields,
|
|
2247
|
+
});
|
|
2248
|
+
for (const [key, value] of Object.entries(syncResult.LegacyColumnUpdates)) {
|
|
2249
|
+
if (value !== undefined) {
|
|
2250
|
+
this.assignLegacyConfigField(key, value);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
if (syncResult.ShouldUpdateConfiguration) {
|
|
2254
|
+
this.Configuration = syncResult.ConfigurationJson;
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
assignLegacyConfigField(fieldName, value) {
|
|
2258
|
+
const target = this;
|
|
2259
|
+
target[fieldName] = value;
|
|
2260
|
+
}
|
|
63
2261
|
async loadTypeConfigSchema() {
|
|
64
2262
|
if (!this.TypeID) {
|
|
65
2263
|
return null;
|
|
66
2264
|
}
|
|
67
|
-
|
|
68
|
-
|
|
2265
|
+
if (!IsMetadataProvider(this.ProviderToUse)) {
|
|
2266
|
+
return null;
|
|
2267
|
+
}
|
|
2268
|
+
const type = await this.ProviderToUse.GetEntityObject('MJ: AI Agent Types', this.ContextCurrentUser);
|
|
69
2269
|
if (!(await type.Load(this.TypeID))) {
|
|
70
|
-
return null;
|
|
2270
|
+
return null;
|
|
71
2271
|
}
|
|
72
2272
|
return type.ConfigSchema ?? null;
|
|
73
2273
|
}
|
|
@@ -78,17 +2278,7 @@ MJAIAgentEntityServer = __decorate([
|
|
|
78
2278
|
export { MJAIAgentEntityServer };
|
|
79
2279
|
/**
|
|
80
2280
|
* PURE validation core for the `TypeConfiguration` ⊨ `ConfigSchema` invariant (exported for
|
|
81
|
-
* unit tests and reuse)
|
|
82
|
-
*
|
|
83
|
-
* - unparseable / non-object `typeConfigurationJson` → one **Failure** on `TypeConfiguration`;
|
|
84
|
-
* - absent/blank `configSchemaJson` → no further checks (freeform configuration);
|
|
85
|
-
* - unparseable / non-object `configSchemaJson` → one **Warning** (metadata bug on the TYPE row
|
|
86
|
-
* — agent saves must not be bricked by it);
|
|
87
|
-
* - schema violations → one **Failure** per violation, with the JSON-path-ish location.
|
|
88
|
-
*
|
|
89
|
-
* @param typeConfigurationJson The agent's `TypeConfiguration` JSON (non-empty).
|
|
90
|
-
* @param configSchemaJson The type's `ConfigSchema` JSON Schema, or `null` when unpublished.
|
|
91
|
-
* @returns Validation errors/warnings (empty array = valid).
|
|
2281
|
+
* unit tests and reuse).
|
|
92
2282
|
*/
|
|
93
2283
|
export function BuildTypeConfigurationValidationErrors(typeConfigurationJson, configSchemaJson) {
|
|
94
2284
|
let config;
|
|
@@ -106,7 +2296,7 @@ export function BuildTypeConfigurationValidationErrors(typeConfigurationJson, co
|
|
|
106
2296
|
];
|
|
107
2297
|
}
|
|
108
2298
|
if (!configSchemaJson || configSchemaJson.trim().length === 0) {
|
|
109
|
-
return [];
|
|
2299
|
+
return [];
|
|
110
2300
|
}
|
|
111
2301
|
let schema;
|
|
112
2302
|
try {
|