var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    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;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Resolver, Mutation, Query, Arg, Ctx, ObjectType, Field, PubSub, PubSubEngine, ID, Int } from 'type-graphql';
import { LogError, LogStatus, Metadata, RunView } from '@memberjunction/core';
import { AgentRunner } from '@memberjunction/ai-agents';
import { ConversationUtility } from '@memberjunction/ai-core-plus';
import { AIEngine } from '@memberjunction/aiengine';
import { ResolverBase } from '../generic/ResolverBase.js';
import { PUSH_STATUS_UPDATES_TOPIC } from '../generic/PushStatusResolver.js';
import { RequireSystemUser } from '../directives/RequireSystemUser.js';
import { GetReadWriteProvider } from '../util.js';
import { SafeJSONParse } from '@memberjunction/global';
import { getAttachmentService } from '@memberjunction/aiengine';
let AIAgentRunResult = class AIAgentRunResult {
    success;
    errorMessage;
    executionTimeMs;
    result;
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], AIAgentRunResult.prototype, "success", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AIAgentRunResult.prototype, "errorMessage", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", Number)
], AIAgentRunResult.prototype, "executionTimeMs", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], AIAgentRunResult.prototype, "result", void 0);
AIAgentRunResult = __decorate([
    ObjectType()
], AIAgentRunResult);
export { AIAgentRunResult };
let AgentExecutionProgress = class AgentExecutionProgress {
    currentStep;
    percentage;
    message;
    agentName;
    agentType;
    stepCount;
    hierarchicalStep;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionProgress.prototype, "currentStep", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", Number)
], AgentExecutionProgress.prototype, "percentage", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionProgress.prototype, "message", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionProgress.prototype, "agentName", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionProgress.prototype, "agentType", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", Number)
], AgentExecutionProgress.prototype, "stepCount", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionProgress.prototype, "hierarchicalStep", void 0);
AgentExecutionProgress = __decorate([
    ObjectType()
], AgentExecutionProgress);
export { AgentExecutionProgress };
let AgentStreamingContent = class AgentStreamingContent {
    content;
    isPartial;
    stepName;
    agentName;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentStreamingContent.prototype, "content", void 0);
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], AgentStreamingContent.prototype, "isPartial", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentStreamingContent.prototype, "stepName", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentStreamingContent.prototype, "agentName", void 0);
AgentStreamingContent = __decorate([
    ObjectType()
], AgentStreamingContent);
export { AgentStreamingContent };
let AgentExecutionStepSummary = class AgentExecutionStepSummary {
    stepId;
    stepName;
    agentName;
    agentType;
    startTime;
    endTime;
    status;
    result;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "stepId", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "stepName", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "agentName", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "agentType", void 0);
__decorate([
    Field(),
    __metadata("design:type", Date)
], AgentExecutionStepSummary.prototype, "startTime", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", Date)
], AgentExecutionStepSummary.prototype, "endTime", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "status", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentExecutionStepSummary.prototype, "result", void 0);
AgentExecutionStepSummary = __decorate([
    ObjectType()
], AgentExecutionStepSummary);
export { AgentExecutionStepSummary };
let AgentPartialResult = class AgentPartialResult {
    currentStep;
    partialOutput;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentPartialResult.prototype, "currentStep", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], AgentPartialResult.prototype, "partialOutput", void 0);
