Member Junction
    Preparing search index...

    Type Alias ExecuteAgentParams<TContext, P, TAgentTypeParams>

    Parameters required to execute an AI Agent.

    // Define a typed context
    interface MyAgentContext {
    apiEndpoint: string;
    userPreferences: { language: string; timezone: string };
    sessionId: string;
    }

    // Use with type safety
    const params: ExecuteAgentParams<MyAgentContext> = {
    agent: myAgent,
    conversationMessages: messages,
    context: {
    apiEndpoint: 'https://api.example.com',
    userPreferences: { language: 'en', timezone: 'UTC' },
    sessionId: 'abc123'
    }
    };

    // Flow agent with type-specific params
    import { FlowAgentExecuteParams } from '@memberjunction/ai-agents';
    const flowParams: ExecuteAgentParams<any, any, FlowAgentExecuteParams> = {
    agent: myFlowAgent,
    conversationMessages: messages,
    agentTypeParams: {
    startAtStep: someStepEntity, // Start at a specific step
    skipSteps: [stepToSkip] // Skip certain steps
    }
    };
    type ExecuteAgentParams<TContext = any, P = any, TAgentTypeParams = unknown> = {
        absoluteMaxIterations?: number;
        actionChanges?: ActionChange[];
        agent: MJAIAgentEntityExtended;
        agentSessionID?: string;
        agentTypeParams?: TAgentTypeParams;
        apiKeys?: AIAPIKey[];
        assignmentStrategy?: AgentRequestAssignmentStrategy;
        autoPopulateLastRunPayload?: boolean;
        cancellationToken?: AbortSignal;
        clientToolTimeoutMs?: number;
        companyId?: string;
        configurationId?: string;
        context?: TContext;
        contextUser?: UserInfo;
        conversationDetailId?: string;
        conversationId?: string;
        conversationMessages: ChatMessage[];
        convertUIMarkupToPlainText?: boolean;
        data?: Record<string, any>;
        disableDataPreloading?: boolean;
        effortLevel?: number;
        inputArtifacts?: InputArtifact[];
        lastRunId?: string;
        maxExecutionTimeMs?: number;
        messageExpirationOverride?: MessageExpirationOverride;
        onAgentRunCreated?: (agentRunId: string) => void | Promise<void>;
        onMessageLifecycle?: MessageLifecycleCallback;
        onProgress?: AgentExecutionProgressCallback;
        onStreaming?: AgentExecutionStreamingCallback;
        override?: {
            modelId?: string;
            storageAccountId?: string;
            vendorId?: string;
        };
        parentAgentHierarchy?: string[];
        parentDepth?: number;
        parentRun?: MJAIAgentRunEntityExtended;
        parentStepCounts?: number[];
        payload?: P;
        planMode?: boolean;
        PrimaryScopeEntityName?: string;
        PrimaryScopeRecordID?: string;
        provider?: IMetadataProvider;
        requestedSkillIDs?: string[];
        SecondaryScopes?: Record<string, SecondaryScopeValue>;
        sessionID?: string;
        subAgentChanges?: SubAgentChange[];
        testRunId?: string;
        userId?: string;
        verbose?: boolean;
    }

    Type Parameters

    • TContext = any

      Type of the context object passed through agent and action execution. This allows for type-safe context propagation throughout the execution hierarchy. TContext may be a class instance with getters and methods — never spread it. Defaults to any for backward compatibility.

    • P = any

      Type of the payload passed to the agent execution

    • TAgentTypeParams = unknown

      Type of agent-type-specific execution parameters. Flow agents use FlowAgentExecuteParams, Loop agents could define their own. Defaults to unknown for backward compatibility.

    Index

    Properties

    absoluteMaxIterations?: number

    Optional absolute maximum number of iterations (steps) for the agent run. This provides a hard limit safety net to prevent infinite loops in case of configuration errors or unexpected agent behavior. This value overrides any agent-level MaxIterationsPerRun setting if it is lower.

    If not specified, defaults to 5000 iterations as a safety measure. Use a higher value only if you have a legitimate need for very long-running agents.

    This is different from MaxIterationsPerRun (agent metadata guardrail):

    • MaxIterationsPerRun: Configurable per-agent business rule
    • absoluteMaxIterations: System-wide safety limit (default: 5000)
    5000
    
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    absoluteMaxIterations: 10000, // Allow more iterations for this specific run
    };
    actionChanges?: ActionChange[]

    Optional runtime modifications to the agent's available actions.

    Action changes allow dynamic customization of which actions are available to agents at runtime, without modifying database configuration. This is particularly useful for:

    • Multi-tenant scenarios where different executions need different integrations
    • Security restrictions where sub-agents should have limited action access
    • Testing scenarios with controlled action availability

    Changes are applied in order. For each agent in the hierarchy:

    1. Start with the agent's configured actions (from AIAgentAction table)
    2. Apply each ActionChange that matches the agent's scope
    3. The resulting action set is what the agent sees and can invoke

    Changes are propagated to sub-agents based on scope:

    • 'global': Propagated as-is to all sub-agents
    • 'root': Not propagated (only applies to root)
    • 'all-subagents': Propagated as 'global' to sub-agents
    • 'specific': Propagated as-is, each agent checks if it's in agentIds
    // Add LMS and CRM integrations for a specific tenant
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    actionChanges: [
    {
    scope: 'global',
    mode: 'add',
    actionIds: ['lms-query-action-id', 'crm-search-action-id']
    }
    ]
    };

    // Remove dangerous actions from sub-agents
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    actionChanges: [
    {
    scope: 'all-subagents',
    mode: 'remove',
    actionIds: ['delete-record-action-id', 'execute-sql-action-id']
    }
    ]
    };

    // Different actions for specific sub-agent
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    actionChanges: [
    { scope: 'global', mode: 'add', actionIds: ['common-action-id'] },
    {
    scope: 'specific',
    mode: 'add',
    actionIds: ['special-data-action-id'],
    agentIds: ['data-gatherer-sub-agent-id']
    }
    ]
    };

    2.123.0

    The agent entity to execute, containing all metadata and configuration

    agentSessionID?: string

    The persisted MJ: AI Agent Sessions record ID this run belongs to, if the run is part of a real-time/long-lived session. Distinct from the transport sessionID (per-connection correlation id). Used to group the multiple AIAgentRuns of one session and to stamp ConversationDetail/AIAgentRun rows.

    agentTypeParams?: TAgentTypeParams

    Optional agent-type-specific execution parameters.

    Different agent types can define their own parameter interfaces for type-specific configuration that doesn't belong in the general ExecuteAgentParams.

    Examples:

    • Flow agents: FlowAgentExecuteParams with startAtStep, skipSteps
    • Loop agents: Could define LoopAgentExecuteParams with custom iteration controls

    The type is determined by the TAgentTypeParams generic parameter. When using a specific agent type, import and use its params interface for type safety.

    import { FlowAgentExecuteParams } from '@memberjunction/ai-agents';

    const params: ExecuteAgentParams<any, any, FlowAgentExecuteParams> = {
    agent: myFlowAgent,
    conversationMessages: messages,
    agentTypeParams: {
    startAtStep: AIEngine.Instance.GetAgentSteps(agentId).find(s => s.Name === 'Approval'),
    skipSteps: [debugStep, testStep]
    }
    };

    2.127.0

    apiKeys?: AIAPIKey[]

    Optional array of API keys to use for AI provider access during agent execution. When provided, these keys will be used instead of the default keys configured in the system. This allows for runtime-specific API key usage, useful for:

    • Multi-tenant scenarios where different users have different API keys
    • Testing with different API key configurations
    • Isolating API usage by application or user

    Each key should specify the driverClass (e.g., 'OpenAILLM', 'AnthropicLLM') and the corresponding apiKey value.

    assignmentStrategy?: AgentRequestAssignmentStrategy

    Optional per-invocation override for feedback request assignment. Takes highest precedence over all metadata-driven defaults (agent type, category, request type).

    When an agent creates a feedback request via Chat step, this strategy determines who the request is assigned to and how. If not provided, the framework walks the resolution chain:

    1. This field (highest precedence)
    2. Agent Type's AssignmentStrategy
    3. Agent's Category AssignmentStrategy (walks up ParentID tree)
    4. Request Type's DefaultAssignmentStrategy
    5. Fallback: assign to contextUser + console warning

    5.12.0

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    assignmentStrategy: {
    type: 'SpecificUser',
    userID: 'finance-manager-user-id',
    priority: 75,
    expirationMinutes: 1440
    }
    };
    autoPopulateLastRunPayload?: boolean

    Optional flag to automatically populate the payload from the last run. When true and lastRunId is provided, the framework will:

    1. Load the last run's FinalPayload
    2. Set it as the StartingPayload for the new run
    3. Use it as the initial payload if no payload is explicitly provided This helps maintain state across run chains and reduces bandwidth by avoiding passing large payloads back and forth.
    cancellationToken?: AbortSignal

    Optional cancellation token to abort the agent execution

    clientToolTimeoutMs?: number

    Optional runtime override for client tool timeout (ms). Takes precedence over the agent's DefaultClientToolTimeoutMs config.

    companyId?: string

    Optional company ID for scoping context memory (notes/examples)

    configurationId?: string

    Optional AI Configuration ID to use for this agent execution. When provided, this configuration will be passed to all prompts executed by this agent and its sub-agents, enabling environment-specific model selection (e.g., Prod vs Dev configurations).

    The configuration ID filters which AI models are available for prompt execution and can provide configuration parameters for dynamic behavior.

    context?: TContext

    Optional additional context data to pass to the agent execution. This context is propagated to all sub-agents and actions throughout the execution hierarchy. Use this for runtime-specific data such as:

    • Environment-specific configuration (API endpoints, feature flags)
    • User-specific settings or preferences
    • Session-specific data (request IDs, correlation IDs)
    • External service credentials or connection information

    IMPORTANT — class instances are supported and must be preserved. TContext may be a class with getters, methods, and private state (e.g., Skip's SkipAgentContext). Any code that touches this object must NOT spread it into a plain object ({...context}) because the spread operator strips the prototype chain, destroying all getters and methods. Instead, mutate properties directly on the original object when augmentation is needed.

    Note: Avoid including sensitive data like passwords or API keys unless absolutely necessary, as context may be passed to multiple agents and actions.

    contextUser?: UserInfo

    Optional user context for permission checking and personalization

    conversationDetailId?: string

    Optional conversation detail ID to associate with this agent execution. When provided, this value is stored in the ConversationDetailID column within the to be created AIAgentRun record. This allows for linking the agent run to a specific conversation detail for tracking and reporting purposes.

    conversationId?: string

    Optional conversation ID — the PREFERRED input for conversation-driven runs. All durable cross-turn context features (persistent summary compaction, the summary-windowed context assembly via ConversationEngine.AssembleContextWindow over LoadWindowRowsFresh rows, and conversation-history retrieval tools) are gated on this being present. When absent, the agent behaves exactly as before: the caller supplies conversationMessages and only in-turn (per-run) context management applies — programmatic runs, internal sub-agent invocations, and tests need no change. When present alongside caller-supplied conversationMessages, the supplied messages win (deliberate override/escape hatch); the id still flows to the run record and gates the compaction/retrieval features.

    conversationMessages: ChatMessage[]

    Array of chat messages representing the conversation history

    convertUIMarkupToPlainText?: boolean

    Optional flag to convert UI markup (@{...} syntax) in user messages to plain text before passing to the agent.

    When true (default), special UI syntax like mentions (@{_mode:"mention",...}) and form responses (@{_mode:"form",...}) are converted to human-readable plain text:

    • Mentions: "@Agent Name" or "@User Name"
    • Forms: "Field1: Value1, Field2: Value2"

    When false, the raw @{...} JSON is preserved in conversation history.

    This prevents agents from:

    • Getting confused by UI-specific JSON syntax
    • Wasting tokens on markup that doesn't provide useful context
    • Trying to replicate or interpret UI-specific formatting
    true
    
    // Default behavior - convert to plain text
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages, // "@{_mode:"mention",...}" becomes "@Agent Name"
    };

    // Preserve raw markup (not recommended)
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    convertUIMarkupToPlainText: false, // Keep raw @{...} syntax
    };
    data?: Record<string, any>

    Optional data for template rendering and prompt execution, passed to the agent's prompt as well as all sub-agents

    disableDataPreloading?: boolean

    Optional flag to disable data preloading from AIAgentDataSource metadata. When true, the agent will not automatically preload data sources even if they are configured in the database. This is useful for:

    • Performance optimization when preloaded data is not needed
    • Testing scenarios where you want to control data explicitly
    • Cases where the caller provides all necessary data manually

    Default: false (data preloading is enabled)

    Note: Caller-provided data in the data parameter always takes precedence over preloaded data, even when preloading is enabled.

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    disableDataPreloading: true, // Skip automatic data preloading
    data: { CUSTOM_DATA: myData } // Use only caller-provided data
    };
    effortLevel?: number

    Optional effort level for all prompt executions in this agent run (1-100).

    Higher values request more thorough reasoning and analysis from AI models. This effort level takes precedence over the agent's DefaultPromptEffortLevel and individual prompt EffortLevel settings for all prompts executed during this agent run.

    Each provider maps the 1-100 scale to their specific effort parameters:

    • OpenAI: Maps to reasoning_effort (1-33=low, 34-66=medium, 67-100=high)
    • Anthropic: Maps to thinking mode with token budgets
    • Groq: Maps to reasoning_effort parameter (experimental)
    • Gemini: Controls reasoning mode intensity

    This setting is inherited by all sub-agents unless they explicitly override it.

    Precedence hierarchy (highest to lowest priority):

    1. This effortLevel parameter (runtime override - highest priority)
    2. Agent's DefaultPromptEffortLevel (agent default)
    3. Prompt's EffortLevel property (prompt default)
    4. No effort level (provider default behavior - lowest priority)
    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    effortLevel: 85, // High effort for thorough analysis across all prompts
    contextUser: user
    };

    const result = await agent.Execute(params);
    inputArtifacts?: InputArtifact[]

    Optional input artifacts for this run. Consumed by the agent's ArtifactToolManager: each artifact is registered, surfaced in the _ARTIFACT_MANIFEST template variable, and reached by the LLM via artifact tool calls (json_path, json_search, etc.).

    Not propagated to sub-agents — sub-agents that need artifact access gather their own from the conversation in AgentRunner.

    InputArtifact

    lastRunId?: string

    Optional ID of the last run in a run chain. When provided, this links the new run to a previous run, allowing agents to maintain context across multiple interactions. Different from parentRun which is for sub-agent hierarchy.

    maxExecutionTimeMs?: number

    Optional wall-clock timeout for the entire agent run, in milliseconds. When set, BaseAgent wraps the execution in an internal AbortController that fires after this many ms. The abort propagates through the existing cancellationToken chain — sub-agents, pending prompt calls, and actions (which carry their own RunActionParams.AbortSignal) all see the cancellation. On timeout, the run terminates with an Aborted result whose message identifies the timeout origin.

    When omitted, BaseAgent falls back to its DefaultAgentTimeoutMS (currently 2 hours) — generous by default because some Loop agents do legitimate long iteration; tighten per-run for anything interactive.

    messageExpirationOverride?: MessageExpirationOverride

    Optional runtime override for message expiration behavior. When specified, these values take precedence over the AIAgentAction configuration for all action results in this agent run. Useful for testing, debugging, or implementing custom expiration strategies.

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    messageExpirationOverride: {
    expirationTurns: 2,
    expirationMode: 'Compact',
    compactMode: 'First N Chars',
    compactLength: 500,
    preserveOriginalContent: true
    }
    };
    onAgentRunCreated?: (agentRunId: string) => void | Promise<void>

    Optional callback fired immediately after the AgentRun record is created and saved. Provides the AgentRun ID for immediate tracking/monitoring purposes.

    This callback is useful for:

    • Linking the AgentRun to parent records (e.g., AIAgentRunStep.TargetLogID for sub-agents)
    • Real-time monitoring and tracking
    • Early logging and debugging

    The callback is invoked after the AgentRun is successfully saved but before the actual agent execution begins. If the callback throws an error, it will be logged but won't fail the agent execution.

    Type Declaration

      • (agentRunId: string): void | Promise<void>
      • Parameters

        • agentRunId: string

          The ID of the newly created AIAgentRun record

        Returns void | Promise<void>

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    onAgentRunCreated: async (agentRunId) => {
    console.log(`Agent run started: ${agentRunId}`);
    // Update parent records, send monitoring events, etc.
    }
    };
    onMessageLifecycle?: MessageLifecycleCallback

    Optional callback for message lifecycle events. Called when messages are expired, compacted, removed, or expanded during agent execution. Useful for monitoring, debugging, and tracking token savings.

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    onMessageLifecycle: (event) => {
    console.log(`[Turn ${event.turn}] ${event.type}: ${event.reason}`);
    if (event.tokensSaved) {
    console.log(` Tokens saved: ${event.tokensSaved}`);
    }
    }
    };

    Optional callback for receiving execution progress updates

    Optional callback for receiving streaming content updates

    override?: { modelId?: string; storageAccountId?: string; vendorId?: string }

    Optional runtime override for agent execution. When specified, these values take precedence over all other model selection methods. Currently supports model and vendor overrides, but can be extended in the future.

    Model selection precedence (highest to lowest):

    1. Runtime override (this parameter)
    2. Agent's ModelSelectionMode configuration:
      • If "Agent": Uses the agent's specific prompt model configuration
      • If "Agent Type" (default): Uses the agent type's system prompt model configuration
    3. Default model selection based on prompt configuration

    This override is passed to all prompt executions within the agent, allowing consistent model usage throughout the agent's execution hierarchy.

    Type Declaration

    • OptionalmodelId?: string
    • OptionalstorageAccountId?: string

      Runtime override for the file storage account used when creating file artifacts. Highest priority in the resolution chain: Runtime → Agent → Category tree → Type → system fallback. Resolves to a FileStorageAccount record which carries both the provider driver (via ProviderID) and credentials (via CredentialID).

    • OptionalvendorId?: string
    parentAgentHierarchy?: string[]

    Optional parent agent hierarchy for sub-agent execution

    parentDepth?: number

    Optional parent depth for sub-agent execution

    Optional parent agent run entity for nested sub-agent execution

    parentStepCounts?: number[]

    Optional parent step counts from root to immediate parent agent. Used to build hierarchical step display (e.g., "2.1.3" for nested agents).

    • Managed automatically by agent execution framework
    payload?: P

    Optional payload to pass to the agent execution, type depends on agent implementation. Payload is the ongoing dynamic state of the agent run.

    planMode?: boolean

    Per-request Plan Mode toggle. Defaults OFF (undefined/false) — no behavior change unless explicitly set. When true AND agent.SupportsPlanMode is on (the agent-level capability gate, default ON/opt-out) AND this is a root agent (depth 0), the agent must present a Plan next step and get human approval via the standard MJ: AI Agent Requests / response-form HITL flow before it may execute Actions or Sub-Agents. Ignored entirely for Realtime/session-driven and Proxy agents (those opt the capability OFF at the agent level).

    On a continuation run (lastRunId set, after the user responds to the plan-approval request), the framework re-resolves whether that prior run's plan was approved — callers do not need to re-derive or persist this themselves.

    5.44.0

    PrimaryScopeEntityName?: string

    Primary scope entity name (e.g., 'Organizations', 'Skip Tenants'). Resolved to PrimaryScopeEntityID on the AIAgentRun record. Used by external applications for multi-tenant memory scoping. Not used by MJ's own chat infrastructure.

    2.132.0

    PrimaryScopeRecordID?: string

    Primary scope record ID — the actual record ID within the primary entity. Stored as an indexed column on AIAgentRun/AIAgentNote for fast filtering. Used by external applications for multi-tenant memory scoping. Not used by MJ's own chat infrastructure.

    2.132.0

    Optional per-request metadata provider for multi-user server isolation. Pass the request-scoped provider from the GraphQL context so agent DB operations never share the global singleton's transaction state with concurrent requests. When omitted, falls back to the global Metadata.Provider (safe for single-user/client-side use).

    requestedSkillIDs?: string[]

    Skills the caller (typically an end user via a /skill-name mention in the composer) explicitly requests be active for this run, identified by AISkill.ID. The framework treats these as pre-activation hints: at run start each requested skill is activated (its Instructions appended + bundled Actions/sub-agents surfaced) only if it survives the guard — it must be in the set the agent accepts (MJAIAgentEntityExtended.AcceptsSkills gate) AND the requesting user must have Run permission on it (open-by-default via AISkillPermissionHelper). Requested skills that fail either check are silently dropped, never surfaced to the model — so a client can never smuggle in a skill the user or agent isn't entitled to. Root-agent only (skills don't cascade to sub-agents). Defaults to none.

    5.44.0

    SecondaryScopes?: Record<string, SecondaryScopeValue>

    Arbitrary key/value dimensions for external-app scoping. Stored as JSON in the SecondaryScopes column on AIAgentRun/AIAgentNote. Used by external applications (Skip, Izzy, etc.) to segment agent memory by custom dimensions. MJ's own chat infrastructure does not use this.

    2.132.0

    params.SecondaryScopes = {
    ContactID: 'contact-456',
    TeamID: 'team-alpha',
    Region: 'EMEA'
    };
    sessionID?: string

    Optional session ID for client tool communication. When provided, enables the agent to invoke client-side tools via PubSub. The session ID correlates tool requests/responses between server and client.

    subAgentChanges?: SubAgentChange[]

    Optional runtime modifications to the agent's available sub-agents.

    The sub-agent counterpart of actionChanges. Lets callers dynamically add or remove which sub-agents are available to agents at runtime, without modifying database configuration. Changes are applied per agent in the hierarchy and propagated to sub-agents by the same scope rules as action changes ('global'/'root'/'all-subagents'/'specific').

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    subAgentChanges: [
    { scope: 'global', mode: 'add', subAgentIds: ['fraud-specialist-agent-id'] }
    ]
    };

    2.132.0

    testRunId?: string

    Optional test run ID to associate with this agent execution. When provided, this value is stored in the TestRunID column within the AIAgentRun record, linking the agent run to a specific test run from the MemberJunction testing framework for tracking and reporting purposes.

    const params: ExecuteAgentParams = {
    agent: myAgent,
    conversationMessages: messages,
    testRunId: '12345678-1234-1234-1234-123456789012', // Link to test run
    };
    userId?: string

    Optional user ID for scoping context memory (notes/examples). If not provided, uses contextUser.ID

    verbose?: boolean

    Optional flag to enable verbose logging during agent execution. When true, detailed information about agent decision-making, action selection, sub-agent invocations, and execution flow will be logged. Can also be controlled via MJ_VERBOSE environment variable.