@memberjunction/core-entities-server 6.3.0-edge.1 → 6.3.0-edge.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/custom/AgentChannelConversationDriver.server.d.ts +87 -0
  2. package/dist/custom/AgentChannelConversationDriver.server.d.ts.map +1 -0
  3. package/dist/custom/AgentChannelConversationDriver.server.js +216 -0
  4. package/dist/custom/AgentChannelConversationDriver.server.js.map +1 -0
  5. package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts +25 -0
  6. package/dist/custom/AudienceNamedPersonAgentRequestService.d.ts.map +1 -0
  7. package/dist/custom/AudienceNamedPersonAgentRequestService.js +304 -0
  8. package/dist/custom/AudienceNamedPersonAgentRequestService.js.map +1 -0
  9. package/dist/custom/ConversationDetailWritePermissionProvider.d.ts +113 -0
  10. package/dist/custom/ConversationDetailWritePermissionProvider.d.ts.map +1 -0
  11. package/dist/custom/ConversationDetailWritePermissionProvider.js +200 -0
  12. package/dist/custom/ConversationDetailWritePermissionProvider.js.map +1 -0
  13. package/dist/custom/ConversationReadSecurityHook.d.ts +61 -0
  14. package/dist/custom/ConversationReadSecurityHook.d.ts.map +1 -0
  15. package/dist/custom/ConversationReadSecurityHook.js +587 -0
  16. package/dist/custom/ConversationReadSecurityHook.js.map +1 -0
  17. package/dist/custom/MJAIAgentEntityServer.server.d.ts +80 -34
  18. package/dist/custom/MJAIAgentEntityServer.server.d.ts.map +1 -1
  19. package/dist/custom/MJAIAgentEntityServer.server.js +383 -43
  20. package/dist/custom/MJAIAgentEntityServer.server.js.map +1 -1
  21. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts +23 -0
  22. package/dist/custom/MJAIAgentPersonaEntityServer.server.d.ts.map +1 -0
  23. package/dist/custom/MJAIAgentPersonaEntityServer.server.js +93 -0
  24. package/dist/custom/MJAIAgentPersonaEntityServer.server.js.map +1 -0
  25. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts +24 -13
  26. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts.map +1 -1
  27. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js +167 -24
  28. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js.map +1 -1
  29. package/dist/custom/MJConversationDetailEntityServer.server.d.ts +27 -2
  30. package/dist/custom/MJConversationDetailEntityServer.server.d.ts.map +1 -1
  31. package/dist/custom/MJConversationDetailEntityServer.server.js +300 -4
  32. package/dist/custom/MJConversationDetailEntityServer.server.js.map +1 -1
  33. package/dist/custom/MJConversationEntityServer.server.d.ts +5 -26
  34. package/dist/custom/MJConversationEntityServer.server.d.ts.map +1 -1
  35. package/dist/custom/MJConversationEntityServer.server.js +236 -8
  36. package/dist/custom/MJConversationEntityServer.server.js.map +1 -1
  37. package/dist/custom/MJGraphConceptEntityServer.server.d.ts +92 -0
  38. package/dist/custom/MJGraphConceptEntityServer.server.d.ts.map +1 -0
  39. package/dist/custom/MJGraphConceptEntityServer.server.js +203 -0
  40. package/dist/custom/MJGraphConceptEntityServer.server.js.map +1 -0
  41. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +16 -2
  42. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -1
  43. package/dist/custom/MJGraphEdgeEntityServer.server.js +26 -4
  44. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -1
  45. package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts +31 -0
  46. package/dist/custom/MJMLModelPublishRecordEntityServer.server.d.ts.map +1 -0
  47. package/dist/custom/MJMLModelPublishRecordEntityServer.server.js +68 -0
  48. package/dist/custom/MJMLModelPublishRecordEntityServer.server.js.map +1 -0
  49. package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts +78 -0
  50. package/dist/custom/MJMLModelScoringBindingEntityServer.server.d.ts.map +1 -0
  51. package/dist/custom/MJMLModelScoringBindingEntityServer.server.js +273 -0
  52. package/dist/custom/MJMLModelScoringBindingEntityServer.server.js.map +1 -0
  53. package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts +18 -0
  54. package/dist/custom/MJMLOutputBindingEntityServer.server.d.ts.map +1 -0
  55. package/dist/custom/MJMLOutputBindingEntityServer.server.js +61 -0
  56. package/dist/custom/MJMLOutputBindingEntityServer.server.js.map +1 -0
  57. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts +3 -3
  58. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts.map +1 -1
  59. package/dist/custom/MJMLPredictionUnitEntityServer.server.js +4 -4
  60. package/dist/custom/MJMLPredictionUnitEntityServer.server.js.map +1 -1
  61. package/dist/custom/MJQueryEntityServer.server.d.ts +33 -0
  62. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  63. package/dist/custom/MJQueryEntityServer.server.js +79 -3
  64. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  65. package/dist/custom/MJQuerySQLEntityServer.server.d.ts +13 -1
  66. package/dist/custom/MJQuerySQLEntityServer.server.d.ts.map +1 -1
  67. package/dist/custom/MJQuerySQLEntityServer.server.js +37 -3
  68. package/dist/custom/MJQuerySQLEntityServer.server.js.map +1 -1
  69. package/dist/custom/MJResourcePermissionEntityServer.server.d.ts +28 -0
  70. package/dist/custom/MJResourcePermissionEntityServer.server.d.ts.map +1 -0
  71. package/dist/custom/MJResourcePermissionEntityServer.server.js +206 -0
  72. package/dist/custom/MJResourcePermissionEntityServer.server.js.map +1 -0
  73. package/dist/custom/MJUserRoutineEntityServer.server.d.ts +23 -0
  74. package/dist/custom/MJUserRoutineEntityServer.server.d.ts.map +1 -1
  75. package/dist/custom/MJUserRoutineEntityServer.server.js +320 -3
  76. package/dist/custom/MJUserRoutineEntityServer.server.js.map +1 -1
  77. package/dist/custom/approvalStamp.d.ts +19 -3
  78. package/dist/custom/approvalStamp.d.ts.map +1 -1
  79. package/dist/custom/approvalStamp.js +13 -3
  80. package/dist/custom/approvalStamp.js.map +1 -1
  81. package/dist/custom/graph/GraphFindPathServerOperation.d.ts +24 -0
  82. package/dist/custom/graph/GraphFindPathServerOperation.d.ts.map +1 -0
  83. package/dist/custom/graph/GraphFindPathServerOperation.js +88 -0
  84. package/dist/custom/graph/GraphFindPathServerOperation.js.map +1 -0
  85. package/dist/custom/graph/index.d.ts +2 -0
  86. package/dist/custom/graph/index.d.ts.map +1 -0
  87. package/dist/custom/graph/index.js +2 -0
  88. package/dist/custom/graph/index.js.map +1 -0
  89. package/dist/index.d.ts +11 -0
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +11 -0
  92. package/dist/index.js.map +1 -1
  93. package/dist/tsconfig.tsbuildinfo +1 -1
  94. package/package.json +31 -31
