Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

28.7 KB
Raw Blame
/**
 * Agent sub-task (Claude `Task`/`Agent`, Codex `collab:*`) status model — shared between
 * desktop and the mobile device-link client so both render identical sub-agent task cards.
 *
 * Ported verbatim (behavior-identical) from the desktop renderer's `makerChatStore`
 * (`normalizeAgentTaskUpdate` / `mergeAgentTaskUpdate` / `isSameAgentTaskAlias` / the
 * `agent_task_update` reducer) and the desktop `AgentTaskCard` view-model logic, so that
 * the two clients stay in lockstep. This module is presentation-neutral (no i18n strings,
 * no React): it returns structured data; each client formats labels in its own locale.
 *
 * The renderer/device-link `agent_task_update` transport remains live-only. The desktop host
 * also projects exact terminal state onto the durable originating tool-call, so history replay
 * does not have to infer failure from result text. Mobile decodes live updates via
 * `applyAgentTaskUpdateEvent`; the render layer links either source to its originating tool-call.
 */

export type AgentTaskStatus = 'running' | 'completed' | 'failed' | 'stopped';
export type AgentTaskTerminalStatus = Exclude<AgentTaskStatus, 'running'>;

export function normalizeAgentTaskTerminalStatus(
  value: unknown,
): AgentTaskTerminalStatus | undefined {
  return value === 'completed' || value === 'failed' || value === 'stopped'
    ? value
    : undefined;
}

export interface AgentTaskUsage {
  totalTokens?: number;
  toolUses?: number;
  durationMs?: number;
  costUsd?: number;
}

/**
 * `workflow_progress` 数组条目 —— Claude Code CLI 在 `task_progress` 系统事件上
 * 原生携带的 workflow 进度树节点(`workflow_phase` 分组行 / `workflow_agent` 逐 agent
 * 行)。字段无公开契约(SDK .d.ts 未声明;实测 CLI 2.1.219 稳定发送,且对纯心跳帧
 * 按 CLI 侧节流**省略整个数组**表示"沿用上一帧"),因此除 type/index 外一律
 * optional、防御式收窄;`state` 原样透传(事件流实测词表:start / progress / done /
 * error;wf 落盘文件另有 queued / running / failed / stopped / killed,消费端按
 * 两套词表兼容)。
 */
export interface WorkflowProgressEntry {
  type: 'workflow_phase' | 'workflow_agent';
  index: number;
  /** phase 标题(workflow_phase 条目)。 */
  title?: string;
  /** 脚本里 agent() 的 label(workflow_agent 条目)。 */
  label?: string;
  phaseIndex?: number;
  phaseTitle?: string;
  agentId?: string;
  model?: string;
  state?: string;
  queuedAt?: number;
  startedAt?: number;
  lastProgressAt?: number;
  lastToolName?: string;
  lastToolSummary?: string;
  resultPreview?: string;
  promptPreview?: string;
  error?: string;
  attempt?: number;
  cached?: boolean;
  agentType?: string;
}

// 防御上限:该字段无契约且随 maker:event 跨进程/跨设备转发,坏数据与超长文本
// 必须在进入任务模型前收口(截断上限同时约束 IPC/隧道 payload 体量)。
const WORKFLOW_PROGRESS_MAX_ENTRIES = 2000;
const WORKFLOW_PROGRESS_PREVIEW_MAX = 300; // resultPreview / promptPreview / error
const WORKFLOW_PROGRESS_SUMMARY_MAX = 160; // lastToolSummary
const WORKFLOW_PROGRESS_TEXT_MAX = 200; // label / title / phaseTitle 等短文本

