/**
 * Flatten sub-agent conversations into a single top-level message stream for the
 * debug-log timeline.
 *
 * A tool call that delegates to a sub-agent carries the sub-agent's entire
 * conversation on `toolCall.subAgentTrace`. The live UI reads that nested shape,
 * but a top-to-bottom timeline reads far better with those messages inline next to
 * the turn that produced them. This walks the list and, for every tool call with a
 * `subAgentTrace`, hoists the sub-agent's messages up as their own timeline
 * entries while **removing** the nested copy from the emitted parent tool call — a
 * move, not a copy. The data is relocated, never duplicated: the export stays the
 * same size and a naive `sum(timeline[].cost)` does not double-count (the
 * canonical `sumCosts` total still reads the un-flattened history).
 *
 * Hoisted entries are:
 * - **breadcrumbed**: `agentName` becomes `"<parent> › <sub-agent>"`, composing for
 *   nested sub-agents (`"<parent> › <sub> › <subsub>"`); the raw sub-agent name is
 *   preserved on `subAgentName`.
 * - **depth-tagged** (`subAgentDepth`) and **correlated** to the spawning tool call
 *   (`subAgentOf`), so the delegation tree is reconstructable even when two
 *   sub-agents run within the same parent turn.
 *
 * Top-level messages (depth 0) are emitted unchanged apart from the trace strip.
 * Order is preserved within each list; the caller sorts the whole timeline by
 * timestamp afterwards, and every sub-agent message carries its own timestamp, so
 * hoisted entries interleave chronologically between the parent's tool-call and
 * tool-result messages.
 *
 * @internal
 */
export function flattenSubAgentMessages(messages, prefix = '', depth = 0, subAgentOf) {
    return messages.flatMap((m) => {
        var _a, _b, _c;
        const breadcrumb = prefix ? `${prefix} › ${(_a = m.agentName) !== null && _a !== void 0 ? _a : '?'}` : m.agentName;
        const traceCalls = (_c = (_b = m.toolCalls) === null || _b === void 0 ? void 0 : _b.filter((tc) => { var _a; return (_a = tc.subAgentTrace) === null || _a === void 0 ? void 0 : _a.length; })) !== null && _c !== void 0 ? _c : [];
        const entry = Object.assign(Object.assign(Object.assign({ kind: 'message' }, m), (traceCalls.length > 0 && {
            toolCalls: m.toolCalls.map((tc) => tc.subAgentTrace ? Object.assign(Object.assign({}, tc), { subAgentTrace: undefined }) : tc),
        })), (depth > 0 && {
            agentName: breadcrumb,
            subAgentName: m.agentName,
            subAgentDepth: depth,
            subAgentOf,
        }));
        if (traceCalls.length === 0)
            return [entry];
        const hoisted = traceCalls.flatMap((tc) => flattenSubAgentMessages(tc.subAgentTrace, breadcrumb !== null && breadcrumb !== void 0 ? breadcrumb : '', depth + 1, tc.id));
        return [entry, ...hoisted];
    });
}