@@ -1,50 +1,96 @@
1
- import { ValidationErrorInfo, ValidationResult } from '@memberjunction/core';
1
+ import { EntityDeleteOptions, EntitySaveOptions, IEntityDataProvider, IMetadataProvider, UserInfo, ValidationErrorInfo, ValidationResult } from '@memberjunction/core';
2
+ import { MJAIAgentEntity, MJAIAgentPermissionEntity } from '@memberjunction/core-entities';
2
3
  import { MJAIAgentEntityExtended } from '@memberjunction/ai-core-plus';
3
4
  /**
4
- * Server-side AI Agent entity that validates `TypeConfiguration` on save:
5
- *
6
- * 1. When non-empty, `TypeConfiguration` must parse as a JSON OBJECT (it is the per-agent
7
- * layer of the effective-configuration merge — arrays/scalars are never valid layers).
8
- * 2. When the agent's TYPE publishes a `ConfigSchema` (JSON Schema subset), the parsed
9
- * configuration must conform to it — checked with the dependency-free
10
- * {@link ValidateJsonAgainstSchemaLite} validator (type / required / properties / enum /
11
- * items / additionalProperties). A type WITHOUT a published schema leaves the
12
- * configuration freeform (rule 1 still applies).
5
+ * Type guard narrowing an `IEntityDataProvider` to `IMetadataProvider` when the provider
6
+ * implements metadata/entity-instantiation methods (e.g., `SQLServerDataProvider`, `PostgreSQLDataProvider`).
7
+ */
8
+ export declare function IsMetadataProvider(provider: IEntityDataProvider | null | undefined): provider is IEntityDataProvider & IMetadataProvider;
9
+ /**
10
+ * Returns true when `user` is an Owner-type user or holds an administrative / Agent Administrator role.
11
+ */
12
+ export declare function IsAgentAdminOrOwnerUser(user: UserInfo | null | undefined): boolean;
13
+ /**
14
+ * Snapshot of an agent record used by the pure {@link ValidateAgentInheritanceAndSandbox} helper.
15
+ */
16
+ export interface AgentSandboxValidationTarget {
17
+ ID: string;
18
+ IsSaved: boolean;
19
+ BaseAgentID: string | null;
20
+ PreSaveBaseAgentID: string | null;
21
+ OwnerUserID: string | null;
22
+ PreSaveOwnerUserID: string | null;
23
+ InstantiationMode: MJAIAgentEntity['InstantiationMode'];
24
+ DriverClass: string | null;
25
+ DriverClassDirty: boolean;
26
+ Isolation: MJAIAgentEntity['Isolation'];
27
+ ExposeAsAction: boolean;
28
+ MaxCostPerRun: number | null;
29
+ MaxTokensPerRun: number | null;
30
+ MaxTimePerRun: number | null;
31
+ MaxIterationsPerRun: number | null;
32
+ }
33
+ /**
34
+ * Pure validation context passed into {@link ValidateAgentInheritanceAndSandbox}.
35
+ */
36
+ export interface AgentSandboxValidationContext {
37
+ Target: AgentSandboxValidationTarget;
38
+ User: UserInfo | null | undefined;
39
+ /** Full agent list (used to trace BaseAgentID chains, cycles, depth, and user instance counts). */
40
+ AllAgents: ReadonlyArray<Pick<MJAIAgentEntity, 'ID' | 'Name' | 'BaseAgentID' | 'OwnerUserID' | 'Status' | 'InstantiationMode' | 'DriverClass' | 'Isolation' | 'MaxCostPerRun' | 'MaxTokensPerRun' | 'MaxTimePerRun' | 'MaxIterationsPerRun' | 'TypeConfiguration'>>;
41
+ AllPermissions: ReadonlyArray<MJAIAgentPermissionEntity>;
42
+ }
43
+ /**
44
+ * PURE validation core for `BaseAgentID` prototype inheritance integrity and non-Owner (`UI` role)
45
+ * sandboxing (exported for unit tests and called by {@link MJAIAgentEntityServer.ValidateAsync}):
13
46
  *
14
- * A malformed/unparseable `ConfigSchema` is a METADATA bug on the type row, not the agent
15
- * being saved — it surfaces as a WARNING (the save proceeds) rather than blocking every agent
16
- * of that type. Extends `MJAIAgentEntityExtended` so all client-side extended behavior is
17
- * preserved; registered last, so the ClassFactory prefers it server-side.
47
+ * 1. **Chain integrity (all users)**:
48
+ * - `BaseAgentID` must reference an existing agent, cannot point to itself or form a cycle,
49
+ * and total inheritance depth must not exceed `MAX_AGENT_INHERITANCE_DEPTH` (5).
50
+ * 2. **Instantiation policy on create**:
51
+ * - Non-admin users can only instantiate from a base agent whose `InstantiationMode !== 'None'`.
52
+ * - Enforces `TypeConfiguration.instantiation.maxInstancesPerUser` when configured.
53
+ * 3. **Non-Owner (`UI` role) sandbox**:
54
+ * - May only create/update derived agents (`BaseAgentID != null`), owned by `User.ID`
55
+ * (checked against pre-save `OldValue` on update), with `InstantiationMode === 'None'`.
56
+ * - Must hold effective `CanRun` on `BaseAgentID`.
57
+ * - Cannot set custom `DriverClass`, loosen `Isolation`, set `ExposeAsAction = true`, or raise
58
+ * finite `MaxCostPerRun` / `MaxTokensPerRun` / `MaxTimePerRun` / `MaxIterationsPerRun` above
59
+ * the base agent's bounds.
60
+ */
61
+ export declare function ValidateAgentInheritanceAndSandbox(ctx: AgentSandboxValidationContext): ValidationErrorInfo[];
62
+ /**
63
+ * Server-side AI Agent entity enforcing:
64
+ * 1. `TypeConfiguration` ⊨ `ConfigSchema` validation.
65
+ * 2. `BaseAgentID` prototype inheritance integrity (`MaxDepth = 5`, cycle detection, `InstantiationMode` & `maxInstancesPerUser`).
66
+ * 3. Non-Owner (`UI` role) sandbox for creating/updating/deleting derived personal instances.
67
+ * 4. Automatic `OwnerUserID` attribution, derived default capability inheritance on create, and
68
+ * `IsPrimaryInstance` uniqueness per `(OwnerUserID, RootBaseAgentID)`.
18
69
  */