const WORKFLOW_PROGRESS_STRING_FIELDS: ReadonlyArray<readonly [string, number]> = [
  ['title', WORKFLOW_PROGRESS_TEXT_MAX],
  ['label', WORKFLOW_PROGRESS_TEXT_MAX],
  ['phaseTitle', WORKFLOW_PROGRESS_TEXT_MAX],
  ['agentId', WORKFLOW_PROGRESS_TEXT_MAX],
  ['model', WORKFLOW_PROGRESS_TEXT_MAX],
  ['state', WORKFLOW_PROGRESS_TEXT_MAX],
  ['lastToolName', WORKFLOW_PROGRESS_TEXT_MAX],
  ['agentType', WORKFLOW_PROGRESS_TEXT_MAX],
  ['lastToolSummary', WORKFLOW_PROGRESS_SUMMARY_MAX],
  ['resultPreview', WORKFLOW_PROGRESS_PREVIEW_MAX],
  ['promptPreview', WORKFLOW_PROGRESS_PREVIEW_MAX],
  ['error', WORKFLOW_PROGRESS_PREVIEW_MAX],
];

const WORKFLOW_PROGRESS_NUMBER_FIELDS: ReadonlyArray<string> = [
  'phaseIndex',
  'queuedAt',
  'startedAt',
  'lastProgressAt',
  'attempt',
];

function clampedString(value: unknown, max: number): string | undefined {
  if (typeof value !== 'string' || value.length === 0) return undefined;
  return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
}

function finiteNumber(value: unknown): number | undefined {
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}

/**
 * 防御式收窄一段来路不明的 workflow_progress 数组(SDK 事件与远程 maker:event
 * 转发共用此收口)。坏条目跳过、超长截断、超量丢弃;没有任何合法条目时返回
 * undefined —— 与 CLI 节流帧的"缺失 = 沿用旧树"语义对齐,交给 merge 保留上一帧。
 */
export function normalizeWorkflowProgressEntries(
  raw: unknown,
): WorkflowProgressEntry[] | undefined {
  if (!Array.isArray(raw)) return undefined;
  const out: WorkflowProgressEntry[] = [];
  for (const item of raw) {
    if (out.length >= WORKFLOW_PROGRESS_MAX_ENTRIES) break;
    if (!item || typeof item !== 'object') continue;
    const e = item as Record<string, unknown>;
    if (e.type !== 'workflow_phase' && e.type !== 'workflow_agent') continue;
    const index = finiteNumber(e.index);
    if (index === undefined) continue;
    const entry: Record<string, unknown> = { type: e.type, index };
    for (const [key, max] of WORKFLOW_PROGRESS_STRING_FIELDS) {
      const value = clampedString(e[key], max);
      if (value !== undefined) entry[key] = value;
    }
    for (const key of WORKFLOW_PROGRESS_NUMBER_FIELDS) {
      const value = finiteNumber(e[key]);
      if (value !== undefined) entry[key] = value;
    }
    if (typeof e.cached === 'boolean') entry.cached = e.cached;
    out.push(entry as unknown as WorkflowProgressEntry);
  }
  return out.length > 0 ? out : undefined;
}

export interface AgentTaskUpdate {
  provider: 'claude-code' | 'codex' | 'pi';
  taskId: string;
  parentToolUseId?: string;
  status: AgentTaskStatus;
  title?: string;
  description?: string;
  summary?: string;
  outputFile?: string;
  usage?: AgentTaskUsage;
  lastToolName?: string;
  taskType?: string;
  workflowName?: string;
  /** `null` is an explicit live-update instruction to clear a stale model badge. */
  model?: string | null;
  reasoningEffort?: string;
  receiverThreadIds?: string[];
  /**
   * workflow 逐 agent 进度树(taskType=local_workflow 时由 task_progress 事件携带)。
   * CLI 对纯心跳帧节流省略本字段,merge 必须沿用上一帧,绝不能清空。
   */
  workflowProgress?: WorkflowProgressEntry[];
  createdAt?: string;
  updatedAt?: string;
}

/**
 * Derive the visible task status from the live update and its paired tool result.
 * A result is a terminal fact, so it closes a stale `running` update without
 * overriding an explicit failure or stopped state.
 *
 * `durableStatus` is the host's `subagent_runs` record for the same task, which
 * is built from structured lifecycle events rather than result text. A terminal
 * record is authoritative. A `running` record only proves the paired result is a
 * launch receipt; the live update still decides whether the task is running, so
 * a record left behind by a process that died never pins a spinner.
 */
