Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

26.0 KB
Raw Blame
import type { AgentInterventionRequestData } from '@lobechat/agent-gateway-client';

import { isEchoedErrorText } from '../errors/echo';
import type { SubagentIntent, SubagentReduceCtx } from '../subagentCoordinator';
import { getEventScope, reduceSubagentRuns } from '../subagentCoordinator';
import type { ToolCallPayload } from '../types';
import type {
  MainAgentIntent,
  MainAgentInterventionState,
  MainAgentReduceCtx,
  MainAgentRunState,
  MainAgentTurnToolState,
} from './types';

/**
 * Pure, transactional main-agent run reducer. See `./types.ts` for the design.
 *
 * `reduce(state, event, ctx)` returns the NEXT state plus the intents to apply
 * β€” it never mutates `state` in place. The caller commits the returned state
 * ONLY after the intents are successfully applied (commit-on-success), so a
 * throwing intent leaves the run un-advanced and a retry replays against the
 * original state β€” the same resilience `reduceSubagentRuns` relies on.
 *
 * Subagent-scoped events (and the parent-spawn `tool_result` / terminal drain)
 * are delegated to `reduceSubagentRuns`; its intents are merged into the
 * returned list so a single call drives both the main thread and every nested
 * subagent.
 */

type AnyIntent = MainAgentIntent | SubagentIntent;

interface ReduceResult {
  intents: AnyIntent[];
  state: MainAgentRunState;
}

// ─── State copy helpers (structural sharing) ───

const copyToolState = (s: MainAgentTurnToolState): MainAgentTurnToolState => ({
  payloads: s.payloads.map((p) => ({ ...p })),
  persistedIds: new Set(s.persistedIds),
  toolMsgIdByCallId: new Map(s.toolMsgIdByCallId),
});

const emptyToolState = (): MainAgentTurnToolState => ({
  payloads: [],
  persistedIds: new Set(),
  toolMsgIdByCallId: new Map(),
});

/** Deep-copy the parts of state a handler may mutate; subagents is swapped wholesale. */
const copyState = (s: MainAgentRunState): MainAgentRunState => ({
  ...s,
  interventionsByCallId: new Map(s.interventionsByCallId),
  toolState: copyToolState(s.toolState),
  turnMetadata: { ...s.turnMetadata },
});

// ─── Echo suppression (pure; mirrors both engines' shouldSuppressTerminalErrorEcho) ───

/**
 * CC sometimes streams the error string into `content` BEFORE emitting the
 * structured error event (e.g. AuthRequired echoes the stderr line). Only
 * suppress when the body is explicitly marked OR matches the AuthRequired code,
 * AND the trimmed strings are equal. Anything else stays β€” accidental partial
 * overlaps are not echo. Operates on the wire `error` event data
 * (`HeterogeneousTerminalErrorData`), so the decision is pure.
 */
const shouldSuppressTerminalErrorEcho = (content: string, errorData: unknown): boolean => {
  const body = errorData as
    { clearEchoedContent?: boolean; code?: string; message?: string; stderr?: string } | undefined;
  // Keep in sync with the interpreters' ECHO_TRIGGER_CODES.
  if (!body?.clearEchoedContent && body?.code !== 'AuthRequired') return false;
  return isEchoedErrorText(content, body?.stderr || body?.message);
};

// ─── Subagent delegation ───

const subagentCtx = (state: MainAgentRunState, ctx: MainAgentReduceCtx): SubagentReduceCtx => ({
  agentId: ctx.agentId,
  mainAssistantId: state.currentAssistantId,
  newId: ctx.newId,
  topicId: ctx.topicId,
});

/** Reduce an event through the nested subagent coordinator, folding its state back in. */
const delegateSubagent = (
  state: MainAgentRunState,
  event: { data?: any; type?: string },
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  const { intents, state: subState } = reduceSubagentRuns(
    state.subagents,
    event,
    subagentCtx(state, ctx),
  );
  return { intents, state: { ...state, subagents: subState } };
};

// ─── Chain rule ───

/**
 * Parent for the NEXT turn's assistant (write-side spine).
 *
 * Normal turns parent off the run's spine (`lastSpineMessageId`, the most recent
 * non-tool / non-signal main message) so the persisted shape is
 * `user β†’ asst β†’ asst …` with tools as inline children; the read side
 * reconstructs the zigzag.
 *
 * Signal / reactive toolless turns (Monitor stdout pushes etc.) are the one
 * exception: they parent off the run's most recent tool (`lastToolMsgIdEver`)
 * so the reader renders them as tool-child callbacks (`collectFlatSignalCallbacks`)
 * instead of spine turns. They fall back to the spine only before any tool has
 * been seen.
 */
