mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
refactor(panel): extract sqlite/wire primitives, localize charts & structured status, and unify overlay/mock-dom (P2)
This commit is contained in:
@@ -10,194 +10,38 @@
|
||||
* 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
|
||||
import {
|
||||
SQLITE_IN_CHUNK_SIZE,
|
||||
computeSqliteWalSig,
|
||||
getNodeSqliteDatabaseSync,
|
||||
hasBuiltinNodeSqlite,
|
||||
normalizeSqliteIsoTime,
|
||||
withReadOnlySqliteDb,
|
||||
} from './sqlite-client.mjs';
|
||||
import {
|
||||
decodeProtoDurationSlice,
|
||||
decodeProtoMapStringEntry,
|
||||
decodeProtoTimestampSlice,
|
||||
readProtoString,
|
||||
readProtoVarint,
|
||||
readSubEnd,
|
||||
skipProtoField,
|
||||
toUint8Array,
|
||||
unescapePbtxtString,
|
||||
} from './proto-wire.mjs';
|
||||
|
||||
export {
|
||||
computeSqliteWalSig,
|
||||
getNodeSqliteDatabaseSync,
|
||||
hasBuiltinNodeSqlite,
|
||||
withReadOnlySqliteDb,
|
||||
};
|
||||
|
||||
const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const SQLITE_IN_CHUNK_SIZE = 400;
|
||||
const utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
|
||||
|
||||
let sqliteResolved = false;
|
||||
let sqliteDatabaseSyncCtor = null;
|
||||
|
||||
/**
|
||||
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。
|
||||
* 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。
|
||||
*
|
||||
* @returns {Function | null}
|
||||
*/
|
||||
export function getNodeSqliteDatabaseSync() {
|
||||
if (typeof globalThis.DatabaseSync === 'function') {
|
||||
return globalThis.DatabaseSync;
|
||||
}
|
||||
if (sqliteResolved) return sqliteDatabaseSyncCtor;
|
||||
sqliteResolved = true;
|
||||
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const origEmitWarning = process.emitWarning;
|
||||
try {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
|
||||
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
|
||||
if (/SQLite is an experimental feature/i.test(msg)) return;
|
||||
return origEmitWarning.call(this, warning, ...rest);
|
||||
};
|
||||
}
|
||||
const mod = process.getBuiltinModule('node:sqlite');
|
||||
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
|
||||
} catch {
|
||||
sqliteDatabaseSyncCtor = null;
|
||||
} finally {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = origEmitWarning;
|
||||
}
|
||||
}
|
||||
return sqliteDatabaseSyncCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasBuiltinNodeSqlite() {
|
||||
return Boolean(getNodeSqliteDatabaseSync());
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
||||
*
|
||||
* @param {string} dbPath
|
||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||
*/
|
||||
export function computeSqliteWalSig(dbPath) {
|
||||
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
let dbStat = null;
|
||||
try {
|
||||
dbStat = statSync(dbPath);
|
||||
} catch {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
||||
|
||||
let walStat = null;
|
||||
const walPath = `${dbPath}-wal`;
|
||||
if (existsSync(walPath)) {
|
||||
try {
|
||||
walStat = statSync(walPath);
|
||||
} catch {
|
||||
walStat = null;
|
||||
}
|
||||
}
|
||||
const dbMtimeMs = Number(dbStat.mtimeMs || 0);
|
||||
const dbSize = Number(dbStat.size || 0);
|
||||
const walMtimeMs = Number(walStat?.mtimeMs || 0);
|
||||
const walSize = Number(walStat?.size || 0);
|
||||
return {
|
||||
exists: true,
|
||||
mtimeMs: Math.max(dbMtimeMs, walMtimeMs),
|
||||
sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`,
|
||||
};
|
||||
}
|
||||
|
||||
function isSqliteBusyError(err) {
|
||||
const msg = String(err?.message || err?.code || '');
|
||||
return /SQLITE_BUSY|database is locked/i.test(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
*/
|
||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(dbPath, { readOnly: true });
|
||||
try {
|
||||
db.exec('PRAGMA busy_timeout = 1000;');
|
||||
} catch {
|
||||
// 兼容最小测试桩
|
||||
}
|
||||
return queryFn(db);
|
||||
} catch (err) {
|
||||
if (attempt === 0 && isSqliteBusyError(err)) {
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
|
||||
*
|
||||
* @param {string} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
function unescapePbtxtString(raw) {
|
||||
if (typeof raw !== 'string' || !raw) return '';
|
||||
if (!raw.includes('\\')) return raw;
|
||||
const bytes = [];
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const ch = raw[i];
|
||||
if (ch !== '\\' || i + 1 >= raw.length) {
|
||||
const encoded = Buffer.from(ch, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
continue;
|
||||
}
|
||||
const next = raw[++i];
|
||||
if (next >= '0' && next <= '7') {
|
||||
let oct = next;
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
bytes.push(parseInt(oct, 8) & 0xff);
|
||||
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
|
||||
const hex = raw.slice(i + 1, i + 3);
|
||||
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
||||
bytes.push(parseInt(hex, 16));
|
||||
i += 2;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'u' && i + 4 < raw.length) {
|
||||
const uHex = raw.slice(i + 1, i + 5);
|
||||
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
|
||||
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
i += 4;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'n') {
|
||||
bytes.push(0x0a);
|
||||
} else if (next === 'r') {
|
||||
bytes.push(0x0d);
|
||||
} else if (next === 't') {
|
||||
bytes.push(0x09);
|
||||
} else {
|
||||
const encoded = Buffer.from(next, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
}
|
||||
}
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `annotations/<cascadeId>.pbtxt` 文本内容中提取顶层 `title` 字段。
|
||||
@@ -243,12 +87,6 @@ export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTA
|
||||
return '';
|
||||
}
|
||||
|
||||
function normalizeSqliteIsoTime(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return '';
|
||||
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -372,133 +210,6 @@ const PROTO_CHAT_MSG_SOURCES = Object.freeze({
|
||||
6: 'CHAT_MESSAGE_SOURCE_CONTEXT',
|
||||
});
|
||||
|
||||
function toUint8Array(raw) {
|
||||
if (!raw) return null;
|
||||
if (raw instanceof Uint8Array) return raw;
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
}
|
||||
if (raw instanceof ArrayBuffer) {
|
||||
return new Uint8Array(raw);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function decodeUtf8Slice(buf, start, end) {
|
||||
if (start >= end) return '';
|
||||
if (utf8Decoder) {
|
||||
return utf8Decoder.decode(buf.subarray(start, end));
|
||||
}
|
||||
return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8');
|
||||
}
|
||||
|
||||
function readProtoVarint(buf, state, limit = buf.length) {
|
||||
if (state.off >= limit) return 0n;
|
||||
const b0 = buf[state.off];
|
||||
if (b0 < 0x80) {
|
||||
state.off += 1;
|
||||
return BigInt(b0);
|
||||
}
|
||||
let result = 0n;
|
||||
let shift = 0n;
|
||||
for (let i = 0; i < 10 && state.off < limit; i++) {
|
||||
const byte = buf[state.off++];
|
||||
result |= BigInt(byte & 0x7f) << shift;
|
||||
if ((byte & 0x80) === 0) {
|
||||
return BigInt.asUintN(64, result);
|
||||
}
|
||||
shift += 7n;
|
||||
}
|
||||
while (state.off < limit && (buf[state.off++] & 0x80) !== 0) {
|
||||
// 安全排空超长 varint 延续字节
|
||||
}
|
||||
return BigInt.asUintN(64, result);
|
||||
}
|
||||
|
||||
function readSubEnd(buf, state, limit = buf.length) {
|
||||
const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||
return Math.min(limit, state.off + len);
|
||||
}
|
||||
|
||||
function readProtoString(buf, state, limit = buf.length) {
|
||||
const end = readSubEnd(buf, state, limit);
|
||||
const str = decodeUtf8Slice(buf, state.off, end);
|
||||
state.off = end;
|
||||
return str;
|
||||
}
|
||||
|
||||
function skipProtoField(buf, state, wireType, limit = buf.length) {
|
||||
if (wireType === 0) {
|
||||
readProtoVarint(buf, state, limit);
|
||||
} else if (wireType === 1) {
|
||||
state.off = Math.min(limit, state.off + 8);
|
||||
} else if (wireType === 2) {
|
||||
state.off = readSubEnd(buf, state, limit);
|
||||
} else if (wireType === 5) {
|
||||
state.off = Math.min(limit, state.off + 4);
|
||||
} else if (wireType === 3) {
|
||||
while (state.off < limit) {
|
||||
const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||
const innerWt = innerTag & 7;
|
||||
if (innerWt === 4) break;
|
||||
skipProtoField(buf, state, innerWt, limit);
|
||||
}
|
||||
} else if (wireType !== 4) {
|
||||
state.off = limit;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeProtoTimestampSlice(buf, state, end) {
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
if (seconds <= 0n || seconds > 253402300799n) return '';
|
||||
const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19);
|
||||
if (nanos > 0n && nanos < 1_000_000_000n) {
|
||||
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
|
||||
return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`;
|
||||
}
|
||||
return `${baseIso}Z`;
|
||||
}
|
||||
|
||||
function decodeProtoDurationSlice(buf, state, end) {
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
const totalNs = seconds * 1_000_000_000n + nanos;
|
||||
if (totalNs < 0n) return '';
|
||||
if (totalNs === 0n) return '0s';
|
||||
const wholeSec = totalNs / 1_000_000_000n;
|
||||
const remNs = Number(totalNs % 1_000_000_000n);
|
||||
if (remNs === 0) return `${wholeSec}s`;
|
||||
const frac = String(remNs).padStart(9, '0').replace(/0+$/, '');
|
||||
return `${wholeSec}.${frac}s`;
|
||||
}
|
||||
|
||||
function decodeProtoModelEnumInt(val) {
|
||||
const n = Math.trunc(Number(val));
|
||||
if (!Number.isFinite(n) || n <= 0) return '';
|
||||
@@ -518,25 +229,6 @@ function decodeProtoStepStatusEnum(val) {
|
||||
return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE';
|
||||
}
|
||||
|
||||
function decodeProtoMapStringEntry(buf, state, end) {
|
||||
let key = '';
|
||||
let val = '';
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
key = readProtoString(buf, state, end);
|
||||
} else if (fn === 2 && wt === 2) {
|
||||
val = readProtoString(buf, state, end);
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return [key, val];
|
||||
}
|
||||
|
||||
function decodeProtoSubagentSpecSlice(buf, state, end) {
|
||||
let typeName = '';
|
||||
let role = '';
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* @fileoverview 零外部依赖的二进制 Protobuf Wire 跳读游标与 `prototext` 字符串反转义原语 (`proto-wire.mjs`)。
|
||||
*
|
||||
* 核心能力:
|
||||
* 1. 无需引入 `protobufjs`,以 `O(1)` 游标位移跳过大体积定长/变长/Group 载荷;
|
||||
* 2. 基于 `BigInt` 无损解码 64-bit Varint、`google.protobuf.Timestamp` 纳秒级时间戳与 `Duration`;
|
||||
* 3. 按原始 UTF-8 字节流无损反转义 `prototext` 的 `\ddd` 八进制、`\xHH` 十六进制与 `\uXXXX` 多字节字符。
|
||||
*/
|
||||
|
||||
const protoUtf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
|
||||
|
||||
/**
|
||||
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
|
||||
*
|
||||
* @param {string} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
export function unescapePbtxtString(raw) {
|
||||
if (typeof raw !== 'string' || !raw) return '';
|
||||
if (!raw.includes('\\')) return raw;
|
||||
const bytes = [];
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const ch = raw[i];
|
||||
if (ch !== '\\' || i + 1 >= raw.length) {
|
||||
const encoded = Buffer.from(ch, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
continue;
|
||||
}
|
||||
const next = raw[++i];
|
||||
if (next >= '0' && next <= '7') {
|
||||
let oct = next;
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
bytes.push(parseInt(oct, 8) & 0xff);
|
||||
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
|
||||
const hex = raw.slice(i + 1, i + 3);
|
||||
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
||||
bytes.push(parseInt(hex, 16));
|
||||
i += 2;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'u' && i + 4 < raw.length) {
|
||||
const uHex = raw.slice(i + 1, i + 5);
|
||||
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
|
||||
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
i += 4;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'n') {
|
||||
bytes.push(0x0a);
|
||||
} else if (next === 'r') {
|
||||
bytes.push(0x0d);
|
||||
} else if (next === 't') {
|
||||
bytes.push(0x09);
|
||||
} else {
|
||||
const encoded = Buffer.from(next, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
}
|
||||
}
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
export function toUint8Array(raw) {
|
||||
if (!raw) return null;
|
||||
if (raw instanceof Uint8Array) return raw;
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
}
|
||||
if (raw instanceof ArrayBuffer) {
|
||||
return new Uint8Array(raw);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function decodeUtf8Slice(buf, start, end) {
|
||||
if (start >= end) return '';
|
||||
if (protoUtf8Decoder) {
|
||||
return protoUtf8Decoder.decode(buf.subarray(start, end));
|
||||
}
|
||||
return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8');
|
||||
}
|
||||
|
||||
export function readProtoVarint(buf, state, limit = buf.length) {
|
||||
if (state.off >= limit) return 0n;
|
||||
const b0 = buf[state.off];
|
||||
if (b0 < 0x80) {
|
||||
state.off += 1;
|
||||
return BigInt(b0);
|
||||
}
|
||||
let result = 0n;
|
||||
let shift = 0n;
|
||||
for (let i = 0; i < 10 && state.off < limit; i++) {
|
||||
const byte = buf[state.off++];
|
||||
result |= BigInt(byte & 0x7f) << shift;
|
||||
if ((byte & 0x80) === 0) {
|
||||
return BigInt.asUintN(64, result);
|
||||
}
|
||||
shift += 7n;
|
||||
}
|
||||
while (state.off < limit && (buf[state.off++] & 0x80) !== 0) {
|
||||
// 安全排空超长 varint 延续字节
|
||||
}
|
||||
return BigInt.asUintN(64, result);
|
||||
}
|
||||
|
||||
export function readSubEnd(buf, state, limit = buf.length) {
|
||||
const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||
return Math.min(limit, state.off + len);
|
||||
}
|
||||
|
||||
export function readProtoString(buf, state, limit = buf.length) {
|
||||
const end = readSubEnd(buf, state, limit);
|
||||
const str = decodeUtf8Slice(buf, state.off, end);
|
||||
state.off = end;
|
||||
return str;
|
||||
}
|
||||
|
||||
export function skipProtoField(buf, state, wireType, limit = buf.length) {
|
||||
if (wireType === 0) {
|
||||
readProtoVarint(buf, state, limit);
|
||||
} else if (wireType === 1) {
|
||||
state.off = Math.min(limit, state.off + 8);
|
||||
} else if (wireType === 2) {
|
||||
state.off = readSubEnd(buf, state, limit);
|
||||
} else if (wireType === 5) {
|
||||
state.off = Math.min(limit, state.off + 4);
|
||||
} else if (wireType === 3) {
|
||||
while (state.off < limit) {
|
||||
const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||
const innerWt = innerTag & 7;
|
||||
if (innerWt === 4) break;
|
||||
skipProtoField(buf, state, innerWt, limit);
|
||||
}
|
||||
} else if (wireType !== 4) {
|
||||
state.off = limit;
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeProtoTimestampSlice(buf, state, end) {
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
if (seconds <= 0n || seconds > 253402300799n) return '';
|
||||
const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19);
|
||||
if (nanos > 0n && nanos < 1_000_000_000n) {
|
||||
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
|
||||
return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`;
|
||||
}
|
||||
return `${baseIso}Z`;
|
||||
}
|
||||
|
||||
export function decodeProtoDurationSlice(buf, state, end) {
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
const totalNs = seconds * 1_000_000_000n + nanos;
|
||||
if (totalNs < 0n) return '';
|
||||
if (totalNs === 0n) return '0s';
|
||||
const wholeSec = totalNs / 1_000_000_000n;
|
||||
const remNs = Number(totalNs % 1_000_000_000n);
|
||||
if (remNs === 0) return `${wholeSec}s`;
|
||||
const frac = String(remNs).padStart(9, '0').replace(/0+$/, '');
|
||||
return `${wholeSec}.${frac}s`;
|
||||
}
|
||||
|
||||
export function decodeProtoMapStringEntry(buf, state, end) {
|
||||
let key = '';
|
||||
let val = '';
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
key = readProtoString(buf, state, end);
|
||||
} else if (fn === 2 && wt === 2) {
|
||||
val = readProtoString(buf, state, end);
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return [key, val];
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* @fileoverview 零业务依赖的本地 SQLite + WAL 非阻塞只读短连接原语 (`sqlite-client.mjs`)。
|
||||
*
|
||||
* 核心能力:
|
||||
* 1. 惰性加载 Node 22.5+ 内置 `node:sqlite`,自动静默实验特性告警,避免污染 CLI / MCP `stdio`;
|
||||
* 2. 组合主库 `.db` 与 `.db-wal` 的 `mtime + size` 生成复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入;
|
||||
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
|
||||
*/
|
||||
|
||||
import { existsSync, statSync } from 'node:fs';
|
||||
|
||||
export const SQLITE_IN_CHUNK_SIZE = 400;
|
||||
|
||||
let sqliteResolved = false;
|
||||
let sqliteDatabaseSyncCtor = null;
|
||||
|
||||
/**
|
||||
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。
|
||||
* 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。
|
||||
*
|
||||
* @returns {Function | null}
|
||||
*/
|
||||
export function getNodeSqliteDatabaseSync() {
|
||||
if (typeof globalThis.DatabaseSync === 'function') {
|
||||
return globalThis.DatabaseSync;
|
||||
}
|
||||
if (sqliteResolved) return sqliteDatabaseSyncCtor;
|
||||
sqliteResolved = true;
|
||||
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const origEmitWarning = process.emitWarning;
|
||||
try {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
|
||||
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
|
||||
if (/SQLite is an experimental feature/i.test(msg)) return;
|
||||
return origEmitWarning.call(this, warning, ...rest);
|
||||
};
|
||||
}
|
||||
const mod = process.getBuiltinModule('node:sqlite');
|
||||
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
|
||||
} catch {
|
||||
sqliteDatabaseSyncCtor = null;
|
||||
} finally {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = origEmitWarning;
|
||||
}
|
||||
}
|
||||
return sqliteDatabaseSyncCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasBuiltinNodeSqlite() {
|
||||
return Boolean(getNodeSqliteDatabaseSync());
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
||||
*
|
||||
* @param {string} dbPath
|
||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||
*/
|
||||
export function computeSqliteWalSig(dbPath) {
|
||||
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
let dbStat = null;
|
||||
try {
|
||||
dbStat = statSync(dbPath);
|
||||
} catch {
|
||||
return { exists: false, mtimeMs: 0, sig: '' };
|
||||
}
|
||||
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
||||
|
||||
let walStat = null;
|
||||
const walPath = `${dbPath}-wal`;
|
||||
if (existsSync(walPath)) {
|
||||
try {
|
||||
walStat = statSync(walPath);
|
||||
} catch {
|
||||
walStat = null;
|
||||
}
|
||||
}
|
||||
const dbMtimeMs = Number(dbStat.mtimeMs || 0);
|
||||
const dbSize = Number(dbStat.size || 0);
|
||||
const walMtimeMs = Number(walStat?.mtimeMs || 0);
|
||||
const walSize = Number(walStat?.size || 0);
|
||||
return {
|
||||
exists: true,
|
||||
mtimeMs: Math.max(dbMtimeMs, walMtimeMs),
|
||||
sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function isSqliteBusyError(err) {
|
||||
const msg = String(err?.message || err?.code || '');
|
||||
return /SQLITE_BUSY|database is locked/i.test(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
*
|
||||
* @template T
|
||||
* @param {string} dbPath
|
||||
* @param {(db: any) => T} queryFn
|
||||
* @returns {T | null}
|
||||
*/
|
||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(dbPath, { readOnly: true });
|
||||
try {
|
||||
db.exec('PRAGMA busy_timeout = 1000;');
|
||||
} catch {
|
||||
// 兼容最小测试桩
|
||||
}
|
||||
return queryFn(db);
|
||||
} catch (err) {
|
||||
if (attempt === 0 && isSqliteBusyError(err)) {
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 SQLite `TEXT` 时间列(如 `'2026-11-18 08:12:00+00:00'` -> ISO-8601),剔除零值哨兵时间。
|
||||
*
|
||||
* @param {unknown} value
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeSqliteIsoTime(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return '';
|
||||
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z');
|
||||
}
|
||||
@@ -190,6 +190,10 @@ function enrichActiveConversationSteps(
|
||||
return {
|
||||
...serializedStep,
|
||||
responseModel: st.responseModel || '',
|
||||
hasKnownModel: Boolean(mInfo.modelId && mInfo.modelId !== 'unknown'),
|
||||
baseModelUpstream: annotatedUpstreamModel,
|
||||
baseModelLabel: mInfo.label,
|
||||
baseModelShort: mInfo.shortName,
|
||||
modelUpstream,
|
||||
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
||||
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
|
||||
@@ -210,6 +214,7 @@ function enrichActiveConversationSteps(
|
||||
// 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示
|
||||
let maxTurnIndex = 0;
|
||||
const promptByTurn = new Map();
|
||||
const mediaByTurn = new Map();
|
||||
for (const st of enrichedActiveSteps) {
|
||||
const tIdx = st.turnIndex;
|
||||
if (!Number.isInteger(tIdx) || tIdx <= 0) continue;
|
||||
@@ -217,6 +222,13 @@ function enrichActiveConversationSteps(
|
||||
if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) {
|
||||
promptByTurn.set(tIdx, st.turnPrompt);
|
||||
}
|
||||
if (st.isTurnStart || !mediaByTurn.has(tIdx)) {
|
||||
mediaByTurn.set(tIdx, {
|
||||
cleanPrompt: st.turnPromptClean ?? '',
|
||||
hasMedia: Boolean(st.turnHasMedia),
|
||||
mediaOnly: Boolean(st.turnMediaOnly),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const st of enrichedActiveSteps) {
|
||||
const tIdx = st.turnIndex;
|
||||
@@ -225,11 +237,18 @@ function enrichActiveConversationSteps(
|
||||
st.isTurnStart = false;
|
||||
st.isLatestTurn = false;
|
||||
st.turnPrompt = '';
|
||||
st.turnPromptClean = '';
|
||||
st.turnHasMedia = false;
|
||||
st.turnMediaOnly = false;
|
||||
continue;
|
||||
}
|
||||
const turnMedia = mediaByTurn.get(tIdx);
|
||||
st.isTurnStart = Boolean(st.isTurnStart);
|
||||
st.isLatestTurn = tIdx === maxTurnIndex;
|
||||
st.turnPrompt = promptByTurn.get(tIdx) || '';
|
||||
st.turnPromptClean = turnMedia?.cleanPrompt || '';
|
||||
st.turnHasMedia = Boolean(turnMedia?.hasMedia);
|
||||
st.turnMediaOnly = Boolean(turnMedia?.mediaOnly);
|
||||
}
|
||||
|
||||
const latestEnriched =
|
||||
@@ -544,12 +563,15 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
|
||||
/**
|
||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
||||
*/
|
||||
function buildAgentUnitTelemetry({
|
||||
export function buildAgentUnitTelemetry({
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
isSideQuestion = false,
|
||||
sideIndex = 0,
|
||||
agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent',
|
||||
agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0,
|
||||
customRole = '',
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
@@ -572,6 +594,9 @@ function buildAgentUnitTelemetry({
|
||||
{
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
agentCustomRole: customRole,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
@@ -599,6 +624,9 @@ function buildAgentUnitTelemetry({
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
||||
index,
|
||||
shortLabel,
|
||||
@@ -631,6 +659,9 @@ function buildAgentUnitTelemetry({
|
||||
: 0,
|
||||
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
||||
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
||||
hasKnownModel: Boolean(enrichedRes.latestEnriched?.hasKnownModel),
|
||||
activeBaseModelShort: enrichedRes.latestEnriched?.baseModelShort || '',
|
||||
activeBaseModelLabel: enrichedRes.latestEnriched?.baseModelLabel || '',
|
||||
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
||||
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
||||
activeModelUpstream:
|
||||
@@ -814,6 +845,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let shortLabel = '';
|
||||
let badgeText = '';
|
||||
let roleLabel = '';
|
||||
@@ -821,6 +855,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
let agentLabel = '';
|
||||
if (isSideQ) {
|
||||
sideIndex = ++sideQuestionCount;
|
||||
agentKind = 'side_question';
|
||||
agentOrdinal = sideIndex;
|
||||
shortLabel = `旁路提问 #${sideIndex}`;
|
||||
badgeText = `旁${sideIndex}`;
|
||||
const cleanSideRole =
|
||||
@@ -830,11 +866,15 @@ export async function buildTelemetryPayloadInternal(
|
||||
rawRole !== 'side_question'
|
||||
? rawRole
|
||||
: '';
|
||||
customRole = cleanSideRole;
|
||||
roleLabel = cleanSideRole || '旁路提问';
|
||||
typeName = 'side_question';
|
||||
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
|
||||
} else {
|
||||
const subOrd = ++normalSubCount;
|
||||
agentKind = 'subagent';
|
||||
agentOrdinal = subOrd;
|
||||
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||
shortLabel = `子代理 #${subOrd}`;
|
||||
badgeText = `子${subOrd}`;
|
||||
roleLabel = rawRole || '子代理';
|
||||
@@ -848,6 +888,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
isMain: false,
|
||||
isSideQuestion: isSideQ,
|
||||
sideIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
index: subIndex,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
@@ -897,6 +940,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
turnIndex: tIdx,
|
||||
startMs: mSt.createdAtMs || 0,
|
||||
prompt: mSt.turnPrompt || '',
|
||||
cleanPrompt: mSt.turnPromptClean ?? '',
|
||||
hasMedia: Boolean(mSt.turnHasMedia),
|
||||
mediaOnly: Boolean(mSt.turnMediaOnly),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -923,6 +969,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
st.rootTurnIndex = matched.turnIndex;
|
||||
st.isRootLatestTurn = matched.turnIndex === maxRootTurn;
|
||||
st.rootTurnPrompt = matched.prompt || '';
|
||||
st.rootTurnPromptClean = matched.cleanPrompt ?? '';
|
||||
st.rootTurnHasMedia = Boolean(matched.hasMedia);
|
||||
st.rootTurnMediaOnly = Boolean(matched.mediaOnly);
|
||||
if (!seenRootStarts.has(matched.turnIndex)) {
|
||||
seenRootStarts.add(matched.turnIndex);
|
||||
st.isRootTurnStart = true;
|
||||
@@ -1004,6 +1053,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
? {
|
||||
...activeActivityAgent.liveActivity,
|
||||
agentId: activeActivityAgent.agentId,
|
||||
agentKind: activeActivityAgent.agentKind || (activeActivityAgent.isMain ? 'main' : activeActivityAgent.isSideQuestion ? 'side_question' : 'subagent'),
|
||||
agentOrdinal: activeActivityAgent.agentOrdinal || 0,
|
||||
agentBadge: activeActivityAgent.badgeText,
|
||||
agentShortLabel: activeActivityAgent.shortLabel,
|
||||
agentRole: activeActivityAgent.role,
|
||||
@@ -1020,12 +1071,16 @@ export async function buildTelemetryPayloadInternal(
|
||||
agentId: 'all',
|
||||
cascadeId: activeCascadeId,
|
||||
isMain: false,
|
||||
agentKind: 'all',
|
||||
agentOrdinal: 0,
|
||||
index: -1,
|
||||
shortLabel: '全部汇总',
|
||||
badgeText: '全部',
|
||||
role: aggregatedRoleLabel,
|
||||
typeName: 'all',
|
||||
activeAgentId: activeMainlineAgent.agentId,
|
||||
activeAgentKind: activeMainlineAgent.agentKind || (activeMainlineAgent.isMain ? 'main' : activeMainlineAgent.isSideQuestion ? 'side_question' : 'subagent'),
|
||||
activeAgentOrdinal: activeMainlineAgent.agentOrdinal || 0,
|
||||
activeAgentShortLabel: activeMainlineAgent.shortLabel,
|
||||
activeAgentBadge: activeMainlineAgent.badgeText,
|
||||
activeAgentRole: activeMainlineAgent.role,
|
||||
@@ -1049,6 +1104,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0,
|
||||
latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
|
||||
sessionCacheHitPct: combinedSessionCacheHitPct,
|
||||
hasKnownModel: Boolean(latestMetricAgent.hasKnownModel),
|
||||
activeBaseModelShort: latestMetricAgent.activeBaseModelShort || '',
|
||||
activeBaseModelLabel: latestMetricAgent.activeBaseModelLabel || '',
|
||||
activeModelShort: latestMetricAgent.activeModelShort,
|
||||
activeModelLabel: latestMetricAgent.activeModelLabel,
|
||||
activeModelUpstream: latestMetricAgent.activeModelUpstream,
|
||||
@@ -1369,11 +1427,16 @@ export async function buildTelemetryPayloadInternal(
|
||||
'';
|
||||
const subIndex = idx + 1;
|
||||
let sideIndex = 0;
|
||||
let agentKind = 'subagent';
|
||||
let agentOrdinal = 0;
|
||||
let customRole = '';
|
||||
let badgeText = '';
|
||||
let shortLabel = '';
|
||||
let role = '';
|
||||
if (isSideQ) {
|
||||
sideIndex = ++runSideIdx;
|
||||
agentKind = 'side_question';
|
||||
agentOrdinal = sideIndex;
|
||||
badgeText = `旁${sideIndex}`;
|
||||
shortLabel = `旁路提问 #${sideIndex}`;
|
||||
const cleanSide =
|
||||
@@ -1383,9 +1446,13 @@ export async function buildTelemetryPayloadInternal(
|
||||
rawRole !== 'side_question'
|
||||
? rawRole
|
||||
: '';
|
||||
customRole = cleanSide;
|
||||
role = cleanSide || shortLabel;
|
||||
} else {
|
||||
const nOrd = ++runNormalSubIdx;
|
||||
agentKind = 'subagent';
|
||||
agentOrdinal = nOrd;
|
||||
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||
badgeText = `子${nOrd}`;
|
||||
shortLabel = `子代理 #${nOrd}`;
|
||||
role = rawRole || shortLabel;
|
||||
@@ -1397,6 +1464,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
? subSum.liveActivity || extractLiveActivity([], true, subModMs)
|
||||
: {
|
||||
phase: 'done',
|
||||
actionKey: 'done',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '已完成',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
@@ -1406,6 +1476,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
return {
|
||||
cascadeId: subCid,
|
||||
index: subIndex,
|
||||
agentKind,
|
||||
agentOrdinal,
|
||||
customRole,
|
||||
...(isSideQ ? { isSideQuestion: true, sideIndex } : {}),
|
||||
badgeText,
|
||||
shortLabel,
|
||||
@@ -1426,14 +1499,18 @@ export async function buildTelemetryPayloadInternal(
|
||||
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
||||
if (
|
||||
isMainRunning &&
|
||||
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') &&
|
||||
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') &&
|
||||
runningSubCount === 0
|
||||
) {
|
||||
const pendingIndex = subItems.length + 1;
|
||||
const pendingRole = mainLiveAct.detail || '子代理';
|
||||
const pendingCustomRole = mainLiveAct.detail || '';
|
||||
const pendingRole = pendingCustomRole || '子代理';
|
||||
subItems.push({
|
||||
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
||||
index: pendingIndex,
|
||||
agentKind: 'subagent',
|
||||
agentOrdinal: pendingIndex,
|
||||
customRole: pendingCustomRole,
|
||||
badgeText: `子${pendingIndex}`,
|
||||
shortLabel: `子代理 #${pendingIndex}`,
|
||||
role: pendingRole,
|
||||
@@ -1444,6 +1521,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
lastModifiedMs: rootFallbackMs,
|
||||
liveActivity: {
|
||||
phase: 'thinking',
|
||||
actionKey: 'starting',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '启动中',
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
@@ -1459,8 +1539,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
(runningSubList.length > 0
|
||||
? {
|
||||
phase: 'waiting',
|
||||
actionKey: 'waiting_subagent',
|
||||
waitingApproval: false,
|
||||
detailKey: '',
|
||||
label: '等待子代理',
|
||||
detail: runningSubList.map((s) => s.role).join(', '),
|
||||
detail: runningSubList.map((s) => s.customRole || s.role).join(', '),
|
||||
stepProgress: '',
|
||||
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
|
||||
signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`,
|
||||
@@ -1570,6 +1653,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
: 0,
|
||||
latestCacheHitPct,
|
||||
sessionCacheHitPct,
|
||||
hasKnownModel: Boolean(latestEnriched?.hasKnownModel),
|
||||
activeBaseModelShort: latestEnriched?.baseModelShort || '',
|
||||
activeBaseModelLabel: latestEnriched?.baseModelLabel || '',
|
||||
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||
activeModelUpstream:
|
||||
|
||||
Reference in New Issue
Block a user