AgentPartialResult = __decorate([
    ObjectType()
], AgentPartialResult);
export { AgentPartialResult };
let AgentExecutionStreamMessage = class AgentExecutionStreamMessage {
    sessionId;
    agentRunId;
    type;
    progress;
    streaming;
    partialResult;
    timestamp;
    agentRun;
};
__decorate([
    Field(() => ID),
    __metadata("design:type", String)
], AgentExecutionStreamMessage.prototype, "sessionId", void 0);
__decorate([
    Field(() => ID),
    __metadata("design:type", String)
], AgentExecutionStreamMessage.prototype, "agentRunId", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], AgentExecutionStreamMessage.prototype, "type", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", AgentExecutionProgress)
], AgentExecutionStreamMessage.prototype, "progress", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", AgentStreamingContent)
], AgentExecutionStreamMessage.prototype, "streaming", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", AgentPartialResult)
], AgentExecutionStreamMessage.prototype, "partialResult", void 0);
__decorate([
    Field(),
    __metadata("design:type", Date)
], AgentExecutionStreamMessage.prototype, "timestamp", void 0);
AgentExecutionStreamMessage = __decorate([
    ObjectType()
], AgentExecutionStreamMessage);
export { AgentExecutionStreamMessage };
let RunAIAgentResolver = class RunAIAgentResolver extends ResolverBase {
    sanitizeAgentResult(result) {
        const sanitized = {
            success: result.success,
            payload: result.payload,
            responseForm: result.responseForm,
            actionableCommands: result.actionableCommands,
            automaticCommands: result.automaticCommands,
            errorMessage: result.agentRun?.ErrorMessage,
            finalStep: result.agentRun?.FinalStep,
            cancelled: result.agentRun?.Status === 'Cancelled',
            cancellationReason: result.agentRun?.CancellationReason
        };
        if (result.agentRun && typeof result.agentRun.GetAll === 'function') {
            sanitized.agentRun = result.agentRun.GetAll();
        }
        else {
            console.error('❌ Unexpected agent run structure:', result.agentRun);
        }
        return sanitized;
    }
    parseJsonInput(jsonString, fieldName) {
        if (!jsonString)
            return {};
        try {
            return JSON.parse(jsonString);
        }
        catch (parseError) {
            throw new Error(`Invalid JSON in ${fieldName}: ${parseError.message}`);
        }
    }
    extractUserMessage(messages) {
        if (!Array.isArray(messages) || messages.length === 0) {
            return undefined;
        }
        for (let i = messages.length - 1; i >= 0; i--) {
            const msg = messages[i];
            if (msg && msg.role === 'user' && msg.content) {
                return msg.content;
            }
        }
        return undefined;
    }
    async validateAgent(agentId, currentUser) {
        await AIEngine.Instance.Config(false, currentUser);
        const agentEntity = AIEngine.Instance.Agents.find((a) => a.ID === agentId);
        if (!agentEntity) {
            throw new Error(`AI Agent with ID ${agentId} not found`);
        }
        if (agentEntity.Status !== 'Active') {
            throw new Error(`AI Agent "${agentEntity.Name}" is not active (Status: ${agentEntity.Status})`);
        }
        return agentEntity;
    }
    createProgressCallback(pubSub, sessionId, userPayload, agentRunRef) {
        return (progress) => {
            const significantSteps = ['prompt_execution', 'action_execution', 'subagent_execution', 'decision_processing'];
            if (!significantSteps.includes(progress.step)) {
                console.log(`🔇 Skipping noise progress: ${progress.step}`);
                return;
            }
            const agentRun = progress.metadata?.agentRun || agentRunRef.current;
            if (!agentRun) {
                console.error('❌ No agent run available for progress callback');
                return;
            }
            console.log('📡 Publishing progress update:', {
                step: progress.step,
                percentage: progress.percentage,
                message: progress.message,
                sessionId,
                agentRunId: agentRun.ID
            });
            const progressMsg = {
                sessionId,
                agentRunId: agentRun.ID,
                type: 'progress',
                agentRun: agentRun.GetAll(),
                progress: {
                    currentStep: progress.step,
                    percentage: progress.percentage,
                    message: progress.message,
                    agentName: progress.metadata?.agentName || undefined,
                    agentType: progress.metadata?.agentType || undefined,
                    stepCount: progress.metadata?.stepCount || undefined,
                    hierarchicalStep: progress.metadata?.hierarchicalStep || undefined
                },
                timestamp: new Date()
            };
            this.PublishProgressUpdate(pubSub, progressMsg, userPayload);
        };
    }
    PublishProgressUpdate(pubSub, data, userPayload) {
        pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, {
            message: JSON.stringify({
                resolver: 'RunAIAgentResolver',
                type: 'ExecutionProgress',
                status: 'ok',
                data,
            }),
            sessionId: userPayload.sessionId,
        });
    }
    PublishStreamingUpdate(pubSub, data, userPayload) {
        pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, {
            message: JSON.stringify({
                resolver: 'RunAIAgentResolver',
                type: 'StreamingContent',
                status: 'ok',
                data,
            }),
            sessionId: userPayload.sessionId,
        });
    }
    createStreamingCallback(pubSub, sessionId, userPayload, agentRunRef) {
        return (chunk) => {
            const agentRun = agentRunRef.current;
            if (!agentRun) {
                console.error('❌ No agent run available for streaming callback');
                return;
            }
            console.log('💬 Publishing streaming content:', {
                content: chunk.content.substring(0, 50) + '...',
                isComplete: chunk.isComplete,
                stepType: chunk.stepType,
                sessionId,
                agentRunId: agentRun.ID
            });
            const streamMsg = {
                sessionId,
                agentRunId: agentRun.ID,
                type: 'streaming',
                agentRun: agentRun.GetAll(),
                streaming: {
                    content: chunk.content,
                    isPartial: !chunk.isComplete,
                    stepName: chunk.stepType,
                    agentName: chunk.modelName
                },
                timestamp: new Date()
            };
            this.PublishStreamingUpdate(pubSub, streamMsg, userPayload);
        };
    }
    async executeAIAgent(p, dataSource, agentId, userPayload, messagesJson, sessionId, pubSub, data, payload, templateData, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts = false, createNotification = false, sourceArtifactId, sourceArtifactVersionId) {
        const startTime = Date.now();
        try {
            LogStatus(`=== RUNNING AI AGENT FOR ID: ${agentId} ===`);
            const parsedMessages = this.parseJsonInput(messagesJson, 'messages');
            if (!Array.isArray(parsedMessages)) {
                throw new Error('Messages must be an array');
            }
            const userMessage = this.extractUserMessage(parsedMessages);
            const parsedData = this.parseJsonInput(data, 'data');
            const parsedTemplateData = this.parseJsonInput(templateData, 'templateData');
            const currentUser = this.GetUserFromPayload(userPayload);
            if (!currentUser) {
                throw new Error('Unable to determine current user');
            }
            const agentEntity = await this.validateAgent(agentId, currentUser);
            const agentRunner = new AgentRunner();
            const agentRunRef = { current: null };
            console.log(`🚀 Starting agent execution with sessionId: ${sessionId}`);
            const conversationResult = await agentRunner.RunAgentInConversation({
                agent: agentEntity,
                conversationMessages: parsedMessages,
                payload: payload ? SafeJSONParse(payload) : undefined,
                contextUser: currentUser,
                onProgress: this.createProgressCallback(pubSub, sessionId, userPayload, agentRunRef),
                onStreaming: this.createStreamingCallback(pubSub, sessionId, userPayload, agentRunRef),
                lastRunId: lastRunId,
                autoPopulateLastRunPayload: autoPopulateLastRunPayload,
                configurationId: configurationId,
                data: parsedData,
                context: {
                    dataSource: dataSource
                }
            }, {
                conversationDetailId: conversationDetailId,
                userMessage: userMessage,
                createArtifacts: createArtifacts || false,
                sourceArtifactId: sourceArtifactId
            });
            const result = conversationResult.agentResult;
            const finalConversationDetailId = conversationResult.agentResponseDetailId || conversationResult.userMessageDetailId;
            const artifactInfo = conversationResult.artifactInfo;
            if (result.agentRun) {
                agentRunRef.current = result.agentRun;
            }
            const executionTime = Date.now() - startTime;
            this.publishFinalEvents(pubSub, sessionId, userPayload, result);
            if (createNotification && result.success && artifactInfo && artifactInfo.artifactId && artifactInfo.versionId && artifactInfo.versionNumber) {
                await this.createCompletionNotification(result.agentRun, {
                    artifactId: artifactInfo.artifactId,
                    versionId: artifactInfo.versionId,
                    versionNumber: artifactInfo.versionNumber
                }, finalConversationDetailId, currentUser, pubSub, userPayload);
            }
            const sanitizedResult = this.sanitizeAgentResult(result);
            const returnResult = JSON.stringify(sanitizedResult);
            if (result.success) {
                LogStatus(`=== AI AGENT RUN COMPLETED FOR: ${agentEntity.Name} (${executionTime}ms) ===`);
            }
            else {
                LogError(`AI Agent run failed for ${agentEntity.Name}: ${result.agentRun?.ErrorMessage}`);
            }
            return {
                success: result.success,
                errorMessage: result.agentRun?.ErrorMessage || undefined,
                executionTimeMs: executionTime,
                result: returnResult
            };
        }
        catch (error) {
            const executionTime = Date.now() - startTime;
            LogError(`AI Agent run failed:`, undefined, error);
            const errorResult = {
                success: false,
                errorMessage: error.message || 'Unknown error occurred',
                executionTimeMs: executionTime
            };
            return {
                success: false,
                errorMessage: errorResult.errorMessage,
                executionTimeMs: executionTime,
                result: JSON.stringify(errorResult)
            };
        }
    }
    publishFinalEvents(pubSub, sessionId, userPayload, result) {
        if (result.agentRun) {
            let lastStep = 'Completed';
            if (result.agentRun?.Steps && result.agentRun.Steps.length > 0) {
                const lastStepEntity = result.agentRun.Steps[result.agentRun.Steps.length - 1];
                lastStep = lastStepEntity?.StepName || 'Completed';
            }
            const partialResult = {
                currentStep: lastStep,
                partialOutput: result.payload || undefined
            };
            const partialMsg = {
                sessionId,
                agentRunId: result.agentRun.ID,
                type: 'partial_result',
                partialResult,
                timestamp: new Date()
            };
            this.PublishStreamingUpdate(pubSub, partialMsg, userPayload);
        }
        const completeMsg = {
            sessionId,
            agentRunId: result.agentRun?.ID || 'unknown',
            type: 'complete',
            timestamp: new Date()
        };
        this.PublishStreamingUpdate(pubSub, completeMsg, userPayload);
    }
    async RunAIAgent(agentId, { userPayload, providers, dataSource }, messagesJson, sessionId, pubSub, data, payload, templateData, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts, createNotification, sourceArtifactId, sourceArtifactVersionId) {
        const p = GetReadWriteProvider(providers);
        return this.executeAIAgent(p, dataSource, agentId, userPayload, messagesJson, sessionId, pubSub, data, payload, templateData, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts || false, createNotification || false, sourceArtifactId, sourceArtifactVersionId);
    }
    async RunAIAgentSystemUser(agentId, { userPayload, providers, dataSource }, messagesJson, sessionId, pubSub, data, payload, templateData, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts, createNotification, sourceArtifactId, sourceArtifactVersionId) {
        const p = GetReadWriteProvider(providers);
        return this.executeAIAgent(p, dataSource, agentId, userPayload, messagesJson, sessionId, pubSub, data, payload, templateData, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts || false, createNotification || false, sourceArtifactId, sourceArtifactVersionId);
    }
    async createCompletionNotification(agentRun, artifactInfo, conversationDetailId, contextUser, pubSub, userPayload) {
        try {
            const md = new Metadata();
            await AIEngine.Instance.Config(false, contextUser);
            const agent = AIEngine.Instance.Agents.find(a => a.ID === agentRun.AgentID);
            const agentName = agent?.Name || 'Agent';
            const detail = await md.GetEntityObject('Conversation Details', contextUser);
            if (!(await detail.Load(conversationDetailId))) {
                throw new Error(`Failed to load conversation detail ${conversationDetailId}`);
            }
            const notification = await md.GetEntityObject('User Notifications', contextUser);
            notification.UserID = contextUser.ID;
            notification.Title = `${agentName} completed your request`;
            if (artifactInfo.versionNumber > 1) {
                notification.Message = `${agentName} has finished processing and created version ${artifactInfo.versionNumber}`;
            }
            else {
                notification.Message = `${agentName} has finished processing and created a new artifact`;
            }
            notification.ResourceConfiguration = JSON.stringify({
                type: 'conversation',
                conversationId: detail.ConversationID,
                messageId: conversationDetailId,
                artifactId: artifactInfo.artifactId,
                versionNumber: artifactInfo.versionNumber
            });
            notification.Unread = true;
            if (!(await notification.Save())) {
                throw new Error('Failed to save notification');
            }
            LogStatus(`📬 Created notification ${notification.ID} for user ${contextUser.ID}`);
            pubSub.publish(PUSH_STATUS_UPDATES_TOPIC, {
                userPayload: JSON.stringify(userPayload),
                message: JSON.stringify({
                    type: 'notification',
                    notificationId: notification.ID,
                    action: 'create',
                    title: notification.Title,
                    message: notification.Message
                })
            });
            LogStatus(`📡 Published notification event to client`);
        }
        catch (error) {
            LogError(`Failed to create completion notification: ${error.message}`);
        }
    }
    async RunAIAgentFromConversationDetail(conversationDetailId, agentId, { userPayload, providers, dataSource }, sessionId, pubSub, maxHistoryMessages, data, payload, lastRunId, autoPopulateLastRunPayload, configurationId, createArtifacts, createNotification, sourceArtifactId, sourceArtifactVersionId) {
        const p = GetReadWriteProvider(providers);
        const currentUser = this.GetUserFromPayload(userPayload);
        if (!currentUser) {
            return {
                success: false,
                errorMessage: 'Unable to determine current user',
                result: JSON.stringify({ success: false, errorMessage: 'Unable to determine current user' })
            };
        }
        try {
            const messages = await this.loadConversationHistoryWithAttachments(conversationDetailId, currentUser, maxHistoryMessages || 20);
            const messagesJson = JSON.stringify(messages);
            return this.executeAIAgent(p, dataSource, agentId, userPayload, messagesJson, sessionId, pubSub, data, payload, undefined, lastRunId, autoPopulateLastRunPayload, configurationId, conversationDetailId, createArtifacts || false, createNotification || false, sourceArtifactId, sourceArtifactVersionId);
        }
        catch (error) {
            const errorMessage = error.message || 'Unknown error loading conversation history';
            LogError(`RunAIAgentFromConversationDetail failed: ${errorMessage}`, undefined, error);
            return {
                success: false,
                errorMessage,
                result: JSON.stringify({ success: false, errorMessage })
            };
        }
    }
    async loadConversationHistoryWithAttachments(conversationDetailId, contextUser, maxMessages) {
        const md = new Metadata();
        const rv = new RunView();
        const attachmentService = getAttachmentService();
        const currentDetail = await md.GetEntityObject('Conversation Details', contextUser);
        if (!await currentDetail.Load(conversationDetailId)) {
            throw new Error(`Conversation detail ${conversationDetailId} not found`);
        }
        const conversationId = currentDetail.ConversationID;
        const detailsResult = await rv.RunView({
            EntityName: 'Conversation Details',
            ExtraFilter: `ConversationID='${conversationId}'`,
            OrderBy: '__mj_CreatedAt DESC',
            MaxRows: maxMessages,
            ResultType: 'entity_object'
        }, contextUser);
        if (!detailsResult.Success || !detailsResult.Results) {
            throw new Error('Failed to load conversation history');
        }
        const details = detailsResult.Results.reverse();
        const messageIds = details.map(d => d.ID);
        const attachmentsByDetailId = await attachmentService.getAttachmentsBatch(messageIds, contextUser);
        const messages = [];
        for (const detail of details) {
            const role = this.mapDetailRoleToMessageRole(detail.Role);
            const attachments = attachmentsByDetailId.get(detail.ID) || [];
            const attachmentDataPromises = attachments.map(att => attachmentService.getAttachmentData(att, contextUser));
            const attachmentDataResults = await Promise.all(attachmentDataPromises);
            const validAttachments = attachmentDataResults
                .filter((result) => result !== null)
                .map(result => ({
                type: ConversationUtility.GetAttachmentTypeFromMime(result.attachment.MimeType),
                mimeType: result.attachment.MimeType,
                fileName: result.attachment.FileName ?? undefined,
                sizeBytes: result.attachment.FileSizeBytes ?? undefined,
                width: result.attachment.Width ?? undefined,
                height: result.attachment.Height ?? undefined,
                durationSeconds: result.attachment.DurationSeconds ?? undefined,
                content: result.contentUrl
            }));
            let content;
            if (validAttachments.length > 0) {
                content = ConversationUtility.BuildChatMessageContent(detail.Message || '', validAttachments);
            }
            else {
                content = detail.Message || '';
            }
            messages.push({
                role,
                content
            });
        }
        return messages;
    }
    mapDetailRoleToMessageRole(role) {
        const roleLower = (role || '').toLowerCase();
        if (roleLower === 'user')
            return 'user';
        if (roleLower === 'assistant' || roleLower === 'agent')
            return 'assistant';
        if (roleLower === 'system')
            return 'system';
        return 'user';
    }
};
__decorate([
    Mutation(() => AIAgentRunResult),
    __param(0, Arg('agentId')),
    __param(1, Ctx()),
    __param(2, Arg('messages')),
    __param(3, Arg('sessionId')),
    __param(4, PubSub()),
    __param(5, Arg('data', { nullable: true })),
    __param(6, Arg('payload', { nullable: true })),
    __param(7, Arg('templateData', { nullable: true })),
    __param(8, Arg('lastRunId', { nullable: true })),
    __param(9, Arg('autoPopulateLastRunPayload', { nullable: true })),
    __param(10, Arg('configurationId', { nullable: true })),
    __param(11, Arg('conversationDetailId', { nullable: true })),
    __param(12, Arg('createArtifacts', { nullable: true })),
    __param(13, Arg('createNotification', { nullable: true })),
    __param(14, Arg('sourceArtifactId', { nullable: true })),
    __param(15, Arg('sourceArtifactVersionId', { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, PubSubEngine, String, String, String, String, Boolean, String, String, Boolean, Boolean, String, String]),
    __metadata("design:returntype", Promise)
], RunAIAgentResolver.prototype, "RunAIAgent", null);
__decorate([
    RequireSystemUser(),
    Query(() => AIAgentRunResult),
    __param(0, Arg('agentId')),
    __param(1, Ctx()),
    __param(2, Arg('messages')),
    __param(3, Arg('sessionId')),
    __param(4, PubSub()),
    __param(5, Arg('data', { nullable: true })),
    __param(6, Arg('payload', { nullable: true })),
    __param(7, Arg('templateData', { nullable: true })),
    __param(8, Arg('lastRunId', { nullable: true })),
    __param(9, Arg('autoPopulateLastRunPayload', { nullable: true })),
    __param(10, Arg('configurationId', { nullable: true })),
    __param(11, Arg('conversationDetailId', { nullable: true })),
    __param(12, Arg('createArtifacts', { nullable: true })),
    __param(13, Arg('createNotification', { nullable: true })),
    __param(14, Arg('sourceArtifactId', { nullable: true })),
    __param(15, Arg('sourceArtifactVersionId', { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, PubSubEngine, String, String, String, String, Boolean, String, String, Boolean, Boolean, String, String]),
    __metadata("design:returntype", Promise)
], RunAIAgentResolver.prototype, "RunAIAgentSystemUser", null);
__decorate([
    Mutation(() => AIAgentRunResult),
    __param(0, Arg('conversationDetailId')),
    __param(1, Arg('agentId')),
    __param(2, Ctx()),
    __param(3, Arg('sessionId')),
    __param(4, PubSub()),
    __param(5, Arg('maxHistoryMessages', () => Int, { nullable: true })),
    __param(6, Arg('data', { nullable: true })),
    __param(7, Arg('payload', { nullable: true })),
    __param(8, Arg('lastRunId', { nullable: true })),
    __param(9, Arg('autoPopulateLastRunPayload', { nullable: true })),
    __param(10, Arg('configurationId', { nullable: true })),
    __param(11, Arg('createArtifacts', { nullable: true })),
    __param(12, Arg('createNotification', { nullable: true })),
    __param(13, Arg('sourceArtifactId', { nullable: true })),
    __param(14, Arg('sourceArtifactVersionId', { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, Object, String, PubSubEngine, Number, String, String, String, Boolean, String, Boolean, Boolean, String, String]),
    __metadata("design:returntype", Promise)
], RunAIAgentResolver.prototype, "RunAIAgentFromConversationDetail", null);
RunAIAgentResolver = __decorate([
    Resolver()
], RunAIAgentResolver);
export { RunAIAgentResolver };
//# sourceMappingURL=RunAIAgentResolver.js.map