mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(panel): guard SQLite schema init and recover .pb sessions (#41)
- Add lock-free 100-byte SQLite header readiness check before opening local DBs so high-frequency scans skip 0-byte, pre-DDL, 32-byte WAL-header-only, and active rollback-journal DBs without triggering schema-init lock races - Separate unready DB skips from confirmed empty-shell DBs and fall back to transcript.jsonl / size-capped transcript_full.jsonl with .pb + transcript signature tracking and subagent ref recovery - Extract shared transcript JSONL fallback parsing reused by local-scanner and cli-statusline, including .pb-aware candidate ranking and root redirect
This commit is contained in:
@@ -24,6 +24,7 @@ import {
|
||||
computeSqliteWalSig,
|
||||
getNodeSqliteDatabaseSync,
|
||||
hasBuiltinNodeSqlite,
|
||||
isSqliteDbReadyForRead,
|
||||
normalizeSqliteIsoTime,
|
||||
withReadOnlySqliteDb,
|
||||
} from './sqlite-client.mjs';
|
||||
@@ -43,6 +44,7 @@ export {
|
||||
computeSqliteWalSig,
|
||||
getNodeSqliteDatabaseSync,
|
||||
hasBuiltinNodeSqlite,
|
||||
isSqliteDbReadyForRead,
|
||||
withReadOnlySqliteDb,
|
||||
};
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-r
|
||||
import {
|
||||
computeSqliteWalSig,
|
||||
hasBuiltinNodeSqlite,
|
||||
isSqliteDbReadyForRead,
|
||||
readAnnotationTitleForCascade,
|
||||
readLocalImageDimensionsFromUri,
|
||||
readLocalSqliteTrajectory,
|
||||
@@ -46,6 +47,11 @@ import {
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||
import {
|
||||
readTranscriptJsonlLines,
|
||||
resolveTranscriptPathInLogsDir,
|
||||
synthesizeTranscriptModelStep,
|
||||
} from './transcript-fallback.mjs';
|
||||
|
||||
const CONV_FILE_RE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i;
|
||||
const TRANSCRIPT_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
@@ -532,7 +538,7 @@ function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountNa
|
||||
export function normalizeEmptyWalSqliteSig(sigStr) {
|
||||
const s = String(sigStr || '');
|
||||
if (!s.includes(':sqlite:')) return s;
|
||||
return s.replace(/\|\d+:0$/, '|0:0');
|
||||
return s.replace(/\|\d+:0(?=~fb:|$)/, '|0:0');
|
||||
}
|
||||
|
||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||
@@ -776,8 +782,10 @@ function findTranscriptPath(cascadeId) {
|
||||
let bestMtime = -1;
|
||||
for (const dir of dirs) {
|
||||
if (!dir) continue;
|
||||
const candidate = join(dir, normId, '.system_generated', 'logs', 'transcript.jsonl');
|
||||
if (!existsSync(candidate)) continue;
|
||||
const candidate = resolveTranscriptPathInLogsDir(
|
||||
join(dir, normId, '.system_generated', 'logs')
|
||||
);
|
||||
if (!candidate) continue;
|
||||
if (dirs.length === 1) return candidate;
|
||||
try {
|
||||
const mtime = Number(statSync(candidate)?.mtimeMs || 0);
|
||||
@@ -910,6 +918,45 @@ function hasLocalSqliteDb(diskFiles = []) {
|
||||
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || '')));
|
||||
}
|
||||
|
||||
function hasLocalPbFile(diskFiles = []) {
|
||||
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.pb$/i.test(String(f || '')));
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算本地 `.pb` 与 `transcript.jsonl` 辅助轨迹文件的复合签名(`mtimeMs + size`)。
|
||||
* 仅在会话不存在有效 SQLite 主库、或同时存在 `.pb` / 处于 `offlineTranscriptFallback` 模式时按需调用,
|
||||
* 确保主 `.db` 因 `database is locked` 沦为空壳而实际数据写入 `.pb` + `transcript.jsonl` 时仍能实时感知变更。
|
||||
*
|
||||
* @param {string[]} [diskFiles=[]]
|
||||
* @returns {{ mtimeMs: number, sig: string }}
|
||||
*/
|
||||
function computeFallbackDiskInfo(diskFiles = []) {
|
||||
if (!Array.isArray(diskFiles) || diskFiles.length === 0) {
|
||||
return { mtimeMs: 0, sig: '' };
|
||||
}
|
||||
let mtimeMs = 0;
|
||||
const parts = [];
|
||||
for (const rawPath of diskFiles) {
|
||||
const p = String(rawPath || '').trim();
|
||||
const isPb = /\.pb$/i.test(p);
|
||||
const isTranscript = /\.jsonl$/i.test(p);
|
||||
if (!isPb && !isTranscript) continue;
|
||||
try {
|
||||
const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p);
|
||||
const st = statSync(fullPath, { throwIfNoEntry: false });
|
||||
if (!st) continue;
|
||||
const m = Number(st.mtimeMs || 0);
|
||||
const sz = Number(st.size || 0);
|
||||
if (m > mtimeMs) mtimeMs = m;
|
||||
parts.push(`${isPb ? 'p' : 't'}:${Math.floor(m)}:${sz}`);
|
||||
} catch {
|
||||
// 忽略单文件瞬时 stat 异常
|
||||
}
|
||||
}
|
||||
if (parts.length > 1) parts.sort();
|
||||
return { mtimeMs, sig: parts.join(',') };
|
||||
}
|
||||
|
||||
function resolveBestSqliteDbInfo(diskFiles = [], { skipMissingWalFromListing = false } = {}) {
|
||||
if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null;
|
||||
let walPathsLower = null;
|
||||
@@ -1062,41 +1109,115 @@ function filterClonedTrajectorySteps(rawSteps, generatorMeta, targetCidLower) {
|
||||
return { steps: filteredSteps, generatorMeta: filteredGen };
|
||||
}
|
||||
|
||||
function unwrapOfflineToolArgString(val) {
|
||||
if (typeof val !== 'string') return '';
|
||||
const trimmed = val.trim();
|
||||
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (typeof parsed === 'string') return parsed.trim();
|
||||
} catch {
|
||||
// 忽略非标准二次转义
|
||||
}
|
||||
}
|
||||
return trimmed.replace(/^"+|"+$/g, '').trim();
|
||||
}
|
||||
|
||||
function extractSubagentRefsFromTranscriptLines(transcriptLines = [], baseSteps = [], cidLower = '') {
|
||||
const refs = extractSubagentRefsFromSteps(baseSteps);
|
||||
const byCid = new Map(refs.map((r) => [r.cascadeId, r]));
|
||||
let nextOrder = refs.length;
|
||||
const pendingSpecs = [];
|
||||
const pendingByCallId = new Map();
|
||||
|
||||
for (const line of transcriptLines || []) {
|
||||
if (!line || typeof line !== 'object') continue;
|
||||
const createdTimeMs = parseIsoMs(line.created_at || line.createdAt) || 0;
|
||||
const toolCalls = Array.isArray(line.tool_calls) ? line.tool_calls : [];
|
||||
for (const tc of toolCalls) {
|
||||
const name = String(tc?.name || tc?.tool_name || '').trim().toLowerCase();
|
||||
if (name === 'invoke_subagent' || name === 'default_api:invoke_subagent') {
|
||||
const args = tc?.args || tc?.arguments || {};
|
||||
const callId = String(tc?.id || tc?.call_id || tc?.tool_call_id || '').trim();
|
||||
const spec = {
|
||||
callId,
|
||||
role: unwrapOfflineToolArgString(args.Role ?? args.role ?? ''),
|
||||
typeName: unwrapOfflineToolArgString(args.TypeName ?? args.typeName ?? ''),
|
||||
createdTimeMs,
|
||||
consumed: false,
|
||||
};
|
||||
pendingSpecs.push(spec);
|
||||
if (callId) pendingByCallId.set(callId, spec);
|
||||
}
|
||||
}
|
||||
const content = typeof line.content === 'string' ? line.content : '';
|
||||
if (content && content.includes('Created the following subagent')) {
|
||||
const resultCallId = String(line.tool_call_id || line.call_id || '').trim();
|
||||
const matches = content.matchAll(
|
||||
/"conversationId"\s*:\s*"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"/gi
|
||||
);
|
||||
for (const m of matches) {
|
||||
const subCid = String(m[1] || '').trim().toLowerCase();
|
||||
if (!subCid || subCid === cidLower) continue;
|
||||
let spec = null;
|
||||
if (resultCallId && pendingByCallId.has(resultCallId)) {
|
||||
const direct = pendingByCallId.get(resultCallId);
|
||||
if (direct && !direct.consumed) {
|
||||
direct.consumed = true;
|
||||
spec = direct;
|
||||
}
|
||||
}
|
||||
if (!spec) {
|
||||
while (pendingSpecs.length > 0 && pendingSpecs[0].consumed) {
|
||||
pendingSpecs.shift();
|
||||
}
|
||||
spec = pendingSpecs.shift() || null;
|
||||
if (spec) spec.consumed = true;
|
||||
}
|
||||
const prev = byCid.get(subCid);
|
||||
const merged = {
|
||||
cascadeId: subCid,
|
||||
role: spec?.role || prev?.role || '',
|
||||
typeName: spec?.typeName || prev?.typeName || '',
|
||||
createdTimeMs: createdTimeMs || spec?.createdTimeMs || prev?.createdTimeMs || 0,
|
||||
spawnOrder: prev ? prev.spawnOrder : nextOrder++,
|
||||
};
|
||||
byCid.set(subCid, merged);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const swarmManifest = cidLower ? readSwarmManifestForCascade(cidLower) : null;
|
||||
if (swarmManifest?.workerRefs?.length) {
|
||||
for (const wRef of swarmManifest.workerRefs) {
|
||||
if (wRef?.cascadeId && !byCid.has(wRef.cascadeId)) {
|
||||
byCid.set(wRef.cascadeId, wRef);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(byCid.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 当 Language Server RPC 离线或跨端不可达(如 `agy` CLI 独立会话目录)时,优先融合本地 SQLite
|
||||
* (`conversations/<id>.db` + `conversation_summaries.db` + `annotations/<id>.pbtxt`) 与 `transcript.jsonl`
|
||||
* (及可选 `.deep_stats_cache.json`)恢复完整步骤耗时、TTFT、思考/正文拆分、10 通道上下文构成与真实标题。
|
||||
* 当 Language Server RPC 离线、跨端不可达(如 `agy` CLI 独立会话目录)或本地 `.db` 因初始化锁冲突降级为 `.pb` 空壳时,
|
||||
* 优先融合本地可用 SQLite、`conversation_summaries.db`、`annotations/<id>.pbtxt` 与 `transcript.jsonl`
|
||||
* (及可选 `.deep_stats_cache.json`)恢复模型步骤、Token 消耗、轮次提问、派生子代理与真实标题。
|
||||
*/
|
||||
function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, localSummary = null) {
|
||||
function loadOfflineTranscriptConversation(
|
||||
conv,
|
||||
diskFiles,
|
||||
externalByLower,
|
||||
localSummary = null,
|
||||
{ skipSqlite = false } = {}
|
||||
) {
|
||||
const cidLower = String(conv?.cascadeId || '').trim().toLowerCase();
|
||||
if (!cidLower) return null;
|
||||
const extMatch = externalByLower?.get(cidLower) || null;
|
||||
const sqliteDbPath = findBestSqliteDbPath(diskFiles);
|
||||
const sqliteDbPath = skipSqlite ? '' : findBestSqliteDbPath(diskFiles);
|
||||
const sqliteTraj = sqliteDbPath ? readLocalSqliteTrajectory(sqliteDbPath) : null;
|
||||
const transcriptPath = findTranscriptPath(cidLower);
|
||||
|
||||
const transcriptLines = [];
|
||||
if (transcriptPath && existsSync(transcriptPath)) {
|
||||
try {
|
||||
const raw = readFileSync(transcriptPath, 'utf8');
|
||||
if (typeof raw === 'string' && raw.trim()) {
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
transcriptLines.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// 忽略尾部半行或损坏 JSON 行
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略文件读取失败
|
||||
}
|
||||
}
|
||||
const transcriptLines = transcriptPath ? readTranscriptJsonlLines(transcriptPath) : [];
|
||||
|
||||
if (!sqliteTraj && transcriptLines.length === 0 && !extMatch) {
|
||||
return null;
|
||||
@@ -1295,65 +1416,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
|
||||
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
||||
modelOrdinal += 1;
|
||||
const isCheckpoint =
|
||||
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const rawStatus = String(line.status || '').trim().toUpperCase();
|
||||
const mappedStatus = /CANCEL/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: /ERROR/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
const finishedAt = String(
|
||||
line.finished_generating_at ||
|
||||
line.finishedGeneratingAt ||
|
||||
line.completed_at ||
|
||||
line.completedAt ||
|
||||
''
|
||||
).trim();
|
||||
const modelKey =
|
||||
String(line.model || line.generator_model || deepStep?.modelKey || 'unknown').trim() ||
|
||||
'unknown';
|
||||
const responseModel = String(line.response_model || deepStep?.responseModel || '').trim();
|
||||
const apiProvider = String(line.api_provider || deepStep?.apiProvider || '').trim();
|
||||
const modelDisplayName = String(
|
||||
line.model_display_name || deepStep?.modelDisplayName || ''
|
||||
).trim();
|
||||
const thinkingTokens = Number(line.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0;
|
||||
const responseTokens = line.response_tokens ?? deepStep?.responseTokens;
|
||||
|
||||
syntheticSteps.push({
|
||||
type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE',
|
||||
status: mappedStatus,
|
||||
plannerResponse: {
|
||||
response: typeof line.content === 'string' ? line.content : '',
|
||||
thinking: typeof line.thinking === 'string' ? line.thinking : '',
|
||||
toolCalls: Array.isArray(line.tool_calls) ? line.tool_calls : [],
|
||||
...(thinkingTokens > 0 ? { thinkingTokens } : {}),
|
||||
...(responseTokens !== undefined ? { responseTokens } : {}),
|
||||
},
|
||||
metadata: {
|
||||
createdAt: String(line.created_at || line.createdAt || deepStep?.createdAt || ''),
|
||||
...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}),
|
||||
sourceTrajectoryStepInfo: {
|
||||
stepIndex: Number.isFinite(Number(line.step_index)) ? Number(line.step_index) : rawIdx,
|
||||
},
|
||||
modelUsage: {
|
||||
model: modelKey,
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
...(apiProvider ? { apiProvider } : {}),
|
||||
inputTokens: line.input_tokens ?? deepStep?.inputTokens ?? 0,
|
||||
cacheReadTokens: line.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0,
|
||||
outputTokens: line.output_tokens ?? deepStep?.outputTokens ?? 0,
|
||||
...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}),
|
||||
...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}),
|
||||
},
|
||||
...(modelDisplayName
|
||||
? { generatorMetadata: [{ chatModel: { modelDisplayName } }] }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
syntheticSteps.push(
|
||||
synthesizeTranscriptModelStep(line, { stepIndex: rawIdx, deepStep })
|
||||
);
|
||||
}
|
||||
|
||||
steps = syntheticSteps.length > 0 ? extractModelSteps(syntheticSteps, []) : [];
|
||||
@@ -1423,6 +1488,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
rawRootCid && rawRootCid !== cidLower ? rawRootCid : parentConversationId;
|
||||
|
||||
const lastStepMs = steps[steps.length - 1]?.createdAtMs || 0;
|
||||
const offlineSubagentRefs = extractSubagentRefsFromTranscriptLines(
|
||||
transcriptLines,
|
||||
sqliteTraj?.steps || [],
|
||||
cidLower
|
||||
);
|
||||
return {
|
||||
steps,
|
||||
fromSqlite,
|
||||
@@ -1437,7 +1507,7 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
extMatch?.lastModifiedMs || 0,
|
||||
lastStepMs
|
||||
),
|
||||
subagentRefs: [],
|
||||
subagentRefs: offlineSubagentRefs,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1761,6 +1831,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
||||
*/
|
||||
export async function enumerateAndSyncConversations({
|
||||
summariesObj = {},
|
||||
summariesFromLocalDb = false,
|
||||
sideQuestionParents = {},
|
||||
currentAccountName = '',
|
||||
requestedConvId = '',
|
||||
@@ -1943,12 +2014,22 @@ export async function enumerateAndSyncConversations({
|
||||
: null;
|
||||
const dbPath = sqliteDbInfo?.dbPath || '';
|
||||
const diskFileSig = sqliteDbInfo?.sig || '';
|
||||
const hasPbFile = !isRemote && hasLocalPbFile(diskFiles);
|
||||
const needFallbackDiskInfo =
|
||||
!isRemote &&
|
||||
diskFiles.length > 0 &&
|
||||
(!sqliteDbInfo || hasPbFile || Boolean(cached?.offlineTranscriptFallback));
|
||||
const fallbackDiskInfo = needFallbackDiskInfo ? computeFallbackDiskInfo(diskFiles) : null;
|
||||
const fallbackDiskSig = fallbackDiskInfo?.sig || '';
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const summaryMtimeMs = parseIsoMs(lastModifiedTime);
|
||||
const rawDiskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskFiles);
|
||||
const diskMtimeMs = sqliteDbInfo
|
||||
const baseDiskMtimeMs = sqliteDbInfo
|
||||
? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0)
|
||||
: rawDiskMtimeMs;
|
||||
const diskMtimeMs = fallbackDiskInfo
|
||||
? Math.max(baseDiskMtimeMs || 0, fallbackDiskInfo.mtimeMs || 0)
|
||||
: baseDiskMtimeMs;
|
||||
const appSource = isRemote
|
||||
? 'ssh'
|
||||
: inferAppSourceFromSummary(
|
||||
@@ -2067,6 +2148,7 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs,
|
||||
dbPath,
|
||||
diskFileSig,
|
||||
fallbackDiskSig,
|
||||
appSource,
|
||||
...(workspaceUri ? { workspaceUri } : {}),
|
||||
inSummaries: true,
|
||||
@@ -2105,6 +2187,7 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs,
|
||||
dbPath,
|
||||
diskFileSig,
|
||||
fallbackDiskSig,
|
||||
appSource,
|
||||
...(workspaceUri ? { workspaceUri } : {}),
|
||||
inSummaries: false,
|
||||
@@ -2135,6 +2218,7 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs,
|
||||
dbPath,
|
||||
diskFileSig,
|
||||
fallbackDiskSig,
|
||||
appSource,
|
||||
...(workspaceUri ? { workspaceUri } : {}),
|
||||
inSummaries: false,
|
||||
@@ -2158,12 +2242,14 @@ export async function enumerateAndSyncConversations({
|
||||
const nowPollMs = Date.now();
|
||||
|
||||
function buildConvSig(conv) {
|
||||
const fbSuffix = conv.fallbackDiskSig ? `~fb:${conv.fallbackDiskSig}` : '';
|
||||
if (conv.dbPath && conv.diskFileSig && sqliteAvailable) {
|
||||
return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}`;
|
||||
return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}${fbSuffix}`;
|
||||
}
|
||||
return conv.inSummaries
|
||||
const base = conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
return `${base}${fbSuffix}`;
|
||||
}
|
||||
|
||||
function isFetchInCooldown(conv, sig) {
|
||||
@@ -2257,24 +2343,50 @@ export async function enumerateAndSyncConversations({
|
||||
const prev = getHydratedEntry(conv.cascadeId);
|
||||
let partialTailSteps = [];
|
||||
let hasTailStepInfo = false;
|
||||
let sqliteNotReady = false;
|
||||
let sqliteProbedEmpty = false;
|
||||
try {
|
||||
const cidLower = conv.cascadeId.toLowerCase();
|
||||
let trajRes = null;
|
||||
let loadedViaSqlite = false;
|
||||
let transcriptFirstTitle = '';
|
||||
if (!isRemote && conv.dbPath && sqliteAvailable) {
|
||||
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
||||
cascadeId: conv.cascadeId,
|
||||
isRunning,
|
||||
});
|
||||
if (sqlRes && Array.isArray(sqlRes.trajectory?.steps)) {
|
||||
trajRes = sqlRes;
|
||||
loadedViaSqlite = true;
|
||||
const enriched = enrichSqliteStepsFromTranscriptIfNeeded(
|
||||
cidLower,
|
||||
trajRes.trajectory.steps
|
||||
);
|
||||
transcriptFirstTitle = enriched.firstUserTitle || '';
|
||||
if (!isSqliteDbReadyForRead(conv.dbPath)) {
|
||||
sqliteNotReady = true;
|
||||
} else {
|
||||
const sqlRes = readLocalSqliteTrajectory(conv.dbPath, {
|
||||
cascadeId: conv.cascadeId,
|
||||
isRunning,
|
||||
});
|
||||
if (sqlRes && Array.isArray(sqlRes.trajectory?.steps)) {
|
||||
trajRes = sqlRes;
|
||||
loadedViaSqlite = true;
|
||||
const enriched = enrichSqliteStepsFromTranscriptIfNeeded(
|
||||
cidLower,
|
||||
trajRes.trajectory.steps
|
||||
);
|
||||
transcriptFirstTitle = enriched.firstUserTitle || '';
|
||||
} else {
|
||||
sqliteProbedEmpty = true;
|
||||
const diskFilesForEmptyCheck = diskConvMap.get(cidLower) || [];
|
||||
if (
|
||||
!isRunning &&
|
||||
Number(conv.rawStepCount || 0) === 0 &&
|
||||
!hasLocalPbFile(diskFilesForEmptyCheck) &&
|
||||
!findTranscriptPath(cidLower)
|
||||
) {
|
||||
// 已初始化但确实为 0 步(无 .pb 降级文件、摘要 0 步且无 transcript)的空本地会话,直接归档空缓存避免无意义 RPC 超时
|
||||
trajRes = {
|
||||
cascadeId: cidLower,
|
||||
numTotalSteps: 0,
|
||||
rawTableStepCount: 0,
|
||||
steps: [],
|
||||
generatorMetadata: [],
|
||||
trajectory: { metadata: {}, steps: [], generatorMetadata: [] },
|
||||
};
|
||||
loadedViaSqlite = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!trajRes) {
|
||||
@@ -2547,7 +2659,9 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
} catch (err) {
|
||||
let offlineRecovered = false;
|
||||
if (!isRemote && !conv.inSummaries && (!prev || prev.offlineTranscriptFallback)) {
|
||||
const cidLower = conv.cascadeId.toLowerCase();
|
||||
const diskFiles = isRemote ? [] : diskConvMap.get(cidLower) || [];
|
||||
if (!isRemote && (!prev || prev.offlineTranscriptFallback)) {
|
||||
if (!lazyExternalByLower) {
|
||||
lazyExternalByLower = new Map();
|
||||
for (const ext of loadExternalDeepStatsCache().values()) {
|
||||
@@ -2559,13 +2673,12 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
}
|
||||
}
|
||||
const cidLower = conv.cascadeId.toLowerCase();
|
||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
||||
const offlineFallback = loadOfflineTranscriptConversation(
|
||||
conv,
|
||||
diskFiles,
|
||||
lazyExternalByLower,
|
||||
localSummaryByLower.get(cidLower) || null
|
||||
localSummaryByLower.get(cidLower) || null,
|
||||
{ skipSqlite: sqliteProbedEmpty || sqliteNotReady }
|
||||
);
|
||||
if (offlineFallback) {
|
||||
offlineRecovered = true;
|
||||
@@ -2598,14 +2711,17 @@ export async function enumerateAndSyncConversations({
|
||||
title: offlineFallback.title,
|
||||
...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}),
|
||||
...(conv.workspaceUri ? { workspaceUri: conv.workspaceUri } : {}),
|
||||
...(conv.diskFileSig ? { diskFileSig: conv.diskFileSig } : {}),
|
||||
lastModifiedMs: offlineFallback.lastModifiedMs,
|
||||
diskMtimeMs: resolvedDiskMtime,
|
||||
rawStepCount: conv.rawStepCount ?? offlineStepsWithOwners.length,
|
||||
wasRunning: isRunning,
|
||||
offlineTranscriptFallback: true,
|
||||
...(offlineFallback.fromSqlite ? { offlineSqliteTelemetry: true } : {}),
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
wakeupTurnTelemetry: true,
|
||||
contextGroupsTelemetry: 3,
|
||||
anomalyTelemetry: 1,
|
||||
steps: offlineStepsWithOwners,
|
||||
@@ -2628,6 +2744,7 @@ export async function enumerateAndSyncConversations({
|
||||
prev.title !== offlineEntry.title ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
|
||||
JSON.stringify(prev.subagentRefs || []) !== JSON.stringify(offlineEntry.subagentRefs || []) ||
|
||||
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
|
||||
if (!changed) offlineEntry.steps = prev.steps;
|
||||
setEntry(conv.cascadeId, offlineEntry);
|
||||
@@ -2636,10 +2753,19 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
!offlineRecovered &&
|
||||
!prev &&
|
||||
!isRemote &&
|
||||
(sqliteProbedEmpty || (!sqliteNotReady && hasLocalPbFile(diskFiles)))
|
||||
) {
|
||||
// 本地 .db 为空壳或会话仅落盘加密 .pb、且连 transcript.jsonl 与 RPC 均无法恢复步骤时,避免顶栏继续虚标原始 step_count
|
||||
conv.stepCount = 0;
|
||||
}
|
||||
if (
|
||||
!offlineRecovered &&
|
||||
!(
|
||||
!conv.inSummaries &&
|
||||
(!conv.inSummaries || summariesFromLocalDb || conv.appSource === 'cli') &&
|
||||
/(?:\(404\)|\bnot_found\b|Language Server address unavailable)/i.test(
|
||||
String(err?.message || '')
|
||||
)
|
||||
@@ -2879,7 +3005,8 @@ export async function enumerateAndSyncConversations({
|
||||
cached.offlineTranscriptFallback &&
|
||||
!cached.offlineSqliteTelemetry &&
|
||||
hasBuiltinNodeSqlite() &&
|
||||
hasLocalSqliteDb(diskConvMap.get(lowerCid))
|
||||
hasLocalSqliteDb(diskConvMap.get(lowerCid)) &&
|
||||
!String(cached.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:sqlite:`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
@@ -2895,8 +3022,13 @@ export async function enumerateAndSyncConversations({
|
||||
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
||||
) return true;
|
||||
} else {
|
||||
const shouldRetryOfflineUpgrade =
|
||||
Boolean(cached.offlineTranscriptFallback) &&
|
||||
(!summariesFromLocalDb ||
|
||||
conv.appSource !== 'cli' ||
|
||||
(forceRefresh && lowerCid === reqLower));
|
||||
if (
|
||||
cached.offlineTranscriptFallback ||
|
||||
shouldRetryOfflineUpgrade ||
|
||||
missingSubagentRefs ||
|
||||
!sigMatches ||
|
||||
isRunning ||
|
||||
@@ -2991,9 +3123,17 @@ export async function enumerateAndSyncConversations({
|
||||
if (!subConv) {
|
||||
const subDiskFiles = diskConvMap.get(subCid) || [];
|
||||
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
|
||||
const subNeedFb =
|
||||
!isRemote &&
|
||||
subDiskFiles.length > 0 &&
|
||||
(!subDbInfo ||
|
||||
hasLocalPbFile(subDiskFiles) ||
|
||||
Boolean(subCached?.offlineTranscriptFallback));
|
||||
const subFallbackInfo = subNeedFb ? computeFallbackDiskInfo(subDiskFiles) : null;
|
||||
const diskMtimeMs = Math.max(
|
||||
readConversationMtime(subDiskFiles),
|
||||
subDbInfo?.mtimeMs || 0
|
||||
subDbInfo?.mtimeMs || 0,
|
||||
subFallbackInfo?.mtimeMs || 0
|
||||
);
|
||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||
const stepCount = Number(subCached?.steps?.length || 0);
|
||||
@@ -3013,6 +3153,7 @@ export async function enumerateAndSyncConversations({
|
||||
diskMtimeMs,
|
||||
dbPath: subDbInfo?.dbPath || '',
|
||||
diskFileSig: subDbInfo?.sig || '',
|
||||
fallbackDiskSig: subFallbackInfo?.sig || '',
|
||||
appSource: isRemote
|
||||
? 'ssh'
|
||||
: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'),
|
||||
@@ -3049,6 +3190,12 @@ export async function enumerateAndSyncConversations({
|
||||
const targetCacheKey = subConv.cascadeId;
|
||||
const existingSubCache = getEntry(targetCacheKey);
|
||||
const isSelectedSubFamily = rootId === selectedRootId;
|
||||
const subSig = buildConvSig(subConv);
|
||||
const canUpgradeOfflineSub =
|
||||
Boolean(existingSubCache?.offlineTranscriptFallback && subConv.inSummaries) &&
|
||||
(!summariesFromLocalDb || subConv.appSource !== 'cli') &&
|
||||
!attemptedFetchIds.has(subCid) &&
|
||||
!isFetchInCooldown(subConv, subSig);
|
||||
const isImgGenSub =
|
||||
String(
|
||||
subConv.subagentSpec?.typeName ||
|
||||
@@ -3060,7 +3207,7 @@ export async function enumerateAndSyncConversations({
|
||||
.toLowerCase() === 'image-generator';
|
||||
const hasValidSubCache =
|
||||
existingSubCache &&
|
||||
!(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) &&
|
||||
!canUpgradeOfflineSub &&
|
||||
String(existingSubCache.signature || '').startsWith(
|
||||
subConv.dbPath && sqliteAvailable
|
||||
? `${CACHE_SCHEMA_VERSION}:sqlite:`
|
||||
@@ -3110,7 +3257,6 @@ export async function enumerateAndSyncConversations({
|
||||
cacheDirty = true;
|
||||
}
|
||||
} else {
|
||||
const subSig = buildConvSig(subConv);
|
||||
if (!attemptedFetchIds.has(subCid) && !isFetchInCooldown(subConv, subSig)) {
|
||||
missingSubagentsToFetch.push(subConv);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,15 @@
|
||||
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
|
||||
*/
|
||||
|
||||
import { existsSync, statSync } from 'node:fs';
|
||||
import { closeSync, existsSync, openSync, readSync, statSync } from 'node:fs';
|
||||
|
||||
export const SQLITE_IN_CHUNK_SIZE = 400;
|
||||
const SQLITE_MIN_READY_BYTES = 4096;
|
||||
const SQLITE_HEADER_BYTES = 100;
|
||||
const SQLITE_WAL_HEADER_BYTES = 32;
|
||||
const SQLITE_MAGIC_PREFIX = 'SQLite format 3\0';
|
||||
const MAX_SQLITE_READY_MEMO = 512;
|
||||
const sqliteWalReadyMemo = new Map();
|
||||
|
||||
let sqliteResolved = false;
|
||||
let sqliteDatabaseSyncCtor = null;
|
||||
@@ -59,8 +65,117 @@ export function hasBuiltinNodeSqlite() {
|
||||
return Boolean(getNodeSqliteDatabaseSync());
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过零 SQLite 锁的 100 字节文件头探测判断本地 `.db` 是否已完成表结构初始化(或已切入 WAL 且含有效提交帧)。
|
||||
*
|
||||
* Windows 下宿主(如 `agy` CLI)新建 `<cid>.db` 执行 `schema init` / `PRAGMA journal_mode = WAL` 的数毫秒内,
|
||||
* 若外部进程对 0 字节或仍处于回滚日志模式(`writeVersion !== 2`)的库发起 `sqlite3_open_v2` 查询并持有 `SHARED` 锁,
|
||||
* 会直接触发宿主 `trajectory db schema init: database is locked` 并迫使整场会话永久降级至加密 `.pb`。
|
||||
* 纯 `fs.openSync` / `fs.readSync` 不申请任何 SQLite 字节区间锁(`LockFileEx`),可安全跳过初始化途中的半成品库。
|
||||
*
|
||||
* @param {string} dbPath
|
||||
* @param {{ dbStat?: import('node:fs').Stats | null, walStat?: import('node:fs').Stats | null, skipWalStat?: boolean }} [opts={}]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isSqliteDbReadyForRead(
|
||||
dbPath,
|
||||
{ dbStat: preDbStat = null, walStat: preWalStat = null, skipWalStat = false } = {}
|
||||
) {
|
||||
if (!dbPath || typeof dbPath !== 'string') return false;
|
||||
if (
|
||||
typeof openSync !== 'function' ||
|
||||
typeof readSync !== 'function' ||
|
||||
typeof closeSync !== 'function'
|
||||
) {
|
||||
return typeof globalThis.DatabaseSync === 'function';
|
||||
}
|
||||
|
||||
let dbStat = preDbStat;
|
||||
if (!dbStat) {
|
||||
try {
|
||||
dbStat = statSync(dbPath, { throwIfNoEntry: false });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const dbSize = Number(dbStat?.size || 0);
|
||||
if (!dbStat || dbSize < SQLITE_MIN_READY_BYTES) {
|
||||
sqliteWalReadyMemo.delete(dbPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
const birthKey = `${Number(dbStat.birthtimeMs || 0)}:${Number(dbStat.ino || 0)}`;
|
||||
const cachedReady = sqliteWalReadyMemo.get(dbPath);
|
||||
if (cachedReady && cachedReady.birthKey === birthKey && dbSize >= cachedReady.minVerifiedSize) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const journalStat = statSync(`${dbPath}-journal`, { throwIfNoEntry: false });
|
||||
if (journalStat && Number(journalStat.size || 0) > 0) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
// 忽略瞬时回滚日志探测异常
|
||||
}
|
||||
|
||||
let fd = -1;
|
||||
try {
|
||||
fd = openSync(dbPath, 'r');
|
||||
const header = Buffer.allocUnsafe(SQLITE_HEADER_BYTES);
|
||||
const bytesRead = readSync(fd, header, 0, SQLITE_HEADER_BYTES, 0);
|
||||
if (bytesRead < SQLITE_HEADER_BYTES) return false;
|
||||
if (header.toString('latin1', 0, 16) !== SQLITE_MAGIC_PREFIX) return false;
|
||||
|
||||
const writeVersion = header[18];
|
||||
const readVersion = header[19];
|
||||
const pageCount = header.readUInt32BE(28);
|
||||
const schemaCookie = header.readUInt32BE(40);
|
||||
const isWalMode = writeVersion === 2 && readVersion === 2;
|
||||
|
||||
if (isWalMode) {
|
||||
let hasCommittedSchema = pageCount >= 2 && schemaCookie > 0;
|
||||
if (!hasCommittedSchema) {
|
||||
let walStat = preWalStat;
|
||||
if (!walStat && !skipWalStat) {
|
||||
try {
|
||||
walStat = statSync(`${dbPath}-wal`, { throwIfNoEntry: false });
|
||||
} catch {
|
||||
walStat = null;
|
||||
}
|
||||
}
|
||||
hasCommittedSchema = Number(walStat?.size || 0) > SQLITE_WAL_HEADER_BYTES;
|
||||
}
|
||||
if (!hasCommittedSchema) return false;
|
||||
|
||||
if (sqliteWalReadyMemo.size >= MAX_SQLITE_READY_MEMO && !sqliteWalReadyMemo.has(dbPath)) {
|
||||
const oldestKey = sqliteWalReadyMemo.keys().next().value;
|
||||
if (oldestKey !== undefined) sqliteWalReadyMemo.delete(oldestKey);
|
||||
}
|
||||
sqliteWalReadyMemo.set(dbPath, {
|
||||
birthKey,
|
||||
minVerifiedSize: SQLITE_MIN_READY_BYTES,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return pageCount >= 2 && schemaCookie > 0;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (fd >= 0) {
|
||||
try {
|
||||
closeSync(fd);
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
||||
* 实际打开前由 `withReadOnlySqliteDb` 经 `isSqliteDbReadyForRead` 拦截未完成 `schema init` 的空文件。
|
||||
*
|
||||
* @param {string} dbPath
|
||||
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||
@@ -104,7 +219,7 @@ export function isSqliteBusyError(err) {
|
||||
|
||||
/**
|
||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
* 打开前先执行无锁头部就绪校验;遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
*
|
||||
* @template T
|
||||
* @param {string} dbPath
|
||||
@@ -114,6 +229,7 @@ export function isSqliteBusyError(err) {
|
||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
if (!isSqliteDbReadyForRead(dbPath)) return null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
let db = null;
|
||||
try {
|
||||
|
||||
@@ -942,6 +942,7 @@ async function readTelemetrySources(
|
||||
summariesObj: localSummaries.available
|
||||
? localSummaries.summariesObj
|
||||
: allTrajRes?.trajectorySummaries || {},
|
||||
summariesFromLocalDb: localSummaries.available,
|
||||
sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {},
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* @fileoverview 共享的 `transcript.jsonl` / `transcript_full.jsonl` 安全解析与离线模型步骤合成辅助模块。
|
||||
*
|
||||
* 供 `local-scanner.mjs` 与 `cli-statusline.mjs` 共用,避免重复维护状态归一化、Token 字段映射
|
||||
* 以及超大 `transcript_full.jsonl` 的体积保护逻辑。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export const TRANSCRIPT_COMPACT_MAX_BYTES = 24 * 1024 * 1024;
|
||||
export const TRANSCRIPT_FULL_MAX_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 在单个日志目录内优先解析 `transcript.jsonl`,不存在时按体积上限安全回退至 `transcript_full.jsonl`。
|
||||
*
|
||||
* @param {string} logsDir
|
||||
* @param {{ maxFullBytes?: number }} [opts={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function resolveTranscriptPathInLogsDir(
|
||||
logsDir,
|
||||
{ maxFullBytes = TRANSCRIPT_FULL_MAX_BYTES } = {}
|
||||
) {
|
||||
if (!logsDir || typeof logsDir !== 'string') return '';
|
||||
const primary = join(logsDir, 'transcript.jsonl');
|
||||
if (existsSync(primary)) return primary;
|
||||
const full = join(logsDir, 'transcript_full.jsonl');
|
||||
if (!existsSync(full)) return '';
|
||||
if (Number.isFinite(maxFullBytes) && maxFullBytes > 0) {
|
||||
try {
|
||||
const st = statSync(full, { throwIfNoEntry: false });
|
||||
if (st && Number(st.size || 0) > maxFullBytes) return '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
return full;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全读取并解析 JSONL 格式的 transcript 文件,按文件类型施加体积保护并跳过损坏行。
|
||||
*
|
||||
* @param {string} transcriptPath
|
||||
* @param {{ maxBytes?: number }} [opts={}]
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function readTranscriptJsonlLines(transcriptPath, { maxBytes } = {}) {
|
||||
if (!transcriptPath || !existsSync(transcriptPath)) return [];
|
||||
const isFullFile = /transcript_full\.jsonl$/i.test(transcriptPath);
|
||||
const limitBytes =
|
||||
Number.isFinite(maxBytes) && maxBytes > 0
|
||||
? maxBytes
|
||||
: isFullFile
|
||||
? TRANSCRIPT_FULL_MAX_BYTES
|
||||
: TRANSCRIPT_COMPACT_MAX_BYTES;
|
||||
try {
|
||||
const st = statSync(transcriptPath, { throwIfNoEntry: false });
|
||||
if (st && Number(st.size || 0) > limitBytes) {
|
||||
return [];
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
let raw = '';
|
||||
try {
|
||||
raw = readFileSync(transcriptPath, 'utf8');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (typeof raw !== 'string' || !raw.trim()) return [];
|
||||
|
||||
const lines = [];
|
||||
for (const rawLine of raw.split(/\r?\n/)) {
|
||||
const trimmed = rawLine.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
lines.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// 忽略尾部半行或损坏 JSON 行
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单条含 Token 统计的 transcript JSONL 记录合成为标准轨迹模型步骤对象。
|
||||
*
|
||||
* @param {object} line
|
||||
* @param {{ stepIndex?: number, deepStep?: object | null }} [opts={}]
|
||||
* @returns {object}
|
||||
*/
|
||||
export function synthesizeTranscriptModelStep(line, { stepIndex = 0, deepStep = null } = {}) {
|
||||
const rawType = String(line?.type || '').trim();
|
||||
const upperType = rawType.toUpperCase();
|
||||
const isCheckpoint =
|
||||
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const rawStatus = String(line?.status || '').trim().toUpperCase();
|
||||
const mappedStatus = /CANCEL/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: /ERROR/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
const finishedAt = String(
|
||||
line?.finished_generating_at ||
|
||||
line?.finishedGeneratingAt ||
|
||||
line?.completed_at ||
|
||||
line?.completedAt ||
|
||||
''
|
||||
).trim();
|
||||
const modelKey =
|
||||
String(line?.model || line?.generator_model || deepStep?.modelKey || 'unknown').trim() ||
|
||||
'unknown';
|
||||
const responseModel = String(line?.response_model || deepStep?.responseModel || '').trim();
|
||||
const apiProvider = String(line?.api_provider || deepStep?.apiProvider || '').trim();
|
||||
const modelDisplayName = String(
|
||||
line?.model_display_name || deepStep?.modelDisplayName || ''
|
||||
).trim();
|
||||
const thinkingTokens = Number(line?.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0;
|
||||
const responseTokens = line?.response_tokens ?? deepStep?.responseTokens;
|
||||
const resolvedStepIndex = Number.isFinite(Number(line?.step_index))
|
||||
? Number(line.step_index)
|
||||
: stepIndex;
|
||||
|
||||
return {
|
||||
type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE',
|
||||
status: mappedStatus,
|
||||
plannerResponse: {
|
||||
response: typeof line?.content === 'string' ? line.content : '',
|
||||
thinking: typeof line?.thinking === 'string' ? line.thinking : '',
|
||||
toolCalls: Array.isArray(line?.tool_calls) ? line.tool_calls : [],
|
||||
...(thinkingTokens > 0 ? { thinkingTokens } : {}),
|
||||
...(responseTokens !== undefined ? { responseTokens } : {}),
|
||||
},
|
||||
metadata: {
|
||||
createdAt: String(line?.created_at || line?.createdAt || deepStep?.createdAt || ''),
|
||||
...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}),
|
||||
sourceTrajectoryStepInfo: { stepIndex: resolvedStepIndex },
|
||||
modelUsage: {
|
||||
model: modelKey,
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
...(apiProvider ? { apiProvider } : {}),
|
||||
inputTokens: line?.input_tokens ?? deepStep?.inputTokens ?? 0,
|
||||
cacheReadTokens: line?.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0,
|
||||
outputTokens: line?.output_tokens ?? deepStep?.outputTokens ?? 0,
|
||||
...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}),
|
||||
...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}),
|
||||
},
|
||||
...(modelDisplayName
|
||||
? { generatorMetadata: [{ chatModel: { modelDisplayName } }] }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `transcript.jsonl`(或受体积保护的 `transcript_full.jsonl`)构建 CLI 状态栏兼容的轨迹载荷。
|
||||
*
|
||||
* @param {string} transcriptPath
|
||||
* @param {string} cascadeId
|
||||
* @param {{ maxBytes?: number }} [opts={}]
|
||||
* @returns {{ cascadeId: string, steps: object[], generatorMetadata: object[] } | null}
|
||||
*/
|
||||
export function buildTranscriptFallbackTrajectory(transcriptPath, cascadeId, opts = {}) {
|
||||
const lines = readTranscriptJsonlLines(transcriptPath, opts);
|
||||
if (lines.length === 0) return null;
|
||||
const rawSteps = [];
|
||||
for (let idx = 0; idx < lines.length; idx++) {
|
||||
const parsed = lines[idx];
|
||||
const hasTokens =
|
||||
parsed.input_tokens !== undefined ||
|
||||
parsed.cache_read_tokens !== undefined ||
|
||||
parsed.output_tokens !== undefined;
|
||||
if (!hasTokens) {
|
||||
rawSteps.push(parsed);
|
||||
continue;
|
||||
}
|
||||
rawSteps.push(synthesizeTranscriptModelStep(parsed, { stepIndex: idx }));
|
||||
}
|
||||
return rawSteps.length > 0 ? { cascadeId, steps: rawSteps, generatorMetadata: [] } : null;
|
||||
}
|
||||
Reference in New Issue
Block a user