import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo } from "react";
import { Bug } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger, } from "../../../../components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../../../components/ui/tooltip";
import { AgentCostDisplay } from "./AgentCostDisplay";
import { ContentInspectorPopover, } from "../../ContentInspectorPopover";
import { formatAgentDiagnosticsEvent, formatSeqRanges, interpretAgentRunDiagnostics, } from "../../agentDiagnostics";
import { HeartbeatDiagnosticsPanel } from "../../HeartbeatDiagnosticsPanel";
function formatDiagnosticTime(value) {
    if (!value)
        return "—";
    const parsed = new Date(value);
    return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
}
function yesNo(value) {
    return value ? "Yes" : "No";
}
function lines(values) {
    return values.filter(Boolean).join("\n");
}
function joinSubsections(subsections) {
    return subsections
        .map((s) => s && s.content
        ? `── ${s.title} ──\n${s.content}`
        : null)
        .filter((v) => Boolean(v))
        .join("\n\n");
}
const CLIENT_SOCKET_RAW_MESSAGE_MAX_LENGTH = 10_000;
function formatClientSocketMessageEvent(event) {
    const header = formatAgentDiagnosticsEvent(event);
    const raw = event.rawMessage;
    if (!raw) {
        return header;
    }
    const payloadSize = event.payloadBytes != null ? `Payload bytes: ${event.payloadBytes}\n` : "";
    const formattedRaw = raw.length > CLIENT_SOCKET_RAW_MESSAGE_MAX_LENGTH
        ? `${raw.slice(0, CLIENT_SOCKET_RAW_MESSAGE_MAX_LENGTH)}\n... [truncated ${raw.length - CLIENT_SOCKET_RAW_MESSAGE_MAX_LENGTH} characters from client WebSocket payload]`
        : raw;
    return `${header}\n${payloadSize}${formattedRaw}`;
}
function formatMachineCapacityLimit(value) {
    return value > 0 ? String(value) : "Unlimited";
}
function buildMachineCapacitySection(currentAgentId, serverDiagnostics) {
    const machineCapacity = serverDiagnostics.machineCapacity;
    if (!machineCapacity)
        return null;
    const occupantBlocks = machineCapacity.occupants.length > 0
        ? machineCapacity.occupants
            .map((occupant, index) => lines([
            `Slot ${index + 1}: ${occupant.agentName || occupant.agentId}`,
            `Agent ID: ${occupant.agentId}`,
            occupant.runId ? `Run ID: ${occupant.runId}` : null,
            `Status: ${occupant.status || "unknown"}`,
            occupant.mode ? `Mode: ${occupant.mode}` : null,
            occupant.userId ? `User: ${occupant.userId}` : null,
            `Started: ${formatDiagnosticTime(occupant.startedAt)}`,
            `Completed: ${formatDiagnosticTime(occupant.completedAt)}`,
            `Active task: ${yesNo(Boolean(occupant.hasActiveExecutionTask))}`,
            `In execution loop: ${yesNo(Boolean(occupant.isInExecutionLoop))}`,
            occupant.executionTaskStatus
                ? `Task status: ${occupant.executionTaskStatus}`
                : null,
            occupant.sessionId ? `Session ID: ${occupant.sessionId}` : null,
            occupant.agentId === currentAgentId ? "Current agent: Yes" : null,
        ]))
            .join("\n\n")
        : "Current slot holders: None";
    return {
        title: "Instance capacity (this instance, admin)",
        content: `${lines([
            `Reporting instance: ${machineCapacity.currentInstanceId || "(non-cluster / unconfigured)"}`,
            'Note: "Max Running Agents" is enforced per-instance. Other cluster instances each have their own slot pool.',
            `Max running agents (this instance): ${formatMachineCapacityLimit(machineCapacity.maxRunningAgents)}`,
            `Actively running executions (this instance): ${machineCapacity.runningExecutions}`,
        ])}\n\n${occupantBlocks}`.trim(),
    };
}
function normalizeInspectorText(value) {
    if (typeof value !== "string")
        return null;
    const normalized = value.replace(/\r\n/g, "\n").trim();
    return normalized.length > 0 ? normalized : null;
}
function extractTextFromUnknown(value, depth = 0) {
    if (depth > 5 || value == null)
        return [];
    if (typeof value === "string") {
        const normalized = normalizeInspectorText(value);
        return normalized ? [normalized] : [];
    }
    if (Array.isArray(value)) {
        return value.flatMap((entry) => extractTextFromUnknown(entry, depth + 1));
    }
    if (typeof value !== "object") {
        return [];
    }
    const record = value;
    if (typeof record.text === "string") {
        return extractTextFromUnknown(record.text, depth + 1);
    }
    if (typeof record.content === "string") {
        return extractTextFromUnknown(record.content, depth + 1);
    }
    const candidates = [
        record.content,
        record.parts,
        record.messages,
        record.message,
        record.input,
        record.output,
        record.prompt,
        record.response,
        record.arguments,
    ];
    for (const candidate of candidates) {
        const extracted = extractTextFromUnknown(candidate, depth + 1);
        if (extracted.length > 0)
            return extracted;
    }
    return [];
}
function joinExtractedText(value) {
    const text = extractTextFromUnknown(value).join("\n").trim();
    return text.length > 0 ? text : null;
}
function extractLastPromptFromPayload(payload) {
    const normalizedPayload = normalizeInspectorText(payload);
    if (!normalizedPayload)
        return null;
    try {
        const parsed = JSON.parse(normalizedPayload);
        const messages = Array.isArray(parsed.messages)
            ? parsed.messages
            : Array.isArray(parsed.input)
                ? parsed.input
                : [];
        for (let i = messages.length - 1; i >= 0; i--) {
            const message = messages[i];
            const role = String(message?.role || "").toLowerCase();
            if (role !== "user")
                continue;
            const extracted = joinExtractedText(message?.content ?? message);
            if (extracted)
                return extracted;
        }
        return joinExtractedText(parsed.prompt ?? parsed.input ?? parsed.messages);
    }
    catch {
        return null;
    }
}
function extractLastResponseFromRawResponse(rawResponse) {
    const normalizedResponse = normalizeInspectorText(rawResponse);
    if (!normalizedResponse)
        return null;
    const parseJsonResponse = (jsonText) => {
        try {
            const parsed = JSON.parse(jsonText);
            const choices = Array.isArray(parsed.choices) ? parsed.choices : [];
            const chunks = [];
            for (const choice of choices) {
                const record = choice;
                const content = joinExtractedText(record.message) ||
                    joinExtractedText(record.delta) ||
                    joinExtractedText(record.text);
                if (content) {
                    chunks.push(content);
                }
            }
            if (chunks.length > 0) {
                return chunks.join("");
            }
            return joinExtractedText(parsed.response ?? parsed.output ?? parsed.message);
        }
        catch {
            return null;
        }
    };
    const direct = parseJsonResponse(normalizedResponse);
    if (direct)
        return direct;
    const sseChunks = [];
    for (const line of normalizedResponse.split("\n")) {
        const trimmed = line.trim();
        if (!trimmed.startsWith("data:"))
            continue;
        const data = trimmed.slice(5).trim();
        if (!data || data === "[DONE]")
            continue;
        const chunk = parseJsonResponse(data);
        if (chunk) {
            sseChunks.push(chunk);
        }
    }
    if (sseChunks.length > 0) {
        return sseChunks.join("").trim() || null;
    }
    return null;
}
function extractLastMessageByRole(messages, role) {
    for (let i = messages.length - 1; i >= 0; i--) {
        const message = messages[i];
        if (message?.role !== role)
            continue;
        const content = normalizeInspectorText(message.content);
        if (content)
            return content;
    }
    return null;
}
function toSingleLine(value, maxLength = 140) {
    const normalized = normalizeInspectorText(value);
    if (!normalized)
        return null;
    const singleLine = normalized.replace(/\s+/g, " ").trim();
    if (!singleLine)
        return null;
    return singleLine.length > maxLength
        ? `${singleLine.slice(0, maxLength)}...`
        : singleLine;
}
function getPersistentLogDetailSummary(log) {
    const details = [
        toSingleLine(log.summary, 180),
        log.error ? `Error: ${toSingleLine(log.error, 120)}` : null,
        log.payloadPreview
            ? `Payload: ${toSingleLine(log.payloadPreview, 90)}`
            : null,
        log.resultPreview ? `Result: ${toSingleLine(log.resultPreview, 90)}` : null,
        log.metadataJson ? `Metadata: ${toSingleLine(log.metadataJson, 90)}` : null,
    ]
        .filter(Boolean)
        .join(" | ");
    return details || null;
}
function formatPersistentLogEntry(log) {
    const heading = [
        `[${formatDiagnosticTime(log.createdAt)}]`,
        log.eventType || "event",
        log.stage ? `(${log.stage})` : null,
        log.status ? `- ${log.status}` : null,
    ]
        .filter(Boolean)
        .join(" ");
    const details = [
        log.source,
        log.seq != null ? `seq ${log.seq}` : null,
        log.durationMs != null ? `${log.durationMs} ms` : null,
        log.success != null ? (log.success ? "success" : "failed") : null,
        getPersistentLogDetailSummary(log),
    ]
        .filter(Boolean)
        .join(" | ");
    return details ? `${heading} | ${details}` : heading;
}
function renderPersistentLogsTable(persistentLogs) {
    return (_jsx("div", { className: "border-border-default min-h-0 flex-1 overflow-x-auto overflow-y-auto rounded border bg-white", children: _jsxs("table", { className: "text-neutral-grey-100 min-w-[1100px] border-collapse text-[11px]", children: [_jsx("thead", { className: "bg-neutral-grey-5 sticky top-0 z-10", children: _jsxs("tr", { className: "border-border-default text-neutral-grey-50 border-b text-left text-[10px] font-semibold tracking-wider", children: [_jsx("th", { className: "px-2 py-2", children: "Time" }), _jsx("th", { className: "px-2 py-2", children: "Event" }), _jsx("th", { className: "px-2 py-2", children: "Stage" }), _jsx("th", { className: "px-2 py-2", children: "Status" }), _jsx("th", { className: "px-2 py-2", children: "Source" }), _jsx("th", { className: "px-2 py-2", children: "Details" })] }) }), _jsx("tbody", { children: persistentLogs.map((log) => {
                        const detailSummary = getPersistentLogDetailSummary(log) ?? "—";
                        return (_jsxs("tr", { className: "border-border-default border-b align-top last:border-b-0", children: [_jsx("td", { className: "text-neutral-grey-50 max-w-32 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: formatDiagnosticTime(log.createdAt), children: formatDiagnosticTime(log.createdAt) }) }), _jsx("td", { className: "text-neutral-grey-100 max-w-28 px-2 py-1.5 font-medium whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.eventType || "event", children: log.eventType || "event" }) }), _jsx("td", { className: "max-w-24 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.stage || "—", children: log.stage || "—" }) }), _jsx("td", { className: "max-w-24 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.status || "—", children: log.status || "—" }) }), _jsx("td", { className: "max-w-28 px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: log.source || "—", children: log.source || "—" }) }), _jsx("td", { className: "min-w-md px-2 py-1.5 whitespace-nowrap", children: _jsx("span", { className: "block truncate", title: detailSummary, children: detailSummary }) })] }, log.logId));
                    }) })] }) }));
}
function buildPersistentLogsSection(persistentLogs) {
    return {
        title: persistentLogs.length > 0
            ? `Agent logs (${persistentLogs.length})`
            : "Agent logs",
        content: persistentLogs.length > 0
            ? persistentLogs.map((log) => formatPersistentLogEntry(log)).join("\n")
            : "No persistent agent logs were recorded for this agent yet.",
        contentNode: persistentLogs.length > 0
            ? renderPersistentLogsTable(persistentLogs)
            : undefined,
    };
}
function formatNumber(value) {
    if (value == null || !Number.isFinite(value))
        return "—";
    return value.toLocaleString();
}
function formatCost(value, currency) {
    if (value == null || !Number.isFinite(value))
        return "—";
    return `${value.toFixed(4)} ${currency}`;
}
function formatPercent(value) {
    if (value == null || !Number.isFinite(value))
        return "—";
    return `${value.toFixed(1)}%`;
}
function buildAgentSummaryLines(agentId, agent, resolvedModelName) {
    if (!agent) {
        return [`Agent ID: ${agentId}`, "Agent details: not available"];
    }
    return [
        `Agent: ${agent.name || "—"}`,
        `Agent ID: ${agent.id}`,
        `Agent status: ${agent.status || "—"}`,
        agent.statusMessage ? `Agent status message: ${agent.statusMessage}` : null,
        `Profile: ${agent.profileName || "—"}${agent.profileId ? ` (${agent.profileId})` : ""}`,
        `Model: ${resolvedModelName || agent.model || "—"}`,
        `Owner: ${agent.ownerName || agent.userId || "—"}`,
        agent.visibilityMode ? `Visibility: ${agent.visibilityMode}` : null,
        agent.effectiveAccessLevel
            ? `Access level: ${agent.effectiveAccessLevel}`
            : null,
        agent.parentAgentId ? `Parent agent: ${agent.parentAgentId}` : null,
        `Created: ${formatDiagnosticTime(agent.createdDate)}`,
        `Updated: ${formatDiagnosticTime(agent.updatedDate)}`,
        `Last message: ${formatDiagnosticTime(agent.lastMessageDate)}`,
        agent.nextRunAt
            ? `Next scheduled run: ${formatDiagnosticTime(agent.nextRunAt)}`
            : null,
        `Messages in conversation: ${agent.messageCount ?? 0}`,
        agent.compressionMarkerIndex != null
            ? `Compression marker index: ${agent.compressionMarkerIndex}`
            : null,
        agent.triggerSubscriptionCount != null
            ? `Trigger subscriptions: ${agent.triggerSubscriptionCount}`
            : null,
        agent.assignedSkillIds && agent.assignedSkillIds.length > 0
            ? `Assigned skills (${agent.assignedSkillIds.length}): ${agent.assignedSkillIds.join(", ")}`
            : `Assigned skills: none`,
    ];
}
function buildTokensSection(params) {
    const { agent, liveTotals, totalTokens, contextWindowStatus, costLimit, resolvedModelName, } = params;
    const currency = liveTotals?.currency || agent?.currency || "USD";
    const breakdown = liveTotals ?? totalTokens;
    const totalCost = breakdown?.totalCost ?? agent?.totalCost ?? 0;
    const limitPercent = costLimit && costLimit > 0 ? (totalCost / costLimit) * 100 : null;
    const liveSection = breakdown
        ? joinSubsections([
            {
                title: "Current run / live totals",
                content: lines([
                    `Input tokens: ${formatNumber(breakdown.input)} (${formatCost(breakdown.inputCost, currency)})`,
                    `Output tokens: ${formatNumber(breakdown.output)} (${formatCost(breakdown.outputCost, currency)})`,
                    `Cached input tokens: ${formatNumber(breakdown.cached)} (${formatCost(breakdown.cachedCost, currency)})`,
                    breakdown.cacheWrite || breakdown.cacheWriteCost
                        ? `Cache write tokens: ${formatNumber(breakdown.cacheWrite ?? 0)} (${formatCost(breakdown.cacheWriteCost ?? 0, currency)})`
                        : null,
                    breakdown.reasoning
                        ? `Reasoning tokens: ${formatNumber(breakdown.reasoning)}`
                        : null,
                    breakdown.inputAudio || breakdown.inputAudioCost
                        ? `Input audio tokens: ${formatNumber(breakdown.inputAudio ?? 0)} (${formatCost(breakdown.inputAudioCost ?? 0, currency)})`
                        : null,
                    breakdown.outputAudio || breakdown.outputAudioCost
                        ? `Output audio tokens: ${formatNumber(breakdown.outputAudio ?? 0)} (${formatCost(breakdown.outputAudioCost ?? 0, currency)})`
                        : null,
                    breakdown.outputImage || breakdown.outputImageCost
                        ? `Output image tokens: ${formatNumber(breakdown.outputImage ?? 0)} (${formatCost(breakdown.outputImageCost ?? 0, currency)})`
                        : null,
                    breakdown.imageCost
                        ? `Image cost: ${formatCost(breakdown.imageCost, currency)}`
                        : null,
                    "markupCost" in breakdown && breakdown.markupCost
                        ? `Provider markup: ${formatCost(breakdown.markupCost, currency)}`
                        : null,
                    "reportedTotalCost" in breakdown &&
                        breakdown.reportedTotalCost != null
                        ? `Provider-reported total: ${formatCost(breakdown.reportedTotalCost, currency)}`
                        : null,
                ]),
            },
        ])
        : "No token usage has been recorded for the current run yet.";
    const cumulativeSection = agent
        ? joinSubsections([
            {
                title: "Cumulative (entire conversation)",
                content: lines([
                    `Total tokens used: ${formatNumber(agent.totalTokensUsed)}`,
                    `Input tokens: ${formatNumber(agent.totalInputTokens)} (${formatCost(agent.totalInputTokenCost, currency)})`,
                    `Output tokens: ${formatNumber(agent.totalOutputTokens)} (${formatCost(agent.totalOutputTokenCost, currency)})`,
                    `Cached input tokens: ${formatNumber(agent.totalCachedInputTokens)} (${formatCost(agent.totalCachedInputTokenCost, currency)})`,
                    agent.totalImageCost
                        ? `Image cost: ${formatCost(agent.totalImageCost, currency)}`
                        : null,
                    `Total cost: ${formatCost(agent.totalCost, currency)}`,
                ]),
            },
        ])
        : "";
    const limitSection = joinSubsections([
        {
            title: "Cost limit",
            content: lines([
                `Cost limit: ${costLimit != null && costLimit > 0 ? formatCost(costLimit, currency) : "Unlimited"}`,
                limitPercent != null
                    ? `Used: ${formatCost(totalCost, currency)} (${formatPercent(limitPercent)})`
                    : `Used: ${formatCost(totalCost, currency)}`,
            ]),
        },
    ]);
    const contextSection = contextWindowStatus
        ? joinSubsections([
            {
                title: "Context window",
                content: lines([
                    resolvedModelName ? `Model: ${resolvedModelName}` : null,
                    `Window size: ${formatNumber(contextWindowStatus.contextWindowTokens)} tokens`,
                    `Estimated input tokens: ${formatNumber(contextWindowStatus.estimatedInputTokens)}`,
                    `Used: ${formatPercent(contextWindowStatus.contextUsedPercent)}`,
                    agent?.contextUsedTokens != null
                        ? `Persisted context tokens: ${formatNumber(agent.contextUsedTokens)}`
                        : null,
                    agent?.contextWindowTokens != null
                        ? `Persisted window size: ${formatNumber(agent.contextWindowTokens)}`
                        : null,
                ]),
            },
        ])
        : agent?.contextUsedTokens != null || agent?.contextWindowTokens != null
            ? joinSubsections([
                {
                    title: "Context window",
                    content: lines([
                        resolvedModelName ? `Model: ${resolvedModelName}` : null,
                        agent?.contextWindowTokens != null
                            ? `Window size: ${formatNumber(agent.contextWindowTokens)} tokens`
                            : null,
                        agent?.contextUsedTokens != null
                            ? `Used tokens: ${formatNumber(agent.contextUsedTokens)}`
                            : null,
                    ]),
                },
            ])
            : "";
    const content = [liveSection, cumulativeSection, limitSection, contextSection]
        .filter((s) => s && s.length > 0)
        .join("\n\n");
    return {
        title: "Tokens & cost",
        content: content || "No token or cost information is available yet.",
    };
}
function buildAllowancesSection(allowances) {
    if (!allowances) {
        return {
            title: "Allowances",
            content: "Operation allowances could not be loaded.",
        };
    }
    const sitecore = allowances.sitecore ?? [];
    const filesystem = allowances.filesystem ?? [];
    const sitecoreBlock = sitecore.length > 0
        ? sitecore
            .map((a) => lines([
            `• ${a.itemPath}`,
            `  ID: ${a.itemId}`,
            `  Operation: ${a.operationType}`,
            `  Scope: ${a.scopeType}`,
            a.source ? `  Source: ${a.source}` : null,
            a.grantedBy ? `  Granted by: ${a.grantedBy}` : null,
            a.grantedAt
                ? `  Granted at: ${formatDiagnosticTime(a.grantedAt)}`
                : null,
        ]))
            .join("\n")
        : "No Sitecore item allowances granted.";
    const filesystemBlock = filesystem.length > 0
        ? filesystem
            .map((a) => lines([
            `• ${a.normalizedPath}`,
            `  Operation: ${a.operationType}`,
            a.source ? `  Source: ${a.source}` : null,
            a.grantedBy ? `  Granted by: ${a.grantedBy}` : null,
            a.grantedAt
                ? `  Granted at: ${formatDiagnosticTime(a.grantedAt)}`
                : null,
        ]))
            .join("\n")
        : "No filesystem allowances granted.";
    return {
        title: `Allowances (${sitecore.length + filesystem.length})`,
        content: joinSubsections([
            {
                title: `Sitecore items (${sitecore.length})`,
                content: sitecoreBlock,
            },
            {
                title: `Filesystem paths (${filesystem.length})`,
                content: filesystemBlock,
            },
        ]),
    };
}
function buildDiagnosticsSections(params) {
    const { agent, socketDiagnostics, runDiagnosticsSnapshot, serverDiagnostics, allowances, liveTotals, totalTokens, contextWindowStatus, costLimit, resolvedModelName = "", messages, payload, rawResponse, subscribeSocketMessages, } = params;
    const summary = interpretAgentRunDiagnostics({
        socketDiagnostics,
        localSnapshot: runDiagnosticsSnapshot,
        serverDiagnostics,
    });
    const lastPrompt = extractLastPromptFromPayload(payload) ||
        extractLastMessageByRole(messages, "user");
    const lastResponse = extractLastResponseFromRawResponse(rawResponse) ||
        extractLastMessageByRole(messages, "assistant");
    const machineCapacitySection = buildMachineCapacitySection(params.agentId, serverDiagnostics);
    const connectionContent = joinSubsections([
        {
            title: "Client connection",
            content: lines([
                `Session ID: ${socketDiagnostics.sessionId || "—"}`,
                `Socket state: ${socketDiagnostics.readyStateLabel}`,
                `Reconnect count: ${socketDiagnostics.reconnectCount}`,
                `Last socket event: ${socketDiagnostics.lastEventType} @ ${formatDiagnosticTime(socketDiagnostics.lastEventAt)}`,
                `Last open: ${formatDiagnosticTime(socketDiagnostics.lastOpenAt)}`,
                `Last message: ${formatDiagnosticTime(socketDiagnostics.lastMessageAt)}`,
                `Last close: ${formatDiagnosticTime(socketDiagnostics.lastCloseAt)}`,
                socketDiagnostics.lastCloseCode != null
                    ? `Last close code: ${socketDiagnostics.lastCloseCode}`
                    : null,
                socketDiagnostics.lastCloseReason
                    ? `Last close reason: ${socketDiagnostics.lastCloseReason}`
                    : null,
                `Last error: ${formatDiagnosticTime(socketDiagnostics.lastErrorAt)}`,
                socketDiagnostics.lastErrorMessage
                    ? `Last error message: ${socketDiagnostics.lastErrorMessage}`
                    : null,
            ]),
        },
        {
            title: "Current session",
            content: lines([
                `Session found: ${yesNo(serverDiagnostics.currentSession.sessionFound)}`,
                `Browser matched: ${yesNo(serverDiagnostics.currentSession.browserMatched)}`,
                `Connected: ${yesNo(serverDiagnostics.currentSession.isConnected)}`,
                `Subscribed: ${yesNo(serverDiagnostics.currentSession.isSubscribed)}`,
                `Connected at: ${formatDiagnosticTime(serverDiagnostics.currentSession.connectedAt)}`,
                `Last delivery attempt: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastAttemptAt)}`,
                `Last delivery success: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastSuccessAt)}`,
                `Last delivery failure: ${formatDiagnosticTime(serverDiagnostics.currentSession.lastDelivery?.lastFailureAt)}`,
                serverDiagnostics.currentSession.lastDelivery?.lastFailureReason
                    ? `Failure reason: ${serverDiagnostics.currentSession.lastDelivery.lastFailureReason}`
                    : null,
                serverDiagnostics.currentSession.lastDelivery?.lastMessageType
                    ? `Last delivered message: ${serverDiagnostics.currentSession.lastDelivery.lastMessageType}`
                    : null,
                serverDiagnostics.currentSession.lastDelivery?.lastSeq != null
                    ? `Last delivered seq: ${serverDiagnostics.currentSession.lastDelivery.lastSeq}`
                    : null,
            ]),
        },
    ]);
    const runContent = joinSubsections([
        {
            title: "Agent stream (client)",
            content: lines([
                `Submitting: ${yesNo(runDiagnosticsSnapshot.isSubmitting)}`,
                `Connecting: ${yesNo(runDiagnosticsSnapshot.isConnecting)}`,
                `Waiting for response: ${yesNo(runDiagnosticsSnapshot.isWaitingForResponse)}`,
                `Agent thinking: ${yesNo(runDiagnosticsSnapshot.isAgentThinking)}`,
                `Executing: ${yesNo(runDiagnosticsSnapshot.isExecuting)}`,
                runDiagnosticsSnapshot.lastStatusReason
                    ? `Last status reason: ${runDiagnosticsSnapshot.lastStatusReason}`
                    : null,
                runDiagnosticsSnapshot.lastStatusMessage
                    ? `Last status message: ${runDiagnosticsSnapshot.lastStatusMessage}`
                    : null,
                `Active streaming message: ${yesNo(runDiagnosticsSnapshot.hasActiveStreaming)}`,
                `Terminal subscribed: ${yesNo(runDiagnosticsSnapshot.isSubscribed)}`,
                `Last local seq: ${runDiagnosticsSnapshot.lastSeq > 0 ? runDiagnosticsSnapshot.lastSeq : "—"}`,
                runDiagnosticsSnapshot.currentRunReceivedSeqs.length > 0
                    ? `Run seqs received: ${runDiagnosticsSnapshot.currentRunReceivedSeqs.length} (${formatSeqRanges(runDiagnosticsSnapshot.currentRunReceivedSeqs)})`
                    : `Run seqs received: 0`,
                runDiagnosticsSnapshot.currentRunReceivedSeqs.length > 0
                    ? `Missing seqs: ${runDiagnosticsSnapshot.currentRunMissingSeqs.length === 0 ? "(none)" : formatSeqRanges(runDiagnosticsSnapshot.currentRunMissingSeqs)}`
                    : null,
                `Last local event: ${runDiagnosticsSnapshot.lastEventType || "—"} @ ${formatDiagnosticTime(runDiagnosticsSnapshot.lastEventAt)}`,
            ]),
        },
        {
            title: "Server execution",
            content: lines([
                `Status: ${serverDiagnostics.execution.status || "unknown"}`,
                `In-memory execution: ${yesNo(serverDiagnostics.execution.isInMemoryExecution)}`,
                `Assigned instance: ${serverDiagnostics.execution.assignedInstanceId || "—"}`,
                serverDiagnostics.execution.assignedInstanceAt
                    ? `Instance assigned at: ${formatDiagnosticTime(serverDiagnostics.execution.assignedInstanceAt)}`
                    : null,
                `Reporting instance: ${serverDiagnostics.execution.currentInstanceId || "—"}`,
                serverDiagnostics.execution.assignedInstanceId &&
                    serverDiagnostics.execution.currentInstanceId &&
                    serverDiagnostics.execution.assignedInstanceId !==
                        serverDiagnostics.execution.currentInstanceId
                    ? "Note: assigned and reporting instances differ; in-memory state below is from the reporting instance."
                    : null,
                `Started: ${formatDiagnosticTime(serverDiagnostics.execution.startedAt)}`,
                `Completed: ${formatDiagnosticTime(serverDiagnostics.execution.completedAt)}`,
                serverDiagnostics.execution.error
                    ? `Error: ${serverDiagnostics.execution.error}`
                    : null,
                `Last message type: ${serverDiagnostics.transport.lastMessageType || "—"}`,
                `Last delta type: ${serverDiagnostics.transport.lastDeltaType || "—"}`,
                `Last status state: ${serverDiagnostics.transport.lastStatusState || "—"}`,
                `Last lifecycle event: ${serverDiagnostics.transport.lastLifecycleEventType || "—"}`,
                `Last produced: ${formatDiagnosticTime(serverDiagnostics.transport.lastProducedAt)}`,
                `Last broadcast: ${formatDiagnosticTime(serverDiagnostics.transport.lastBroadcastAt)}`,
                `Target sessions: ${serverDiagnostics.transport.targetSessionCount}`,
                `Successful sends: ${serverDiagnostics.transport.successfulSessionCount}`,
                `Failed sends: ${serverDiagnostics.transport.failedSessionCount}`,
                `Connected subscribers: ${serverDiagnostics.transport.connectedSubscriberCount}`,
                serverDiagnostics.transport.lastFailure
                    ? `Last transport failure: ${serverDiagnostics.transport.lastFailure}`
                    : null,
            ]),
        },
        {
            title: "Run telemetry",
            content: lines([
                `Run requested: ${formatDiagnosticTime(serverDiagnostics.lastRunRequest?.requestedAt)}`,
                `Run source: ${serverDiagnostics.lastRunRequest?.source || "—"}`,
                serverDiagnostics.lastRunRequest?.detail
                    ? `Run detail: ${serverDiagnostics.lastRunRequest.detail}`
                    : null,
                `Cancel requested: ${formatDiagnosticTime(serverDiagnostics.lastCancellation?.requestedAt)}`,
                `Cancel source: ${serverDiagnostics.lastCancellation?.source || "—"}`,
                serverDiagnostics.lastCancellation?.requestedBy
                    ? `Cancel requested by: ${serverDiagnostics.lastCancellation.requestedBy}`
                    : null,
                serverDiagnostics.lastCancellation?.reason
                    ? `Cancel reason: ${serverDiagnostics.lastCancellation.reason}`
                    : null,
                serverDiagnostics.lastCancellation?.detail
                    ? `Cancel detail: ${serverDiagnostics.lastCancellation.detail}`
                    : null,
                `Cancellation observed: ${formatDiagnosticTime(serverDiagnostics.lastCancellation?.observedAt)}`,
                `Observed by: ${serverDiagnostics.lastCancellation?.observedSource || "—"}`,
                serverDiagnostics.lastCancellation?.observedDetail
                    ? `Observed detail: ${serverDiagnostics.lastCancellation.observedDetail}`
                    : null,
            ]),
        },
        {
            title: "Tool UI state",
            content: lines([
                `Assistant messages: ${runDiagnosticsSnapshot.assistantMessageCount}`,
                `Assistant groups: ${runDiagnosticsSnapshot.assistantGroupCount}`,
                `Groups with renderable tool calls: ${runDiagnosticsSnapshot.assistantGroupsWithRenderableToolCalls}`,
                `Messages with tool calls: ${runDiagnosticsSnapshot.messagesWithToolCalls}`,
                `Total tool calls in local state: ${runDiagnosticsSnapshot.totalToolCallCount}`,
                `Incomplete tool calls in local state: ${runDiagnosticsSnapshot.incompleteToolCallCount}`,
            ]),
        },
    ]);
    const clientEventsBlock = (() => {
        const events = runDiagnosticsSnapshot.recentEvents;
        if (events.length === 0) {
            return "No recent client-side agent stream events were captured for this terminal.";
        }
        const total = runDiagnosticsSnapshot.currentRunTotalEventCount;
        const header = total > events.length
            ? `Showing last ${events.length} of ${total} agent:run:* events received in current run.`
            : `Showing all ${events.length} agent:run:* events received in current run.`;
        const body = events
            .slice()
            .reverse()
            .map((event) => formatAgentDiagnosticsEvent(event))
            .join("\n");
        return `${header}\n${body}`;
    })();
    const clientWebSocketBlock = (() => {
        const events = runDiagnosticsSnapshot.recentEvents;
        if (events.length === 0) {
            return "No raw client-side agent WebSocket messages were captured for this terminal.";
        }
        const total = runDiagnosticsSnapshot.currentRunTotalEventCount;
        const header = total > events.length
            ? `Showing last ${events.length} of ${total} agent:run:* messages received in current run.`
            : `Showing all ${events.length} agent:run:* messages received in current run.`;
        const body = events
            .slice()
            .reverse()
            .map((event) => formatClientSocketMessageEvent(event))
            .join("\n\n");
        return `${header}\n\n${body}`;
    })();
    const toolUiEventsBlock = runDiagnosticsSnapshot.recentToolUiEvents.length > 0
        ? runDiagnosticsSnapshot.recentToolUiEvents
            .slice()
            .reverse()
            .map((event) => formatAgentDiagnosticsEvent(event))
            .join("\n")
        : "No recent tool-specific UI events were captured for this terminal.";
    const serverEventsBlock = serverDiagnostics.transport.recentEvents.length > 0
        ? serverDiagnostics.transport.recentEvents
            .map((event) => formatAgentDiagnosticsEvent(event))
            .join("\n")
        : "No recent server-side agent transport events were recorded.";
    const eventsContent = joinSubsections([
        { title: "Client events", content: clientEventsBlock },
        { title: "Server events", content: serverEventsBlock },
        { title: "Tool UI events", content: toolUiEventsBlock },
        { title: "Client WebSocket messages (raw)", content: clientWebSocketBlock },
    ]);
    const promptContent = joinSubsections([
        {
            title: "Last prompt",
            content: lastPrompt ?? "No prompt was captured for this agent run yet.",
        },
        payload
            ? {
                title: "Raw full prompt",
                content: payload,
            }
            : null,
    ]);
    const assembledResponse = rawResponse
        ? extractLastResponseFromRawResponse(rawResponse)
        : null;
    const responseContent = joinSubsections([
        {
            title: "Last response",
            content: lastResponse ??
                "No assistant response was captured for this agent run yet.",
        },
        assembledResponse
            ? { title: "Response", content: assembledResponse }
            : null,
        rawResponse ? { title: "Raw response", content: rawResponse } : null,
    ]);
    const summaryCurrency = liveTotals?.currency || agent?.currency || "USD";
    const summaryTotalCost = liveTotals?.totalCost ?? totalTokens?.totalCost ?? agent?.totalCost ?? null;
    const summaryLimitPercent = summaryTotalCost != null && costLimit && costLimit > 0
        ? (summaryTotalCost / costLimit) * 100
        : null;
    const tokensSection = buildTokensSection({
        agent,
        liveTotals: liveTotals ?? null,
        totalTokens: totalTokens ?? null,
        contextWindowStatus: contextWindowStatus ?? null,
        costLimit,
        resolvedModelName,
    });
    const allowancesSection = buildAllowancesSection(allowances ?? null);
    const agentSummaryLines = buildAgentSummaryLines(params.agentId, agent, resolvedModelName);
    const sections = [
        {
            title: "Summary",
            content: lines([
                `Diagnosis: ${summary.title}`,
                summary.detail,
                ...agentSummaryLines,
                serverDiagnostics.execution.runId
                    ? `Run ID: ${serverDiagnostics.execution.runId}`
                    : null,
                serverDiagnostics.execution.assignedInstanceId
                    ? `Assigned instance: ${serverDiagnostics.execution.assignedInstanceId}${serverDiagnostics.execution.currentInstanceId &&
                        serverDiagnostics.execution.currentInstanceId !==
                            serverDiagnostics.execution.assignedInstanceId
                        ? ` (reporting from ${serverDiagnostics.execution.currentInstanceId})`
                        : ""}`
                    : serverDiagnostics.execution.currentInstanceId
                        ? `Reporting instance: ${serverDiagnostics.execution.currentInstanceId}`
                        : null,
                `Socket: ${socketDiagnostics.readyStateLabel}`,
                `Session connected: ${yesNo(serverDiagnostics.currentSession.isConnected)}`,
                `Session subscribed: ${yesNo(serverDiagnostics.currentSession.isSubscribed)}`,
                `Server status: ${serverDiagnostics.execution.status || "unknown"}`,
                `Last seq: ${serverDiagnostics.transport.lastSeq ?? runDiagnosticsSnapshot.lastSeq ?? "—"}`,
                agent?.messageCount != null ? `Messages: ${agent.messageCount}` : null,
                summaryTotalCost != null
                    ? `Total cost: ${formatCost(summaryTotalCost, summaryCurrency)}${costLimit && costLimit > 0
                        ? ` / ${formatCost(costLimit, summaryCurrency)}${summaryLimitPercent != null ? ` (${formatPercent(summaryLimitPercent)})` : ""}`
                        : ""}`
                    : null,
                contextWindowStatus
                    ? `Context: ${formatNumber(contextWindowStatus.estimatedInputTokens)} / ${formatNumber(contextWindowStatus.contextWindowTokens)} (${formatPercent(contextWindowStatus.contextUsedPercent)})`
                    : null,
            ]),
        },
        { title: "Prompt", content: promptContent },
        { title: "Response", content: responseContent },
        tokensSection,
        {
            title: "Connection & run",
            content: joinSubsections([
                { title: "Connection", content: connectionContent },
                { title: "Run", content: runContent },
            ]),
        },
        { title: "Events", content: eventsContent },
        {
            title: "Heartbeat",
            contentNode: (_jsx(HeartbeatDiagnosticsPanel, { agentId: params.agentId, subscribeSocketMessages: subscribeSocketMessages, seedRecoveryEvents: runDiagnosticsSnapshot.recentToolUiEvents.filter((event) => event.type?.startsWith("recovery:")) })),
        },
        buildPersistentLogsSection(serverDiagnostics.persistentLogs ?? []),
        allowancesSection,
        ...(machineCapacitySection ? [machineCapacitySection] : []),
    ];
    return sections;
}
export function AgentTerminalStatusBar({ agent, contextWindowStatus, effectiveModelName, socketDiagnostics, runDiagnosticsSnapshot, liveTotals, totalTokens, costLimit, messages, showDebugButtons, showCompressionPopover, setShowCompressionPopover, subscribeSocketMessages, loadRunDiagnostics, loadLastPayload, loadOperationAllowances, }) {
    const hasData = !!contextWindowStatus?.contextWindowTokens;
    const percentValue = hasData
        ? typeof contextWindowStatus?.contextUsedPercent === "number"
            ? contextWindowStatus.contextUsedPercent
            : 0
        : 0;
    const pct = hasData ? `${percentValue.toFixed(1)}%` : "—";
    const resolvedModelName = (contextWindowStatus?.model ||
        effectiveModelName ||
        "").trim();
    const localSummary = useMemo(() => interpretAgentRunDiagnostics({
        socketDiagnostics,
        localSnapshot: runDiagnosticsSnapshot,
    }), [runDiagnosticsSnapshot, socketDiagnostics]);
    const getContextColor = (percent) => {
        if (percent < 50)
            return "var(--color-feedback-green)";
        if (percent < 80)
            return "var(--color-feedback-orange)";
        return "var(--color-feedback-red)";
    };
    const contextColor = hasData
        ? getContextColor(percentValue)
        : "var(--color-neutral-grey-50)";
    const radius = 15.915;
    const formatTokens = (tokens) => {
        if (tokens >= 1000) {
            return `${(tokens / 1000).toFixed(1)}k`;
        }
        return tokens.toString();
    };
    const hasAssistantMessages = messages.some((m) => m.role === "assistant");
    const canOpenDiagnostics = Boolean(agent?.id) && agent?.status !== "new";
    return (_jsxs("div", { className: "text-neutral-grey-50 mt-1 flex items-center gap-2 text-[11px]", children: [agent?.id && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { className: "flex cursor-help items-center justify-center", children: _jsxs("svg", { className: "h-3 w-3 shrink-0", viewBox: "0 0 36 36", "aria-hidden": "true", children: [_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: "var(--color-border-default)", strokeWidth: "4" }), hasData && (_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: contextColor, strokeWidth: "4", strokeDasharray: `${percentValue} 100`, strokeLinecap: "round", style: {
                                            transformOrigin: "center",
                                            transform: "rotate(-90deg)",
                                        } })), !hasData && (_jsx("circle", { cx: "18", cy: "18", r: radius, fill: "none", stroke: contextColor, strokeWidth: "4", strokeDasharray: "0 100", strokeLinecap: "round", opacity: 0.5 }))] }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: hasData && contextWindowStatus ? (_jsxs("div", { className: "max-w-[320px] space-y-1 text-[11px]", children: [resolvedModelName && (_jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Model:" }), " ", resolvedModelName] })), _jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Context window:" }), " ", formatTokens(contextWindowStatus.estimatedInputTokens || 0), " ", "/ ", formatTokens(contextWindowStatus.contextWindowTokens), " ", "tokens"] }), _jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Used:" }), " ", pct] })] })) : (_jsxs("div", { className: "max-w-[320px] space-y-1 text-[11px]", children: [resolvedModelName && (_jsxs("div", { children: [_jsx("span", { className: "font-semibold", children: "Model:" }), " ", resolvedModelName] })), _jsx("div", { children: "Context window usage will appear here when the agent starts processing." })] })) })] })), agent?.compressionMarkerIndex != null && (_jsxs(Popover, { open: showCompressionPopover, onOpenChange: setShowCompressionPopover, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", className: "border-highlight-100/20 bg-highlight-10/50 text-highlight-100 hover:bg-highlight-10 badge-pad-sm flex cursor-pointer items-center rounded border text-[11px] transition-colors", onClick: () => setShowCompressionPopover(!showCompressionPopover), children: "Compressed" }) }), _jsx(PopoverContent, { className: "w-96 p-4", align: "start", side: "top", children: _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "text-neutral-grey-100 text-[10px] font-semibold", children: "Conversation Compressed" }), _jsxs("p", { className: "text-neutral-grey-50 mt-1 text-[11px]", children: ["First ", agent.compressionMarkerIndex, " messages have been summarized to reduce context usage."] })] }), agent.compressedSummary && (_jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-neutral-grey-100 text-[11px] font-medium", children: "Summary:" }), _jsx("div", { className: "border-border-default bg-neutral-grey-5 text-neutral-grey-100 max-h-64 overflow-y-auto rounded border p-3 text-[11px] whitespace-pre-wrap", children: agent.compressedSummary })] }))] }) })] })), _jsx(AgentCostDisplay, { totalTokens: liveTotals
                    ? {
                        input: liveTotals.input,
                        output: liveTotals.output,
                        cached: liveTotals.cached,
                        cacheWrite: liveTotals.cacheWrite ?? 0,
                        inputCost: liveTotals.inputCost,
                        outputCost: liveTotals.outputCost,
                        cachedCost: liveTotals.cachedCost,
                        cacheWriteCost: liveTotals.cacheWriteCost ?? 0,
                        imageCost: liveTotals.imageCost ?? 0,
                        totalCost: liveTotals.totalCost,
                    }
                    : totalTokens, costLimit: costLimit }), showDebugButtons && agent?.id && (_jsxs(Tooltip, { children: [_jsx(ContentInspectorPopover, { title: "Run diagnostics", emptyMessage: "No diagnostics are available for this agent yet.", downloadFileName: `agent-${agent.id}-diagnostics.txt`, className: "w-[min(64rem,calc(100vw-2rem))]", loadSections: async () => {
                            if (!agent?.id)
                                return [];
                            const [diagnosticsResult, payloadResult, allowancesResult] = await Promise.allSettled([
                                loadRunDiagnostics(agent.id, socketDiagnostics.sessionId),
                                loadLastPayload(agent.id),
                                loadOperationAllowances(agent.id),
                            ]);
                            if (diagnosticsResult.status !== "fulfilled") {
                                throw diagnosticsResult.reason;
                            }
                            const payload = payloadResult.status === "fulfilled"
                                ? payloadResult.value.payload
                                : "";
                            const rawResponse = payloadResult.status === "fulfilled"
                                ? payloadResult.value.rawResponse
                                : "";
                            const allowances = allowancesResult.status === "fulfilled"
                                ? allowancesResult.value
                                : null;
                            return buildDiagnosticsSections({
                                agentId: agent.id,
                                agent,
                                socketDiagnostics,
                                runDiagnosticsSnapshot,
                                serverDiagnostics: diagnosticsResult.value,
                                allowances,
                                liveTotals,
                                totalTokens,
                                contextWindowStatus,
                                costLimit,
                                resolvedModelName,
                                messages,
                                payload,
                                rawResponse,
                                subscribeSocketMessages,
                            });
                        }, trigger: _jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", "data-testid": "agent-diagnostics-button", disabled: !canOpenDiagnostics, className: "text-neutral-grey-50 hover:text-neutral-grey-50 flex items-center text-[10px] disabled:cursor-not-allowed disabled:opacity-30", children: _jsx(Bug, { className: "h-3 w-3", strokeWidth: 1.5 }) }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: !canOpenDiagnostics
                            ? "Available after the agent starts"
                            : hasAssistantMessages
                                ? `${localSummary.title}: open diagnostics`
                                : "Inspect socket, stream, and server diagnostics" })] }))] }));
}
//# sourceMappingURL=AgentTerminalStatusBar.js.map