garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/tools.ts

raw

import type {LogItem} from '@/lib/stream'

/** The call a tool call was made inside: a subagent's (an Agent or Task call's) id, if any. */
export function parentOf(it: LogItem): string | null {
    const meta = (it as {_meta?: {parentToolCallId?: unknown}})._meta
    const p = it.parent ?? meta?.parentToolCallId
    return typeof p === 'string' && p ? p : null
}

/**
 * Each tool call as it stands now (its updates folded in), and the calls a
 * subagent made, by the call that started the subagent. A call whose parent
 * is not in the log stays where it is.
 */
export function toolCalls(items: LogItem[]): {calls: Map<string, LogItem>; children: Map<string, LogItem[]>} {
    const calls = new Map<string, LogItem>()
    for (const it of items) {
        if (it.kind === 'tool') calls.set(it.id ?? '', {...it})
        if (it.kind === 'tool_update' && it.id && calls.has(it.id)) {
            const t = calls.get(it.id)!
            if (it.status) t.status = it.status
            if (it.title) t.title = it.title
            if (it.output) t.output = it.output
        }
    }
    const children = new Map<string, LogItem[]>()
    for (const t of calls.values()) {
        const p = parentOf(t)
        if (p && p !== t.id && calls.has(p)) children.set(p, [...(children.get(p) ?? []), t])
    }
    return {calls, children}
}