const computeTurnParentId = (state: MainAgentRunState, data: any): string => {
  if (data?.externalSignal) return state.lastToolMsgIdEver ?? state.lastSpineMessageId;
  return state.lastSpineMessageId;
};

// ─── Per-event handlers ───

/** `stream_start { newStep: true }` β€” flush the prior turn, open a new assistant. */
const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx): ReduceResult => {
  const intents: AnyIntent[] = [];

  // 1. Durably flush the prior turn's accumulators + model/provider.
  const flush: Record<string, any> = {};
  if (state.accContent) flush.content = state.accContent;
  if (state.accReasoning) flush.reasoning = state.accReasoning;
  if (state.turnModel) flush.model = state.turnModel;
  if (state.turnProvider) flush.provider = state.turnProvider;
  if (Object.keys(flush).length > 0) {
    intents.push({ kind: 'persistAssistant', messageId: state.currentAssistantId, ...flush });
  }

  // 2. Open the new turn's assistant, chained off the spine (chain rule);
  //    signal/reactive turns parent off the last tool β€” see computeTurnParentId.
  const messageId = ctx.newId('message');
  const mainMessageId = typeof data?.messageId === 'string' ? data.messageId : undefined;
  const isSignalTurn = !!data?.externalSignal;
  intents.push({
    agentId: ctx.agentId,
    kind: 'createAssistant',
    mainMessageId,
    messageId,
    model: state.turnModel,
    parentId: computeTurnParentId(state, data),
    provider: state.turnProvider,
    signal: data?.externalSignal,
    topicId: ctx.topicId,
  });

  // 3. Advance: model/provider carry across (a fresh turn_metadata overwrites).
  const next = copyState(state);
  next.currentAssistantId = messageId;
  // The spine only advances on NORMAL turns β€” a signal/reactive turn is a
  // tool-child callback, so the next normal turn re-mounts on the pre-callback
  // spine assistant, not on the callback. A signal turn that then emits a
  // tool_use is really back on the main chain; `reduceToolsChunk` advances the
  // spine onto it at that point (derived from `currentAssistantId`, so it holds
  // on a cold replica too β€” see there).
  if (!isSignalTurn) next.lastSpineMessageId = messageId;
  next.currentMainMessageId = mainMessageId;
  next.accContent = '';
  next.accReasoning = '';
  next.lastReasoningSnapshotSeq = 0;
  next.lastTextSnapshotSeq = 0;
  next.turnMetadata = {};
  next.toolState = emptyToolState();
  return { intents, state: next };
};

/** First `stream_start` (no newStep) carries the CLI's authoritative model/provider. */
const streamInit = (state: MainAgentRunState, data: any): ReduceResult => {
  const update: Record<string, any> = {};
  if (data?.model) update.model = data.model;
  if (data?.provider) update.provider = data.provider;

  // The seeded assistant's CC message.id arrives on the first non-newStep
  // stream_start after system:init (the seed was opened with no id). Record it
  // as `currentMainMessageId` so the first turn's rows get `heteroMessageId`
  // provenance; `openTurn` owns it for every later turn. Only seed it once β€” a
  // later non-newStep stream_start must not clobber the open turn's id.
  const seedMainMessageId =
    typeof data?.messageId === 'string' && !state.currentMainMessageId ? data.messageId : undefined;

  if (Object.keys(update).length === 0 && !seedMainMessageId) return { intents: [], state };

  const next = copyState(state);
  if (data.model) next.turnModel = data.model;
  if (data.provider) next.turnProvider = data.provider;
  if (seedMainMessageId) next.currentMainMessageId = seedMainMessageId;
  return {
    intents:
      Object.keys(update).length > 0
        ? [{ kind: 'persistAssistant', messageId: state.currentAssistantId, ...update }]
        : [],
    state: next,
  };
};