export function deriveAgentTaskStatus(
  updateStatus: AgentTaskStatus | undefined,
  result?: string,
  options?: {
    resultIsLaunchReceipt?: boolean;
    persistedStatus?: AgentTaskTerminalStatus;

    resultIsError?: boolean;

    durableStatus?: AgentTaskStatus;

  },
): AgentTaskStatus {
  const persistedStatus = normalizeAgentTaskTerminalStatus(options?.persistedStatus);
  if (persistedStatus) return persistedStatus;
  const durableTerminalStatus = normalizeAgentTaskTerminalStatus(options?.durableStatus);
  if (durableTerminalStatus) return durableTerminalStatus;
  const resultIsLaunchReceipt =
    options?.resultIsLaunchReceipt === true || options?.durableStatus === 'running';
  const hasResult = typeof result === 'string' && result.trim().length > 0;
  // resultIsError 只应收口 stale `running` / 缺失 live update 的历史回放;显式
  // failed / stopped 是用户或系统声明的终态,不得被配对的 tool result 覆盖 ——
  // live `stopped`(用户中断)配上 SDK 的 <tool_use_error> 回执会被误显示为失败。
  if (
    options?.resultIsError
    && hasResult
    && (updateStatus === undefined || updateStatus === 'running')
  ) {
    return 'failed';
  }
  if (updateStatus === 'running' && hasResult && !resultIsLaunchReceipt) return 'completed';
  return updateStatus ?? (hasResult ? 'completed' : 'running');
}

/**

 * 判断子任务工具结果是否以协议级错误收尾(历史回放恢复 failed 的依据)。
 *
 * 仅识别 Claude SDK 协议标记 `<tool_use_error>` — 这是 SDK 在 tool call 失败时
 * 发出的结构化错误格式。不解析任意 JSON 字段或自然语言错误短语,因为子任务结果
 * 内容是用户工作产物,其中 "errors"/"status"/"stderr" 等字段是数据而非执行信号。
 *
 * 调用方约束:此函数仅应在已确认为子任务上下文的调用点使用
 * (AgentTaskCard / listSessionTasks)。普通工具结果包含 `<tool_use_error>` 时
 * 不应传入此函数,否则会将非子任务结果误判为失败。
 *
 * Authority: Claude protocol `<tool_use_error>` — SDK 在 tool call 失败时发出。
 */
export function isSubagentResultError(result: string | undefined): boolean {
  const text = typeof result === 'string' ? result.trim() : '';
  if (text.length === 0) return false;
  // Only trust protocol-level error markers. Subagent result content is arbitrary
  // user work product -- fields like "errors", "status", "stderr" in JSON output
  // are data, not execution failure signals. Parsing arbitrary body for
  // error-looking fields creates false positives that mark successful tasks as
  // failed after Desktop reload / Mobile reconnect.
  //
  // Authority sources:
  // 1. Claude protocol <tool_use_error> -- emitted by the SDK when a tool call fails
  // 2. Persisted structured terminal status (agentTaskStatus) -- written by
  //    messagePersistBroadcaster on terminal observations
  //
  // Note: <error> prefix removed -- too generic. A subagent returning
  // `<error>校验报告</error>` as work output would be misclassified as failure.
  // Only <tool_use_error> is a reliable protocol-owned error marker.
  return text.startsWith('<tool_use_error>');
}

/**
 * Durable `subagent_runs` status, keyed by every id a spawning tool call or its
 * live update may carry (parent tool-use id, harness task id, Cindy aliases).
 */
export type SubagentRunStatusIndex = ReadonlyMap<string, AgentTaskStatus>;

export interface SubagentRunStatusSource {
  parentToolUseId?: string;
  logicalAgentId?: string;
  identityAliases?: readonly string[];
  status: string;
  updatedAt?: number;
}

