/**
 * Orchestrator Message Types (TB-O14a)
 *
 * Defines typed message conventions for inter-agent communication.
 * These types extend the base Stoneforge messaging system with
 * orchestrator-specific semantics.
 *
 * Message types:
 * - task-assignment: New task has been assigned to an agent
 * - status-update: Progress update from an agent
 * - help-request: Agent requesting assistance
 * - handoff: Session handoff between agents
 * - health-check: Health monitoring ping
 *
 * @module
 */
import { createTimestamp } from '@stoneforge/core';
// ============================================================================
// Message Type Constants
// ============================================================================
/**
 * Known message types for orchestrator inter-agent communication.
 */
export const MessageTypeValue = {
    TASK_ASSIGNMENT: 'task-assignment',
    STATUS_UPDATE: 'status-update',
    HELP_REQUEST: 'help-request',
    HANDOFF: 'handoff',
    HEALTH_CHECK: 'health-check',
    GENERIC: 'generic',
};
/**
 * Array of all message type values for iteration
 */
export const AllMessageTypes = Object.values(MessageTypeValue);
/**
 * Validates a TaskAssignmentMessage
 */
export function isTaskAssignmentMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'task-assignment')
        return false;
    if (typeof value.taskId !== 'string')
        return false;
    if (typeof value.taskTitle !== 'string')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated TaskAssignmentMessage
 */
export function createTaskAssignmentMessage(input) {
    return {
        type: 'task-assignment',
        timestamp: input.timestamp ?? createTimestamp(),
        taskId: input.taskId,
        taskTitle: input.taskTitle,
        priority: input.priority,
        assignedBy: input.assignedBy,
        branch: input.branch,
        worktree: input.worktree,
        isReassignment: input.isReassignment,
        previousAssignee: input.previousAssignee,
        correlationId: input.correlationId,
    };
}
// ============================================================================
// Status Update Message (TB-O14a)
// ============================================================================
/**
 * Status update severity levels
 */
export const StatusUpdateSeverity = {
    INFO: 'info',
    WARNING: 'warning',
    ERROR: 'error',
};
/**
 * Validates a StatusUpdateMessage
 */
export function isStatusUpdateMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'status-update')
        return false;
    if (typeof value.agentId !== 'string')
        return false;
    if (typeof value.message !== 'string')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated StatusUpdateMessage
 */
export function createStatusUpdateMessage(input) {
    return {
        type: 'status-update',
        timestamp: input.timestamp ?? createTimestamp(),
        agentId: input.agentId,
        message: input.message,
        severity: input.severity,
        taskId: input.taskId,
        progress: input.progress,
        phase: input.phase,
        details: input.details,
        correlationId: input.correlationId,
    };
}
// ============================================================================
// Help Request Message (TB-O14a)
// ============================================================================
/**
 * Help request urgency levels
 */
export const HelpRequestUrgency = {
    LOW: 'low',
    NORMAL: 'normal',
    HIGH: 'high',
    CRITICAL: 'critical',
};
/**
 * Validates a HelpRequestMessage
 */
export function isHelpRequestMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'help-request')
        return false;
    if (typeof value.agentId !== 'string')
        return false;
    if (typeof value.problem !== 'string')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated HelpRequestMessage
 */
export function createHelpRequestMessage(input) {
    return {
        type: 'help-request',
        timestamp: input.timestamp ?? createTimestamp(),
        agentId: input.agentId,
        problem: input.problem,
        attemptedSolutions: input.attemptedSolutions,
        taskId: input.taskId,
        urgency: input.urgency,
        errorMessage: input.errorMessage,
        stackTrace: input.stackTrace,
        suggestedActions: input.suggestedActions,
        correlationId: input.correlationId,
    };
}
/**
 * Validates a HandoffMessage
 */
export function isHandoffMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'handoff')
        return false;
    if (typeof value.fromAgent !== 'string')
        return false;
    if (!Array.isArray(value.taskIds))
        return false;
    if (typeof value.contextSummary !== 'string')
        return false;
    if (typeof value.isSelfHandoff !== 'boolean')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated HandoffMessage
 */