const reduceTextChunk = (state: MainAgentRunState, data: any): ReduceResult => {
  const next = copyState(state);
  const snapshotMode = data?.snapshotMode;
  const snapshotSeq = typeof data?.snapshotSeq === 'number' ? data.snapshotSeq : undefined;

  if (snapshotMode === 'replace' && snapshotSeq !== undefined) {
    if (snapshotSeq <= state.lastTextSnapshotSeq) return { intents: [], state }; // stale snapshot
    next.lastTextSnapshotSeq = snapshotSeq;
    next.turnMetadata = { ...next.turnMetadata, heteroTextSnapshotSeq: snapshotSeq };
    next.accContent = data.content;
  } else {
    if (!data?.content) return { intents: [], state };
    next.accContent = state.accContent + data.content;
  }

  return {
    intents: [
      { content: next.accContent, kind: 'streamContent', messageId: next.currentAssistantId },
    ],
    state: next,
  };
};

const reduceReasoningChunk = (state: MainAgentRunState, data: any): ReduceResult => {
  const next = copyState(state);
  const snapshotMode = data?.snapshotMode;
  const snapshotSeq = typeof data?.snapshotSeq === 'number' ? data.snapshotSeq : undefined;

  // Mirrors `reduceTextChunk`: `replace` snapshots are idempotent under batch
  // redelivery (a raw delta re-append would durably duplicate reasoning on a
  // cold-replica retry), and the seq guard drops stale/out-of-order ones.
  if (snapshotMode === 'replace' && snapshotSeq !== undefined) {
    if (snapshotSeq <= state.lastReasoningSnapshotSeq) return { intents: [], state }; // stale snapshot
    next.lastReasoningSnapshotSeq = snapshotSeq;
    next.turnMetadata = { ...next.turnMetadata, heteroReasoningSnapshotSeq: snapshotSeq };
    next.accReasoning = data.reasoning;
  } else {
    if (!data?.reasoning) return { intents: [], state };
    next.accReasoning = state.accReasoning + data.reasoning;
  }

  return {
    intents: [
      { kind: 'streamContent', messageId: next.currentAssistantId, reasoning: next.accReasoning },
    ],
    state: next,
  };
};

const reduceToolsChunk = (
  state: MainAgentRunState,
  tools: ToolCallPayload[],
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  const next = copyState(state);
  const newToolMsgIds: string[] = [];
  const newToolCallIds: string[] = [];

  for (const tool of tools) {
    if (next.toolState.persistedIds.has(tool.id)) continue;
    next.toolState.persistedIds.add(tool.id);
    next.toolState.payloads.push({
      apiName: tool.apiName,
      arguments: tool.arguments,
      id: tool.id,
      identifier: tool.identifier,
      type: tool.type,
    });
    const toolMessageId = ctx.newId('message');
    next.toolState.toolMsgIdByCallId.set(tool.id, toolMessageId);
    newToolCallIds.push(tool.id);
    newToolMsgIds.push(toolMessageId);
  }

  const intents: AnyIntent[] = [
    {
      assistantMessageId: next.currentAssistantId,
      content: next.accContent || undefined,
      kind: 'persistToolBatch',
      reasoning: next.accReasoning || undefined,
      tools: next.toolState.payloads.map((p) => ({
        isNew: newToolMsgIds.includes(next.toolState.toolMsgIdByCallId.get(p.id)!),
        payload: { ...p },
        toolMessageId: next.toolState.toolMsgIdByCallId.get(p.id)!,
      })),
    },
  ];

  // A response can beat the provider's tool lifecycle event. Once the tool
  // row is materialized, replay the buffered latest transition after the
  // persistToolBatch intent so the interpreter always has a valid target.
  for (const toolCallId of newToolCallIds) {
    const intervention = next.interventionsByCallId.get(toolCallId);
    if (intervention) {
      intents.push({ ...intervention, kind: 'setToolIntervention', toolCallId });
    }
  }

  // Advance the chain fallback to this turn's last tool message.
  const lastToolMsgId = newToolMsgIds.at(-1);
  if (lastToolMsgId) next.lastToolMsgIdEver = lastToolMsgId;

  // Any assistant that emits a tool_use is on the main chain, so it is a spine
  // message β€” advance the spine onto it. For a normal turn this is a no-op
  // (`openTurn` already pointed the spine here). For a turn OPENED as a
  // signal/reactive callback that then called a tool, this promotes it so the
  // NEXT normal turn chains off THIS turn instead of the pre-signal assistant β€”
  // otherwise the wire forks and the read side drops everything after the fork.
  //
  // Deriving the promotion from `currentAssistantId` (not a per-turn "opened as
  // signal" flag) is what keeps it correct on a cold / non-sticky serverless
  // replica: an in-memory flag is NOT rehydrated by `refreshMainStateFromDb`,
  // but `currentAssistantId` and `lastSpineMessageId` ARE β€” and a mid-flight
  // signal turn is still toolless in the DB, so the recovered spine is the
  // pre-signal assistant (β‰  currentAssistantId) and this batch's `tools_calling`
  // promotes it exactly as a warm replica would.
  next.lastSpineMessageId = next.currentAssistantId;

  return { intents, state: next };
};