/** When several runs claim one alias, the most recently updated run wins. */
export function buildSubagentRunStatusIndex(
  runs: readonly SubagentRunStatusSource[],
): SubagentRunStatusIndex {
  const index = new Map<string, AgentTaskStatus>();
  const updatedAtByKey = new Map<string, number>();
  for (const run of runs) {
    const status = run.status === 'running' ? 'running' : normalizeAgentTaskTerminalStatus(run.status);
    if (!status) continue;
    const updatedAt = typeof run.updatedAt === 'number' ? run.updatedAt : 0;
    const keys = [run.parentToolUseId, run.logicalAgentId, ...(run.identityAliases ?? [])];
    for (const key of keys) {
      if (typeof key !== 'string' || key.length === 0) continue;
      const previous = updatedAtByKey.get(key);
      if (previous !== undefined && previous > updatedAt) continue;
      index.set(key, status);
      updatedAtByKey.set(key, updatedAt);
    }
  }
  return index;
}

/** First durable status found under the call's tool-use id or its update's ids. */
export function lookupSubagentRunStatus(
  index: SubagentRunStatusIndex | undefined,
  toolUseId: string | undefined,
  update?: Pick<AgentTaskUpdate, 'taskId' | 'parentToolUseId'>,
): AgentTaskStatus | undefined {
  if (!index || index.size === 0) return undefined;
  for (const key of [toolUseId, update?.parentToolUseId, update?.taskId]) {
    if (typeof key !== 'string' || key.length === 0) continue;
    const status = index.get(key);
    if (status) return status;
  }
  return undefined;

}

/**
 * Tool names that spawn a sub-agent task: Claude `Task`/`Agent`, Codex collab agents,
 * PI `subagent`(Cindy 自有扩展注册的工具名,与 pi 社区惯例一致)。
 *
 * MCP 工具一律带 `mcp__` 前缀,不会与裸 `subagent` 撞名。
 */
export function isSubagentSpawnToolName(toolName: string): boolean {
  return toolName === 'Agent'
    || toolName === 'Task'
    || toolName === PI_SUBAGENT_TOOL_NAME
    || toolName === 'collab:spawn'
    || toolName === 'collab:spawnAgent';
}

export function isAgentTaskToolName(toolName: string): boolean {
  return isSubagentSpawnToolName(toolName) || toolName.startsWith('collab:');
}

/**
 * Claude 子任务工具名(`Agent` / `Task`)。
 *
 * `isSubagentResultError` 识别的 `<tool_use_error>` 是 Claude SDK 协议级标记,只对这两个
 * 工具的结果有意义。后台 Bash、PI subagent 与 Codex `collab:*` 的成功产物可能合法地以该
 * 前缀开头(例如把该标记当成搜索命中打印出来),无条件按它收口会把成功任务误标成
 * `failed`。调用方必须先确认工具名属于 Claude 子任务,再把结果交给 `isSubagentResultError`。
 */
export function isClaudeSubagentToolName(toolName: string | undefined): boolean {
  return toolName === 'Agent' || toolName === 'Task';
}

/** PI 子代理工具名 —— maker-core 的 pi 扩展注册端与本文件的卡片判据共用,不各写字面量。 */
export const PI_SUBAGENT_TOOL_NAME = 'subagent';

/**
 * Validate + shape a raw `agent_task_update` event payload into an `AgentTaskUpdate`.
 * Returns null when neither a taskId nor a parentToolUseId is present (un-linkable).
 */