export function createHandoffMessage(input) {
    return {
        type: 'handoff',
        timestamp: input.timestamp ?? createTimestamp(),
        fromAgent: input.fromAgent,
        toAgent: input.toAgent,
        taskIds: input.taskIds,
        contextSummary: input.contextSummary,
        nextSteps: input.nextSteps,
        reason: input.reason,
        providerSessionId: input.providerSessionId,
        handoffDocumentId: input.handoffDocumentId,
        isSelfHandoff: input.isSelfHandoff ?? (input.toAgent === undefined),
        correlationId: input.correlationId,
    };
}
// ============================================================================
// Health Check Message (TB-O14a)
// ============================================================================
/**
 * Health check result status
 */
export const HealthCheckStatus = {
    HEALTHY: 'healthy',
    DEGRADED: 'degraded',
    UNHEALTHY: 'unhealthy',
    UNKNOWN: 'unknown',
};
/**
 * Validates a HealthCheckMessage
 */
export function isHealthCheckMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'health-check')
        return false;
    if (typeof value.targetAgentId !== 'string')
        return false;
    if (typeof value.sourceAgentId !== 'string')
        return false;
    if (typeof value.isResponse !== 'boolean')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated HealthCheckMessage (request)
 */
export function createHealthCheckRequest(input) {
    return {
        type: 'health-check',
        timestamp: input.timestamp ?? createTimestamp(),
        targetAgentId: input.targetAgentId,
        sourceAgentId: input.sourceAgentId,
        isResponse: false,
        correlationId: input.correlationId ?? `health-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    };
}
/**
 * Creates a validated HealthCheckMessage (response)
 */
export function createHealthCheckResponse(input) {
    return {
        type: 'health-check',
        timestamp: input.timestamp ?? createTimestamp(),
        targetAgentId: input.targetAgentId,
        sourceAgentId: input.sourceAgentId,
        isResponse: true,
        status: input.status,
        lastActivityAt: input.lastActivityAt,
        currentTaskId: input.currentTaskId,
        metrics: input.metrics,
        correlationId: input.correlationId,
    };
}
/**
 * Validates a GenericMessage
 */
export function isGenericMessage(value) {
    if (!isObject(value))
        return false;
    if (value.type !== 'generic')
        return false;
    if (!isTimestamp(value.timestamp))
        return false;
    return true;
}
/**
 * Creates a validated GenericMessage
 */
export function createGenericMessage(input) {
    return {
        type: 'generic',
        timestamp: input.timestamp ?? createTimestamp(),
        content: input.content,
        data: input.data,
        correlationId: input.correlationId,
    };
}
// ============================================================================
// Validation Utilities
// ============================================================================
/**
 * Validates any orchestrator message
 */
export function isOrchestratorMessage(value) {
    if (!isObject(value))
        return false;
    switch (value.type) {
        case 'task-assignment':
            return isTaskAssignmentMessage(value);
        case 'status-update':
            return isStatusUpdateMessage(value);
        case 'help-request':
            return isHelpRequestMessage(value);
        case 'handoff':
            return isHandoffMessage(value);
        case 'health-check':
            return isHealthCheckMessage(value);
        case 'generic':
            return isGenericMessage(value);
        default:
            return false;
    }
}
/**
 * Parses a message from raw metadata
 */
export function parseMessageMetadata(metadata) {
    if (!isOrchestratorMessage(metadata)) {
        return null;
    }
    return metadata;
}
/**
 * Extracts message type from raw metadata
 */
export function getMessageType(metadata) {
    if (!isObject(metadata))
        return null;
    const type = metadata.type;
    if (typeof type !== 'string')
        return null;
    if (AllMessageTypes.includes(type)) {
        return type;
    }
    return null;
}
/**
 * Validates message type value
 */
export function isMessageType(value) {
    return typeof value === 'string' && AllMessageTypes.includes(value);
}
// ============================================================================
// Internal Helpers
// ============================================================================
function isObject(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isTimestamp(value) {
    // Timestamps can be numbers or ISO strings
    if (typeof value === 'number' && value > 0)
        return true;
    if (typeof value === 'string') {
        const date = new Date(value);
        return !isNaN(date.getTime());
    }
    return false;
}
//# sourceMappingURL=message-types.js.map