Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

13.9 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
import posthog from 'posthog-js'

import type { RunLifecycleEvent, ToolStreamEvent, TurnCompleteEvent } from '../types/streamTypes'
import { foregroundStreamLogic } from './foregroundStreamLogic'

export interface ToolStreamSubscription {
    /** Resolved tool names to match, or `'*'` for every tool. */
    tools: string[] | '*'
    onEvent: (event: ToolStreamEvent) => void
    /** When true, replay-sourced events are delivered too. Defaults to false (live only). */
    includeReplay?: boolean
    /**
     * When true, an event (tool or run-lifecycle) is delivered only if its `streamKey` matches the
     * current `foregroundStreamLogic` value at delivery time — the run rendered in the side panel the
     * user is watching. Defaults to false (every stream).
     */
    foregroundOnly?: boolean
    /** Optional: called when the run this event streamed under reaches a terminal status (once per run). */
    onRunTerminal?: (event: RunLifecycleEvent) => void
    /** Optional: called when a live agent turn completes, including on a persistent run. */
    onTurnComplete?: (event: TurnCompleteEvent) => void
    /**
     * Optional: called when the foreground stream actually changes (a different key, or null when the
     * side panel stops rendering a run) — the kea-native way to react to foreground updates without
     * subscribing a component to `foregroundStreamLogic`. Not called for same-value re-registrations.
     */
    onForegroundChange?: (foregroundStreamKey: string | null) => void
    /** Apply-back registrations are delivered only when this target owns the stream's current claim. */
    applyBackTargetId?: string
}

export interface ApplyBackTargetClaim {
    targetId: string
    tools: string[] | '*'
}

function passesForegroundGate(
    subscription: ToolStreamSubscription,
    streamKey: string,
    foregroundStreamKey: string | null
): boolean {
    return !subscription.foregroundOnly || streamKey === foregroundStreamKey
}

function subscriptionMatches(
    subscription: ToolStreamSubscription,
    event: ToolStreamEvent,
    foregroundStreamKey: string | null
): boolean {
    if (event.source === 'replay' && !subscription.includeReplay) {
        return false
    }
    if (!passesForegroundGate(subscription, event.streamKey, foregroundStreamKey)) {
        return false
    }
    if (subscription.tools === '*') {
        return true
    }
    return subscription.tools.includes(event.toolName)
}

function toolsMatch(tools: string[] | '*', toolName: string): boolean {
    return tools === '*' || tools.includes(toolName)
}

