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.

1.7 KB
Raw Blame
import type { AssistantContentBlock, ChatToolPayload, MessageSignal } from '@lobechat/types';

export interface TaskCompletionSource {
  /** The source call's `description` argument, e.g. a subagent's task title. */
  description?: string;
  /** API name of the tool whose completion woke the turn, e.g. `Agent`. */
  toolName: string;
}

/** Anything that carries tool calls: reply blocks or raw messages. */
interface ToolCallHost {
  tools?: Pick<ChatToolPayload, 'apiName' | 'arguments' | 'id'>[] | null;
}

const readDescription = (args?: string): string | undefined => {
  if (!args) return;
  try {
    const description = JSON.parse(args)?.description;
    return typeof description === 'string' && description.trim() ? description.trim() : undefined;
  } catch {
    return;
  }
};

const findToolCall = (hosts: ToolCallHost[], toolCallId: string) => {
  for (const host of hosts) {
    const call = host.tools?.find((tool) => tool.id === toolCallId);
    if (call) return call;
  }
};

/**
 * The long-running tool (a background subagent, Bash, Monitor…) whose
 * completion woke a task-completion turn, looked up among the given tool-call
 * hosts so the notice can name it. Undefined for any other block.
 */
export const resolveTaskCompletionSource = (
  block: Pick<AssistantContentBlock, 'metadata'>,
  hosts: ToolCallHost[],
): TaskCompletionSource | undefined => {
  const signal = block.metadata?.signal as MessageSignal | undefined;
  if (signal?.type !== 'task-completion') return;

  const sourceCall = findToolCall(hosts, signal.sourceToolCallId);

  return {
    description: readDescription(sourceCall?.arguments),
    toolName: sourceCall?.apiName ?? signal.sourceToolName,
  };
};