19
70
  export declare class MJAIAgentEntityServer extends MJAIAgentEntityExtended {
20
- /** Enable async validation so the TypeConfiguration ⊨ ConfigSchema check runs. */
71
+ /** Enable async validation so TypeConfiguration, BaseAgentID chain, and sandbox checks run. */
21
72
  get DefaultSkipAsyncValidation(): boolean;
22
- /**
23
- * Async invariant: `TypeConfiguration` must be a JSON object conforming to the agent
24
- * type's published `ConfigSchema`. Cheap fast-path — only runs when the configuration is
25
- * present AND (the record is new, or `TypeConfiguration`/`TypeID` is dirty).
26
- */
73
+ Save(options?: EntitySaveOptions): Promise<boolean>;
74
+ Delete(options?: EntityDeleteOptions): Promise<boolean>;
27
75
  ValidateAsync(): Promise<ValidationResult>;
28
76
  /**
29
- * Loads the agent type's `ConfigSchema` through the same request-scoped provider that owns
30
- * this entity. Returns `null` (freeform) when the agent has no type, the type row cannot be
31
- * loaded, or no schema is published.
77
+ * Copies core capability defaults from `baseAgent` onto a newly-created derived instance
78
+ * ONLY for fields the caller left untouched (not dirty). This ensures newly minted instances
79
+ * like *Pepper* immediately inherit `TypeID`, `AcceptsSkills`, `SkillActivationMode`,
80
+ * `ModelSelectionMode`, `Isolation`, and memory settings without requiring every caller to
81
+ * manually copy 20 columns.
32
82
  */
83
+ private inheritDefaultsFromBaseAgent;
84
+ private findRootBaseAgentId;
85
+ private findActiveSiblingsForOwnerAndRoot;
86
+ private clearOtherPrimaryInstances;
87
+ private loadAllAgentsForGuard;
88
+ private loadAllAgentPermissionsForGuard;
33
89
  private loadTypeConfigSchema;
34
90
  }
35
91
  /**
36
92
  * PURE validation core for the `TypeConfiguration` ⊨ `ConfigSchema` invariant (exported for
37
- * unit tests and reuse):
38
- *
39
- * - unparseable / non-object `typeConfigurationJson` → one **Failure** on `TypeConfiguration`;
40
- * - absent/blank `configSchemaJson` → no further checks (freeform configuration);
41
- * - unparseable / non-object `configSchemaJson` → one **Warning** (metadata bug on the TYPE row
42
- * — agent saves must not be bricked by it);
43
- * - schema violations → one **Failure** per violation, with the JSON-path-ish location.
44
- *
45
- * @param typeConfigurationJson The agent's `TypeConfiguration` JSON (non-empty).
46
- * @param configSchemaJson The type's `ConfigSchema` JSON Schema, or `null` when unpublished.
47
- * @returns Validation errors/warnings (empty array = valid).
93
+ * unit tests and reuse).
48
94
  */
49
95
  export declare function BuildTypeConfigurationValidationErrors(typeConfigurationJson: string, configSchemaJson: string | null): ValidationErrorInfo[];
50
96
  //# sourceMappingURL=MJAIAgentEntityServer.server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"MJAIAgentEntityServer.server.d.ts","sourceRoot":"","sources":["../../src/custom/MJAIAgentEntityServer.server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiC,mBAAmB,EAAuB,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAGjI,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAGvE;;;;;;;;;;;;;;;GAeG;AACH,qBACa,qBAAsB,SAAQ,uBAAuB;IAC9D,kFAAkF;IAClF,IAAoB,0BAA0B,IAAI,OAAO,CAExD;IAED;;;;OAIG;IACmB,aAAa,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAwBhE;;;;OAIG;YACW,oBAAoB;CAWrC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sCAAsC,CAClD,qBAAqB,EAAE,MAAM,EAC7B,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAChC,mBAAmB,EAAE,CAwDvB"}