function matchingClaimedTargetIds(claims: ApplyBackTargetClaim[], toolName: string): Set<string> {
    return new Set(claims.filter((claim) => toolsMatch(claim.tools, toolName)).map((claim) => claim.targetId))
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolStreamEventsLogicValues {
    foregroundStreamKey: string | null // foregroundStreamLogic
    applyBackTargetClaims: Record<string, ApplyBackTargetClaim[]>
    toolListeners: Record<string, ToolStreamSubscription>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolStreamEventsLogicActions {
    claimApplyBackTargets: (streamKey: string) => {
        streamKey: string
    }
    deregisterToolListener: (listenerId: string) => {
        listenerId: string
    }
    emitRunLifecycleEvent: (event: RunLifecycleEvent) => {
        event: RunLifecycleEvent
    }
    emitToolEvent: (event: ToolStreamEvent) => {
        event: ToolStreamEvent
    }
    emitTurnCompleteEvent: (event: TurnCompleteEvent) => {
        event: TurnCompleteEvent
    }
    registerToolListener: (
        listenerId: string,
        subscription: ToolStreamSubscription
    ) => {
        listenerId: string
        subscription: ToolStreamSubscription
    }
    releaseApplyBackTargets: (streamKey: string) => {
        streamKey: string
    }
    setApplyBackTargets: (
        streamKey: string,
        targets: ApplyBackTargetClaim[]
    ) => {
        streamKey: string
        targets: ApplyBackTargetClaim[]
    }
    transferApplyBackTargets: (
        fromStreamKey: string,
        toStreamKey: string
    ) => {
        fromStreamKey: string
        toStreamKey: string
    }
}

export type toolStreamEventsLogicType = MakeLogicType<toolStreamEventsLogicValues, toolStreamEventsLogicActions>

/** Notifies opted-in subscriptions when the foreground key actually changed since the last notification. */
function notifyForegroundChange(
    values: { foregroundStreamKey: string | null; toolListeners: Record<string, ToolStreamSubscription> },
    cache: Record<string, unknown>
): void {
    const next = values.foregroundStreamKey
    if (next === cache.notifiedForegroundKey) {
        return
    }
    cache.notifiedForegroundKey = next
    for (const subscription of Object.values(values.toolListeners)) {
        if (!subscription.onForegroundChange) {
            continue
        }
        try {
            subscription.onForegroundChange(next)
        } catch (error) {
            posthog.captureException(error, { feature: 'posthog_ai_tool_stream_listener' })
        }
    }
}
/**
 * Global event bus for tool-call lifecycle events. `runStreamLogic` emits `ToolStreamEvent`s
 * (with resolved tool names) plus turn-complete and run-terminal lifecycle events; consumers register
 * a listener that fires their `onEvent` for matching tools and optional lifecycle callbacks. Callbacks
 * live in reducer state — the same precedent as `maxGlobalLogic.toolMap`. Replay events are suppressed
 * unless a subscription opts in via `includeReplay`; a `foregroundOnly` subscription only sees events
 * for the stream currently rendered in the side panel. Apply-back listeners add a target id; send paths
 * snapshot those targets by stream so an in-flight response cannot mutate a newly opened editor.
 *
 * Kea-native alternative: `connect` to this bus and add
 * `listeners({ [toolStreamEventsLogic.actionTypes.emitToolEvent]: ({ event }) => ... })`.
 */
export const toolStreamEventsLogic = kea<toolStreamEventsLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'toolStreamEventsLogic']),

    connect(() => ({
        values: [foregroundStreamLogic, ['foregroundStreamKey']],
    })),

    actions({
        emitToolEvent: (event: ToolStreamEvent) => ({ event }),
        emitTurnCompleteEvent: (event: TurnCompleteEvent) => ({ event }),
        emitRunLifecycleEvent: (event: RunLifecycleEvent) => ({ event }),
        registerToolListener: (listenerId: string, subscription: ToolStreamSubscription) => ({
            listenerId,
            subscription,
        }),
        deregisterToolListener: (listenerId: string) => ({ listenerId }),
        claimApplyBackTargets: (streamKey: string) => ({ streamKey }),
        setApplyBackTargets: (streamKey: string, targets: ApplyBackTargetClaim[]) => ({ streamKey, targets }),
        transferApplyBackTargets: (fromStreamKey: string, toStreamKey: string) => ({ fromStreamKey, toStreamKey }),
        releaseApplyBackTargets: (streamKey: string) => ({ streamKey }),
    }),

    reducers({
        toolListeners: [
            {} as Record<string, ToolStreamSubscription>,
            {
                registerToolListener: (state, { listenerId, subscription }) => ({
                    ...state,
                    [listenerId]: subscription,
                }),
                deregisterToolListener: (state, { listenerId }) => {
                    if (!(listenerId in state)) {
                        return state
                    }
                    const { [listenerId]: _dropped, ...rest } = state
                    return rest
                },
            },
        ],
        applyBackTargetClaims: [
            {} as Record<string, ApplyBackTargetClaim[]>,
            {
                setApplyBackTargets: (state, { streamKey, targets }) => {
                    const { [streamKey]: _previous, ...rest } = state
                    return targets.length > 0 ? { ...rest, [streamKey]: targets } : rest
                },
                transferApplyBackTargets: (state, { fromStreamKey, toStreamKey }) => {
                    if (fromStreamKey === toStreamKey) {
                        return state
                    }
                    const targets = state[fromStreamKey]
                    const { [fromStreamKey]: _source, [toStreamKey]: _destination, ...rest } = state
                    return targets ? { ...rest, [toStreamKey]: targets } : rest
                },
                releaseApplyBackTargets: (state, { streamKey }) => {
                    if (!(streamKey in state)) {
                        return state
                    }
                    const { [streamKey]: _released, ...rest } = state
                    return rest
                },
            },
        ],
    }),

    listeners(({ actions, values, cache }) => ({
        // The bus is connected to `foregroundStreamLogic`, so listening to its actions here is what lets
        // subscriptions react to foreground updates kea-natively (no component-level `useValues`). Both
        // actions funnel through one change-detector: registrations renew with the same key (no-op) and a
        // key-checked clear can leave the value untouched, so compare against the last notified value
        // rather than trusting the action.
        [foregroundStreamLogic.actionTypes.setForegroundStream]: () => notifyForegroundChange(values, cache),
        [foregroundStreamLogic.actionTypes.clearForegroundStream]: () => notifyForegroundChange(values, cache),
        claimApplyBackTargets: ({ streamKey }) => {
            const targetsById = new Map<string, ApplyBackTargetClaim>()
            for (const subscription of Object.values(values.toolListeners)) {
                if (subscription.applyBackTargetId) {
                    targetsById.set(subscription.applyBackTargetId, {
                        targetId: subscription.applyBackTargetId,
                        tools: subscription.tools,
                    })
                }
            }
            actions.setApplyBackTargets(streamKey, [...targetsById.values()])
        },
        emitToolEvent: ({ event }) => {
            const claimedTargetIds = matchingClaimedTargetIds(
                values.applyBackTargetClaims[event.streamKey] ?? [],
                event.toolName
            )
            for (const subscription of Object.values(values.toolListeners)) {
                if (!subscriptionMatches(subscription, event, values.foregroundStreamKey)) {
                    continue
                }
                if (
                    subscription.applyBackTargetId &&
                    (claimedTargetIds.size !== 1 || !claimedTargetIds.has(subscription.applyBackTargetId))
                ) {
                    continue
                }
                // The emit is dispatched synchronously from `runStreamLogic`'s frame ingestion — one
                // throwing subscriber must not break the stream (or starve later subscribers).
                try {
                    subscription.onEvent(event)
                } catch (error) {
                    posthog.captureException(error, { feature: 'posthog_ai_tool_stream_listener' })
                }
            }
        },
        emitTurnCompleteEvent: ({ event }) => {
            const claimedTargetIds = new Set(
                (values.applyBackTargetClaims[event.streamKey] ?? []).map((claim) => claim.targetId)
            )
            for (const subscription of Object.values(values.toolListeners)) {
                if (!subscription.onTurnComplete) {
                    continue
                }
                if (!passesForegroundGate(subscription, event.streamKey, values.foregroundStreamKey)) {
                    continue
                }
                if (subscription.applyBackTargetId && !claimedTargetIds.has(subscription.applyBackTargetId)) {
                    continue
                }
                try {
                    subscription.onTurnComplete(event)
                } catch (error) {
                    posthog.captureException(error, { feature: 'posthog_ai_tool_stream_listener' })
                }
            }
            actions.releaseApplyBackTargets(event.streamKey)
        },
        emitRunLifecycleEvent: ({ event }) => {
            const claimedTargetIds = new Set(
                (values.applyBackTargetClaims[event.streamKey] ?? []).map((claim) => claim.targetId)
            )
            for (const subscription of Object.values(values.toolListeners)) {
                if (!subscription.onRunTerminal) {
                    continue
                }
                if (!passesForegroundGate(subscription, event.streamKey, values.foregroundStreamKey)) {
                    continue
                }
                if (subscription.applyBackTargetId && !claimedTargetIds.has(subscription.applyBackTargetId)) {
                    continue
                }
                try {
                    subscription.onRunTerminal(event)
                } catch (error) {
                    posthog.captureException(error, { feature: 'posthog_ai_tool_stream_listener' })
                }
            }
            actions.releaseApplyBackTargets(event.streamKey)
        },
    })),

    afterMount(({ values, cache }) => {
        // Baseline for the change detector: a subscriber registering later must not get a spurious
        // notification for a foreground key that was already set before this bus mounted.
        cache.notifiedForegroundKey = values.foregroundStreamKey
    }),
])

/** Whether any registered listener wants replay events — a cheap guard so `runStreamLogic` skips
 * per-frame resolution during history replay when nobody is listening for it. */
export function hasReplayListener(toolListeners: Record<string, ToolStreamSubscription>): boolean {
    return Object.values(toolListeners).some((subscription) => subscription.includeReplay)
}