Open-source, local-first AI agent for real work.
TypeScript agent-toolsai-agentbyokcoding-agentcross-platformdesktop-appdeveloper-toolselectronharnessknowledge-basellmwikilocal-firstmcpplugin-systemprivacy-firstskillstypescriptvettaworkflow-automation
import {
applyConversationDocumentCommand,
applyStoredEventToConversationDocument,
assertConversationDocumentGraph,
type ConversationDocument,
type ConversationDocumentEntry,
type ConversationDocumentEntryReference,
conversationDocumentEntryPersistence,
createEmptyConversationDocument,
createSeededConversationDocument,
nativeConversationEntryId,
selectConversationDocumentModelMessages,
} from "@vetta/runtime-core/conversation";
import type { StoredConversation, StoredSessionEvent } from "@vetta/runtime-core/kernel";
import {
CONVERSATION_SCHEMA_VERSION,
CONVERSATION_STORAGE_ERROR_CODES,
type ConversationContinuationSeedRecord,
type ConversationDocumentOperationRecord,
type ConversationEventRecord,
type ConversationFileHeader,
type ConversationImportSeedRecord,
type ConversationSeedRecord,
ConversationStorageError,
getStoredSessionEventValidationIssue,
isConversationContinuationSeedRecord,
isConversationDocumentOperationRecord,
isConversationFileHeader,
isConversationImportSeedRecord,
isConversationSeedRecord,
isStoredSessionEvent,
type NormalizedReadConversationEventRecord,
type ReadConversationFileHeader,
readConversationEventRecord,
} from "@vetta/runtime-storage/conversation";
export type ConversationBodyRecord = NormalizedReadConversationEventRecord | ConversationDocumentOperationRecord;
export interface ParsedConversationFile {
readonly header: ReadConversationFileHeader;
readonly seed?: ConversationSeedRecord;
readonly continuationSeed?: ConversationContinuationSeedRecord;
readonly importSeed?: ConversationImportSeedRecord;
readonly records: readonly ConversationBodyRecord[];
readonly eventRecords: readonly NormalizedReadConversationEventRecord[];
}
export function parseConversationFile(text: string, sessionId: string): ParsedConversationFile {
const records = parseRecords(text, sessionId);
const [header, ...body] = records;
if (!isConversationFileHeader(header) || header.sessionId !== sessionId) {
throw corruptConversation(sessionId, "missing or mismatched header");
}
const eventRecords: NormalizedReadConversationEventRecord[] = [];
const conversationRecords: ConversationBodyRecord[] = [];
const documentEntryIds = new Set<string>();
let seed: ConversationSeedRecord | undefined;
let continuationSeed: ConversationContinuationSeedRecord | undefined;
let importSeed: ConversationImportSeedRecord | undefined;
let expectedEventSequence = 1;
for (let index = 0; index < body.length; index += 1) {
const record = body[index];
if (isConversationSeedRecord(record)) {
if (
header.schemaVersion !== CONVERSATION_SCHEMA_VERSION ||
index !== 0 ||
seed ||
continuationSeed ||
importSeed
) {
throw corruptConversation(sessionId, `invalid seed at line ${index + 2}`);
}
seed = record;
for (const entry of record.entries) {
if (documentEntryIds.has(entry.id)) {
throw corruptConversation(sessionId, `duplicate seed entry at line ${index + 2}`);
}
documentEntryIds.add(entry.id);
}
continue;
}
if (isConversationContinuationSeedRecord(record)) {
if (
header.schemaVersion !== CONVERSATION_SCHEMA_VERSION ||
index !== 0 ||
seed ||
continuationSeed ||
importSeed ||
header.parentSessionPath !== record.sourceSessionPath ||
header.parentEntryId !== record.sourceEntryId
) {
throw corruptConversation(sessionId, `invalid continuation seed at line ${index + 2}`);
}
continuationSeed = record;
for (const entry of record.entries) {
if (documentEntryIds.has(entry.id)) {
throw corruptConversation(sessionId, `duplicate continuation entry at line ${index + 2}`);
}
documentEntryIds.add(entry.id);
}
continue;
}
if (isConversationImportSeedRecord(record)) {
if (
header.schemaVersion !== CONVERSATION_SCHEMA_VERSION ||
index !== 0 ||
seed ||
continuationSeed ||
importSeed
) {
throw corruptConversation(sessionId, `invalid import seed at line ${index + 2}`);
}
importSeed = record;
for (const entry of record.entries) {
if (documentEntryIds.has(entry.id)) {
throw corruptConversation(sessionId, `duplicate import entry at line ${index + 2}`);
}
documentEntryIds.add(entry.id);
}
continue;
}
if (isConversationDocumentOperationRecord(record)) {
if (header.schemaVersion !== CONVERSATION_SCHEMA_VERSION) {
throw corruptConversation(sessionId, `document operation is not supported at line ${index + 2}`);
}
const entryId = documentOperationEntryId(record);
if (entryId) {
if (documentEntryIds.has(entryId)) {
throw corruptConversation(sessionId, `duplicate document entry at line ${index + 2}`);
}
documentEntryIds.add(entryId);
}
conversationRecords.push(record);
continue;
}
const eventRecord = readConversationEventRecord(record);
if (!eventRecord) {
throw corruptConversation(sessionId, `invalid conversation record at line ${index + 2}`);
}
if (eventRecord.schemaVersion !== header.schemaVersion) {
throw corruptConversation(sessionId, `event schema version does not match header at line ${index + 2}`);
}
if (eventRecord.sequence !== expectedEventSequence) {
throw corruptConversation(
sessionId,
`event sequence ${eventRecord.sequence} does not match expected ${expectedEventSequence}`,
);
}
expectedEventSequence += 1;
validateConversationEvent(sessionId, eventRecord.event);
if (eventRecord.schemaVersion === CONVERSATION_SCHEMA_VERSION) {
const persistence = conversationDocumentEntryPersistence(eventRecord.event);
if ((eventRecord.documentEntry !== null) !== (persistence === "reference")) {
throw corruptConversation(sessionId, `event has inconsistent document entry at line ${index + 2}`);
}
if (eventRecord.documentEntry) {
if (documentEntryIds.has(eventRecord.documentEntry.id)) {
throw corruptConversation(sessionId, `duplicate document entry at line ${index + 2}`);
}
if (eventRecord.documentEntry.parentId && !documentEntryIds.has(eventRecord.documentEntry.parentId)) {
throw corruptConversation(sessionId, `unknown document parent at line ${index + 2}`);
}
documentEntryIds.add(eventRecord.documentEntry.id);
}
// 隐式节点的 id 不落盘,但同样会成为后续事件的父节点,必须一并登记。
if (persistence === "implicit") {
const implicitId = nativeConversationEntryId(eventRecord.sequence);
if (documentEntryIds.has(implicitId)) {
throw corruptConversation(sessionId, `duplicate document entry at line ${index + 2}`);
}
documentEntryIds.add(implicitId);
}
}
eventRecords.push(eventRecord);
conversationRecords.push(eventRecord);
}
const initialSeed = seed ?? continuationSeed ?? importSeed;
if (initialSeed) {
try {
assertConversationDocumentGraph(
initialSeed.entries as readonly ConversationDocumentEntry[],
initialSeed.activeLeafId,
);
} catch (error) {
throw corruptConversation(sessionId, "invalid conversation seed graph", error);
}
}
return { header, seed, continuationSeed, importSeed, records: conversationRecords, eventRecords };
}
function documentOperationEntryId(record: ConversationDocumentOperationRecord): string | undefined {
switch (record.command.type) {
case "branch_summary.append":
case "custom.append":
case "entry.label.set":
return record.command.entryId;
default:
return undefined;
}
}
export function validateConversationEvent(sessionId: string, event: StoredSessionEvent): void {
if (!isStoredSessionEvent(event)) {
const issue = getStoredSessionEventValidationIssue(event);
const eventLabel = issue?.eventType ? ` ${issue.eventType}` : "";
const diagnostic = issue ? ` at ${issue.path}: ${issue.message}` : "";
throw new ConversationStorageError(
CONVERSATION_STORAGE_ERROR_CODES.INVALID_EVENT,
`Stored${eventLabel} event for ${sessionId} does not match the schema${diagnostic}`,
);
}
if (event.sessionId !== sessionId) {
throw new ConversationStorageError(
CONVERSATION_STORAGE_ERROR_CODES.INVALID_EVENT,
`Event session ${event.sessionId} does not match ${sessionId}`,
);
}
}
export function encodeConversationSessionId(sessionId: string): string {
return Buffer.from(sessionId, "utf8").toString("base64url");
}
export function serializeConversationLine(
value:
| ConversationFileHeader
| ConversationEventRecord
| NormalizedReadConversationEventRecord
| ConversationContinuationSeedRecord
| ConversationImportSeedRecord
| ConversationSeedRecord
| ConversationDocumentOperationRecord,
): string {
return `${JSON.stringify(value)}\n`;
}
export function conversationFromFile(sessionId: string, file: ParsedConversationFile): StoredConversation {
const events = file.eventRecords.map((record) => record.event);
const document = documentFromFile(sessionId, file);
return {
sessionId,
createdAt: file.header.createdAt,
version: events.length,
messages: selectConversationDocumentModelMessages(document),
events,
};
}
export function documentFromFile(sessionId: string, file: ParsedConversationFile): ConversationDocument {
const identity = {
sessionId,
createdAt: file.header.createdAt,
...(file.header.schemaVersion === CONVERSATION_SCHEMA_VERSION
? {
agentId: file.header.agentId,
cwd: file.header.cwd,
parentSessionPath: file.header.parentSessionPath,
parentEntryId: file.header.parentEntryId,
}
: {}),
};
try {
const initialSeed = file.seed ?? file.continuationSeed ?? file.importSeed;
let document = initialSeed
? createSeededConversationDocument(
identity,
initialSeed.entries as readonly ConversationDocumentEntry[],
initialSeed.activeLeafId,
)
: createEmptyConversationDocument(identity);
const seedName = file.seed?.name ?? file.importSeed?.name;
if (seedName !== undefined) {
document = { ...document, name: seedName };
}
return replayConversationRecords(document, file.records);
} catch (error) {
throw corruptConversation(sessionId, "invalid conversation document projection", error);
}
}
/**
* 解析接在一份已校验文件之后的整行记录,事件按与整份解析相同的规则校验版本、序号与内容。
* 种子记录只允许出现在文件开头,遇到时返回 undefined,调用方回退整份解析;格式错误直接抛出。
* 文档节点的重复与父节点检查留给 {@link extendDocumentWithRecords} 的重放。
*/
export function parseAppendedConversationRecords(
text: string,
sessionId: string,
header: ReadConversationFileHeader,
expectedEventSequence: number,
): { readonly records: ConversationBodyRecord[]; readonly nextEventSequence: number } | undefined {
const records: ConversationBodyRecord[] = [];
let nextEventSequence = expectedEventSequence;
for (const record of parseRecords(text, sessionId)) {
if (isConversationDocumentOperationRecord(record)) {
if (header.schemaVersion !== CONVERSATION_SCHEMA_VERSION) return undefined;
records.push(record);
continue;
}
const eventRecord = readConversationEventRecord(record);
if (!eventRecord) return undefined;
if (eventRecord.schemaVersion !== header.schemaVersion || eventRecord.sequence !== nextEventSequence) {
return undefined;
}
validateConversationEvent(sessionId, eventRecord.event);
if (
eventRecord.schemaVersion === CONVERSATION_SCHEMA_VERSION &&
(eventRecord.documentEntry !== null) !==
(conversationDocumentEntryPersistence(eventRecord.event) === "reference")
) {
return undefined;
}
nextEventSequence += 1;
records.push(eventRecord);
}
return { records, nextEventSequence };
}
/** 在已有文档投影上按读盘规则重放记录;增量追加与整份投影共用,保证两条路径结果一致。 */
export function extendDocumentWithRecords(
sessionId: string,
document: ConversationDocument,
records: readonly ConversationBodyRecord[],
): ConversationDocument {
try {
return replayConversationRecords(document, records);
} catch (error) {
throw corruptConversation(sessionId, "invalid conversation document projection", error);
}
}
function replayConversationRecords(
initial: ConversationDocument,
records: readonly ConversationBodyRecord[],
): ConversationDocument {
let document = initial;
for (const record of records) {
if (record.recordType === "conversation.event") {
const reference = record.schemaVersion === CONVERSATION_SCHEMA_VERSION ? record.documentEntry : undefined;
document = applyStoredEventToConversationDocument(
document,
record.event,
record.sequence,
reference ?? undefined,
);
continue;
}
const result = applyConversationDocumentCommand(document, record.command, record.revision);
if (!result.changed) throw new Error(`Document operation ${record.revision} is a persisted no-op`);
document = result.document;
}
return document;
}
export function createDocumentEntryReference(
event: StoredSessionEvent,
sequence: number,
parentId: string | null,
): ConversationDocumentEntryReference | null {
if (conversationDocumentEntryPersistence(event) !== "reference") return null;
return {
id: nativeConversationEntryId(sequence),
parentId,
timestamp: new Date(event.timestamp).toISOString(),
};
}
function parseRecords(text: string, sessionId: string): unknown[] {
if (!text.endsWith("\n")) {
throw corruptConversation(sessionId, "file does not end with a complete record");
}
const lines = text.slice(0, -1).split(/\r?\n/);
if (lines.some((line) => line.length === 0)) {
throw corruptConversation(sessionId, "file contains an empty record");
}
return lines.map((line, index) => {
try {
const parsed: unknown = JSON.parse(line);
return parsed;
} catch (error) {
throw corruptConversation(sessionId, `invalid JSON at line ${index + 1}`, error);
}
});
}
function corruptConversation(sessionId: string, details: string, cause?: unknown): ConversationStorageError {
return new ConversationStorageError(
CONVERSATION_STORAGE_ERROR_CODES.CORRUPT,
`Conversation ${sessionId} is corrupt: ${details}`,
cause === undefined ? undefined : { cause },
);
}