User class for managing platform users

This class represents a user account in the Mosaia platform. Users are the primary actors who can create and manage AI resources, interact with agents, and collaborate within organizations.

Features:

  • Profile management
  • Resource ownership
  • Organization membership
  • Access control
  • Resource management

Users can manage:

  • AI agents and groups
  • Applications
  • Models and tools
  • Organization memberships
  • OAuth clients

Available resources:

  • Personal agents
  • Custom applications
  • Model configurations
  • Integration tools
  • Organization access

Basic user setup:

import { User } from 'mosaia-node-sdk';

// Create user profile
const user = new User({
username: 'jsmith',
name: 'John Smith',
email: 'john@example.com',
metadata: {
title: 'Senior Developer',
department: 'Engineering',
location: 'San Francisco'
}
});

await user.save();

// Add profile image
const image = new File(['...'], 'avatar.jpg', { type: 'image/jpeg' });
await user.uploadProfileImage(image);

Resource management:

// Access user's resources
const [agents, apps, models] = await Promise.all([
user.agents.get(),
user.apps.get(),
user.models.get()
]);

console.log('User Resources:');
console.log(`- ${agents.length} AI agents`);
console.log(`- ${apps.length} applications`);
console.log(`- ${models.length} models`);

// Create new agent
const agent = await user.agents.create({
name: 'Personal Assistant',
model: 'gpt-4',
temperature: 0.7,
system_prompt: 'You are a helpful assistant.'
});

// Create application
const app = await user.apps.create({
name: 'Task Manager',
short_description: 'AI-powered task management'
});

// Check organization memberships
const orgs = await user.orgs.get();
orgs.forEach(org => {
console.log(`${org.org.name}: ${org.permission}`);
});

Hierarchy (View Summary)

Constructors

  • Creates a new user profile

    Initializes a user account with the provided profile information. Users are the primary actors in the platform who can create and manage AI resources.

    Parameters

    • data: Partial<UserInterface>

      Profile data including: - username: Unique identifier - name: Display name - email: Contact email - description: Bio or description - metadata: Additional profile data

    • Optionaluri: string

      Optional custom URI path for the user endpoint

    Returns User

    Basic profile:

    const user = new User({
    username: 'jdoe',
    name: 'Jane Doe',
    email: 'jane@example.com',
    description: 'AI Developer'
    });

    Detailed profile:

    const user = new User({
    username: 'jsmith',
    name: 'John Smith',
    email: 'john@example.com',
    description: 'Senior AI Engineer',
    metadata: {
    title: 'Engineering Lead',
    department: 'AI Research',
    location: 'New York',
    skills: ['machine-learning', 'nlp', 'python'],
    joined_date: new Date().toISOString(),
    preferences: {
    theme: 'dark',
    notifications: true,
    language: 'en-US'
    }
    }
    }, '/enterprise/user');