export function normalizeAgentTaskUpdate(
  data: unknown,
  source?: 'claude-code' | 'codex' | 'pi',
): AgentTaskUpdate | null {
  if (!data || typeof data !== 'object') return null;
  const raw = data as Record<string, unknown>;
  const taskId = typeof raw.taskId === 'string' && raw.taskId.length > 0 ? raw.taskId : undefined;
  const parentToolUseId =
    typeof raw.parentToolUseId === 'string' && raw.parentToolUseId.length > 0
      ? raw.parentToolUseId
      : undefined;
  if (!taskId && !parentToolUseId) return null;
  const rawStatus = raw.status;
  const status: AgentTaskStatus =
    rawStatus === 'completed' || rawStatus === 'failed' || rawStatus === 'stopped'
      ? rawStatus
      : 'running';
  const provider = raw.provider === 'codex' || raw.provider === 'claude-code' || raw.provider === 'pi'
    ? raw.provider
    : source === 'codex' || source === 'pi'
      ? source
      : 'claude-code';
  const usageRaw = raw.usage && typeof raw.usage === 'object' ? raw.usage as Record<string, unknown> : null;
  const usage: AgentTaskUsage | undefined = usageRaw
    ? {
        ...(typeof usageRaw.totalTokens === 'number' ? { totalTokens: usageRaw.totalTokens } : {}),
        ...(typeof usageRaw.toolUses === 'number' ? { toolUses: usageRaw.toolUses } : {}),
        ...(typeof usageRaw.durationMs === 'number' ? { durationMs: usageRaw.durationMs } : {}),
        ...(typeof usageRaw.costUsd === 'number' ? { costUsd: usageRaw.costUsd } : {}),
      }
    : undefined;
  const workflowProgress = normalizeWorkflowProgressEntries(raw.workflowProgress);
  return {
    provider,
    taskId: taskId ?? parentToolUseId!,
    ...(parentToolUseId ? { parentToolUseId } : {}),
    status,
    ...(typeof raw.title === 'string' && raw.title ? { title: raw.title } : {}),
    ...(typeof raw.description === 'string' && raw.description ? { description: raw.description } : {}),
    ...(typeof raw.summary === 'string' && raw.summary ? { summary: raw.summary } : {}),
    ...(typeof raw.outputFile === 'string' && raw.outputFile ? { outputFile: raw.outputFile } : {}),
    ...(usage && Object.keys(usage).length > 0 ? { usage } : {}),
    ...(typeof raw.lastToolName === 'string' && raw.lastToolName ? { lastToolName: raw.lastToolName } : {}),
    ...(typeof raw.taskType === 'string' && raw.taskType ? { taskType: raw.taskType } : {}),
    ...(typeof raw.workflowName === 'string' && raw.workflowName ? { workflowName: raw.workflowName } : {}),
    ...(raw.model === null
      ? { model: null }
      : typeof raw.model === 'string' && raw.model
        ? { model: raw.model }
        : {}),
    ...(typeof raw.reasoningEffort === 'string' && raw.reasoningEffort ? { reasoningEffort: raw.reasoningEffort } : {}),
    ...(Array.isArray(raw.receiverThreadIds)
      ? { receiverThreadIds: raw.receiverThreadIds.filter((id): id is string => typeof id === 'string') }
      : {}),
    ...(workflowProgress ? { workflowProgress } : {}),
    ...(typeof raw.createdAt === 'string' && raw.createdAt ? { createdAt: raw.createdAt } : {}),
    ...(typeof raw.updatedAt === 'string' && raw.updatedAt ? { updatedAt: raw.updatedAt } : {}),
  };
}

/** Field-wise merge of a newer update over a prior one (newer non-empty fields win). */
export function mergeAgentTaskUpdate(prev: AgentTaskUpdate | undefined, next: AgentTaskUpdate): AgentTaskUpdate {
  if (!prev) return next;
  return {
    ...prev,
    ...next,
    usage: next.usage ?? prev.usage,
    title: next.title ?? prev.title,
    description: next.description ?? prev.description,
    summary: next.summary ?? prev.summary,
    outputFile: next.outputFile ?? prev.outputFile,
    lastToolName: next.lastToolName ?? prev.lastToolName,
    // CLI 节流帧不带 workflowProgress(undefined = 沿用旧树),必须保留上一帧。
    workflowProgress: next.workflowProgress ?? prev.workflowProgress,
    createdAt: prev.createdAt ?? next.createdAt,
    model: next.model === null ? null : next.model ?? prev.model,
    updatedAt: next.updatedAt ?? prev.updatedAt,
  };
}