const isInterventionRequest = (data: any): boolean =>
  typeof data?.apiName === 'string' &&
  typeof data?.arguments === 'string' &&
  typeof data?.deadline === 'number' &&
  typeof data?.identifier === 'string' &&
  typeof data?.toolCallId === 'string' &&
  data.toolCallId.length > 0;

const reduceInterventionRequest = (
  state: MainAgentRunState,
  data: any,
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  if (!isInterventionRequest(data)) return { intents: [], state };

  const request = data as AgentInterventionRequestData;
  const existing = state.interventionsByCallId.get(request.toolCallId);
  const preparedState = copyState(state);
  const intervention: MainAgentInterventionState = existing
    ? { ...existing, request }
    : { intervention: { status: 'pending' }, request, transition: 'pending' };
  if (state.ended && intervention.intervention.status === 'pending') {
    intervention.intervention = {
      rejectedReason: 'session_ended',
      resolving: false,
      status: 'aborted',
    };
    intervention.transition = 'session_ended';
  }
  preparedState.interventionsByCallId.set(request.toolCallId, intervention);

  // The bridge and the adapter run on independent async pumps, so the request
  // can arrive before tools_calling. The request already carries the complete
  // canonical tool payload; materialize it here instead of dropping pending
  // state or relying on process affinity for a later replay.
  if (
    !state.toolState.toolMsgIdByCallId.has(request.toolCallId) &&
    !ctx.toolMessageIds?.has(request.toolCallId)
  ) {
    return reduceToolsChunk(
      preparedState,
      [
        {
          apiName: request.apiName,
          arguments: request.arguments,
          id: request.toolCallId,
          identifier: request.identifier,
          type: 'default',
        },
      ],
      ctx,
    );
  }

  return {
    intents: [{ ...intervention, kind: 'setToolIntervention', toolCallId: request.toolCallId }],
    state: preparedState,
  };
};

const reduceInterventionResponse = (
  state: MainAgentRunState,
  data: any,
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  if (typeof data?.toolCallId !== 'string' || data.toolCallId.length === 0) {
    return { intents: [], state };
  }
  // New two-leg resolution: the first XADD only delivers the user's intent to
  // the producer. It becomes terminal only after AskUserBridge echoes an ACK.
  // Legacy responses had no request id, so retain their historical behavior.
  if (typeof data.resolutionRequestId === 'string' && data.producerAck !== true) {
    return { intents: [], state };
  }

  const existing = state.interventionsByCallId.get(data.toolCallId);
  const transition: MainAgentInterventionState['transition'] = !data.cancelled
    ? 'resolved'
    : data.cancelReason === 'timeout'
      ? 'timed_out'
      : data.cancelReason === 'session_ended'
        ? 'session_ended'
        : 'cancelled';
  const intervention: MainAgentInterventionState = {
    intervention: data.cancelled
      ? { rejectedReason: data.cancelReason ?? 'user_cancelled', status: 'rejected' }
      : { status: 'approved' },
    request: existing?.request,
    resolutionRequestId:
      typeof data.resolutionRequestId === 'string' ? data.resolutionRequestId : undefined,
    transition,
  };
  const next = copyState(state);
  next.interventionsByCallId.set(data.toolCallId, intervention);

  if (
    !state.toolState.toolMsgIdByCallId.has(data.toolCallId) &&
    !ctx.toolMessageIds?.has(data.toolCallId)
  ) {
    return { intents: [], state: next };
  }

  return {
    intents: [{ ...intervention, kind: 'setToolIntervention', toolCallId: data.toolCallId }],
    state: next,
  };
};

/** A terminal tool/run is authoritative even when its bridge ACK never arrives. */
const endInterventions = (
  state: MainAgentRunState,
  toolCallIds: Iterable<string>,
): ReduceResult => {
  const next = copyState(state);
  const intents: AnyIntent[] = [];
  for (const toolCallId of toolCallIds) {
    const existing = next.interventionsByCallId.get(toolCallId);
    if (existing && existing.intervention.status !== 'pending') continue;
    const ended: MainAgentInterventionState = {
      ...existing,
      intervention: { rejectedReason: 'session_ended', resolving: false, status: 'aborted' },
      transition: 'session_ended',
    };
    // Remember results that race ahead of the bridge request, without creating
    // an intervention write/notification for ordinary tools.
    next.interventionsByCallId.set(toolCallId, ended);
    if (existing?.request) {
      intents.push({ ...ended, kind: 'setToolIntervention', toolCallId });
    }
  }
  return { intents, state: next };
};