1
+ {"version":3,"file":"MJAIAgentEntityServer.server.d.ts","sourceRoot":"","sources":["../../src/custom/MJAIAgentEntityServer.server.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,EAEjB,QAAQ,EACR,mBAAmB,EAEnB,gBAAgB,EACnB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAuB,MAAM,+BAA+B,CAAC;AAChH,OAAO,EAEH,uBAAuB,EAE1B,MAAM,8BAA8B,CAAC;AAmBtC;;;GAGG;AACH,wBAAgB,kBAAkB,CAC9B,QAAQ,EAAE,mBAAmB,GAAG,IAAI,GAAG,SAAS,GACjD,QAAQ,IAAI,mBAAmB,GAAG,iBAAiB,CAErD;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CASlF;AAED;;GAEG;AACH,MAAM,WAAW,4BAA4B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,iBAAiB,EAAE,eAAe,CAAC,mBAAmB,CAAC,CAAC;IACxD,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,EAAE,OAAO,CAAC;IAC1B,SAAS,EAAE,eAAe,CAAC,WAAW,CAAC,CAAC;IACxC,cAAc,EAAE,OAAO,CAAC;IACxB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,WAAW,6BAA6B;IAC1C,MAAM,EAAE,4BAA4B,CAAC;IACrC,IAAI,EAAE,QAAQ,GAAG,IAAI,GAAG,SAAS,CAAC;IAClC,mGAAmG;IACnG,SAAS,EAAE,aAAa,CACpB,IAAI,CACA,eAAe,EACb,IAAI,GACJ,MAAM,GACN,aAAa,GACb,aAAa,GACb,QAAQ,GACR,mBAAmB,GACnB,aAAa,GACb,WAAW,GACX,eAAe,GACf,iBAAiB,GACjB,eAAe,GACf,qBAAqB,GACrB,mBAAmB,CACxB,CACJ,CAAC;IACF,cAAc,EAAE,aAAa,CAAC,yBAAyB,CAAC,CAAC;CAC5D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,kCAAkC,CAC9C,GAAG,EAAE,6BAA6B,GACnC,mBAAmB,EAAE,CA6PvB;AAED;;;;;;;GAOG;AACH,qBACa,qBAAsB,SAAQ,uBAAuB;IAC9D,+FAA+F;IAC/F,IAAoB,0BAA0B,IAAI,OAAO,CAExD;IAEqB,IAAI,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IA8CnD,MAAM,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC;IAsBvD,aAAa,IAAI,OAAO,CAAC,gBAAgB,CAAC;IA+DhE;;;;;;OAMG;IACH,OAAO,CAAC,4BAA4B;IA6CpC,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,iCAAiC;YAkB3B,0BAA0B;YA+B1B,qBAAqB;YAYrB,+BAA+B;YAY/B,oBAAoB;CAgBrC;AAED;;;GAGG;AACH,wBAAgB,sCAAsC,CAClD,qBAAqB,EAAE,MAAM,EAC7B,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAChC,mBAAmB,EAAE,CAwDvB"}
@@ -4,70 +4,420 @@ 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 { BaseEntity, RunView, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/core';
8
+ import { EscapeSQLString, IndexByUUID, RegisterClass, UUIDsEqual, UUIDSet } from '@memberjunction/global';
9
+ import { MAX_AGENT_INHERITANCE_DEPTH, MJAIAgentEntityExtended, ParseAgentInstantiationConfig, } from '@memberjunction/ai-core-plus';
10
+ import { AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';
10
11
  import { ValidateJsonAgainstSchemaLite } from './json-schema-lite.js';
12
+ const ADMIN_ROLE_NAMES = new Set([
13
+ 'system administrator',
14
+ 'administrator',
15
+ 'admin',
16
+ 'administration',
17
+ 'agent administrator',
18
+ ]);
19
+ const ISOLATION_RANK = {
20
+ InProcess: 0,
21
+ Worker: 1,
22
+ Process: 2,
23
+ Container: 3,
24
+ };
11
25
  /**
12
- * Server-side AI Agent entity that validates `TypeConfiguration` on save:
13
- *
14
- * 1. When non-empty, `TypeConfiguration` must parse as a JSON OBJECT (it is the per-agent
15
- * layer of the effective-configuration merge — arrays/scalars are never valid layers).
16
- * 2. When the agent's TYPE publishes a `ConfigSchema` (JSON Schema subset), the parsed
17
- * configuration must conform to it — checked with the dependency-free
18
- * {@link ValidateJsonAgainstSchemaLite} validator (type / required / properties / enum /
19
- * items / additionalProperties). A type WITHOUT a published schema leaves the
20
- * configuration freeform (rule 1 still applies).
26
+ * Type guard narrowing an `IEntityDataProvider` to `IMetadataProvider` when the provider
27
+ * implements metadata/entity-instantiation methods (e.g., `SQLServerDataProvider`, `PostgreSQLDataProvider`).
28
+ */
29
+ export function IsMetadataProvider(provider) {
30
+ return Boolean(provider && 'GetEntityObject' in provider && 'Entities' in provider);
31
+ }
32
+ /**
33
+ * Returns true when `user` is an Owner-type user or holds an administrative / Agent Administrator role.
34
+ */
35
+ export function IsAgentAdminOrOwnerUser(user) {
36
+ if (!user) {
37
+ return true; // System / unauthenticated internal context
38
+ }
39
+ if (user.Type?.trim().toLowerCase() === 'owner') {
40
+ return true;
41
+ }
42
+ const roles = user.UserRoles ?? [];
43
+ return roles.some((ur) => ADMIN_ROLE_NAMES.has((ur.Role ?? '').trim().toLowerCase()));
44
+ }
45
+ /**
46
+ * PURE validation core for `BaseAgentID` prototype inheritance integrity and non-Owner (`UI` role)
47
+ * sandboxing (exported for unit tests and called by {@link MJAIAgentEntityServer.ValidateAsync}):
21
48
  *
22
- * A malformed/unparseable `ConfigSchema` is a METADATA bug on the type row, not the agent
23
- * being saved — it surfaces as a WARNING (the save proceeds) rather than blocking every agent
24
- * of that type. Extends `MJAIAgentEntityExtended` so all client-side extended behavior is
25
- * preserved; registered last, so the ClassFactory prefers it server-side.
49
+ * 1. **Chain integrity (all users)**:
50
+ * - `BaseAgentID` must reference an existing agent, cannot point to itself or form a cycle,
51
+ * and total inheritance depth must not exceed `MAX_AGENT_INHERITANCE_DEPTH` (5).
52
+ * 2. **Instantiation policy on create**:
53
+ * - Non-admin users can only instantiate from a base agent whose `InstantiationMode !== 'None'`.
54
+ * - Enforces `TypeConfiguration.instantiation.maxInstancesPerUser` when configured.
55
+ * 3. **Non-Owner (`UI` role) sandbox**:
56
+ * - May only create/update derived agents (`BaseAgentID != null`), owned by `User.ID`
57
+ * (checked against pre-save `OldValue` on update), with `InstantiationMode === 'None'`.
58
+ * - Must hold effective `CanRun` on `BaseAgentID`.
59
+ * - Cannot set custom `DriverClass`, loosen `Isolation`, set `ExposeAsAction = true`, or raise
60
+ * finite `MaxCostPerRun` / `MaxTokensPerRun` / `MaxTimePerRun` / `MaxIterationsPerRun` above
61
+ * the base agent's bounds.
62
+ */
63
+ export function ValidateAgentInheritanceAndSandbox(ctx) {
64
+ const errors = [];
65
+ const { Target, User, AllAgents, AllPermissions } = ctx;
66
+ const isAdmin = IsAgentAdminOrOwnerUser(User);
67
+ // 1. Non-admin sandbox on root vs derived + ownership + InstantiationMode
68
+ if (!isAdmin && User) {
69
+ const effectiveBaseId = Target.BaseAgentID;
70
+ if (!effectiveBaseId) {
71
+ errors.push(new ValidationErrorInfo('BaseAgentID', 'Non-administrator users can only create or modify derived agent instances with BaseAgentID set.', null, ValidationErrorType.Failure));
72
+ return errors;
73
+ }
74
+ if (Target.IsSaved && Target.PreSaveBaseAgentID && !UUIDsEqual(Target.PreSaveBaseAgentID, effectiveBaseId)) {
75
+ errors.push(new ValidationErrorInfo('BaseAgentID', 'Cannot re-parent BaseAgentID on an existing derived agent instance.', effectiveBaseId, ValidationErrorType.Failure));
76
+ }
77
+ const preSaveOwner = Target.IsSaved ? (Target.PreSaveOwnerUserID ?? Target.OwnerUserID) : Target.OwnerUserID;
78
+ if (preSaveOwner && !UUIDsEqual(preSaveOwner, User.ID)) {
79
+ errors.push(new ValidationErrorInfo('OwnerUserID', 'You can only create or modify your own personal agent instances.', Target.OwnerUserID, ValidationErrorType.Failure));
80
+ }
81
+ if (Target.OwnerUserID && !UUIDsEqual(Target.OwnerUserID, User.ID)) {
82
+ errors.push(new ValidationErrorInfo('OwnerUserID', 'Cannot reassign OwnerUserID to another user.', Target.OwnerUserID, ValidationErrorType.Failure));
83
+ }
84
+ if ((Target.InstantiationMode ?? 'None') !== 'None') {
85
+ errors.push(new ValidationErrorInfo('InstantiationMode', 'Only administrators may publish instantiable agent templates (InstantiationMode must be None for personal instances).', Target.InstantiationMode, ValidationErrorType.Failure));
86
+ }
87
+ if (Target.ExposeAsAction) {
88
+ errors.push(new ValidationErrorInfo('ExposeAsAction', 'Personal agent instances cannot set ExposeAsAction = true.', true, ValidationErrorType.Failure));
89
+ }
90
+ }
91
+ // 2. BaseAgentID chain integrity (existence, no cycle, depth <= MAX_AGENT_INHERITANCE_DEPTH)
92
+ if (!Target.BaseAgentID) {
93
+ return errors;
94
+ }
95
+ if (Target.ID && UUIDsEqual(Target.ID, Target.BaseAgentID)) {
96
+ errors.push(new ValidationErrorInfo('BaseAgentID', 'An agent cannot set BaseAgentID to itself.', Target.BaseAgentID, ValidationErrorType.Failure));
97
+ return errors;
98
+ }
99
+ const agentsById = IndexByUUID(AllAgents);
100
+ const baseAgent = agentsById.Get(Target.BaseAgentID);
101
+ if (!baseAgent) {
102
+ errors.push(new ValidationErrorInfo('BaseAgentID', `BaseAgentID '${Target.BaseAgentID}' does not reference an existing AI Agent.`, Target.BaseAgentID, ValidationErrorType.Failure));
103
+ return errors;
104
+ }
105
+ // Walk up BaseAgentID chain to detect cycles and enforce max depth (5 hops)
106
+ const visited = new UUIDSet(Target.ID ? [Target.ID] : []);
107
+ let cursor = baseAgent;
108
+ let hops = 1; // Target -> baseAgent is hop 1
109
+ while (cursor) {
110
+ if (visited.Has(cursor.ID)) {
111
+ errors.push(new ValidationErrorInfo('BaseAgentID', 'BaseAgentID inheritance cycle detected.', Target.BaseAgentID, ValidationErrorType.Failure));
112
+ return errors;
113
+ }
114
+ visited.Add(cursor.ID);
115
+ if (hops > MAX_AGENT_INHERITANCE_DEPTH) {
116
+ errors.push(new ValidationErrorInfo('BaseAgentID', `Agent prototype inheritance depth exceeds maximum allowed depth of ${MAX_AGENT_INHERITANCE_DEPTH}.`, Target.BaseAgentID, ValidationErrorType.Failure));
117
+ return errors;
118
+ }
119
+ if (!cursor.BaseAgentID) {
120
+ break;
121
+ }
122
+ const nextParent = agentsById.Get(cursor.BaseAgentID);
123
+ if (!nextParent) {
124
+ break;
125
+ }
126
+ cursor = nextParent;
127
+ hops++;
128
+ }
129
+ // 3. InstantiationMode & maxInstancesPerUser check on create
130
+ if (!Target.IsSaved) {
131
+ if (!isAdmin && (baseAgent.InstantiationMode ?? 'None') === 'None') {
132
+ errors.push(new ValidationErrorInfo('BaseAgentID', `Agent '${baseAgent.Name ?? baseAgent.ID}' does not allow creating derived instances (InstantiationMode is 'None').`, Target.BaseAgentID, ValidationErrorType.Failure));
133
+ }
134
+ const instCfg = ParseAgentInstantiationConfig(baseAgent.TypeConfiguration);
135
+ const ownerId = Target.OwnerUserID ?? User?.ID ?? null;
136
+ if (instCfg?.maxInstancesPerUser && ownerId) {
137
+ const existingCount = AllAgents.filter((a) => a.Status === 'Active' &&
138
+ a.BaseAgentID != null &&
139
+ UUIDsEqual(a.BaseAgentID, baseAgent.ID) &&
140
+ UUIDsEqual(a.OwnerUserID, ownerId)).length;
141
+ if (existingCount >= instCfg.maxInstancesPerUser) {
142
+ errors.push(new ValidationErrorInfo('BaseAgentID', `Maximum of ${instCfg.maxInstancesPerUser} active instance(s) of '${baseAgent.Name ?? baseAgent.ID}' per user reached.`, Target.BaseAgentID, ValidationErrorType.Failure));
143
+ }
144
+ }
145
+ }
146
+ // 4. Non-admin runtime capability & bounds sandbox against baseAgent
147
+ if (!isAdmin && User) {
148
+ const basePerms = AIAgentPermissionHelper.ComputeEffectivePermissionsSync(baseAgent, AllAgents, AllPermissions, User);
149
+ if (!basePerms.canRun) {
150
+ errors.push(new ValidationErrorInfo('BaseAgentID', `You do not have permission to run base agent '${baseAgent.Name ?? baseAgent.ID}'.`, Target.BaseAgentID, ValidationErrorType.Failure));
151
+ }
152
+ const baseDriver = baseAgent.DriverClass?.trim() || null;
153
+ const targetDriver = Target.DriverClass?.trim() || null;
154
+ if (Target.DriverClassDirty && targetDriver !== null && targetDriver !== baseDriver) {
155
+ errors.push(new ValidationErrorInfo('DriverClass', 'Non-administrator users cannot set a custom DriverClass on a derived agent instance.', Target.DriverClass, ValidationErrorType.Failure));
156
+ }
157
+ const baseIsoRank = ISOLATION_RANK[baseAgent.Isolation ?? 'InProcess'] ?? 0;
158
+ const targetIsoRank = ISOLATION_RANK[Target.Isolation ?? 'InProcess'] ?? 0;
159
+ if (targetIsoRank < baseIsoRank) {
160
+ errors.push(new ValidationErrorInfo('Isolation', `Derived agent Isolation ('${Target.Isolation}') cannot be less strict than base agent Isolation ('${baseAgent.Isolation}').`, Target.Isolation, ValidationErrorType.Failure));
161
+ }
162
+ const checkUpperBound = (fieldName, baseLimit, childLimit) => {
163
+ if (baseLimit != null && childLimit != null && childLimit > baseLimit) {
164
+ errors.push(new ValidationErrorInfo(fieldName, `Derived agent ${fieldName} (${childLimit}) cannot exceed base agent ceiling (${baseLimit}).`, childLimit, ValidationErrorType.Failure));
165
+ }
166
+ };
167
+ checkUpperBound('MaxCostPerRun', baseAgent.MaxCostPerRun, Target.MaxCostPerRun);
168
+ checkUpperBound('MaxTokensPerRun', baseAgent.MaxTokensPerRun, Target.MaxTokensPerRun);
169
+ checkUpperBound('MaxTimePerRun', baseAgent.MaxTimePerRun, Target.MaxTimePerRun);
170
+ checkUpperBound('MaxIterationsPerRun', baseAgent.MaxIterationsPerRun, Target.MaxIterationsPerRun);
171
+ }
172
+ return errors;
173
+ }
174
+ /**
175
+ * Server-side AI Agent entity enforcing:
176
+ * 1. `TypeConfiguration` ⊨ `ConfigSchema` validation.
177
+ * 2. `BaseAgentID` prototype inheritance integrity (`MaxDepth = 5`, cycle detection, `InstantiationMode` & `maxInstancesPerUser`).
178
+ * 3. Non-Owner (`UI` role) sandbox for creating/updating/deleting derived personal instances.
179
+ * 4. Automatic `OwnerUserID` attribution, derived default capability inheritance on create, and
180
+ * `IsPrimaryInstance` uniqueness per `(OwnerUserID, RootBaseAgentID)`.
26
181
  */
27
182
  let MJAIAgentEntityServer = class MJAIAgentEntityServer extends MJAIAgentEntityExtended {
28
- /** Enable async validation so the TypeConfiguration ⊨ ConfigSchema check runs. */
183
+ /** Enable async validation so TypeConfiguration, BaseAgentID chain, and sandbox checks run. */
29
184
  get DefaultSkipAsyncValidation() {
30
185
  return false;
31
186
  }
32
- /**
33
- * Async invariant: `TypeConfiguration` must be a JSON object conforming to the agent
34
- * type's published `ConfigSchema`. Cheap fast-path — only runs when the configuration is
35
- * present AND (the record is new, or `TypeConfiguration`/`TypeID` is dirty).
36
- */
187
+ async Save(options) {
188
+ const isCreate = !this.IsSaved;
189
+ let baseAgent = null;
190
+ let resolvedRootBaseId = null;
191
+ if (isCreate && !this.OwnerUserID && this.ContextCurrentUser) {
192
+ this.OwnerUserID = this.ContextCurrentUser.ID;
193
+ }
194
+ if (this.BaseAgentID) {
195
+ const allAgents = await this.loadAllAgentsForGuard();
196
+ baseAgent = allAgents.find((a) => UUIDsEqual(a.ID, this.BaseAgentID)) ?? null;
197
+ if (baseAgent) {
198
+ resolvedRootBaseId = this.findRootBaseAgentId(baseAgent, allAgents);
199
+ if (isCreate) {
200
+ this.inheritDefaultsFromBaseAgent(baseAgent);
201
+ const primaryDirty = this.GetFieldByName('IsPrimaryInstance')?.Dirty ?? false;
202
+ if (!primaryDirty && !this.IsPrimaryInstance && this.OwnerUserID) {
203
+ const existingSiblings = this.findActiveSiblingsForOwnerAndRoot(allAgents, this.OwnerUserID, resolvedRootBaseId, this.ID);
204
+ if (existingSiblings.length === 0) {
205
+ this.IsPrimaryInstance = true;
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ const saved = await super.Save(options);
212
+ if (!saved) {
213
+ return false;
214
+ }
215
+ // Maintain single IsPrimaryInstance per (OwnerUserID, RootBaseAgentID)
216
+ if (this.BaseAgentID && this.OwnerUserID && this.IsPrimaryInstance === true) {
217
+ const rootId = this.RootBaseAgentID ?? resolvedRootBaseId ?? this.BaseAgentID;
218
+ await this.clearOtherPrimaryInstances(this.OwnerUserID, rootId, this.ID);
219
+ }
220
+ return true;
221
+ }
222
+ async Delete(options) {
223
+ const user = this.ContextCurrentUser;
224
+ if (!IsAgentAdminOrOwnerUser(user) && user) {
225
+ const preSaveBase = this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID;
226
+ const preSaveOwner = this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID;
227
+ if (!preSaveBase || !preSaveOwner || !UUIDsEqual(preSaveOwner, user.ID)) {
228
+ this.LatestResult?.Errors.push(new ValidationErrorInfo('OwnerUserID', 'Non-administrator users can only delete their own derived agent instances.', this.ID, ValidationErrorType.Failure));
229
+ return false;
230
+ }
231
+ }
232
+ return super.Delete(options);
233
+ }
37
234
  async ValidateAsync() {
38
235
  const result = await super.ValidateAsync();
39
236
  if (!result.Success)
40
237
  return result;
238
+ // 1. BaseAgentID inheritance & non-admin sandbox checks
239
+ const user = this.ContextCurrentUser;
240
+ const isAdmin = IsAgentAdminOrOwnerUser(user);
241
+ if (this.BaseAgentID || !isAdmin) {
242
+ const [allAgents, allPermissions] = await Promise.all([
243
+ this.loadAllAgentsForGuard(),
244
+ this.loadAllAgentPermissionsForGuard(),
245
+ ]);
246
+ const sandboxErrors = ValidateAgentInheritanceAndSandbox({
247
+ Target: {
248
+ ID: this.ID,
249
+ IsSaved: this.IsSaved,
250
+ BaseAgentID: this.BaseAgentID,
251
+ PreSaveBaseAgentID: this.GetFieldByName('BaseAgentID')?.OldValue ?? this.BaseAgentID,
252
+ OwnerUserID: this.OwnerUserID,
253
+ PreSaveOwnerUserID: this.GetFieldByName('OwnerUserID')?.OldValue ?? this.OwnerUserID,
254
+ InstantiationMode: this.InstantiationMode,
255
+ DriverClass: this.DriverClass,
256
+ DriverClassDirty: this.GetFieldByName('DriverClass')?.Dirty ?? false,
257
+ Isolation: this.Isolation,
258
+ ExposeAsAction: this.ExposeAsAction,
259
+ MaxCostPerRun: this.MaxCostPerRun,
260
+ MaxTokensPerRun: this.MaxTokensPerRun,
261
+ MaxTimePerRun: this.MaxTimePerRun,
262
+ MaxIterationsPerRun: this.MaxIterationsPerRun,
263
+ },
264
+ User: user,
265
+ AllAgents: allAgents,
266
+ AllPermissions: allPermissions,
267
+ });
268
+ if (sandboxErrors.length > 0) {
269
+ result.Errors.push(...sandboxErrors);
270
+ result.Success = result.Success && sandboxErrors.every((e) => e.Type !== ValidationErrorType.Failure);
271
+ }
272
+ }
273
+ // 2. TypeConfiguration ⊨ ConfigSchema invariant
41
274
  const configJson = this.TypeConfiguration;
42
275
  if (!configJson || configJson.trim().length === 0) {
43
- return result; // null/empty = type defaults apply; nothing to validate
276
+ return result;
44
277
  }
45
278
  const configDirty = this.GetFieldByName('TypeConfiguration')?.Dirty ?? false;
46
279
  const typeDirty = this.GetFieldByName('TypeID')?.Dirty ?? false;
47
280
  if (this.IsSaved && !configDirty && !typeDirty) {
48
- return result; // unchanged configuration against an unchanged type — already validated
281
+ return result;
49
282
  }
50
283
  const schemaJson = await this.loadTypeConfigSchema();
51
284
  const errors = BuildTypeConfigurationValidationErrors(configJson, schemaJson);
52
285
  if (errors.length > 0) {
53
286
  result.Errors.push(...errors);
54
- result.Success = errors.every((e) => e.Type !== ValidationErrorType.Failure);
287
+ result.Success = result.Success && errors.every((e) => e.Type !== ValidationErrorType.Failure);
55
288
  }
56
289
  return result;
57
290
  }
58
291
  /**
59
- * Loads the agent type's `ConfigSchema` through the same request-scoped provider that owns
60
- * this entity. Returns `null` (freeform) when the agent has no type, the type row cannot be
61
- * loaded, or no schema is published.
292
+ * Copies core capability defaults from `baseAgent` onto a newly-created derived instance
293
+ * ONLY for fields the caller left untouched (not dirty). This ensures newly minted instances
294
+ * like *Pepper* immediately inherit `TypeID`, `AcceptsSkills`, `SkillActivationMode`,
295
+ * `ModelSelectionMode`, `Isolation`, and memory settings without requiring every caller to
296
+ * manually copy 20 columns.
62
297
  */
298
+ inheritDefaultsFromBaseAgent(baseAgent) {
299
+ const copyIfNotDirty = (fieldName) => {
300
+ const field = this.GetFieldByName(String(fieldName));
301
+ if (field && !field.Dirty) {
302
+ const baseVal = baseAgent[fieldName];
303
+ if (baseVal !== undefined) {
304
+ this[fieldName] = baseVal;
305
+ }
306
+ }
307
+ };
308
+ if (!this.TypeID && baseAgent.TypeID) {
309
+ this.TypeID = baseAgent.TypeID;
310
+ }
311
+ copyIfNotDirty('ModelSelectionMode');
312
+ copyIfNotDirty('AcceptsSkills');
313
+ copyIfNotDirty('SkillActivationMode');
314
+ copyIfNotDirty('SearchScopeAccess');
315
+ copyIfNotDirty('ArtifactCreationMode');
316
+ copyIfNotDirty('DefaultArtifactTypeID');
317
+ copyIfNotDirty('InjectNotes');
318
+ copyIfNotDirty('MaxNotesToInject');
319
+ copyIfNotDirty('NoteInjectionStrategy');
320
+ copyIfNotDirty('InjectExamples');
321
+ copyIfNotDirty('MaxExamplesToInject');
322
+ copyIfNotDirty('ExampleInjectionStrategy');
323
+ copyIfNotDirty('AllowMemoryWrite');
324
+ copyIfNotDirty('DeclareActionsAsNativeTools');
325
+ copyIfNotDirty('Isolation');
326
+ copyIfNotDirty('SupportsPlanMode');
327
+ copyIfNotDirty('RequirePlanMode');
328
+ copyIfNotDirty('EnableContextCompression');
329
+ copyIfNotDirty('ContextCompressionMessageThreshold');
330
+ copyIfNotDirty('ContextCompressionPromptID');
331
+ copyIfNotDirty('ContextCompressionMessageRetentionCount');
332
+ copyIfNotDirty('RerankerConfiguration');
333
+ copyIfNotDirty('ContextWindowMaxTokens');
334
+ copyIfNotDirty('CompactionTriggerPercent');
335
+ copyIfNotDirty('CompactionTargetPercent');
336
+ copyIfNotDirty('ConversationSummaryPromptID');
337
+ if (!this.CategoryID && baseAgent.CategoryID) {
338
+ this.CategoryID = baseAgent.CategoryID;
339
+ }
340
+ }
341
+ findRootBaseAgentId(start, allAgents) {
342
+ const agentsById = IndexByUUID(allAgents);
343
+ const visited = new UUIDSet([start.ID]);
344
+ let cursor = start;
345
+ let hops = 0;
346
+ while (cursor.BaseAgentID && hops < MAX_AGENT_INHERITANCE_DEPTH) {
347
+ if (visited.Has(cursor.BaseAgentID)) {
348
+ break;
349
+ }
350
+ visited.Add(cursor.BaseAgentID);
351
+ const parent = agentsById.Get(cursor.BaseAgentID);
352
+ if (!parent) {
353
+ return cursor.BaseAgentID;
354
+ }
355
+ cursor = parent;
356
+ hops++;
357
+ }
358
+ return cursor.ID;
359
+ }
360
+ findActiveSiblingsForOwnerAndRoot(allAgents, ownerUserId, rootBaseId, excludeAgentId) {
361
+ return allAgents.filter((a) => {
362
+ if (a.Status !== 'Active' || !a.BaseAgentID || !UUIDsEqual(a.OwnerUserID, ownerUserId)) {
363
+ return false;
364
+ }
365
+ if (excludeAgentId && UUIDsEqual(a.ID, excludeAgentId)) {
366
+ return false;
367
+ }
368
+ const aRoot = a.RootBaseAgentID ?? this.findRootBaseAgentId(a, allAgents);
369
+ return UUIDsEqual(aRoot, rootBaseId);
370
+ });
371
+ }
372
+ async clearOtherPrimaryInstances(ownerUserId, rootBaseId, currentAgentId) {
373
+ const rv = new RunView(this.RunViewProviderToUse);
374
+ const safeOwner = EscapeSQLString(ownerUserId);
375
+ const res = await rv.RunView({
376
+ EntityName: 'MJ: AI Agents',
377
+ ExtraFilter: `OwnerUserID='${safeOwner}' AND BaseAgentID IS NOT NULL AND IsPrimaryInstance=1 AND Status='Active'`,
378
+ ResultType: 'entity_object',
379
+ }, this.ContextCurrentUser);
380
+ if (!res.Success || res.Results.length === 0) {
381
+ return;
382
+ }
383
+ const allAgents = await this.loadAllAgentsForGuard();
384
+ for (const sibling of res.Results) {
385
+ if (UUIDsEqual(sibling.ID, currentAgentId)) {
386
+ continue;
387
+ }
388
+ const sibRoot = sibling.RootBaseAgentID ?? this.findRootBaseAgentId(sibling, allAgents);
389
+ if (UUIDsEqual(sibRoot, rootBaseId)) {
390
+ sibling.IsPrimaryInstance = false;
391
+ await sibling.Save();
392
+ }
393
+ }
394
+ }
395
+ async loadAllAgentsForGuard() {
396
+ const rv = new RunView(this.RunViewProviderToUse);
397
+ const res = await rv.RunView({
398
+ EntityName: 'MJ: AI Agents',
399
+ ResultType: 'entity_object',
400
+ }, this.ContextCurrentUser);
401
+ return res.Success ? res.Results : [];
402
+ }
403
+ async loadAllAgentPermissionsForGuard() {
404
+ const rv = new RunView(this.RunViewProviderToUse);
405
+ const res = await rv.RunView({
406
+ EntityName: 'MJ: AI Agent Permissions',
407
+ ResultType: 'entity_object',
408
+ }, this.ContextCurrentUser);
409
+ return res.Success ? res.Results : [];
410
+ }
63
411
  async loadTypeConfigSchema() {
64
412
  if (!this.TypeID) {
65
413
  return null;
66
414
  }
67
- const md = this.ProviderToUse;
68
- const type = await md.GetEntityObject('MJ: AI Agent Types', this.ContextCurrentUser);
415
+ if (!IsMetadataProvider(this.ProviderToUse)) {
416
+ return null;
417
+ }
418
+ const type = await this.ProviderToUse.GetEntityObject('MJ: AI Agent Types', this.ContextCurrentUser);
69
419
  if (!(await type.Load(this.TypeID))) {
70
- return null; // dangling TypeID is the FK constraint's problem, not this check's
420
+ return null;
71
421
  }
72
422
  return type.ConfigSchema ?? null;
73
423
  }
@@ -78,17 +428,7 @@ MJAIAgentEntityServer = __decorate([
78
428
  export { MJAIAgentEntityServer };
79
429
  /**
80
430
  * 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).
431
+ * unit tests and reuse).
92
432
  */
93
433
  export function BuildTypeConfigurationValidationErrors(typeConfigurationJson, configSchemaJson) {
94
434
  let config;
@@ -106,7 +446,7 @@ export function BuildTypeConfigurationValidationErrors(typeConfigurationJson, co
106
446
  ];
107
447
  }
108
448
  if (!configSchemaJson || configSchemaJson.trim().length === 0) {
109
- return []; // no published schema — freeform configuration
449
+ return [];
110
450
  }
111
451
  let schema;
112
452
  try {