refactor: add canonical transcript assembly seam
This commit is contained in:
+10
-30
@@ -10,6 +10,7 @@ import { createIndexerService } from './indexer-service.ts';
|
||||
import { createWorkerBuildIndex } from './indexer-worker-client.ts';
|
||||
import { buildRecapExportQuery } from './recap-capture-query.ts';
|
||||
import { acquireWriterLease, writerLockPathFor } from '../../../packages/core/src/writer-lease.ts';
|
||||
import { migrateCoreSchemaColumns } from '../../../packages/core/src/schema-migrations.ts';
|
||||
import { createBuiltinProviderRegistry } from '../../../packages/core/src/providers/builtins.ts';
|
||||
import {
|
||||
buildSourceCatalog,
|
||||
@@ -32,7 +33,7 @@ import type {
|
||||
SessionWorkflowRow,
|
||||
} from '../shared/session-detail-types.ts';
|
||||
import { createSessionPatch } from '../shared/session-patch.mjs';
|
||||
import { assembleSessionMessages } from '../shared/session-detail-assembly.mjs';
|
||||
import { assembleSessionDetail } from '../shared/session-detail-assembly.mjs';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -160,35 +161,12 @@ function resolveSchemaPath() {
|
||||
return candidates.find(p => fs.existsSync(p));
|
||||
}
|
||||
|
||||
function ensureColumn(db, table, column, definition) {
|
||||
const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name);
|
||||
if (!columns.includes(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
||||
}
|
||||
|
||||
function tableExists(db, table) {
|
||||
return Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(table));
|
||||
}
|
||||
|
||||
function migrateExistingColumns(db) {
|
||||
if (tableExists(db, 'sessions')) ensureColumn(db, 'sessions', 'source', "TEXT DEFAULT 'claude'");
|
||||
if (tableExists(db, 'messages')) {
|
||||
ensureColumn(db, 'messages', 'content_type', 'TEXT');
|
||||
ensureColumn(db, 'messages', 'is_meta', 'INTEGER DEFAULT 0');
|
||||
ensureColumn(db, 'messages', 'source', "TEXT DEFAULT 'claude'");
|
||||
}
|
||||
if (tableExists(db, 'memories')) {
|
||||
ensureColumn(db, 'memories', 'anchors', 'TEXT');
|
||||
ensureColumn(db, 'memories', 'deleted_at', 'TEXT');
|
||||
ensureColumn(db, 'memories', 'deleted_reason', 'TEXT');
|
||||
}
|
||||
}
|
||||
|
||||
function migrateDb(db) {
|
||||
if (typeof db.exec !== 'function' || typeof db.prepare !== 'function') return;
|
||||
migrateExistingColumns(db);
|
||||
migrateCoreSchemaColumns(db);
|
||||
const schemaPath = resolveSchemaPath();
|
||||
if (schemaPath) db.exec(fs.readFileSync(schemaPath, 'utf8'));
|
||||
migrateExistingColumns(db);
|
||||
migrateCoreSchemaColumns(db);
|
||||
}
|
||||
|
||||
function closeDb() {
|
||||
@@ -417,7 +395,7 @@ function querySessionMessages(sessionId: string): SessionMessageRow[] {
|
||||
return db.prepare(`
|
||||
SELECT m.uuid, m.session_id, m.type, m.parent_uuid, m.timestamp, m.role, m.text, m.model,
|
||||
m.is_sidechain, m.agent_id, m.input_tokens, m.output_tokens, m.cwd, m.skill, m.turn_duration_ms,
|
||||
m.content_type, m.is_meta, m.source
|
||||
m.content_type, m.is_meta, m.visibility, m.source
|
||||
FROM messages m WHERE m.session_id = ? AND m.agent_id IS NULL ORDER BY m.timestamp, m.uuid
|
||||
`).all(sessionId) as SessionMessageRow[];
|
||||
}
|
||||
@@ -464,9 +442,11 @@ function querySessionSnapshot(sessionId: string): SessionDetailAssemblyInput {
|
||||
|
||||
function querySessionDisplaySnapshot(sessionId: string): SessionPatchSnapshot {
|
||||
const snapshot = querySessionSnapshot(sessionId);
|
||||
const detail = assembleSessionDetail(snapshot);
|
||||
return {
|
||||
messages: assembleSessionMessages(snapshot),
|
||||
workflows: snapshot.workflows,
|
||||
messages: detail.messages,
|
||||
workflows: detail.workflows,
|
||||
summaries: detail.summaries,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -544,7 +524,7 @@ ipcMain.handle('db:getSubagentMessages', (_, agentId) => {
|
||||
return db.prepare(`
|
||||
SELECT m.uuid, m.session_id, m.type, m.parent_uuid, m.timestamp, m.role, m.text, m.model,
|
||||
m.is_sidechain, m.agent_id, m.input_tokens, m.output_tokens, m.cwd, m.skill, m.turn_duration_ms,
|
||||
m.content_type, m.is_meta, m.source
|
||||
m.content_type, m.is_meta, m.visibility, m.source
|
||||
FROM messages m WHERE m.agent_id = ? ORDER BY m.timestamp, m.uuid
|
||||
`).all(agentId);
|
||||
});
|
||||
|
||||
+2
-99
@@ -11,23 +11,18 @@ import {
|
||||
writeProviderIndexMarkers,
|
||||
} from '../../../packages/core/src/provider-indexing.ts';
|
||||
import { runWriteTransaction, configureConnection, betterSqliteTransactionAdapter } from '../../../packages/core/src/tx.ts';
|
||||
import { migrateCoreSchemaColumns } from '../../../packages/core/src/schema-migrations.ts';
|
||||
import { acquireWriterLease, writerLockPathFor } from '../../../packages/core/src/writer-lease.ts';
|
||||
import { runRetryableWriteTransaction, isBeginBusyFailure, hasUnusableTransaction } from '../../../packages/core/src/write-coordinator.ts';
|
||||
import {
|
||||
inferProjectPath,
|
||||
isDir,
|
||||
readLines,
|
||||
codexDbId,
|
||||
} from '../../../packages/core/src/parsing.ts';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const DEFAULT_CLAUDE_DIR = path.join(os.homedir(), '.claude');
|
||||
const DEFAULT_CODEX_DIR = path.join(os.homedir(), '.codex');
|
||||
const DEFAULT_OBELISK_DIR = path.join(os.homedir(), '.obelisk');
|
||||
const DEFAULT_DB_PATH = path.join(DEFAULT_OBELISK_DIR, 'obelisk.sqlite');
|
||||
const DEFAULT_PROJECTS_DIR = path.join(DEFAULT_CLAUDE_DIR, 'projects');
|
||||
const DEFAULT_HISTORY_PATH = path.join(DEFAULT_CLAUDE_DIR, 'history.jsonl');
|
||||
|
||||
function resolveSchemaPath() {
|
||||
const candidates = [
|
||||
@@ -42,7 +37,7 @@ function resolveSchemaPath() {
|
||||
|
||||
function installSchema(db, schemaPath = resolveSchemaPath()) {
|
||||
db.exec(fs.readFileSync(schemaPath, 'utf8'));
|
||||
migrateDb(db);
|
||||
migrateCoreSchemaColumns(db);
|
||||
}
|
||||
|
||||
function openIndexDb({ dbPath = DEFAULT_DB_PATH, schemaPath = resolveSchemaPath(), DatabaseImpl = Database }: { dbPath?: string; schemaPath?: string; DatabaseImpl?: new (dbPath: string) => any } = {}) {
|
||||
@@ -53,21 +48,6 @@ function openIndexDb({ dbPath = DEFAULT_DB_PATH, schemaPath = resolveSchemaPath(
|
||||
return db;
|
||||
}
|
||||
|
||||
function ensureColumn(db, table, column, definition) {
|
||||
const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name);
|
||||
if (!columns.includes(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
||||
}
|
||||
|
||||
function migrateDb(db) {
|
||||
ensureColumn(db, 'sessions', 'source', "TEXT DEFAULT 'claude'");
|
||||
ensureColumn(db, 'messages', 'content_type', 'TEXT');
|
||||
ensureColumn(db, 'messages', 'is_meta', 'INTEGER DEFAULT 0');
|
||||
ensureColumn(db, 'messages', 'source', "TEXT DEFAULT 'claude'");
|
||||
ensureColumn(db, 'memories', 'anchors', 'TEXT');
|
||||
ensureColumn(db, 'memories', 'deleted_at', 'TEXT');
|
||||
ensureColumn(db, 'memories', 'deleted_reason', 'TEXT');
|
||||
}
|
||||
|
||||
function copyMemoriesFromDb(db, sourceDbPath) {
|
||||
if (!sourceDbPath || !fs.existsSync(sourceDbPath)) return false;
|
||||
db.prepare('ATTACH DATABASE ? AS previous_obelisk').run(sourceDbPath);
|
||||
@@ -126,23 +106,6 @@ function sessionIdFromChangedPath(projectsDir, changedPath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function indexCodexSessionIndex(db, { codexDir = DEFAULT_CODEX_DIR } = {}) {
|
||||
const indexPath = path.join(codexDir, 'session_index.jsonl');
|
||||
if (!fs.existsSync(indexPath)) return;
|
||||
readLines(indexPath, (line) => {
|
||||
let item;
|
||||
try {
|
||||
item = JSON.parse(line);
|
||||
} catch (error) {
|
||||
console.warn(`Warning: malformed Codex session index line: ${(error as Error).message}`);
|
||||
return;
|
||||
}
|
||||
if (!item.id || !item.thread_name) return;
|
||||
db.prepare('UPDATE sessions SET title=COALESCE(title, ?), ended_at=COALESCE(ended_at, ?) WHERE id=? AND source=?')
|
||||
.run(item.thread_name, item.updated_at || null, codexDbId(item.id), 'codex');
|
||||
});
|
||||
}
|
||||
|
||||
function refreshSessionProjectPaths(db) {
|
||||
const sessions = db.prepare('SELECT id, project FROM sessions').all();
|
||||
const cwdStmt = db.prepare(`
|
||||
@@ -158,61 +121,6 @@ function refreshSessionProjectPaths(db) {
|
||||
}
|
||||
}
|
||||
|
||||
function indexWorkflows(db, { projectsDir = DEFAULT_PROJECTS_DIR } = {}) {
|
||||
if (!fs.existsSync(projectsDir)) return;
|
||||
let projects;
|
||||
try { projects = fs.readdirSync(projectsDir); } catch { return; }
|
||||
for (const proj of projects) {
|
||||
const pp = path.join(projectsDir, proj);
|
||||
if (!isDir(pp)) continue;
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(pp); } catch { continue; }
|
||||
for (const sd of entries) {
|
||||
const wd = path.join(pp, sd, 'workflows');
|
||||
if (!isDir(wd)) continue;
|
||||
let wfFiles;
|
||||
try { wfFiles = fs.readdirSync(wd); } catch { continue; }
|
||||
for (const f of wfFiles) {
|
||||
if (!f.endsWith('.json')) continue;
|
||||
let wf;
|
||||
try {
|
||||
wf = JSON.parse(fs.readFileSync(path.join(wd, f), 'utf8'));
|
||||
} catch (error) {
|
||||
console.warn(`Warning: failed to read workflow ${f}: ${(error as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
if (!wf.runId) continue;
|
||||
const ac = db.prepare('SELECT COUNT(*) as c FROM workflow_agents WHERE run_id=?').get(wf.runId);
|
||||
db.prepare('INSERT OR REPLACE INTO workflows (run_id,session_id,task_id,script,result_json,timestamp,agent_count,duration_ms,total_tokens,status,workflow_name) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(
|
||||
wf.runId, sd, wf.taskId||null, wf.script||null,
|
||||
wf.result ? JSON.stringify(wf.result) : null, wf.timestamp||null, ac?.c||0,
|
||||
wf.durationMs||null, wf.totalTokens||null, wf.status||null, wf.workflowName||null);
|
||||
const progress = wf.workflowProgress || [];
|
||||
for (const item of progress) {
|
||||
if (item.type !== 'workflow_agent' || !item.agentId) continue;
|
||||
db.prepare('UPDATE workflow_agents SET phase=?, label=?, model=?, state=?, duration_ms=?, tokens=?, tool_calls=? WHERE agent_id=?').run(
|
||||
item.phaseTitle||null, item.label||null, item.model||null, item.state||null,
|
||||
item.durationMs||null, item.tokens||null, item.toolCalls||null, 'agent-' + item.agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function indexHistory(db, { historyPath = DEFAULT_HISTORY_PATH } = {}) {
|
||||
if (!fs.existsSync(historyPath)) return;
|
||||
readLines(historyPath, (line) => {
|
||||
let item;
|
||||
try {
|
||||
item = JSON.parse(line);
|
||||
} catch (error) {
|
||||
console.warn(`Warning: malformed history line: ${(error as Error).message}`);
|
||||
return;
|
||||
}
|
||||
if (item.sessionId && item.title) db.prepare('UPDATE sessions SET title=? WHERE id=? AND title IS NULL').run(item.title, item.sessionId);
|
||||
});
|
||||
}
|
||||
|
||||
function rebuildFts(db) {
|
||||
db.exec("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')");
|
||||
db.exec("INSERT INTO memories_fts(memories_fts) VALUES('rebuild')");
|
||||
@@ -286,7 +194,6 @@ interface BuildIndexOptions {
|
||||
claudeDir?: string;
|
||||
codexDir?: string;
|
||||
projectsDir?: string;
|
||||
historyPath?: string;
|
||||
dbPath?: string;
|
||||
schemaPath?: string;
|
||||
DatabaseImpl?: new (dbPath: string) => any;
|
||||
@@ -339,7 +246,6 @@ function buildIndex({
|
||||
claudeDir = DEFAULT_CLAUDE_DIR,
|
||||
codexDir = path.join(path.dirname(claudeDir), '.codex'),
|
||||
projectsDir = path.join(claudeDir, 'projects'),
|
||||
historyPath = path.join(claudeDir, 'history.jsonl'),
|
||||
dbPath = DEFAULT_DB_PATH,
|
||||
schemaPath = resolveSchemaPath(),
|
||||
DatabaseImpl = Database,
|
||||
@@ -489,10 +395,7 @@ function buildIndex({
|
||||
// index would otherwise be left inconsistent).
|
||||
try {
|
||||
runRetryableWriteTransaction(txDb, () => {
|
||||
indexWorkflows(db, { projectsDir });
|
||||
refreshSessionProjectPaths(db);
|
||||
indexHistory(db, { historyPath });
|
||||
indexCodexSessionIndex(db, { codexDir });
|
||||
if (messageFtsTriggersDropped) installSchema(db, schemaPath);
|
||||
ftsRebuilt = ensureFtsReady(db, { force });
|
||||
writeIndexMarker(db, '__last_build__');
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
applySessionPatch,
|
||||
createSessionPatchCursor,
|
||||
} from '../../shared/session-patch.mjs';
|
||||
import { assembleSessionMessages } from '../../shared/session-detail-assembly.mjs';
|
||||
import { assembleSessionDetail } from '../../shared/session-detail-assembly.mjs';
|
||||
|
||||
const sessionMessageSnapshots = new Map();
|
||||
const MAX_SESSION_MESSAGE_SNAPSHOTS = 3;
|
||||
@@ -25,6 +25,7 @@ function sessionMetadata(session) {
|
||||
const metadata = { ...session };
|
||||
delete metadata.messages;
|
||||
delete metadata.workflow;
|
||||
delete metadata.summaries;
|
||||
return markRaw(metadata);
|
||||
}
|
||||
|
||||
@@ -96,9 +97,11 @@ export async function loadSessionDetail(sessionId) {
|
||||
window.obelisk.getSessionWorkflows(sessionId),
|
||||
window.obelisk.getSessionSummaries(sessionId),
|
||||
]);
|
||||
const detail = assembleSessionDetail({ messages, toolCalls, toolResults, subagents, workflows, summaries });
|
||||
const snapshot = {
|
||||
messages: assembleSessionMessages({ messages, toolCalls, toolResults, subagents, workflows }),
|
||||
workflows,
|
||||
messages: detail.messages,
|
||||
workflows: detail.workflows,
|
||||
summaries: detail.summaries,
|
||||
};
|
||||
const metadata = sessionMetadata(state.sessions.find(candidate => candidate.id === sessionId));
|
||||
rememberSessionMessageSnapshot(sessionId, {
|
||||
@@ -154,13 +157,14 @@ export function getCachedSessionDetail(sessionId) {
|
||||
});
|
||||
}
|
||||
|
||||
function commitSessionDetail(sessionId, { messages, workflows = [] }, { updateStore, metadata = null }) {
|
||||
function commitSessionDetail(sessionId, { messages, workflows = [], summaries = [] }, { updateStore, metadata = null }) {
|
||||
const session = state.sessions.find(candidate => candidate.id === sessionId);
|
||||
const assembled = {
|
||||
...(session || {}),
|
||||
...(metadata || {}),
|
||||
id: sessionId,
|
||||
messages: markRaw(messages),
|
||||
summaries: markRaw(summaries),
|
||||
};
|
||||
if (workflows.length > 0) assembled.workflow = workflows[0];
|
||||
|
||||
@@ -181,13 +185,13 @@ export async function loadSubagentDetail(agentId) {
|
||||
window.obelisk.getSubagentToolCalls(agentId),
|
||||
window.obelisk.getSubagentToolResults(agentId),
|
||||
]);
|
||||
return assembleSessionMessages({
|
||||
return assembleSessionDetail({
|
||||
messages,
|
||||
toolCalls,
|
||||
toolResults,
|
||||
subagents: [],
|
||||
workflows: [],
|
||||
});
|
||||
}).messages;
|
||||
}
|
||||
|
||||
const TEXT_LIMIT = 10000;
|
||||
|
||||
@@ -1,173 +1,9 @@
|
||||
// @ts-check
|
||||
import { assembleSessionDetail } from '../../../packages/core/src/session-detail.ts';
|
||||
|
||||
/** @typedef {import('./session-detail-types.ts').AssembledMessage} AssembledMessage */
|
||||
/** @typedef {import('./session-detail-types.ts').AssembledToolCall} AssembledToolCall */
|
||||
/** @typedef {import('./session-detail-types.ts').SessionDetailAssemblyInput} SessionDetailAssemblyInput */
|
||||
/** @typedef {import('./session-detail-types.ts').SessionSubagentRow} SessionSubagentRow */
|
||||
/** @typedef {import('./session-detail-types.ts').SessionToolResultRow} SessionToolResultRow */
|
||||
export { assembleSessionDetail };
|
||||
|
||||
/**
|
||||
* @param {SessionDetailAssemblyInput} input
|
||||
* @returns {AssembledMessage[]}
|
||||
*/
|
||||
export function assembleSessionMessages({ messages, toolCalls, toolResults, subagents, workflows }) {
|
||||
const resultsByCallId = /** @type {Map<string, SessionToolResultRow>} */ (new Map());
|
||||
for (const result of toolResults || []) resultsByCallId.set(result.tool_use_id, result);
|
||||
|
||||
const subagentsByCallId = /** @type {Map<string, SessionSubagentRow>} */ (new Map());
|
||||
for (const subagent of subagents || []) {
|
||||
if (subagent.parent_tool_use_id) subagentsByCallId.set(subagent.parent_tool_use_id, subagent);
|
||||
}
|
||||
|
||||
const callsByMessageUuid = /** @type {Map<string, AssembledToolCall[]>} */ (new Map());
|
||||
for (const toolCall of toolCalls || []) {
|
||||
const call = /** @type {AssembledToolCall} */ ({
|
||||
id: toolCall.id,
|
||||
name: toolCall.name,
|
||||
input_json: toolCall.input_json,
|
||||
result: resultsByCallId.get(toolCall.id) || null,
|
||||
});
|
||||
const subagent = subagentsByCallId.get(toolCall.id);
|
||||
if (subagent) {
|
||||
call.subagent = {
|
||||
agent_id: subagent.agent_id,
|
||||
agent_type: subagent.agent_type,
|
||||
description: subagent.description,
|
||||
};
|
||||
}
|
||||
const messageUuid = toolCall.message_uuid;
|
||||
const calls = callsByMessageUuid.get(messageUuid) || [];
|
||||
calls.push(call);
|
||||
callsByMessageUuid.set(messageUuid, calls);
|
||||
}
|
||||
|
||||
for (const workflow of workflows || []) {
|
||||
for (const calls of callsByMessageUuid.values()) {
|
||||
for (const call of calls) {
|
||||
if (call.name !== 'Workflow' || call.workflow) continue;
|
||||
const resultText = call.result?.content || '';
|
||||
if (!resultText.includes(workflow.run_id) && !resultText.includes(workflow.workflow_name || '___none___')) continue;
|
||||
call.workflow = {
|
||||
run_id: workflow.run_id,
|
||||
workflow_name: workflow.workflow_name,
|
||||
status: workflow.status,
|
||||
duration_ms: workflow.duration_ms,
|
||||
total_tokens: workflow.total_tokens,
|
||||
agent_count: workflow.agent_count,
|
||||
agents: (workflow.agents || []).map(agent => ({
|
||||
agent_id: agent.agent_id,
|
||||
phase: agent.phase,
|
||||
label: agent.label,
|
||||
state: agent.state,
|
||||
tokens: agent.tokens,
|
||||
duration_ms: agent.duration_ms,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const metaPattern = /^\s*<(task-notification|command-name|local-command|system-reminder)/;
|
||||
const rawAssembled = (messages || []).map(message => {
|
||||
const assembled = /** @type {AssembledMessage} */ ({
|
||||
uuid: message.uuid,
|
||||
type: message.type || message.role,
|
||||
timestamp: message.timestamp,
|
||||
text: message.text,
|
||||
content_type: message.content_type || null,
|
||||
is_meta: message.is_meta || (message.text && metaPattern.test(message.text) ? 1 : 0),
|
||||
});
|
||||
const calls = callsByMessageUuid.get(message.uuid);
|
||||
if (calls?.length) assembled.tool_calls = calls;
|
||||
return assembled;
|
||||
});
|
||||
|
||||
const assembledMessages = /** @type {AssembledMessage[]} */ ([]);
|
||||
for (let index = 0; index < rawAssembled.length; index++) {
|
||||
const message = rawAssembled[index];
|
||||
if (message.content_type === 'tool_result') continue;
|
||||
|
||||
if (message.type === 'assistant' && message.content_type === 'thinking') {
|
||||
const thinkingParts = [message.text || ''];
|
||||
let nextIndex = index + 1;
|
||||
while (
|
||||
nextIndex < rawAssembled.length
|
||||
&& rawAssembled[nextIndex].type === 'assistant'
|
||||
&& rawAssembled[nextIndex].content_type === 'thinking'
|
||||
) {
|
||||
thinkingParts.push(rawAssembled[nextIndex].text || '');
|
||||
nextIndex++;
|
||||
}
|
||||
if (
|
||||
nextIndex < rawAssembled.length
|
||||
&& rawAssembled[nextIndex].type === 'assistant'
|
||||
&& rawAssembled[nextIndex].content_type !== 'thinking'
|
||||
) {
|
||||
rawAssembled[nextIndex]._thinking = thinkingParts.join('\n\n');
|
||||
index = nextIndex - 1;
|
||||
continue;
|
||||
}
|
||||
assembledMessages.push({ ...message, text: thinkingParts.join('\n\n'), content_type: 'thinking' });
|
||||
index = nextIndex - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.type === 'assistant' && message.content_type === 'tool_use') {
|
||||
const merged = /** @type {AssembledMessage} */ ({
|
||||
...message,
|
||||
tool_calls: [...(message.tool_calls || [])],
|
||||
});
|
||||
const mergedCalls = merged.tool_calls || [];
|
||||
if (message._thinking) merged._thinking = message._thinking;
|
||||
const skillOnly = mergedCalls.length === 1 && mergedCalls[0].name === 'Skill';
|
||||
let nextIndex = index + 1;
|
||||
while (nextIndex < rawAssembled.length) {
|
||||
const next = rawAssembled[nextIndex];
|
||||
if (next.content_type === 'tool_result') {
|
||||
nextIndex++;
|
||||
continue;
|
||||
}
|
||||
if (next.is_meta && next.text && next.text.includes('Base directory for this skill')) {
|
||||
merged._skillMd = next.text;
|
||||
nextIndex++;
|
||||
continue;
|
||||
}
|
||||
if (!skillOnly && next.type === 'assistant' && next.content_type === 'tool_use') {
|
||||
if (next.tool_calls) mergedCalls.push(...next.tool_calls);
|
||||
if (next.text && !merged.text) merged.text = next.text;
|
||||
nextIndex++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
assembledMessages.push(merged);
|
||||
index = nextIndex - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const output = /** @type {AssembledMessage} */ ({ ...message });
|
||||
if (message._thinking) output._thinking = message._thinking;
|
||||
if (message.type === 'assistant' && message.content_type !== 'tool_use' && message.content_type !== 'thinking') {
|
||||
if (!output.tool_calls) output.tool_calls = [];
|
||||
let nextIndex = index + 1;
|
||||
while (nextIndex < rawAssembled.length) {
|
||||
const next = rawAssembled[nextIndex];
|
||||
if (next.content_type === 'tool_result') {
|
||||
nextIndex++;
|
||||
continue;
|
||||
}
|
||||
if (next.type === 'assistant' && next.content_type === 'tool_use') {
|
||||
if (next.tool_calls) output.tool_calls.push(...next.tool_calls);
|
||||
nextIndex++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!output.tool_calls.length) delete output.tool_calls;
|
||||
index = nextIndex - 1;
|
||||
}
|
||||
assembledMessages.push(output);
|
||||
}
|
||||
|
||||
return assembledMessages;
|
||||
// Compatibility for local/generated app tooling; production callers use the
|
||||
// single Core assembleSessionDetail seam.
|
||||
export function assembleSessionMessages(input) {
|
||||
return assembleSessionDetail(input).messages;
|
||||
}
|
||||
|
||||
@@ -1,105 +1,13 @@
|
||||
export interface SessionMessageRow {
|
||||
[key: string]: unknown;
|
||||
uuid: string;
|
||||
type?: string | null;
|
||||
role?: string | null;
|
||||
timestamp?: string | null;
|
||||
text?: string | null;
|
||||
content_type?: string | null;
|
||||
is_meta?: number | boolean | null;
|
||||
}
|
||||
|
||||
export interface SessionToolResultRow {
|
||||
[key: string]: unknown;
|
||||
tool_use_id: string;
|
||||
content?: string | null;
|
||||
}
|
||||
|
||||
export interface SessionToolCallRow {
|
||||
[key: string]: unknown;
|
||||
id: string;
|
||||
message_uuid: string;
|
||||
name: string;
|
||||
input_json?: string | null;
|
||||
}
|
||||
|
||||
export interface SessionSubagentRow {
|
||||
[key: string]: unknown;
|
||||
agent_id: string;
|
||||
parent_tool_use_id?: string | null;
|
||||
agent_type?: string | null;
|
||||
description?: string | null;
|
||||
}
|
||||
|
||||
export interface SessionWorkflowAgentRow {
|
||||
[key: string]: unknown;
|
||||
agent_id: string;
|
||||
phase?: string | null;
|
||||
label?: string | null;
|
||||
state?: string | null;
|
||||
tokens?: number | null;
|
||||
duration_ms?: number | null;
|
||||
}
|
||||
|
||||
export interface SessionWorkflowRow {
|
||||
[key: string]: unknown;
|
||||
run_id: string;
|
||||
workflow_name?: string | null;
|
||||
status?: string | null;
|
||||
duration_ms?: number | null;
|
||||
total_tokens?: number | null;
|
||||
agent_count?: number | null;
|
||||
agents?: SessionWorkflowAgentRow[] | null;
|
||||
}
|
||||
|
||||
export interface SessionSummaryRow {
|
||||
[key: string]: unknown;
|
||||
id: string | number;
|
||||
}
|
||||
|
||||
export interface SessionDetailAssemblyInput {
|
||||
messages?: SessionMessageRow[];
|
||||
toolCalls?: SessionToolCallRow[];
|
||||
toolResults?: SessionToolResultRow[];
|
||||
subagents?: SessionSubagentRow[];
|
||||
workflows?: SessionWorkflowRow[];
|
||||
summaries?: SessionSummaryRow[];
|
||||
}
|
||||
|
||||
export interface AssembledToolCall {
|
||||
[key: string]: unknown;
|
||||
id: string;
|
||||
name: string;
|
||||
input_json?: string | null;
|
||||
result: SessionToolResultRow | null;
|
||||
subagent?: {
|
||||
agent_id: string;
|
||||
agent_type?: string | null;
|
||||
description?: string | null;
|
||||
};
|
||||
workflow?: {
|
||||
run_id: string;
|
||||
workflow_name?: string | null;
|
||||
status?: string | null;
|
||||
duration_ms?: number | null;
|
||||
total_tokens?: number | null;
|
||||
agent_count?: number | null;
|
||||
agents: Array<{
|
||||
agent_id: string;
|
||||
phase?: string | null;
|
||||
label?: string | null;
|
||||
state?: string | null;
|
||||
tokens?: number | null;
|
||||
duration_ms?: number | null;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssembledMessage extends SessionMessageRow {
|
||||
type?: string | null;
|
||||
content_type?: string | null;
|
||||
is_meta?: number | boolean | null;
|
||||
tool_calls?: AssembledToolCall[];
|
||||
_thinking?: string;
|
||||
_skillMd?: string;
|
||||
}
|
||||
export type {
|
||||
AssembledMessage,
|
||||
AssembledToolCall,
|
||||
SessionDetailRows as SessionDetailAssemblyInput,
|
||||
SessionDetailSessionRow,
|
||||
SessionMessageRow,
|
||||
SessionSubagentRow,
|
||||
SessionSummaryRow,
|
||||
SessionToolCallRow,
|
||||
SessionToolResultRow,
|
||||
SessionWorkflowAgentRow,
|
||||
SessionWorkflowRow,
|
||||
} from '../../../packages/core/src/session-detail.ts';
|
||||
|
||||
Reference in New Issue
Block a user