const reduceStreamChunk = (
  state: MainAgentRunState,
  data: any,
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  if (data?.chunkType === 'text' && typeof data.content === 'string') {
    return reduceTextChunk(state, data);
  }
  if (data?.chunkType === 'reasoning' && typeof data.reasoning === 'string') {
    return reduceReasoningChunk(state, data);
  }
  if (
    data?.chunkType === 'tool_state' &&
    data.snapshotMode === 'replace' &&
    typeof data.toolCallId === 'string' &&
    data.toolCallId.length > 0 &&
    Number.isInteger(data.snapshotSeq) &&
    data.snapshotSeq > 0 &&
    typeof data.pluginState === 'object' &&
    data.pluginState !== null &&
    !Array.isArray(data.pluginState)
  ) {
    return {
      intents: [
        {
          kind: 'updateToolState',
          pluginState: data.pluginState,
          snapshotSeq: data.snapshotSeq,
          toolCallId: data.toolCallId,
        },
      ],
      state,
    };
  }
  if (data?.chunkType === 'tools_calling') {
    const tools = (data.toolsCalling as ToolCallPayload[] | undefined) ?? [];
    if (tools.length === 0) return { intents: [], state };
    return reduceToolsChunk(state, tools, ctx);
  }
  return { intents: [], state };
};

/** Main-agent (and parent-spawn) tool_result. Inner subagent results are delegated. */
const reduceToolResult = (
  state: MainAgentRunState,
  event: { data?: any },
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  const data = event.data ?? {};
  const toolCallId: string | undefined = data.toolCallId;
  if (!toolCallId) return { intents: [], state };

  // Resolve the (main-scoped) tool message content, then delegate so a
  // parent-spawn tool_result finalizes its subagent run (no-op otherwise).
  const main: AnyIntent = {
    content: data.content ?? '',
    isError: !!data.isError,
    kind: 'resolveToolResult',
    pluginState: data.pluginState,
    toolCallId,
  };
  const ended = endInterventions(state, [
    toolCallId,
    ...(state.subagents.runs.get(toolCallId)?.lifetimeToolCallIds ?? []),
  ]);
  const delegated = delegateSubagent(ended.state, event, ctx);
  return { intents: [main, ...ended.intents, ...delegated.intents], state: delegated.state };
};

const reduceTurnMetadata = (state: MainAgentRunState, data: any): ReduceResult => {
  const next = copyState(state);
  if (data?.model) next.turnModel = data.model;
  if (data?.provider) next.turnProvider = data.provider;
  const usage = data?.usage;
  if (usage) next.turnMetadata = { ...next.turnMetadata, usage };

  if (!data?.model && !data?.provider && !usage) return { intents: [], state: next };
  return {
    intents: [
      {
        kind: 'recordUsage',
        messageId: state.currentAssistantId,
        model: data?.model,
        provider: data?.provider,
        usage,
      },
    ],
    state: next,
  };
};

/**
 * `visible_output_end` β€” the CLI finished its visible reply, but the run may
 * stay open (CC SDK mode keeps the transport alive for background tasks, so
 * the terminal flush can land minutes later). The UI already lets the user
 * send a follow-up at this point, and that send replaces the store with the
 * server's rows β€” so the final step's text must be durable NOW, or the prior
 * answer renders empty until a refresh.
 *
 * Accumulators are kept, not reset: the later terminal flush rewrites the same
 * content idempotently, and a background-task turn opens a new step through
 * `openTurn` as usual.
 */
const reduceVisibleOutputEnd = (state: MainAgentRunState): ReduceResult => {
  if (!state.accContent && !state.accReasoning) return { intents: [], state };

  const flush: Record<string, any> = {};
  if (state.accContent) flush.content = state.accContent;
  if (state.accReasoning) flush.reasoning = state.accReasoning;
  if (state.turnModel) flush.model = state.turnModel;
  if (state.turnProvider) flush.provider = state.turnProvider;
  return {
    intents: [{ kind: 'persistAssistant', messageId: state.currentAssistantId, ...flush }],
    state,
  };
};

