/** * `zhin trace ` — print an Agent turn trace from the * persistent archive in data/agent-traces/ (#728) or an Engagement collaboration * graph from `engagement_events` (ADR 0048 H5). */ import { Command } from 'commander'; import { formatDateTime } from '@zhin.js/plugin-runtime'; import { sessionDisplayNameOf, sessionLabelOf, shortSessionKey } from '@zhin.js/gateway/usage'; import { importProjectInstanceCli, type InstanceCliModule } from '../utils/project-instance.js'; interface TraceCommandOptions { readonly json?: boolean; readonly list?: boolean; readonly sessions?: boolean; readonly engagements?: boolean; readonly timeline?: boolean; readonly cwd?: string; readonly dir?: string; readonly session?: string; readonly since?: string; readonly until?: string; readonly limit?: string; } /** #1250 b35: pre-b35 records still merged; only the instance splits them. */ const LEGACY_ENGAGEMENTS_PENDING_NOTICE = '旧版协作记录尚未拆分,重启实例后会自动整理。'; const RELATIVE = /^(\d+(?:\.\d+)?)\s*(m|h|d)$/i; const UNIT_MS: Record = { m: 60_000, h: 3_600_000, d: 86_400_000 }; /** `30m` / `2h` / `7d` (ago), an ISO date/time, or epoch ms. */ export function parseTraceTime(value: string | undefined, now = Date.now()): number | undefined { if (value === undefined || value.trim() === '') return undefined; const text = value.trim(); const relative = RELATIVE.exec(text); if (relative) return now - Number(relative[1]) * UNIT_MS[relative[2]!.toLowerCase()]!; if (/^\d{12,}$/.test(text)) return Number(text); const parsed = Date.parse(text); if (Number.isNaN(parsed)) throw new Error(`无法解析时间:${value}(示例:2h、7d、2026-10-14、2026-10-14T08:00)`); return parsed; } function withSessionDisplayName(trace: unknown): unknown { const name = sessionDisplayNameOf(trace); return name && trace && typeof trace === 'object' ? { ...trace, session_display_name: name } : trace; } /** Readable-name fields of a session summary / chat (`@zhin.js/agent/trace` `TurnTraceSessionLabelFields`). */ interface TraceSessionLabel { readonly origin?: unknown; readonly platform?: string; readonly scope_kind?: string; readonly scene_label?: string; readonly display_name?: string; } /** One `zhin trace --sessions` row: the summary of `TurnTraceArchive.sessions()`; `origin`, the name fields and `conversations` are newer (#1250 b63). */ export interface TraceSessionRow extends TraceSessionLabel { readonly session_key: string; readonly turns: number; readonly last_started_at: number; readonly last_status: string; readonly total_tokens: number; readonly conversations?: ReadonlyArray; readonly conversations_total?: number; } /** Terminal-unsafe characters: C0 / C1 controls (ESC …), U+2028 / U+2029, bidi embeddings / overrides / isolates. */ const TERMINAL_UNSAFE = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069]/gu; /** * Last line of defence before a name reaches the terminal: unsafe characters are escaped as * `\uXXXX`. Names are cleaned when recorded and labelled, but a summary from an older * `@zhin.js/agent` may still carry raw platform text. */ export function escapeTerminalText(value: string): string { return value.replace(TERMINAL_UNSAFE, ch => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`); } /** * `平台 · 私聊 名称` (the `zhin usage report` format) of a session summary or one of its chats: its * `display_name`, else built from its `origin` (an older `@zhin.js/agent` without name fields); * `undefined` without either. Escaped for the terminal ({@link escapeTerminalText}). */ export function traceSessionName(row: TraceSessionLabel): string | undefined { const name = row.display_name || sessionDisplayNameOf({ origin: row.origin }); return name ? escapeTerminalText(name) : undefined; } /** Lines of one `zhin trace --sessions` row; chats of a session spanning several are indented below it. */ export function formatTraceSessionRow(row: TraceSessionRow): string[] { const name = traceSessionName(row); const key = name ? `${name}(${escapeTerminalText(shortSessionKey(row.session_key))})` : escapeTerminalText(row.session_key); const lines = [`${key} ${row.turns} 回合 最近 ${formatDateTime(row.last_started_at)} ${escapeTerminalText(String(row.last_status))} ${row.total_tokens} tokens`]; for (const chat of row.conversations ?? []) { lines.push(` · ${traceSessionName(chat) ?? '未记录来源'} ${chat.turns} 回合 最近 ${formatDateTime(chat.last_started_at)}`); } const shown = row.conversations?.length ?? 0; if (row.conversations_total && row.conversations_total > shown) lines.push(` · 另有 ${row.conversations_total - shown} 段聊天`); return lines; } export const traceCommand = new Command('trace') .description('查看 Agent 回合的 trace 或多 Agent 协作 Engagement 拓扑图') .argument('[turn]', '回合 id / engagement id(可只写前缀),或 last 表示最近一次', 'last') .option('-l, --list', '列出记录的回合(可配合 --session / --since / --until / --engagements)') .option('--sessions', '列出有 trace 的会话') .option('--engagements', '列出或查看协作 Engagement(来自 engagement_events 日志)') .option('-s, --session ', '只看这个会话(sessionKey)') .option('--since