/** Two updates describe the same task if their taskId/parentToolUseId aliases overlap. */
export function isSameAgentTaskAlias(left: AgentTaskUpdate, right: AgentTaskUpdate): boolean {
  if (left.taskId === right.taskId) return true;
  if (left.parentToolUseId && left.parentToolUseId === right.taskId) return true;
  if (right.parentToolUseId && right.parentToolUseId === left.taskId) return true;
  return Boolean(left.parentToolUseId && right.parentToolUseId && left.parentToolUseId === right.parentToolUseId);
}

/**
 * Reduce a raw `agent_task_update` event into the per-session task-update map.
 * Mirrors the desktop `makerChatStore` reducer: keys every update by its taskId and
 * parentToolUseId (plus any aliased existing keys) so a single task is reachable by either
 * the live taskId or the originating tool-call id. Returns a NEW map, or null when the
 * payload is un-linkable (caller should treat null as a no-op). `nowIso` is injected so the
 * function stays pure/deterministic for tests.
 */
export function applyAgentTaskUpdateEvent(
  prevMap: ReadonlyMap<string, AgentTaskUpdate> | undefined,
  data: unknown,
  source: 'claude-code' | 'codex' | 'pi' | undefined,
  nowIso: string,
): Map<string, AgentTaskUpdate> | null {
  const update = normalizeAgentTaskUpdate(data, source);
  if (!update) return null;
  const nextMap = new Map(prevMap ?? []);
  const keys = new Set<string>([update.taskId]);
  if (update.parentToolUseId) keys.add(update.parentToolUseId);
  for (const [key, value] of nextMap) {
    if (!isSameAgentTaskAlias(value, update)) continue;
    keys.add(key);
    keys.add(value.taskId);
    if (value.parentToolUseId) keys.add(value.parentToolUseId);
  }
  const existing = [...keys].map((key) => nextMap.get(key)).find((value): value is AgentTaskUpdate => Boolean(value));
  const timedUpdate: AgentTaskUpdate = {
    ...update,
    createdAt: update.createdAt ?? existing?.createdAt ?? nowIso,
    updatedAt: update.updatedAt ?? nowIso,
  };
  let merged: AgentTaskUpdate | undefined;
  for (const key of keys) {
    merged = mergeAgentTaskUpdate(nextMap.get(key), merged ?? timedUpdate);
  }
  if (!merged) merged = timedUpdate;
  for (const key of keys) nextMap.set(key, merged);
  return nextMap;
}

/**
 * Look up the live update for a tool-call by its tool-use id, then its client id —
 * the two keys the reducer indexes a task under. Mirrors desktop `findTaskUpdate`.
 */
export function findAgentTaskUpdate(
  taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined,
  toolUseId: string | null | undefined,
  clientId: string | null | undefined,
): AgentTaskUpdate | undefined {
  if (!taskUpdates) return undefined;
  if (toolUseId) {
    const byToolUseId = taskUpdates.get(toolUseId);
    if (byToolUseId) return byToolUseId;
  }
  if (clientId) return taskUpdates.get(clientId);
  return undefined;
}

/**
 * Presentation-neutral view-model for a sub-agent task card, derived from the originating
 * tool-call input and/or the live update. Mirrors the desktop `AgentTaskCard` field-selection
 * (title fallback chain, description/summary precedence, status inference). Returns structured
 * data only — each client renders status/provider/usage labels in its own locale.
 */
export interface AgentTaskCardModel {
  status: AgentTaskStatus;
  provider: 'claude-code' | 'codex' | 'pi';
  /** Best title, or null when nothing usable was found (caller supplies its own fallback). */
  title: string | null;
  description?: string;
  summary?: string;
  /**
   * Codex `collab:spawn` 启动回执:translator 的 tool_result 只放 agentPath 原文
   * (恰等于 input.name,见 subagentSpawnReceiptName 判据)。命中时 summary 不携带
   * 裸路径,各端用本字段按自己的 locale 组装「Subagent 已启动」句子。
   */
  spawnedAgentName?: string;
  lastToolName?: string;
  outputFile?: string;
  totalTokens?: number;
  toolUses?: number;
  durationMs?: number;
}

/**
 * codex spawn 启动回执判据:translator(maker-core codex)约定 `collab:spawn` 卡的
 * tool_result fullText 只放 agentPath 原文、且与 `input.name` 逐字相等。命中即返回
 * 该名字,供各端替换为本地化句子;未来 vendored Codex 升级后的富卡(agentsStates
 * 摘要)不会与 input.name 相等,自然不命中。桌面 AgentTaskCard 与本文件的
 * buildAgentTaskCardModel 共用本判据,不要各自内联复制。
 */
export function subagentSpawnReceiptName(
  toolName: string | undefined,
  toolInput: unknown,
  result: string | undefined,
): string | undefined {
  if (toolName !== 'collab:spawn') return undefined;
  const name = readInputString(toolInput, ['name']);
  const trimmed = result?.trim();
  return name && trimmed && trimmed === name ? name : undefined;
}

/**
 * V1 `collab:spawnAgent` returns a compact child-state summary. A `running`
 * summary is a launch receipt for the spawn tool, not a terminal result for
 * the child task, so it must not close a stale running update.
 */
export function subagentSpawnResultIndicatesRunning(
  toolName: string | undefined,
  result: string | null | undefined,
): boolean {
  const trimmed = typeof result === 'string'
    ? result.trim().replace(/\r\n/g, '\n')
    : '';
  // Claude's asynchronous Agent tool returns a textual launch receipt while the
  // child is still running. Treat it like the structured Codex V1 receipt so a
  // paired stale `running` update does not close the task prematurely.
  if (toolName === PI_SUBAGENT_TOOL_NAME
    && trimmed === 'Cindy subagent launched. The agent is working in the background.') {
    return true;
  }
  // Claude Code 2.1.280 appends a notice to the first line (`Async agent
  // launched successfully. (This tool result is internal metadata …)`) and to
  // the agentId line, so match the lines by prefix instead of exact text.
  if ((toolName === 'Agent' || toolName === 'Task')
    && (
      trimmed === 'Async agent launched successfully.'
      || (
        trimmed.startsWith('Async agent launched successfully.')
        && /\nagentId: \S/.test(trimmed)
        && trimmed.includes('\nThe agent is working in the background.')
      )
    )) {
    return true;
  }
  if (toolName !== 'collab:spawnAgent') return false;
  return (result ?? '').split(/\r?\n/).some((line) =>
    /^[^:\n]+:\s*(?:running|in[_-]?progress|started|active)\s*$/i.test(line.trim()),
  );
}

/** Hide Codex's collaboration-tree address in UI only; keep raw IDs for routing. */
export function formatAgentTaskTitle(
  provider: AgentTaskUpdate['provider'],
  title: string | undefined,
): string | undefined {
  const text = title?.trim();
  if (provider === 'codex' && text && /^\/root(?:\/[^/\s]+)+\/?$/.test(text)) {
    return text.split('/').filter(Boolean).at(-1);
  }
  return title;
}

export function buildAgentTaskCardModel(input: {
  toolName?: string;
  toolInput?: unknown;
  update?: AgentTaskUpdate;
  result?: string;
  persistedStatus?: AgentTaskTerminalStatus;
  durableStatus?: AgentTaskStatus;
}): AgentTaskCardModel {
  const { toolName, toolInput, update, result, persistedStatus, durableStatus } = input;
  // `<tool_use_error>` is only a trustworthy failure witness for Claude
  // subagent tools (Agent/Task). PI `subagent` / Codex `collab:*` results are
  // arbitrary work products that may legitimately start with that marker, so
  // the shared card model narrows by tool name exactly like the desktop
  // callers (AgentTaskCard / listSessionTasks). With no tool name (history
  // replay of a legacy update card) fall back to the provider heuristic below,
  // matching AgentTaskCard's claudeProtocolResult.
  const providerFallback: 'claude-code' | 'codex' | 'pi' =
    update?.provider
    ?? (toolName?.startsWith('collab:')
      ? 'codex'
      : toolName === PI_SUBAGENT_TOOL_NAME
        ? 'pi'
        : 'claude-code');
  const claudeProtocolResult = toolName !== undefined
    ? isClaudeSubagentToolName(toolName)
    : providerFallback === 'claude-code';
  const status = deriveAgentTaskStatus(update?.status, result, {
    persistedStatus,
    durableStatus,
    resultIsLaunchReceipt:
      subagentSpawnReceiptName(toolName, toolInput, result) !== undefined
      || subagentSpawnResultIndicatesRunning(toolName, result),
    resultIsError: claudeProtocolResult && isSubagentResultError(result),
  });
  const provider = providerFallback;
  const title = compactText(
    formatAgentTaskTitle(provider, update?.title
      ?? readInputString(toolInput, ['description', 'task', 'name'])
      ?? readInputString(toolInput, ['prompt'])),
    96,
  );
  const description = compactText(
    update?.description ?? readInputString(toolInput, ['prompt', 'description', 'task']),
  );
  const spawnReceiptName = subagentSpawnReceiptName(toolName, toolInput, result);
  // 有实时 update(子线程送来的 tokens / 工具调用数 / 终态)时不再暴露启动回执:
  // title 与运行状态已经表达了同样的信息,再显示「Subagent X 已启动」会让 codex 卡
  // 比 Claude 子代理卡多出一行冗余文案 —— 两者共用同一张卡,形态必须一致。历史回放
  // 拿不到 live update,回执仍是唯一可读摘要,保留原样。
  const spawnedAgentName = update ? undefined : formatAgentTaskTitle(provider, spawnReceiptName);
  // 启动回执命中时 summary 不携带裸路径(路径已在 spawnedAgentName / title 中),
  // 否则手机端会把 agentPath 原样当摘要展示。
  // Claude 异步 Agent 的启动回执是写给模型的内部元数据(agentId / output 文件),不当摘要展示。
  const claudeLaunchReceipt = (toolName === 'Agent' || toolName === 'Task')
    && subagentSpawnResultIndicatesRunning(toolName, result);
  const summary = spawnReceiptName || claudeLaunchReceipt
    ? detailText(update?.summary)
    : detailText(result, update?.summary);
  return {
    status,
    provider,
    title: title ?? null,
    ...(description ? { description } : {}),
    ...(summary ? { summary } : {}),
    ...(spawnedAgentName ? { spawnedAgentName } : {}),
    ...(update?.lastToolName ? { lastToolName: update.lastToolName } : {}),
    ...(update?.outputFile ? { outputFile: update.outputFile } : {}),
    ...(typeof update?.usage?.totalTokens === 'number' ? { totalTokens: update.usage.totalTokens } : {}),
    ...(typeof update?.usage?.toolUses === 'number' ? { toolUses: update.usage.toolUses } : {}),
    ...(typeof update?.usage?.durationMs === 'number' ? { durationMs: update.usage.durationMs } : {}),
  };
}

function readInputString(input: unknown, keys: string[]): string | undefined {
  if (!input || typeof input !== 'object') return undefined;
  const obj = input as Record<string, unknown>;
  for (const key of keys) {
    const value = obj[key];
    if (typeof value === 'string' && value.trim()) return value.trim();
  }
  return undefined;
}

function compactText(text: string | undefined, max = 260): string | undefined {
  if (!text) return undefined;
  const oneLine = text.replace(/\s+/g, ' ').trim();
  if (oneLine.length <= max) return oneLine;
  return `${oneLine.slice(0, max - 1)}…`;
}

function detailText(...values: Array<string | undefined>): string | undefined {
  for (const value of values) {
    const trimmed = value?.trim();
    if (trimmed) return trimmed;
  }
  return undefined;
}