const reduceTerminal = (
  state: MainAgentRunState,
  event: { data?: any; type?: string },
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  const isError = event.type === 'error';
  const suppress = isError ? shouldSuppressTerminalErrorEcho(state.accContent, event.data) : false;

  const intents: AnyIntent[] = [];
  const flush: Record<string, any> = {};
  if (suppress) flush.content = '';
  else if (state.accContent) flush.content = state.accContent;
  if (state.accReasoning) flush.reasoning = state.accReasoning;
  if (state.turnModel) flush.model = state.turnModel;
  if (state.turnProvider) flush.provider = state.turnProvider;
  if (Object.keys(flush).length > 0) {
    intents.push({ kind: 'persistAssistant', messageId: state.currentAssistantId, ...flush });
  }
  if (isError) {
    intents.push({
      clearContent: suppress,
      errorData: event.data,
      kind: 'setError',
      messageId: state.currentAssistantId,
    });
  }

  // Reset accumulators so a follow-up terminal/flush is an idempotent no-op,
  // then drain any subagent runs that never saw their parent tool_result.
  const ended = endInterventions(state, state.interventionsByCallId.keys());
  const drained = ended.state;
  drained.accContent = '';
  drained.accReasoning = '';
  drained.ended = true;
  const delegated = delegateSubagent(drained, event, ctx);
  return { intents: [...intents, ...ended.intents, ...delegated.intents], state: delegated.state };
};

/**
 * A background task snapshot for a main-agent tool. Valid even after the run's
 * terminal event: on the `on-result` runtime-end strategy CC keeps reporting a
 * task after the result that ended the operation.
 */
const reduceBackgroundTask = (state: MainAgentRunState, data: any): ReduceResult => {
  const task = data?.task;
  if (
    typeof data?.toolCallId !== 'string' ||
    !data.toolCallId ||
    typeof task?.taskId !== 'string' ||
    typeof task.status !== 'string'
  ) {
    return { intents: [], state };
  }
  return {
    intents: [{ backgroundTask: task, kind: 'updateBackgroundTask', toolCallId: data.toolCallId }],
    state,
  };
};

/**
 * Reduce a single stream event. Returns the next state and intents to apply.
 * Subagent-scoped events are routed entirely through the subagent coordinator;
 * `tool_result` / terminal events run the main path AND delegate.
 */
export const reduce = (
  state: MainAgentRunState,
  event: { data?: any; type?: string },
  ctx: MainAgentReduceCtx,
): ReduceResult => {
  // Subagent-tagged chunks / turn_metadata belong wholly to the coordinator.
  if (getEventScope(event).kind === 'subagent') {
    const ended =
      event.type === 'tool_result' &&
      typeof event.data?.toolCallId === 'string' &&
      event.data.toolCallId
        ? endInterventions(state, [event.data?.toolCallId])
        : { intents: [], state };
    const delegated = delegateSubagent(ended.state, event, ctx);
    return { intents: [...ended.intents, ...delegated.intents], state: delegated.state };
  }

  const data = event.data ?? {};
  switch (event.type) {
    case 'stream_start': {
      if (!data?.newStep) return streamInit(state, data);
      // Idempotency: a `newStep` whose CC message.id matches the turn already
      // open is a REPLAY (BatchIngester retry reprocessed on a cold replica
      // with an empty in-memory `processedKeys`). Opening again would mint a
      // duplicate assistant and orphan the first as a usage-only empty shell.
      // The adapter only emits `newStep` when message.id CHANGES, so a genuine
      // new turn never collides with the current id.
      if (typeof data.messageId === 'string' && data.messageId === state.currentMainMessageId) {
        return { intents: [], state };
      }
      return openTurn(state, data, ctx);
    }
    case 'stream_chunk': {
      return reduceStreamChunk(state, data, ctx);
    }
    case 'tool_result': {
      return reduceToolResult(state, event, ctx);
    }
    case 'agent_intervention_request': {
      return reduceInterventionRequest(state, data, ctx);
    }
    case 'agent_intervention_response': {
      return reduceInterventionResponse(state, data, ctx);
    }
    case 'step_complete': {
      if (data?.phase === 'turn_metadata') return reduceTurnMetadata(state, data);
      return { intents: [], state };
    }
    case 'visible_output_end': {
      return reduceVisibleOutputEnd(state);
    }
    case 'background_task': {
      return reduceBackgroundTask(state, data);
    }
    case 'agent_runtime_end':
    case 'error': {
      return reduceTerminal(state, event, ctx);
    }
    default: {
      return { intents: [], state };
    }
  }
};