Accessors

  • get agents(): Agents

    Get the user's AI agents

    This getter provides access to the user's AI agents through the Agents collection. It enables management of personal agents and their configurations.

    Returns Agents

    Agents collection for managing AI agents

    List agents:

    const agents = await user.agents.get();
    agents.forEach(agent => {
    console.log(`Agent: ${agent.name}`);
    console.log(`Model: ${agent.model}`);
    });

    Create agent:

    const agent = await user.agents.create({
    name: 'Code Assistant',
    model: 'gpt-4',
    temperature: 0.7,
    system_prompt: 'You are an expert programmer.',
    metadata: {
    purpose: 'code-review',
    languages: ['typescript', 'python', 'go']
    }
    });
  • get apps(): Apps

    Get the user's applications

    This getter provides access to the user's applications through the Apps collection. It enables management of personal applications and their configurations.

    Returns Apps

    Apps collection for managing applications

    List applications:

    const apps = await user.apps.get();
    apps.forEach(app => {
    console.log(`App: ${app.name}`);
    console.log(`URL: ${app.external_app_url}`);
    });

    Create application:

    const app = await user.apps.create({
    name: 'AI Dashboard',
    short_description: 'Personal AI management',
    external_app_url: 'https://dashboard.example.com',
    metadata: {
    type: 'web-application',
    features: ['agent-management', 'analytics'],
    version: '1.0'
    }
    });
  • get clients(): Clients

    Get the user's OAuth clients

    This getter provides access to the user's OAuth clients through the Clients collection. It enables management of authentication and authorization for external applications.

    Returns Clients

    Clients collection for managing OAuth clients

    List clients:

    const clients = await user.clients.get();
    clients.forEach(client => {
    console.log(`Client: ${client.name}`);
    console.log(`ID: ${client.client_id}`);
    });

    Create OAuth client:

    const client = await user.clients.create({
    name: 'Mobile App',
    redirect_uris: ['com.example.app://oauth/callback'],
    scopes: ['read:agents', 'write:apps'],
    metadata: {
    platform: 'ios',
    version: '2.0',
    environment: 'production'
    }
    });

    console.log('Client credentials:');
    console.log(`ID: ${client.client_id}`);
    console.log(`Secret: ${client.client_secret}`);
  • get models(): Models

    Get the user's AI models

    This getter provides access to the user's AI models through the Models collection. It enables management of model configurations and customizations.

    Returns Models

    Models collection for managing AI models

    List models:

    const models = await user.models.get();
    models.forEach(model => {
    console.log(`Model: ${model.name}`);
    console.log(`Provider: ${model.provider}`);
    console.log(`ID: ${model.model_id}`);
    });

    Create custom model:

    const model = await user.models.create({
    name: 'Enhanced GPT-4',
    provider: 'openai',
    model_id: 'gpt-4',
    temperature: 0.7,
    max_tokens: 2000,
    metadata: {
    purpose: 'code-generation',
    training: 'fine-tuned',
    version: '1.0',
    specialties: ['typescript', 'python'],
    performance: {
    avg_latency: 500,
    max_concurrent: 10
    }
    }
    });
  • get orgs(): OrgUsers

    Get the user's organization memberships

    This getter provides access to the user's organization memberships through the OrgUsers collection. It enables management of team memberships and organization access.

    Returns OrgUsers

    OrgUsers collection for managing organization memberships

    List memberships:

    const memberships = await user.orgs.get();
    memberships.forEach(membership => {
    console.log(`Organization: ${membership.org.name}`);
    console.log(`Role: ${membership.permission}`);
    console.log(`Active: ${membership.isActive()}`);
    });

    Manage memberships:

    // Join organization
    const membership = await user.orgs.create({
    org: 'org-123',
    permission: 'member',
    metadata: {
    department: 'engineering',
    title: 'Senior Developer',
    start_date: new Date().toISOString()
    }
    });

    // Get authenticated session
    const config = await membership.session();
    const mosaia = new Mosaia(config);

    // Access organization resources
    const orgAgents = await mosaia.agents.get();
    console.log(`Organization has ${orgAgents.length} agents`);
  • get tools(): Tools

    Get the user's integration tools

    This getter provides access to the user's integration tools through the Tools collection. It enables management of external service integrations and custom tools.

    Returns Tools

    Tools collection for managing integrations

    List tools:

    const tools = await user.tools.get();
    tools.forEach(tool => {
    console.log(`Tool: ${tool.name}`);
    console.log(`Type: ${tool.type}`);
    console.log(`Schema: ${tool.tool_schema}`);
    });

    Create integration:

    const tool = await user.tools.create({
    name: 'jira-integration',
    friendly_name: 'Jira Service',
    short_description: 'Create and manage Jira issues',
    tool_schema: JSON.stringify({
    type: 'object',
    properties: {
    project: {
    type: 'string',
    description: 'Jira project key'
    },
    type: {
    type: 'string',
    enum: ['bug', 'task', 'story'],
    default: 'task'
    },
    title: {
    type: 'string',
    minLength: 1
    },
    description: {
    type: 'string'
    },
    priority: {
    type: 'string',
    enum: ['high', 'medium', 'low'],
    default: 'medium'
    }
    },
    required: ['project', 'title']
    }),
    required_environment_variables: [
    'JIRA_HOST',
    'JIRA_EMAIL',
    'JIRA_API_TOKEN'
    ],
    source_url: 'https://your-domain.atlassian.net',
    metadata: {
    type: 'issue-tracker',
    provider: 'atlassian',
    version: '1.0',
    capabilities: ['create', 'read', 'update']
    }
    });
  • get image(): Image

    Get the image functionality for this user's profile

    This getter provides access to the user's profile image operations through the Image class. It allows for profile image uploads and other image-related operations specific to this user.

    Returns Image

    A new Image instance configured for this user's profile

    const updatedUser = await user.image.upload<User, GetUserPayload>(file);
    
  • get policies(): AccessPolicies

    Get the user's access policies

    This getter provides access to the user's access control policies through the AccessPolicies collection. It enables management of IAM policies that define fine-grained permissions for resources and actions.

    Returns AccessPolicies

    AccessPolicies collection for managing access control policies

    const policies = await user.policies.get();
    const policy = await user.policies.create({
    name: 'Personal Access',
    effect: 'allow',
    actions: ['agents:read', 'apps:read'],
    resources: ['agents', 'apps']
    });
  • get permissions(): UserPermissions

    Get the user's permissions

    This getter provides access to the user's permissions through the UserPermissions collection. It enables management of permissions that associate clients with access policies for this user.

    Returns UserPermissions

    UserPermissions collection for managing user permissions

    const permissions = await user.permissions.get();
    const permission = await user.permissions.create({
    client: 'client-id',
    policy: 'policy-id'
    });
  • get meters(): Meters

    Get the user's usage meters

    This getter provides access to the user's usage meters through the Meters collection. It enables tracking of service consumption and associated costs for billing purposes.

    Returns Meters

    Meters collection for managing usage meters

    const meters = await user.meters.get();
    
  • get wallets(): Wallets

    Get the user's wallet

    This getter provides access to the user's wallet through the Wallets collection. It enables management of balances, payment methods, and financial transactions.

    Returns Wallets

    Wallets collection for managing the user wallet

    const wallet = await user.wallets.get();
    

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns UserInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<UserInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    • updates: Partial<UserInterface>

      Object containing properties to update

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<UserInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }