Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero): add local Claude Code / Codex session import backend (#17051)

Arvin Xu9aa8598d6fd8
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 15f621a316f..ab13e2d88ce 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -1,5 +1,7 @@
import {
chatTopicStatusSchema,
+ type HeteroSessionImportPayload,
+ heteroSessionImportPayloadSchema,
type RecentTopic,
type RecentTopicGroup,
type RecentTopicGroupMember,
@@ -19,6 +21,7 @@ import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
+import { HeteroSessionImporterRepo } from '@/database/repositories/heteroSessionImporter';
import { TopicImporterRepo } from '@/database/repositories/topicImporter';
import { chatGroups } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
@@ -43,6 +46,7 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
agentOperationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),
chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
+ heteroSessionImporterRepo: new HeteroSessionImporterRepo(ctx.serverDB, ctx.userId, wsId),
topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),
@@ -386,6 +390,33 @@ export const topicRouter = router({
return (await ctx.topicModel.count()) === 0;
}),
+ getHeteroSessionImportStatus: topicProcedure
+ .input(
+ z.object({
+ sessions: z.array(z.object({ sessionId: z.string(), topicClientId: z.string() })),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.heteroSessionImporterRepo.getImportStatus(input.sessions);
+ }),
+
+ importHeteroSessions: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ groupId: z.string().nullish(),
+ sessions: z.array(heteroSessionImportPayloadSchema),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.heteroSessionImporterRepo.importSessions({
+ agentId: input.agentId,
+ groupId: input.groupId,
+ sessions: input.sessions as HeteroSessionImportPayload[],
+ });
+ }),
+
importTopic: topicProcedure
.use(withScopedPermission('topic:create'))
.input(
diff --git a/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts
new file mode 100644
index 00000000000..035c1f74723
--- /dev/null
+++ b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts
@@ -0,0 +1,406 @@
+import type { HeteroSessionImportPayload } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agents,
+ messagePlugins,
+ messages,
+ threads,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { HeteroSessionImporterRepo } from '../index';
+
+const userId = 'session-importer-user';
+const agentId = 'session-importer-agent';
+let serverDB: LobeChatDatabase;
+
+const basePayload = (): HeteroSessionImportPayload => ({
+ messages: [
+ {
+ clientId: 'cc-s1-u1',
+ content: 'hello',
+ createdAt: '2026-07-01T00:00:00.000Z',
+ role: 'user',
+ },
+ {
+ clientId: 'cc-s1-a1',
+ content: 'running a tool',
+ createdAt: '2026-07-01T00:00:01.000Z',
+ metadata: { heteroMessageId: 'msg_1', heteroSessionId: 's1' },
+ model: 'claude-opus-4-8',
+ parentClientId: 'cc-s1-u1',
+ provider: 'claude-code',
+ reasoning: { content: 'thinking...' },
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tool_1',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ usage: { totalInputTokens: 5, totalOutputTokens: 7, totalTokens: 12 },
+ },
+ {
+ clientId: 'cc-s1-r1',
+ content: 'file list',
+ createdAt: '2026-07-01T00:00:02.000Z',
+ parentClientId: 'cc-s1-a1',
+ plugin: {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ role: 'tool',
+ toolCallId: 'tool_1',
+ },
+ ],
+ metadata: {
+ heteroSessionId: 's1',
+ heteroSessionIdByWorkingDirectory: { '/repo': 's1' },
+ importedFrom: 'claude-code-local',
+ },
+ sessionId: 's1',
+ source: 'claude-code',
+ title: 'Session One',
+ topicClientId: 'cc-session-s1',
+});
+
+describe('HeteroSessionImporterRepo.importSessions', () => {
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }]);
+ await tx.insert(agents).values({ id: agentId, title: 'Test Agent', userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ it('imports a session as topic + messages + plugin rows with clientIds', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [result] = await repo.importSessions({ agentId, sessions: [basePayload()] });
+
+ expect(result.created).toBe(true);
+ expect(result.insertedMessages).toBe(3);
+ expect(result.skippedMessages).toBe(0);
+
+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, result.topicId));
+ expect(topic.clientId).toBe('cc-session-s1');
+ expect(topic.title).toBe('Session One');
+ expect((topic.metadata as any).heteroSessionId).toBe('s1');
+
+ const rows = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.topicId, result.topicId))
+ .orderBy(messages.createdAt);
+ expect(rows).toHaveLength(3);
+ expect(rows.map((r) => r.role)).toEqual(['user', 'assistant', 'tool']);
+ expect(rows[1].parentId).toBe(rows[0].id);
+ expect(rows[2].parentId).toBe(rows[1].id);
+ expect(rows[1].usage).toEqual({ totalInputTokens: 5, totalOutputTokens: 7, totalTokens: 12 });
+ expect(rows[1].tools).toHaveLength(1);
+ expect(rows.map((r) => r.clientId)).toEqual(['cc-s1-u1', 'cc-s1-a1', 'cc-s1-r1']);
+
+ const [pluginRow] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, rows[2].id));
+ expect(pluginRow.toolCallId).toBe('tool_1');
+ expect(pluginRow.apiName).toBe('Bash');
+ });
+
+ it('is idempotent: re-importing the same payload inserts nothing', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ await repo.importSessions({ agentId, sessions: [basePayload()] });
+ const [second] = await repo.importSessions({ agentId, sessions: [basePayload()] });
+
+ expect(second.created).toBe(false);
+ expect(second.insertedMessages).toBe(0);
+ expect(second.skippedMessages).toBe(3);
+
+ const rows = await serverDB
+ .select()
+ .from(messages)
+ .where(and(eq(messages.userId, userId)));
+ expect(rows).toHaveLength(3);
+ });
+
+ it('imports incrementally: a grown transcript only inserts the new tail', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [first] = await repo.importSessions({ agentId, sessions: [basePayload()] });
+
+ const grown = basePayload();
+ grown.messages.push({
+ clientId: 'cc-s1-a2',
+ content: 'follow-up answer',
+ createdAt: '2026-07-01T00:00:03.000Z',
+ parentClientId: 'cc-s1-r1',
+ provider: 'claude-code',
+ role: 'assistant',
+ });
+ const [second] = await repo.importSessions({ agentId, sessions: [grown] });
+
+ expect(second.created).toBe(false);
+ expect(second.topicId).toBe(first.topicId);
+ expect(second.insertedMessages).toBe(1);
+ expect(second.skippedMessages).toBe(3);
+
+ const rows = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.topicId, first.topicId))
+ .orderBy(messages.createdAt);
+ expect(rows).toHaveLength(4);
+ // new tail's parentId resolves to the PRE-EXISTING tool message row
+ expect(rows[3].parentId).toBe(rows[2].id);
+ });
+
+ it('imports subagent transcripts as threads under the session topic', async () => {
+ const payload = basePayload();
+ payload.threads = [
+ {
+ clientId: 'cc-s1-agent-x',
+ messages: [
+ {
+ clientId: 'cc-s1-agent-x-u1',
+ content: 'subagent prompt',
+ role: 'user',
+ },
+ {
+ clientId: 'cc-s1-agent-x-a1',
+ content: 'subagent answer',
+ parentClientId: 'cc-s1-agent-x-u1',
+ provider: 'claude-code',
+ role: 'assistant',
+ },
+ ],
+ sourceMessageClientId: 'cc-s1-r1',
+ title: 'Explore something',
+ type: 'standalone',
+ },
+ ];
+
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [result] = await repo.importSessions({ agentId, sessions: [payload] });
+
+ expect(result.insertedThreads).toBe(1);
+ expect(result.insertedMessages).toBe(5);
+
+ const [threadRow] = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.topicId, result.topicId));
+ expect(threadRow.clientId).toBe('cc-s1-agent-x');
+ expect(threadRow.type).toBe('standalone');
+
+ const threadMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.threadId, threadRow.id))
+ .orderBy(messages.createdAt);
+ expect(threadMessages).toHaveLength(2);
+ // thread hangs on the main-chain tool message
+ const [sourceRow] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.clientId, 'cc-s1-r1'));
+ expect(threadRow.sourceMessageId).toBe(sourceRow.id);
+
+ // re-import: thread and its messages are skipped
+ const [second] = await repo.importSessions({ agentId, sessions: [payload] });
+ expect(second.insertedThreads).toBe(0);
+ expect(second.insertedMessages).toBe(0);
+ });
+
+ it('keeps message order when the source repeats identical timestamps', async () => {
+ // Codex rewrites resumed history with identical timestamps; the UI sorts by
+ // createdAt, so the importer must keep timestamps strictly increasing
+ const payload = basePayload();
+ const sameTs = '2026-07-01T00:00:00.000Z';
+ for (const m of payload.messages) m.createdAt = sameTs;
+
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [result] = await repo.importSessions({ agentId, sessions: [payload] });
+
+ const rows = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.topicId, result.topicId))
+ .orderBy(messages.createdAt);
+ expect(rows.map((r) => r.clientId)).toEqual(['cc-s1-u1', 'cc-s1-a1', 'cc-s1-r1']);
+ expect(rows[1].createdAt.getTime()).toBeGreaterThan(rows[0].createdAt.getTime());
+ expect(rows[2].createdAt.getTime()).toBeGreaterThan(rows[1].createdAt.getTime());
+ });
+
+ it('records the source-transcript end timestamp for syncable detection', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const [first] = await repo.importSessions({ agentId, sessions: [basePayload()] });
+
+ let [topic] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId));
+ expect((topic.metadata as any).heteroSourceEndAt).toBe('2026-07-01T00:00:02.000Z');
+
+ // incremental import with a newer tail advances the fingerprint
+ const grown = basePayload();
+ grown.messages.push({
+ clientId: 'cc-s1-a2',
+ content: 'later',
+ createdAt: '2026-07-02T00:00:00.000Z',
+ parentClientId: 'cc-s1-r1',
+ role: 'assistant',
+ });
+ await repo.importSessions({ agentId, sessions: [grown] });
+
+ [topic] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId));
+ expect((topic.metadata as any).heteroSourceEndAt).toBe('2026-07-02T00:00:00.000Z');
+ });
+
+ it('persists the transcript workingDirectory on create and on incremental update', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const payload = { ...basePayload(), workingDirectory: '/repo' };
+ const [first] = await repo.importSessions({ agentId, sessions: [payload] });
+
+ const [created] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId));
+ expect((created.metadata as any).workingDirectory).toBe('/repo');
+
+ // the session later moves cwd (e.g. worktree) — re-import refreshes the binding
+ await repo.importSessions({
+ agentId,
+ sessions: [{ ...basePayload(), workingDirectory: '/repo/worktree' }],
+ });
+ const [updated] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId));
+ expect((updated.metadata as any).workingDirectory).toBe('/repo/worktree');
+ expect((updated.metadata as any).heteroSessionId).toBe('s1');
+ });
+
+ it('scopes lookups to the active workspace and rejects cross-scope re-imports', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: 'ws-1', name: 'Team', primaryOwnerId: userId, slug: 'team-ws' });
+ const personalRepo = new HeteroSessionImporterRepo(serverDB, userId);
+ const workspaceRepo = new HeteroSessionImporterRepo(serverDB, userId, 'ws-1');
+
+ const [personal] = await personalRepo.importSessions({ agentId, sessions: [basePayload()] });
+
+ // (clientId, userId) is globally unique: importing the same session from a
+ // workspace must NOT silently append to the personal topic — it rejects
+ // with the owning scope instead
+ await expect(
+ workspaceRepo.importSessions({ agentId, sessions: [basePayload()] }),
+ ).rejects.toThrow('personal space');
+ const personalRows = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.topicId, personal.topicId));
+ expect(personalRows).toHaveLength(3);
+ expect(personalRows.every((r) => r.workspaceId === null)).toBe(true);
+
+ // a session imported IN the workspace lands there and stays scope-local
+ const wsPayload = basePayload();
+ wsPayload.sessionId = 's2';
+ wsPayload.topicClientId = 'cc-session-s2';
+ for (const m of wsPayload.messages) {
+ m.clientId = `ws-${m.clientId}`;
+ if (m.parentClientId) m.parentClientId = `ws-${m.parentClientId}`;
+ }
+ const [team] = await workspaceRepo.importSessions({ agentId, sessions: [wsPayload] });
+ expect(team.created).toBe(true);
+
+ // status badges are scoped: each side only reports its own scope's topics
+ const wanted = [
+ { sessionId: 's1', topicClientId: 'cc-session-s1' },
+ { sessionId: 's2', topicClientId: 'cc-session-s2' },
+ ];
+ const personalStatus = await personalRepo.getImportStatus(wanted);
+ const teamStatus = await workspaceRepo.getImportStatus(wanted);
+ expect(personalStatus.imported.map((i) => i.topicId)).toEqual([personal.topicId]);
+ expect(teamStatus.imported.map((i) => i.topicId)).toEqual([team.topicId]);
+ });
+
+ it('seeds incremental timestamps past the already-imported tail', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ // codex-style: every record repeats the same source timestamp
+ const t = '2026-07-01T00:00:00.000Z';
+ const flat = basePayload();
+ for (const m of flat.messages) m.createdAt = t;
+ await repo.importSessions({ agentId, sessions: [flat] });
+
+ const grown = basePayload();
+ for (const m of grown.messages) m.createdAt = t;
+ grown.messages.push({
+ clientId: 'cc-s1-a2',
+ content: 'synced follow-up',
+ createdAt: t,
+ parentClientId: 'cc-s1-r1',
+ role: 'assistant',
+ });
+ const [second] = await repo.importSessions({ agentId, sessions: [grown] });
+ expect(second.insertedMessages).toBe(1);
+
+ const rows = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.topicId, second.topicId))
+ .orderBy(messages.createdAt);
+ // the synced tail must sort AFTER the rows bumped to t+1, t+2 on first import
+ expect(rows.map((r) => r.clientId)).toEqual(['cc-s1-u1', 'cc-s1-a1', 'cc-s1-r1', 'cc-s1-a2']);
+ });
+
+ describe('getImportStatus', () => {
+ it('reports imported topics and flags LobeHub-originated sessions as linked', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ await repo.importSessions({ agentId, sessions: [basePayload()] });
+ // a live-run topic carries heteroSessionId in metadata but has no import clientId
+ await serverDB.insert(topics).values({
+ agentId,
+ id: 'tpc_live_run',
+ metadata: { heteroSessionId: 's-live' },
+ title: 'live run',
+ userId,
+ });
+
+ const status = await repo.getImportStatus([
+ { sessionId: 's1', topicClientId: 'cc-session-s1' },
+ { sessionId: 's-live', topicClientId: 'cc-session-s-live' },
+ { sessionId: 's-none', topicClientId: 'cc-session-s-none' },
+ ]);
+
+ expect(status.imported).toHaveLength(1);
+ expect(status.imported[0]).toMatchObject({
+ messageCount: 3,
+ sourceEndAt: '2026-07-01T00:00:02.000Z',
+ topicClientId: 'cc-session-s1',
+ });
+ expect(status.linked).toEqual(['s-live']);
+ });
+ });
+
+ it('keeps sessions independent: one failing session does not roll back others', async () => {
+ const repo = new HeteroSessionImporterRepo(serverDB, userId);
+ const bad = basePayload();
+ bad.sessionId = 's2';
+ bad.topicClientId = 'cc-session-s2';
+ // force a failure: message referencing an agent that does not exist
+ const ok = basePayload();
+
+ const results = await repo
+ .importSessions({ agentId: 'missing-agent', sessions: [bad] })
+ .catch(() => null);
+ expect(results).toBeNull();
+
+ const [okResult] = await repo.importSessions({ agentId, sessions: [ok] });
+ expect(okResult.insertedMessages).toBe(3);
+ });
+});
diff --git a/packages/database/src/repositories/heteroSessionImporter/index.ts b/packages/database/src/repositories/heteroSessionImporter/index.ts
new file mode 100644
index 00000000000..c160a79d8cf
--- /dev/null
+++ b/packages/database/src/repositories/heteroSessionImporter/index.ts
@@ -0,0 +1,376 @@
+import type {
+ HeteroSessionImportMessage,
+ HeteroSessionImportPayload,
+ HeteroSessionImportResult,
+ HeteroSessionImportStatus,
+} from '@lobechat/types';
+import { and, count, eq, inArray, or, sql } from 'drizzle-orm';
+
+import { messagePlugins, messages, threads, topics } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { idGenerator } from '../../utils/idGenerator';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+export interface ImportHeteroSessionsParams {
+ agentId: string;
+ groupId?: string | null;
+ /** normalized payloads produced by `@lobechat/heterogeneous-agents/transcript` */
+ sessions: HeteroSessionImportPayload[];
+}
+
+const BATCH_SIZE = 100;
+
+/**
+ * Dedicated importer for external CLI agent sessions (Claude Code / Codex
+ * local transcripts).
+ *
+ * Unlike `TopicImporterRepo` (generic user-facing JSON import, always creates
+ * a new topic), this importer is IDEMPOTENT and INCREMENTAL:
+ * - every entity carries a deterministic `clientId` derived from the source
+ * transcript; the `(clientId, userId)` unique indexes make re-imports skip
+ * existing rows
+ * - importing a session whose topic already exists only inserts the new
+ * messages (the transcript grew since the last import), rebuilding
+ * `parentId` references across old and new rows
+ * - subagent transcripts import as threads under the session topic
+ */
+export class HeteroSessionImporterRepo {
+ private userId: string;
+ private db: LobeChatDatabase;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.userId = userId;
+ this.db = db;
+ this.workspaceId = workspaceId;
+ }
+
+ /**
+ * Workspace-aware ownership predicate: lookups must stay inside the active
+ * personal/team scope, or importing from a workspace would reuse (and append
+ * to) a topic the same user already imported in another scope.
+ */
+ private scopeWhere = (cols: { userId: any; workspaceId: any }) =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);
+
+ importSessions = async (
+ params: ImportHeteroSessionsParams,
+ ): Promise<HeteroSessionImportResult[]> => {
+ const results: HeteroSessionImportResult[] = [];
+ // one transaction per session: a corrupt session must not roll back the batch
+ for (const session of params.sessions) {
+ results.push(await this.importSession(session, params.agentId, params.groupId));
+ }
+ return results;
+ };
+
+ importSession = async (
+ session: HeteroSessionImportPayload,
+ agentId: string,
+ groupId?: string | null,
+ ): Promise<HeteroSessionImportResult> =>
+ this.db.transaction(async (tx) => {
+ // the source transcript's last timestamp — the picker UI compares it with
+ // a fresh digest's endAt to detect "grew since last import" (message
+ // counts are NOT comparable across transcript records and DB rows)
+ const sourceEndAt = [
+ ...session.messages,
+ ...(session.threads ?? []).flatMap((t) => t.messages),
+ ].reduce<string | undefined>(
+ (max, m) => (m.createdAt && (!max || m.createdAt > max) ? m.createdAt : max),
+ undefined,
+ );
+
+ // hetero resume + project grouping read the bound cwd off
+ // `topic.metadata.workingDirectory` — persist the transcript cwd so
+ // imported topics resume/group under the directory they were recorded in
+ const metadataPatch = {
+ ...(sourceEndAt ? { heteroSourceEndAt: sourceEndAt } : {}),
+ ...(session.workingDirectory ? { workingDirectory: session.workingDirectory } : {}),
+ };
+
+ // 1. find or create the topic by clientId within the active scope
+ const [existingTopic] = await tx
+ .select({ id: topics.id, metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.clientId, session.topicClientId), this.scopeWhere(topics)));
+
+ // the (clientId, userId) unique index makes one session = one topic per
+ // user GLOBALLY — if it exists outside the active scope, appending there
+ // would leak content across scopes and inserting here would violate the
+ // index. Reject explicitly with the reason instead.
+ if (!existingTopic) {
+ const [foreignTopic] = await tx
+ .select({ id: topics.id, workspaceId: topics.workspaceId })
+ .from(topics)
+ .where(and(eq(topics.clientId, session.topicClientId), eq(topics.userId, this.userId)));
+ if (foreignTopic) {
+ throw new Error(
+ `session ${session.sessionId} is already imported in ${
+ foreignTopic.workspaceId ? `workspace ${foreignTopic.workspaceId}` : 'personal space'
+ }; switch to that scope to sync it`,
+ );
+ }
+ }
+
+ let topicId = existingTopic?.id;
+ const created = !existingTopic;
+ if (topicId) {
+ if (Object.keys(metadataPatch).length > 0)
+ await tx
+ .update(topics)
+ .set({ metadata: { ...existingTopic.metadata, ...metadataPatch } })
+ .where(eq(topics.id, topicId));
+ } else {
+ topicId = idGenerator('topics');
+ await tx.insert(topics).values({
+ agentId,
+ clientId: session.topicClientId,
+ groupId: groupId || null,
+ id: topicId,
+ metadata: { ...session.metadata, ...metadataPatch },
+ title: session.title || 'Imported Session',
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ });
+ }
+
+ // 2. load existing message clientIds of this session (incremental base)
+ const existingRows = existingTopic
+ ? await tx
+ .select({
+ clientId: messages.clientId,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ threadId: messages.threadId,
+ })
+ .from(messages)
+ .where(and(eq(messages.topicId, topicId), this.scopeWhere(messages)))
+ : [];
+ const clientIdToDbId = new Map<string, string>();
+ for (const row of existingRows) if (row.clientId) clientIdToDbId.set(row.clientId, row.id);
+
+ // incremental syncs must continue AFTER the already-imported tail: the
+ // first import may have bumped identical source timestamps to t+1, t+2…,
+ // so a fresh batch seeded at the raw source time would sort before them
+ const maxExistingTs = (threadId: string | null) =>
+ existingRows.reduce(
+ (max: number, row: (typeof existingRows)[number]) =>
+ row.threadId === threadId && row.createdAt && row.createdAt.getTime() > max
+ ? row.createdAt.getTime()
+ : max,
+ 0,
+ );
+
+ // 3. insert main-chain messages
+ const mainStats = await this.insertMessages(tx, {
+ agentId,
+ clientIdToDbId,
+ importMessages: session.messages,
+ seedTs: maxExistingTs(null),
+ topicId,
+ });
+
+ // 4. threads (subagent transcripts)
+ let insertedThreads = 0;
+ for (const thread of session.threads ?? []) {
+ const [existingThread] = await tx
+ .select({ id: threads.id })
+ .from(threads)
+ .where(and(eq(threads.clientId, thread.clientId), this.scopeWhere(threads)));
+
+ let threadId = existingThread?.id;
+ if (!threadId) {
+ threadId = idGenerator('threads', 16);
+ await tx.insert(threads).values({
+ agentId,
+ clientId: thread.clientId,
+ id: threadId,
+ sourceMessageId: thread.sourceMessageClientId
+ ? (clientIdToDbId.get(thread.sourceMessageClientId) ?? null)
+ : null,
+ status: thread.status ?? 'completed',
+ title: thread.title?.slice(0, 200) ?? null,
+ topicId,
+ type: thread.type,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ });
+ insertedThreads++;
+ }
+
+ const threadStats = await this.insertMessages(tx, {
+ agentId,
+ clientIdToDbId,
+ importMessages: thread.messages,
+ seedTs: existingThread ? maxExistingTs(threadId) : 0,
+ threadId,
+ topicId,
+ });
+ mainStats.inserted += threadStats.inserted;
+ mainStats.skipped += threadStats.skipped;
+ }
+
+ return {
+ created,
+ insertedMessages: mainStats.inserted,
+ insertedThreads,
+ sessionId: session.sessionId,
+ skippedMessages: mainStats.skipped,
+ topicId,
+ };
+ });
+
+ private insertMessages = async (
+ tx: any,
+ params: {
+ agentId: string;
+ /** shared across main chain + threads; mutated with newly assigned ids */
+ clientIdToDbId: Map<string, string>;
+ importMessages: HeteroSessionImportMessage[];
+ /** max createdAt (ms) of the already-imported rows in this chain */
+ seedTs?: number;
+ threadId?: string;
+ topicId: string;
+ },
+ ): Promise<{ inserted: number; skipped: number }> => {
+ const { agentId, clientIdToDbId, importMessages, threadId, topicId } = params;
+
+ const fresh = importMessages.filter((m) => !clientIdToDbId.has(m.clientId));
+ const skipped = importMessages.length - fresh.length;
+ if (fresh.length === 0) return { inserted: 0, skipped };
+
+ // assign db ids first so parent references resolve across old + new rows
+ for (const m of fresh) clientIdToDbId.set(m.clientId, idGenerator('messages'));
+
+ // Codex rewrites resumed history with IDENTICAL timestamps, and the UI
+ // orders by createdAt — keep timestamps strictly increasing within a batch
+ // (seeded past the already-imported tail) so the transcript order survives
+ // the sort even across incremental syncs
+ const now = Date.now();
+ let lastTs = params.seedTs ?? 0;
+ const messageRows = fresh.map((m, index) => {
+ const parsedTs = m.createdAt ? new Date(m.createdAt).getTime() : now + index;
+ const ts = Math.max(parsedTs, lastTs + 1);
+ lastTs = ts;
+ const timestamp = new Date(ts);
+ return {
+ agentId,
+ clientId: m.clientId,
+ content: m.content,
+ createdAt: timestamp,
+ id: clientIdToDbId.get(m.clientId)!,
+ metadata: m.metadata ?? null,
+ model: m.model ?? null,
+ parentId: m.parentClientId ? (clientIdToDbId.get(m.parentClientId) ?? null) : null,
+ provider: m.provider ?? null,
+ reasoning: m.reasoning ?? null,
+ role: m.role,
+ threadId: threadId ?? null,
+ tools: m.tools ?? null,
+ topicId,
+ updatedAt: timestamp,
+ usage: m.usage ?? null,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ };
+ });
+
+ const pluginRows = fresh
+ .filter((m) => m.plugin || m.toolCallId)
+ .map((m) => ({
+ apiName: m.plugin?.apiName ?? null,
+ arguments: m.plugin?.arguments ?? null,
+ clientId: m.clientId,
+ id: clientIdToDbId.get(m.clientId)!,
+ identifier: m.plugin?.identifier ?? null,
+ state: m.pluginState ?? null,
+ toolCallId: m.toolCallId ?? null,
+ type: m.plugin?.type ?? null,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ }));
+
+ for (let i = 0; i < messageRows.length; i += BATCH_SIZE) {
+ await tx.insert(messages).values(messageRows.slice(i, i + BATCH_SIZE));
+ }
+ for (let i = 0; i < pluginRows.length; i += BATCH_SIZE) {
+ await tx.insert(messagePlugins).values(pluginRows.slice(i, i + BATCH_SIZE));
+ }
+
+ return { inserted: fresh.length, skipped };
+ };
+
+ /**
+ * Import status of local sessions, for the picker UI badges:
+ * - `imported`: a topic with the session's clientId exists (re-import = incremental sync)
+ * - `linked`: a topic carries the sessionId in `metadata.heteroSessionId` but was NOT
+ * imported — the session originated from a LobeHub live run and importing it
+ * would duplicate the conversation
+ */
+ getImportStatus = async (
+ sessions: { sessionId: string; topicClientId: string }[],
+ ): Promise<HeteroSessionImportStatus> => {
+ if (sessions.length === 0) return { imported: [], linked: [] };
+
+ const clientIds = sessions.map((s) => s.topicClientId);
+ const sessionIds = sessions.map((s) => s.sessionId);
+ const metadataSessionId = sql<string>`${topics.metadata}->>'heteroSessionId'`;
+ const metadataSourceEndAt = sql<string>`${topics.metadata}->>'heteroSourceEndAt'`;
+
+ const rows = await this.db
+ .select({
+ clientId: topics.clientId,
+ id: topics.id,
+ metaSessionId: metadataSessionId,
+ sourceEndAt: metadataSourceEndAt,
+ })
+ .from(topics)
+ .where(
+ and(
+ this.scopeWhere(topics),
+ or(inArray(topics.clientId, clientIds), inArray(metadataSessionId, sessionIds)),
+ ),
+ );
+
+ const wantedClientIds = new Set(clientIds);
+ const importedRows = rows.filter((r) => r.clientId && wantedClientIds.has(r.clientId));
+
+ const messageCounts = new Map<string, number>();
+ if (importedRows.length > 0) {
+ const counts = await this.db
+ .select({ topicId: messages.topicId, total: count() })
+ .from(messages)
+ .where(
+ and(
+ this.scopeWhere(messages),
+ inArray(
+ messages.topicId,
+ importedRows.map((r) => r.id),
+ ),
+ ),
+ )
+ .groupBy(messages.topicId);
+ for (const row of counts) if (row.topicId) messageCounts.set(row.topicId, Number(row.total));
+ }
+
+ const importedClientIds = new Set(importedRows.map((r) => r.clientId));
+ const linked = [
+ ...new Set(
+ rows
+ .filter((r) => r.metaSessionId && !importedClientIds.has(r.clientId))
+ .map((r) => r.metaSessionId),
+ ),
+ ];
+
+ return {
+ imported: importedRows.map((r) => ({
+ messageCount: messageCounts.get(r.id) ?? 0,
+ sourceEndAt: r.sourceEndAt ?? undefined,
+ topicClientId: r.clientId!,
+ topicId: r.id,
+ })),
+ linked,
+ };
+ };
+}
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 97f5d9550eb..796e96bb74f 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -9,7 +9,8 @@
"./client": "./src/client/index.ts",
"./protocol": "./src/protocol/index.ts",
"./resolveCliCommand": "./src/spawn/resolveCliCommand.ts",
- "./spawn": "./src/spawn/index.ts"
+ "./spawn": "./src/spawn/index.ts",
+ "./transcript": "./src/transcript/index.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/packages/heterogeneous-agents/src/transcript/claudeCode.test.ts b/packages/heterogeneous-agents/src/transcript/claudeCode.test.ts
new file mode 100644
index 00000000000..05492c1ff93
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/claudeCode.test.ts
@@ -0,0 +1,325 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildClaudeCodeImportPayload,
+ parseClaudeCodeSession,
+ parseClaudeCodeSessionDigest,
+} from './claudeCode';
+
+const SESSION_ID = 'sess-0001';
+
+const line = (record: Record<string, any>) => JSON.stringify(record);
+
+const userRecord = (uuid: string, parentUuid: string | null, text: string, extra?: any) =>
+ line({
+ cwd: '/repo',
+ gitBranch: 'main',
+ isSidechain: false,
+ message: { content: [{ text, type: 'text' }], role: 'user' },
+ parentUuid,
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:00.000Z',
+ type: 'user',
+ uuid,
+ ...extra,
+ });
+
+const assistantRecord = (
+ uuid: string,
+ parentUuid: string,
+ msgId: string,
+ block: Record<string, any>,
+ extra?: any,
+) =>
+ line({
+ isSidechain: false,
+ message: {
+ content: [block],
+ id: msgId,
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 10, output_tokens: 20, service_tier: 'standard', speed: 'fast' },
+ },
+ parentUuid,
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:01.000Z',
+ type: 'assistant',
+ uuid,
+ ...extra,
+ });
+
+const toolResultRecord = (uuid: string, parentUuid: string, toolUseId: string, text: string) =>
+ line({
+ isSidechain: false,
+ message: {
+ content: [{ content: text, tool_use_id: toolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ parentUuid,
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:02.000Z',
+ type: 'user',
+ uuid,
+ });
+
+describe('parseClaudeCodeSession', () => {
+ it('merges assistant lines sharing message.id into one message', () => {
+ const transcript = [
+ userRecord('u1', null, 'hello'),
+ assistantRecord('a1', 'u1', 'msg_1', { thinking: 'let me think', type: 'thinking' }),
+ assistantRecord('a2', 'a1', 'msg_1', { text: 'the answer', type: 'text' }),
+ line({ leafUuid: 'a2', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ expect(result.messages).toHaveLength(2);
+ const assistant = result.messages[1];
+ expect(assistant.role).toBe('assistant');
+ expect(assistant.content).toBe('the answer');
+ expect(assistant.reasoning?.content).toBe('let me think');
+ expect(assistant.model).toBe('claude-opus-4-8');
+ expect(assistant.provider).toBe('claude-code');
+ // raw Anthropic usage is normalized into the ModelUsage shape; non-token
+ // extras (service_tier / speed) are relocated into metadata
+ expect(assistant.usage).toEqual({
+ inputCacheMissTokens: 10,
+ totalInputTokens: 10,
+ totalOutputTokens: 20,
+ totalTokens: 30,
+ });
+ expect(assistant.metadata?.serviceTier).toBe('standard');
+ expect(assistant.metadata?.speed).toBe('fast');
+ // heteroMessageId = the record's own uuid in the CC session file (first
+ // record of the merged group), NOT the reusable Anthropic API message.id
+ expect(assistant.metadata?.heteroMessageId).toBe('a1');
+ expect(result.messages[0].metadata?.heteroMessageId).toBe('u1');
+ expect(assistant.parentClientId).toBe(`claude-code-u1`);
+ });
+
+ it('skips signature-only empty thinking blocks instead of writing empty reasoning', () => {
+ const transcript = [
+ userRecord('u1', null, 'hello'),
+ assistantRecord('a1', 'u1', 'msg_1', { signature: 'sig==', thinking: '', type: 'thinking' }),
+ assistantRecord('a2', 'a1', 'msg_1', { text: 'the answer', type: 'text' }),
+ line({ leafUuid: 'a2', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ const assistant = result.messages[1];
+ expect(assistant.content).toBe('the answer');
+ expect(assistant.reasoning).toBeUndefined();
+ });
+
+ it('collects parallel tool_use results living on sibling branches of the trunk', () => {
+ // a2/a3 are two tool_use lines of the same assistant turn; r1 answers the
+ // first tool but hangs on a SIBLING branch (parent a2), while the trunk
+ // continues a2 -> a3 -> r2 -> a4
+ const transcript = [
+ userRecord('u1', null, 'run two things'),
+ assistantRecord('a2', 'u1', 'msg_1', {
+ id: 'tool_A',
+ input: { cmd: 'first' },
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ assistantRecord('a3', 'a2', 'msg_1', {
+ id: 'tool_B',
+ input: { cmd: 'second' },
+ name: 'Bash',
+ type: 'tool_use',
+ }),
+ toolResultRecord('r1', 'a2', 'tool_A', 'result A'),
+ toolResultRecord('r2', 'a3', 'tool_B', 'result B'),
+ assistantRecord('a4', 'r2', 'msg_2', { text: 'done', type: 'text' }),
+ line({ leafUuid: 'a4', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ const toolMessages = result.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(2);
+ expect(toolMessages.map((m) => m.content)).toEqual(['result A', 'result B']);
+ expect(toolMessages.map((m) => m.toolCallId)).toEqual(['tool_A', 'tool_B']);
+ // both tool messages hang on the merged assistant message
+ const assistant = result.messages.find((m) => (m.tools?.length ?? 0) > 0)!;
+ expect(assistant.tools).toHaveLength(2);
+ for (const toolMessage of toolMessages)
+ expect(toolMessage.parentClientId).toBe(assistant.clientId);
+ });
+
+ it('walks the trunk through meta records and picks the last-prompt leaf', () => {
+ // attachment record sits between user and assistant in the parent chain
+ const transcript = [
+ userRecord('u1', null, 'question'),
+ line({
+ isSidechain: false,
+ parentUuid: 'u1',
+ sessionId: SESSION_ID,
+ type: 'attachment',
+ uuid: 'att1',
+ }),
+ assistantRecord('a1', 'att1', 'msg_1', { text: 'abandoned branch', type: 'text' }),
+ assistantRecord('a2', 'att1', 'msg_2', { text: 'current branch', type: 'text' }),
+ line({ leafUuid: 'a2', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].content).toBe('current branch');
+ // the attachment is transparent: assistant parents to the user message
+ expect(result.messages[1].parentClientId).toBe(`claude-code-u1`);
+ });
+
+ it('strips NUL characters and replaces embedded images with placeholders', () => {
+ const nul = String.fromCodePoint(0);
+ const transcript = [
+ line({
+ isSidechain: false,
+ message: {
+ content: [
+ { text: `binary${nul}output`, type: 'text' },
+ {
+ source: { data: 'aGVsbG8=', media_type: 'image/png', type: 'base64' },
+ type: 'image',
+ },
+ ],
+ role: 'user',
+ },
+ parentUuid: null,
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:00.000Z',
+ type: 'user',
+ uuid: 'u1',
+ }),
+ assistantRecord('a1', 'u1', 'msg_1', { text: 'ok', type: 'text' }),
+ line({ leafUuid: 'a1', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ expect(result.messages[0].content).toContain('binaryoutput');
+ expect(result.messages[0].content).toContain('![imported image placeholder]');
+ expect(result.imageCount).toBe(1);
+ });
+
+ it('parses sidechain records when the sidechain option is set', () => {
+ const transcript = [
+ line({
+ agentId: 'sub1',
+ isSidechain: true,
+ message: { content: [{ text: 'subagent prompt', type: 'text' }], role: 'user' },
+ parentUuid: null,
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:00.000Z',
+ type: 'user',
+ uuid: 's1',
+ }),
+ line({
+ agentId: 'sub1',
+ isSidechain: true,
+ message: {
+ content: [{ text: 'subagent answer', type: 'text' }],
+ id: 'msg_s1',
+ model: 'claude-opus-4-8',
+ },
+ parentUuid: 's1',
+ sessionId: SESSION_ID,
+ timestamp: '2026-07-01T00:00:01.000Z',
+ type: 'assistant',
+ uuid: 's2',
+ }),
+ ].join('\n');
+
+ expect(parseClaudeCodeSession(transcript)).toBeNull();
+ const result = parseClaudeCodeSession(transcript, { sidechain: true })!;
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].content).toBe('subagent answer');
+ });
+
+ it('tolerates corrupt lines and unknown record types', () => {
+ const transcript = [
+ 'not json at all{{{',
+ line({ operation: 'enqueue', sessionId: SESSION_ID, type: 'queue-operation' }),
+ userRecord('u1', null, 'hi'),
+ assistantRecord('a1', 'u1', 'msg_1', { text: 'hello', type: 'text' }),
+ line({ leafUuid: 'a1', sessionId: SESSION_ID, type: 'last-prompt' }),
+ line({ some: 'future-record-type', type: 'shiny-new-thing' }),
+ ].join('\n');
+
+ const result = parseClaudeCodeSession(transcript)!;
+ expect(result.messages).toHaveLength(2);
+ });
+
+ it('returns null for transcripts without conversation', () => {
+ expect(parseClaudeCodeSession('')).toBeNull();
+ expect(
+ parseClaudeCodeSession(
+ line({ operation: 'enqueue', sessionId: SESSION_ID, type: 'queue-operation' }),
+ ),
+ ).toBeNull();
+ });
+});
+
+describe('buildClaudeCodeImportPayload', () => {
+ it('produces a payload with resume metadata and deterministic topic clientId', () => {
+ const transcript = [
+ userRecord('u1', null, 'hello'),
+ assistantRecord('a1', 'u1', 'msg_1', { text: 'hi', type: 'text' }),
+ line({ aiTitle: '打个招呼', sessionId: SESSION_ID, type: 'ai-title' }),
+ line({ leafUuid: 'a1', sessionId: SESSION_ID, type: 'last-prompt' }),
+ ].join('\n');
+
+ const payload = buildClaudeCodeImportPayload(transcript)!;
+ expect(payload.topicClientId).toBe(`claude-code-session-${SESSION_ID}`);
+ expect(payload.source).toBe('claude-code');
+ expect(payload.title).toBe('打个招呼');
+ expect(payload.metadata).toEqual({
+ heteroSessionId: SESSION_ID,
+ heteroSessionIdByWorkingDirectory: { '/repo': SESSION_ID },
+ importedFrom: 'claude-code-local',
+ });
+ });
+});
+
+describe('parseClaudeCodeSessionDigest', () => {
+ it('extracts list metadata without building the payload', () => {
+ const transcript = [
+ userRecord('u1', null, 'first question'),
+ assistantRecord('a1', 'u1', 'msg_1', { text: 'answer', type: 'text' }),
+ line({ aiTitle: 'Digest title', sessionId: SESSION_ID, type: 'ai-title' }),
+ ].join('\n');
+
+ const digest = parseClaudeCodeSessionDigest(transcript, '/tmp/x.jsonl')!;
+ expect(digest.sessionId).toBe(SESSION_ID);
+ expect(digest.title).toBe('Digest title');
+ expect(digest.firstPrompt).toBe('first question');
+ expect(digest.messageCount).toBe(2);
+ expect(digest.gitBranch).toBe('main');
+ expect(digest.workingDirectory).toBe('/repo');
+ expect(digest.source).toBe('claude-code');
+ expect(digest.tokens).toBe(30); // 10 input + 20 output
+ });
+
+ it('counts tokens once per assistant message.id despite one line per block', () => {
+ const transcript = [
+ userRecord('u1', null, 'q'),
+ assistantRecord('a1', 'u1', 'msg_1', { thinking: 't', type: 'thinking' }),
+ assistantRecord('a2', 'a1', 'msg_1', { text: 'a', type: 'text' }),
+ assistantRecord('a3', 'a2', 'msg_2', { text: 'b', type: 'text' }),
+ ].join('\n');
+
+ const digest = parseClaudeCodeSessionDigest(transcript, '/tmp/x.jsonl')!;
+ // msg_1 counted once (not twice), plus msg_2
+ expect(digest.tokens).toBe(60);
+ });
+
+ it('strips the injected Workspace preamble from title fallbacks', () => {
+ const preambled =
+ "## Workspace\nYou are running on the user's own machine. Your working directory is `/repo`.帮我修个 bug";
+ const transcript = [
+ userRecord('u1', null, preambled),
+ assistantRecord('a1', 'u1', 'msg_1', { text: 'ok', type: 'text' }),
+ ].join('\n');
+
+ const digest = parseClaudeCodeSessionDigest(transcript, '/tmp/x.jsonl')!;
+ expect(digest.firstPrompt).toBe('帮我修个 bug');
+ expect(digest.title).toBe('帮我修个 bug');
+ });
+});
diff --git a/packages/heterogeneous-agents/src/transcript/claudeCode.ts b/packages/heterogeneous-agents/src/transcript/claudeCode.ts
new file mode 100644
index 00000000000..7ee95c17fae
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/claudeCode.ts
@@ -0,0 +1,351 @@
+import type {
+ HeteroSessionDigest,
+ HeteroSessionImportMessage,
+ HeteroSessionImportPayload,
+ HeteroSessionImportToolCall,
+} from '@lobechat/types';
+
+import { parseJsonlRecords, stripNulDeep, toModelUsageFromAnthropic, truncateTitle } from './utils';
+
+/**
+ * Parser for Claude Code local session transcripts
+ * (`~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl`).
+ *
+ * Format notes (verified against real transcripts):
+ * - one JSON record per line; `user` / `assistant` records carry
+ * `uuid` / `parentUuid` / `isSidechain` / `sessionId` / `cwd` / `gitBranch` / `timestamp`
+ * - `assistant.message` is a full Anthropic API message; ONE LINE PER CONTENT BLOCK,
+ * consecutive lines share the same `message.id` and must be merged
+ * - the current trunk is the `parentUuid` ancestor chain of `last-prompt.leafUuid`;
+ * the chain passes through meta records (`attachment`, ...) as well
+ * - parallel tool_use results live on SIBLING branches of the trunk, so tool_results
+ * must be matched globally by `tool_use_id`, not collected from the chain
+ * - `ai-title` / `last-prompt` appear once per turn — the last one wins
+ * - Claude Code may REUSE an assistant `message.id` non-consecutively (post-tool
+ * text); uuid-based clientIds keep rows unique regardless
+ * - subagent transcripts live in `<sessionId>/subagents/agent-*.jsonl` with
+ * `isSidechain: true` records; parse them with `{ sidechain: true }`
+ */
+
+export const CLAUDE_CODE_IDENTIFIER = 'claude-code';
+
+export interface ParseClaudeCodeOptions {
+ /**
+ * Override the sessionId stamped into `metadata.heteroSessionId` (defaults
+ * to the transcript's own). Subagent transcripts carry the parent session.
+ */
+ sessionIdOverride?: string;
+ /**
+ * Parse sidechain (subagent) records instead of main-chain records.
+ * Used for `subagents/agent-*.jsonl` transcripts.
+ */
+ sidechain?: boolean;
+}
+
+interface ImageStats {
+ bytes: number;
+ count: number;
+}
+
+const textOfContent = (content: any, img?: ImageStats): string => {
+ if (typeof content === 'string') return content;
+ if (!Array.isArray(content)) return '';
+ return content
+ .map((block: any) => {
+ if (block?.type === 'text') return block.text;
+ if (block?.type === 'image') {
+ if (img) {
+ img.count++;
+ img.bytes += block.source?.data?.length ?? 0;
+ }
+ return '![imported image placeholder]';
+ }
+ return '';
+ })
+ .filter(Boolean)
+ .join('\n\n');
+};
+
+/**
+ * Claude Code prepends an injected `## Workspace` preamble to the first user
+ * message; strip it when the message doubles as the title / prompt preview.
+ */
+const CC_PREAMBLE_RE = /^##\s*workspace\b[\S\s]+?working directory is[^\n]*?\.\s*/i;
+const stripCcPreamble = (text: string): string => {
+ if (!/^##\s*workspace\b/i.test(text)) return text;
+ const stripped = text.replace(CC_PREAMBLE_RE, '').trim();
+ return stripped || text;
+};
+
+/** total input+output tokens, counted once per assistant message.id */
+const sumCcTokens = (records: any[]): number => {
+ let total = 0;
+ const seen = new Set<string>();
+ for (const r of records) {
+ if (r.type !== 'assistant' || r.isSidechain) continue;
+ const id = r.message?.id ?? r.uuid;
+ const usage = r.message?.usage;
+ if (!usage || seen.has(id)) continue;
+ seen.add(id);
+ total += (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0);
+ }
+ return total;
+};
+
+export interface ParsedClaudeCodeSession {
+ /** total base64 chars of embedded images replaced by placeholders */
+ imageBytes: number;
+ imageCount: number;
+ messages: HeteroSessionImportMessage[];
+ sessionId: string;
+ title?: string;
+ workingDirectory?: string;
+}
+
+/**
+ * Parse a Claude Code transcript into normalized import messages.
+ * Returns null when the transcript contains no importable conversation.
+ */
+export const parseClaudeCodeSession = (
+ content: string,
+ options?: ParseClaudeCodeOptions,
+): ParsedClaudeCodeSession | null => {
+ const sidechain = options?.sidechain ?? false;
+ const records = parseJsonlRecords(content);
+ if (records.length === 0) return null;
+
+ const matchesSide = (r: any) => Boolean(r.isSidechain) === sidechain;
+ const byUuid = new Map<string, any>();
+ for (const r of records) if (r.uuid) byUuid.set(r.uuid, r);
+
+ const aiTitle: string | undefined = records.findLast((r) => r.type === 'ai-title')?.aiTitle;
+ const lastPrompt = records.findLast((r) => r.type === 'last-prompt');
+ const firstUserRec = records.find((r) => r.type === 'user' && matchesSide(r));
+ const transcriptSessionId: string | undefined = records.find((r) => r.sessionId)?.sessionId;
+ const sessionId = options?.sessionIdOverride ?? transcriptSessionId;
+ if (!sessionId) return null;
+ const workingDirectory: string | undefined = records.find((r) => r.cwd)?.cwd;
+
+ const leafUuid: string | undefined =
+ lastPrompt?.leafUuid ??
+ records.findLast(
+ (r) => r.uuid && matchesSide(r) && (r.type === 'user' || r.type === 'assistant'),
+ )?.uuid;
+ if (!leafUuid) return null;
+
+ // walk the trunk leaf -> root; the chain passes through meta records too
+ const chain: any[] = [];
+ let cursor = byUuid.get(leafUuid);
+ const visited = new Set<string>();
+ while (cursor && cursor.uuid && !visited.has(cursor.uuid)) {
+ visited.add(cursor.uuid);
+ chain.unshift(cursor);
+ cursor = cursor.parentUuid ? byUuid.get(cursor.parentUuid) : undefined;
+ }
+
+ // index ALL tool_results by tool_use_id — parallel tool_use results are
+ // sibling branches of the trunk and would be lost by a pure ancestor walk
+ const toolResultByUseId = new Map<string, { block: any; record: any }>();
+ for (const r of records) {
+ if (r.type !== 'user' || !matchesSide(r) || !Array.isArray(r.message?.content)) continue;
+ for (const block of r.message.content) {
+ if (block?.type === 'tool_result' && block.tool_use_id)
+ toolResultByUseId.set(block.tool_use_id, { block, record: r });
+ }
+ }
+
+ const img: ImageStats = { bytes: 0, count: 0 };
+ const messages: HeteroSessionImportMessage[] = [];
+ let prevClientId: string | null = null;
+ // record uuids are globally unique across session files (CC forks generate
+ // fresh uuids, never copies), so clientIds don't need session scoping —
+ // unlike codex, whose stream indexes (`i<n>`) repeat in every rollout
+ const clientIdOf = (key: string) => `claude-code-${key}`;
+
+ const chainMain = chain.filter(
+ (r) => matchesSide(r) && (r.type === 'user' || r.type === 'assistant'),
+ );
+
+ let i = 0;
+ while (i < chainMain.length) {
+ const rec = chainMain[i];
+
+ if (rec.type === 'user') {
+ const content_ = rec.message?.content;
+ const isToolResultOnly =
+ Array.isArray(content_) && content_.every((b: any) => b?.type === 'tool_result');
+ // tool_result-only records are emitted via the assistant's tool_use blocks
+ if (!isToolResultOnly) {
+ const clientId = clientIdOf(rec.uuid);
+ messages.push({
+ clientId,
+ content: textOfContent(content_, img),
+ createdAt: rec.timestamp,
+ metadata: { heteroMessageId: rec.uuid, heteroSessionId: sessionId },
+ parentClientId: prevClientId,
+ role: 'user',
+ });
+ prevClientId = clientId;
+ }
+ i++;
+ continue;
+ }
+
+ // assistant: merge consecutive records sharing message.id (one line per block)
+ const msgId: string = rec.message?.id ?? rec.uuid;
+ const group: any[] = [];
+ while (i < chainMain.length && chainMain[i].type === 'assistant') {
+ if ((chainMain[i].message?.id ?? chainMain[i].uuid) !== msgId) break;
+ group.push(chainMain[i]);
+ i++;
+ }
+
+ const reasoningParts: string[] = [];
+ const textParts: string[] = [];
+ const tools: HeteroSessionImportToolCall[] = [];
+ for (const g of group)
+ for (const block of g.message?.content ?? []) {
+ // signature-only thinking blocks (interleaved thinking) carry an empty
+ // `thinking` string — skip them so no `{content: ''}` reasoning is written
+ if (block?.type === 'thinking' && block.thinking?.trim())
+ reasoningParts.push(block.thinking);
+ else if (block?.type === 'text') textParts.push(block.text);
+ else if (block?.type === 'tool_use')
+ tools.push({
+ apiName: block.name,
+ arguments: JSON.stringify(block.input ?? {}),
+ id: block.id,
+ identifier: CLAUDE_CODE_IDENTIFIER,
+ type: 'default',
+ });
+ }
+
+ const rawUsage = group.at(-1)?.message?.usage;
+ const usage = toModelUsageFromAnthropic(rawUsage);
+ // message.id may be reused non-consecutively — uuid keeps the clientId unique
+ const assistantClientId = clientIdOf(group[0].uuid);
+ messages.push({
+ clientId: assistantClientId,
+ content: textParts.join('\n\n'),
+ createdAt: group[0].timestamp,
+ metadata: {
+ // the record's own id in the CC session file (`uuid`), NOT the
+ // Anthropic API `message.id` (which is reused across records)
+ heteroMessageId: group[0].uuid,
+ heteroSessionId: sessionId,
+ // non-token usage extras belong to metadata, not the usage column
+ ...(rawUsage?.service_tier ? { serviceTier: rawUsage.service_tier } : {}),
+ ...(rawUsage?.speed ? { speed: rawUsage.speed } : {}),
+ },
+ model: group[0].message?.model,
+ parentClientId: prevClientId,
+ provider: CLAUDE_CODE_IDENTIFIER,
+ role: 'assistant',
+ ...(reasoningParts.length > 0 ? { reasoning: { content: reasoningParts.join('\n\n') } } : {}),
+ ...(tools.length > 0 ? { tools } : {}),
+ ...(usage ? { usage } : {}),
+ });
+ prevClientId = assistantClientId;
+
+ for (const tool of tools) {
+ const match = toolResultByUseId.get(tool.id);
+ if (!match) continue;
+ const toolClientId = clientIdOf(`${match.record.uuid}#${tool.id}`);
+ messages.push({
+ clientId: toolClientId,
+ content: textOfContent(match.block.content, img),
+ createdAt: match.record.timestamp,
+ metadata: { heteroMessageId: match.record.uuid, heteroSessionId: sessionId },
+ parentClientId: assistantClientId,
+ plugin: {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ identifier: CLAUDE_CODE_IDENTIFIER,
+ type: 'default',
+ },
+ role: 'tool',
+ toolCallId: tool.id,
+ });
+ prevClientId = toolClientId;
+ }
+ }
+
+ if (messages.length === 0) return null;
+
+ return {
+ imageBytes: img.bytes,
+ imageCount: img.count,
+ messages: stripNulDeep(messages),
+ sessionId,
+ title: aiTitle ?? truncateTitle(stripCcPreamble(textOfContent(firstUserRec?.message?.content))),
+ workingDirectory,
+ };
+};
+
+/**
+ * Build the full normalized import payload for a Claude Code session.
+ */
+export const buildClaudeCodeImportPayload = (
+ content: string,
+ options?: ParseClaudeCodeOptions,
+): HeteroSessionImportPayload | null => {
+ const parsed = parseClaudeCodeSession(content, options);
+ if (!parsed) return null;
+
+ return {
+ messages: parsed.messages,
+ metadata: {
+ heteroSessionId: parsed.sessionId,
+ ...(parsed.workingDirectory
+ ? { heteroSessionIdByWorkingDirectory: { [parsed.workingDirectory]: parsed.sessionId } }
+ : {}),
+ importedFrom: 'claude-code-local',
+ },
+ sessionId: parsed.sessionId,
+ source: 'claude-code',
+ title: parsed.title,
+ topicClientId: `claude-code-session-${parsed.sessionId}`,
+ workingDirectory: parsed.workingDirectory,
+ };
+};
+
+/**
+ * Lightweight digest for the import-picker list. Reads meta rows and counts
+ * without building the full message payload.
+ */
+export const parseClaudeCodeSessionDigest = (
+ content: string,
+ filePath: string,
+): HeteroSessionDigest | null => {
+ const records = parseJsonlRecords(content);
+ if (records.length === 0) return null;
+
+ const sessionId: string | undefined = records.find((r) => r.sessionId)?.sessionId;
+ if (!sessionId) return null;
+
+ const main = records.filter(
+ (r) => !r.isSidechain && (r.type === 'user' || r.type === 'assistant'),
+ );
+ if (main.length === 0) return null;
+
+ const aiTitle: string | undefined = records.findLast((r) => r.type === 'ai-title')?.aiTitle;
+ const firstUserRec = records.find((r) => r.type === 'user' && !r.isSidechain);
+ const firstPrompt = truncateTitle(
+ stripCcPreamble(textOfContent(firstUserRec?.message?.content)),
+ 200,
+ );
+
+ return {
+ endAt: main.at(-1)?.timestamp,
+ filePath,
+ firstPrompt,
+ gitBranch: records.find((r) => r.gitBranch)?.gitBranch,
+ messageCount: main.length,
+ sessionId,
+ source: 'claude-code',
+ startAt: main[0]?.timestamp,
+ title: aiTitle ?? truncateTitle(firstPrompt),
+ tokens: sumCcTokens(records),
+ workingDirectory: records.find((r) => r.cwd)?.cwd,
+ };
+};
diff --git a/packages/heterogeneous-agents/src/transcript/codex.test.ts b/packages/heterogeneous-agents/src/transcript/codex.test.ts
new file mode 100644
index 00000000000..2d31ee90164
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/codex.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCodexImportPayload, parseCodexSession, parseCodexSessionDigest } from './codex';
+
+const SESSION_ID = '019db91a-a0ea-7b71-9a8c-377aefb30219';
+
+const line = (record: Record<string, any>) => JSON.stringify(record);
+
+const sessionMeta = () =>
+ line({
+ payload: {
+ cli_version: '0.122.0',
+ cwd: '/repo',
+ git: { branch: 'feat/some-branch' },
+ id: SESSION_ID,
+ source: 'exec',
+ },
+ timestamp: '2026-04-23T06:50:25.085Z',
+ type: 'session_meta',
+ });
+
+const responseItem = (payload: Record<string, any>, timestamp = '2026-04-23T06:50:30.000Z') =>
+ line({ payload, timestamp, type: 'response_item' });
+
+const userMessage = (text: string) =>
+ responseItem({ content: [{ text, type: 'input_text' }], role: 'user', type: 'message' });
+
+const assistantMessage = (text: string) =>
+ responseItem({ content: [{ text, type: 'output_text' }], role: 'assistant', type: 'message' });
+
+describe('parseCodexSession', () => {
+ it('maps the linear rollout into user/assistant/tool messages', () => {
+ const transcript = [
+ sessionMeta(),
+ line({ payload: { cwd: '/repo', model: 'gpt-5.4' }, type: 'turn_context' }),
+ userMessage('# AGENTS.md instructions for /repo\nscaffolding'),
+ userMessage('<environment_context>...</environment_context>'),
+ userMessage('帮我看下这个 commit'),
+ responseItem({
+ content: [],
+ encrypted_content: 'xxx',
+ summary: [{ text: 'I should inspect the repo', type: 'summary_text' }],
+ type: 'reasoning',
+ }),
+ responseItem({
+ arguments: '{"cmd":"git log -1"}',
+ call_id: 'call_1',
+ name: 'exec_command',
+ type: 'function_call',
+ }),
+ responseItem({ call_id: 'call_1', output: 'commit abc123', type: 'function_call_output' }),
+ assistantMessage('这个 commit 修复了 FK 问题'),
+ line({
+ payload: {
+ info: {
+ last_token_usage: {
+ cached_input_tokens: 80,
+ input_tokens: 100,
+ output_tokens: 50,
+ reasoning_output_tokens: 10,
+ total_tokens: 150,
+ },
+ },
+ type: 'token_count',
+ },
+ type: 'event_msg',
+ }),
+ ].join('\n');
+
+ const result = parseCodexSession(transcript)!;
+ expect(result.sessionId).toBe(SESSION_ID);
+ expect(result.workingDirectory).toBe('/repo');
+ expect(result.gitBranch).toBe('feat/some-branch');
+ expect(result.title).toBe('帮我看下这个 commit');
+
+ const roles = result.messages.map((m) => m.role);
+ expect(roles).toEqual(['user', 'assistant', 'tool', 'assistant']);
+
+ const [user, callMsg, toolMsg, answer] = result.messages;
+ expect(user.content).toBe('帮我看下这个 commit');
+
+ // the function_call becomes an assistant message carrying the tool + reasoning
+ expect(callMsg.tools).toHaveLength(1);
+ expect(callMsg.tools![0]).toMatchObject({
+ apiName: 'exec_command',
+ id: 'call_1',
+ identifier: 'codex',
+ });
+ expect(callMsg.reasoning?.content).toBe('I should inspect the repo');
+ expect(callMsg.model).toBe('gpt-5.4');
+
+ expect(toolMsg.content).toBe('commit abc123');
+ expect(toolMsg.toolCallId).toBe('call_1');
+ expect(toolMsg.parentClientId).toBe(callMsg.clientId);
+ expect(toolMsg.plugin).toMatchObject({ apiName: 'exec_command', identifier: 'codex' });
+
+ expect(answer.content).toBe('这个 commit 修复了 FK 问题');
+ // token_count usage lands on the latest assistant message, normalized to
+ // the ModelUsage shape (codex input_tokens INCLUDES the cached portion)
+ expect(answer.usage).toEqual({
+ inputCacheMissTokens: 20,
+ inputCachedTokens: 80,
+ outputReasoningTokens: 10,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ });
+ });
+
+ it('skips scaffolding and developer messages entirely', () => {
+ const transcript = [
+ sessionMeta(),
+ responseItem({
+ content: [{ text: 'be a good agent', type: 'input_text' }],
+ role: 'developer',
+ type: 'message',
+ }),
+ userMessage('# AGENTS.md instructions for /repo'),
+ userMessage('<user_instructions>stuff</user_instructions>'),
+ userMessage('real question'),
+ assistantMessage('real answer'),
+ ].join('\n');
+
+ const result = parseCodexSession(transcript)!;
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toBe('real question');
+ });
+
+ it('produces deterministic clientIds so re-parsing is stable', () => {
+ const transcript = [sessionMeta(), userMessage('q'), assistantMessage('a')].join('\n');
+ const first = parseCodexSession(transcript)!.messages.map((m) => m.clientId);
+ const second = parseCodexSession(transcript)!.messages.map((m) => m.clientId);
+ expect(first).toEqual(second);
+ // appending records must not shift existing ids
+ const grown = parseCodexSession(`${transcript}\n${assistantMessage('more')}`)!;
+ expect(grown.messages.slice(0, 2).map((m) => m.clientId)).toEqual(first);
+ });
+
+ it('returns null for rollouts without conversation', () => {
+ expect(parseCodexSession('')).toBeNull();
+ expect(parseCodexSession(sessionMeta())).toBeNull();
+ expect(
+ parseCodexSession([sessionMeta(), userMessage('# AGENTS.md instructions')].join('\n')),
+ ).toBeNull();
+ });
+});
+
+describe('buildCodexImportPayload', () => {
+ it('produces a payload with resume metadata and deterministic topic clientId', () => {
+ const transcript = [sessionMeta(), userMessage('hello'), assistantMessage('hi')].join('\n');
+ const payload = buildCodexImportPayload(transcript)!;
+ expect(payload.topicClientId).toBe(`codex-session-${SESSION_ID}`);
+ expect(payload.source).toBe('codex');
+ expect(payload.metadata).toEqual({
+ heteroSessionId: SESSION_ID,
+ heteroSessionIdByWorkingDirectory: { '/repo': SESSION_ID },
+ importedFrom: 'codex-local',
+ });
+ });
+});
+
+describe('parseCodexSessionDigest', () => {
+ it('extracts list metadata', () => {
+ const transcript = [
+ sessionMeta(),
+ userMessage('# AGENTS.md instructions'),
+ userMessage('first real prompt'),
+ assistantMessage('answer'),
+ ].join('\n');
+
+ const digest = parseCodexSessionDigest(transcript, '/tmp/rollout.jsonl')!;
+ expect(digest.sessionId).toBe(SESSION_ID);
+ expect(digest.title).toBe('first real prompt');
+ expect(digest.workingDirectory).toBe('/repo');
+ expect(digest.gitBranch).toBe('feat/some-branch');
+ expect(digest.source).toBe('codex');
+ });
+
+ it('accumulates fresh-input + output tokens across turns', () => {
+ const tokenCount = (input: number, cached: number, output: number) =>
+ line({
+ payload: {
+ info: {
+ last_token_usage: {
+ cached_input_tokens: cached,
+ input_tokens: input,
+ output_tokens: output,
+ },
+ },
+ type: 'token_count',
+ },
+ type: 'event_msg',
+ });
+ const transcript = [
+ sessionMeta(),
+ userMessage('q'),
+ assistantMessage('a'),
+ tokenCount(1000, 800, 50),
+ tokenCount(2000, 1900, 100),
+ ].join('\n');
+
+ const digest = parseCodexSessionDigest(transcript, '/tmp/rollout.jsonl')!;
+ expect(digest.tokens).toBe(200 + 250); // (1000-800+50) + (2000-1900+100)
+ });
+
+ it('returns null when only scaffolding user messages exist', () => {
+ const transcript = [sessionMeta(), userMessage('# AGENTS.md instructions')].join('\n');
+ expect(parseCodexSessionDigest(transcript, '/tmp/rollout.jsonl')).toBeNull();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/transcript/codex.ts b/packages/heterogeneous-agents/src/transcript/codex.ts
new file mode 100644
index 00000000000..f5e37c75b75
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/codex.ts
@@ -0,0 +1,338 @@
+import type {
+ HeteroSessionDigest,
+ HeteroSessionImportMessage,
+ HeteroSessionImportPayload,
+} from '@lobechat/types';
+
+import { parseJsonlRecords, stripNulDeep, toModelUsageFromCodex, truncateTitle } from './utils';
+
+/**
+ * Parser for Codex CLI local rollout transcripts
+ * (`~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<uuid>.jsonl`).
+ *
+ * Format notes (verified against real rollouts):
+ * - linear record stream, no parent tree / sidechains
+ * - `session_meta` carries id / cwd / cli_version / git info
+ * - `turn_context` carries the model per turn
+ * - `response_item` payloads: `message` (roles developer/user/assistant),
+ * `reasoning` (summary often empty + encrypted content), `function_call`
+ * {name, call_id, arguments}, `function_call_output` {call_id, output},
+ * plus tool_search / web_search / custom tool variants
+ * - `event_msg` `token_count` carries per-turn usage in `info.last_token_usage`
+ * - the first user messages are scaffolding (`# AGENTS.md instructions`,
+ * `<user_instructions>`, `<environment_context>`) and are skipped
+ */
+
+export const CODEX_IDENTIFIER = 'codex';
+
+const SCAFFOLD_PREFIXES = [
+ '# AGENTS.md instructions',
+ '<user_instructions>',
+ '<environment_context>',
+ '<ENVIRONMENT_CONTEXT>',
+];
+
+const isScaffoldText = (text: string) =>
+ SCAFFOLD_PREFIXES.some((prefix) => text.trimStart().startsWith(prefix));
+
+const textOfCodexContent = (content: any): string => {
+ if (typeof content === 'string') return content;
+ if (!Array.isArray(content)) return '';
+ return content
+ .map((block: any) => {
+ if (block?.type === 'input_text' || block?.type === 'output_text') return block.text;
+ if (block?.type === 'input_image') return '![imported image placeholder]';
+ return '';
+ })
+ .filter(Boolean)
+ .join('\n\n');
+};
+
+/** normalize the various tool-call payload flavors into {name, callId, arguments} */
+const asToolCall = (payload: any): { args: string; callId: string; name: string } | null => {
+ const callId = payload.call_id ?? payload.id;
+ if (!callId) return null;
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call')
+ return {
+ args:
+ typeof payload.arguments === 'string'
+ ? payload.arguments
+ : JSON.stringify(payload.arguments ?? payload.input ?? {}),
+ callId,
+ name: payload.name ?? payload.type,
+ };
+ if (payload.type === 'local_shell_call')
+ return { args: JSON.stringify(payload.action ?? {}), callId, name: 'local_shell' };
+ if (payload.type === 'tool_search_call' || payload.type === 'web_search_call')
+ return {
+ args: JSON.stringify(payload.action ?? payload.query ?? {}),
+ callId,
+ name: payload.type.replace('_call', ''),
+ };
+ return null;
+};
+
+const isToolOutput = (payload: any): boolean =>
+ typeof payload?.type === 'string' && payload.type.endsWith('_output') && Boolean(payload.call_id);
+
+const textOfToolOutput = (payload: any): string => {
+ const output = payload.output;
+ if (typeof output === 'string') return output;
+ if (output && typeof output === 'object')
+ return typeof output.content === 'string' ? output.content : JSON.stringify(output);
+ if (typeof payload.result === 'string') return payload.result;
+ return '';
+};
+
+export interface ParsedCodexSession {
+ gitBranch?: string;
+ messages: HeteroSessionImportMessage[];
+ sessionId: string;
+ title?: string;
+ workingDirectory?: string;
+}
+
+/**
+ * Parse a Codex rollout into normalized import messages.
+ * Returns null when the rollout contains no importable conversation.
+ */
+export const parseCodexSession = (content: string): ParsedCodexSession | null => {
+ const records = parseJsonlRecords(content);
+ if (records.length === 0) return null;
+
+ const meta = records.find((r) => r.type === 'session_meta')?.payload;
+ const sessionId: string | undefined = meta?.id;
+ if (!sessionId) return null;
+
+ const messages: HeteroSessionImportMessage[] = [];
+ const clientIdOf = (key: string) => `codex-${sessionId}-${key}`;
+ // call_id -> the assistant message that carried the call (for tool results)
+ const callIndex = new Map<string, { apiName: string; args: string; clientId: string }>();
+
+ let prevClientId: string | null = null;
+ let pendingReasoning: string[] = [];
+ let model: string | undefined = meta?.model;
+ let title: string | undefined;
+ let lastAssistant: HeteroSessionImportMessage | null = null;
+ let itemIndex = -1;
+
+ for (const record of records) {
+ if (record.type === 'turn_context') {
+ model = record.payload?.model ?? model;
+ continue;
+ }
+
+ if (record.type === 'event_msg') {
+ // per-turn usage lands on the latest assistant message
+ const usage =
+ record.payload?.type === 'token_count' &&
+ toModelUsageFromCodex(record.payload?.info?.last_token_usage);
+ if (usage && lastAssistant) lastAssistant.usage = usage;
+ continue;
+ }
+
+ if (record.type !== 'response_item') continue;
+ itemIndex++;
+ const payload = record.payload;
+ if (!payload?.type) continue;
+
+ if (payload.type === 'reasoning') {
+ const parts: string[] = [];
+ for (const s of payload.summary ?? []) if (s?.text?.trim()) parts.push(s.text);
+ for (const c of payload.content ?? []) if (c?.text?.trim()) parts.push(c.text);
+ if (parts.length > 0) pendingReasoning.push(...parts);
+ continue;
+ }
+
+ if (payload.type === 'message') {
+ const text = textOfCodexContent(payload.content);
+ if (payload.role === 'user') {
+ if (!text || isScaffoldText(text)) continue;
+ title ??= truncateTitle(text);
+ const clientId = clientIdOf(`i${itemIndex}`);
+ messages.push({
+ clientId,
+ content: text,
+ createdAt: record.timestamp,
+ metadata: { heteroSessionId: sessionId },
+ parentClientId: prevClientId,
+ role: 'user',
+ });
+ prevClientId = clientId;
+ pendingReasoning = [];
+ } else if (payload.role === 'assistant') {
+ const clientId = clientIdOf(`i${itemIndex}`);
+ const message: HeteroSessionImportMessage = {
+ clientId,
+ content: text,
+ createdAt: record.timestamp,
+ metadata: { heteroSessionId: sessionId },
+ model,
+ parentClientId: prevClientId,
+ provider: CODEX_IDENTIFIER,
+ role: 'assistant',
+ ...(pendingReasoning.length > 0
+ ? { reasoning: { content: pendingReasoning.join('\n\n') } }
+ : {}),
+ };
+ messages.push(message);
+ prevClientId = clientId;
+ lastAssistant = message;
+ pendingReasoning = [];
+ }
+ // developer / system messages are instructions scaffolding — skipped
+ continue;
+ }
+
+ const toolCall = asToolCall(payload);
+ if (toolCall) {
+ const clientId = clientIdOf(`call-${toolCall.callId}`);
+ const message: HeteroSessionImportMessage = {
+ clientId,
+ content: '',
+ createdAt: record.timestamp,
+ // codex `message` items carry no native id in rollouts; only call
+ // items do (`fc_...` / `ctc_...`) — stamp it where it exists
+ metadata: {
+ ...(payload.id ? { heteroMessageId: payload.id } : {}),
+ heteroSessionId: sessionId,
+ },
+ model,
+ parentClientId: prevClientId,
+ provider: CODEX_IDENTIFIER,
+ role: 'assistant',
+ tools: [
+ {
+ apiName: toolCall.name,
+ arguments: toolCall.args,
+ id: toolCall.callId,
+ identifier: CODEX_IDENTIFIER,
+ type: 'default',
+ },
+ ],
+ ...(pendingReasoning.length > 0
+ ? { reasoning: { content: pendingReasoning.join('\n\n') } }
+ : {}),
+ };
+ messages.push(message);
+ callIndex.set(toolCall.callId, {
+ apiName: toolCall.name,
+ args: toolCall.args,
+ clientId,
+ });
+ prevClientId = clientId;
+ lastAssistant = message;
+ pendingReasoning = [];
+ continue;
+ }
+
+ if (isToolOutput(payload)) {
+ const call = callIndex.get(payload.call_id);
+ if (!call) continue;
+ const clientId = clientIdOf(`result-${payload.call_id}`);
+ messages.push({
+ clientId,
+ content: textOfToolOutput(payload),
+ createdAt: record.timestamp,
+ metadata: { heteroSessionId: sessionId },
+ parentClientId: call.clientId,
+ plugin: {
+ apiName: call.apiName,
+ arguments: call.args,
+ identifier: CODEX_IDENTIFIER,
+ type: 'default',
+ },
+ role: 'tool',
+ toolCallId: payload.call_id,
+ });
+ prevClientId = clientId;
+ }
+ }
+
+ if (messages.length === 0) return null;
+
+ return {
+ gitBranch: meta?.git?.branch,
+ messages: stripNulDeep(messages),
+ sessionId,
+ title,
+ workingDirectory: meta?.cwd,
+ };
+};
+
+/**
+ * Build the full normalized import payload for a Codex session.
+ */
+export const buildCodexImportPayload = (content: string): HeteroSessionImportPayload | null => {
+ const parsed = parseCodexSession(content);
+ if (!parsed) return null;
+
+ return {
+ messages: parsed.messages,
+ metadata: {
+ heteroSessionId: parsed.sessionId,
+ ...(parsed.workingDirectory
+ ? { heteroSessionIdByWorkingDirectory: { [parsed.workingDirectory]: parsed.sessionId } }
+ : {}),
+ importedFrom: 'codex-local',
+ },
+ sessionId: parsed.sessionId,
+ source: 'codex',
+ title: parsed.title,
+ topicClientId: `codex-session-${parsed.sessionId}`,
+ workingDirectory: parsed.workingDirectory,
+ };
+};
+
+/**
+ * Lightweight digest for the import-picker list.
+ */
+export const parseCodexSessionDigest = (
+ content: string,
+ filePath: string,
+): HeteroSessionDigest | null => {
+ const records = parseJsonlRecords(content);
+ if (records.length === 0) return null;
+
+ const meta = records.find((r) => r.type === 'session_meta')?.payload;
+ if (!meta?.id) return null;
+
+ const items = records.filter((r) => r.type === 'response_item');
+ const userTexts = items
+ .filter((r) => r.payload?.type === 'message' && r.payload.role === 'user')
+ .map((r) => textOfCodexContent(r.payload.content))
+ .filter((t) => t && !isScaffoldText(t));
+ if (userTexts.length === 0) return null;
+
+ const conversational = items.filter(
+ (r) =>
+ r.payload?.type === 'message' &&
+ (r.payload.role === 'assistant' || r.payload.role === 'user'),
+ );
+
+ // fresh input (minus cache reads) + output, accumulated across turns
+ let tokens = 0;
+ for (const r of records) {
+ const usage =
+ r.type === 'event_msg' &&
+ r.payload?.type === 'token_count' &&
+ r.payload?.info?.last_token_usage;
+ if (usage)
+ tokens +=
+ (usage.input_tokens ?? 0) - (usage.cached_input_tokens ?? 0) + (usage.output_tokens ?? 0);
+ }
+
+ return {
+ endAt: items.at(-1)?.timestamp,
+ filePath,
+ firstPrompt: truncateTitle(userTexts[0], 200),
+ gitBranch: meta.git?.branch,
+ messageCount: conversational.length,
+ sessionId: meta.id,
+ source: 'codex',
+ startAt: items[0]?.timestamp,
+ title: truncateTitle(userTexts[0]),
+ tokens,
+ workingDirectory: meta.cwd,
+ };
+};
diff --git a/packages/heterogeneous-agents/src/transcript/index.ts b/packages/heterogeneous-agents/src/transcript/index.ts
new file mode 100644
index 00000000000..3480812fcf8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/index.ts
@@ -0,0 +1,15 @@
+export type { ParseClaudeCodeOptions, ParsedClaudeCodeSession } from './claudeCode';
+export {
+ buildClaudeCodeImportPayload,
+ CLAUDE_CODE_IDENTIFIER,
+ parseClaudeCodeSession,
+ parseClaudeCodeSessionDigest,
+} from './claudeCode';
+export type { ParsedCodexSession } from './codex';
+export {
+ buildCodexImportPayload,
+ CODEX_IDENTIFIER,
+ parseCodexSession,
+ parseCodexSessionDigest,
+} from './codex';
+export { parseJsonlRecords, stripNulDeep, truncateTitle } from './utils';
diff --git a/packages/heterogeneous-agents/src/transcript/utils.ts b/packages/heterogeneous-agents/src/transcript/utils.ts
new file mode 100644
index 00000000000..50ca9e7e571
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/utils.ts
@@ -0,0 +1,112 @@
+/**
+ * Shared helpers for transcript parsers.
+ */
+
+const NUL = String.fromCodePoint(0);
+
+/**
+ * Postgres rejects NUL characters in text/jsonb columns, and real-world
+ * transcripts do contain them (e.g. binary tool output). Deep-strip real NUL
+ * characters from every string in the value (literal `\u0000` escape sequences
+ * that appear as text in code snippets are untouched).
+ */
+export const stripNulDeep = <T>(value: T): T => {
+ if (typeof value === 'string')
+ return (value.includes(NUL) ? value.replaceAll(NUL, '') : value) as T;
+ if (Array.isArray(value)) return value.map((item) => stripNulDeep(item)) as T;
+ if (value && typeof value === 'object')
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, stripNulDeep(v)])) as T;
+ return value;
+};
+
+/**
+ * Parse a JSONL transcript into records, silently skipping unparsable lines
+ * (truncated writes, corrupt tails).
+ */
+export const parseJsonlRecords = (content: string): any[] => {
+ const records: any[] = [];
+ for (const line of content.split('\n')) {
+ if (!line) continue;
+ try {
+ records.push(JSON.parse(line));
+ } catch {
+ /* skip bad line */
+ }
+ }
+ return records;
+};
+
+export const truncateTitle = (text: string | undefined, max = 50): string | undefined => {
+ const cleaned = text?.replaceAll(/\s+/g, ' ').trim();
+ if (!cleaned) return undefined;
+ return cleaned.length > max ? cleaned.slice(0, max) : cleaned;
+};
+
+/**
+ * Convert a raw Anthropic-shape usage object (Claude Code transcripts) into
+ * the LobeHub `ModelUsage` shape stored in the messages `usage` column —
+ * same mapping as the live adapter's `toUsageData`. Non-token extras
+ * (`service_tier`, `speed`, `cache_creation`, …) must NOT land here; callers
+ * relocate the meaningful ones into message metadata.
+ */
+export const toModelUsageFromAnthropic = (
+ raw:
+ | {
+ cache_creation_input_tokens?: number;
+ cache_read_input_tokens?: number;
+ input_tokens?: number;
+ output_tokens?: number;
+ }
+ | null
+ | undefined,
+): Record<string, number> | undefined => {
+ if (!raw) return undefined;
+ const inputCacheMissTokens = raw.input_tokens || 0;
+ const inputCachedTokens = raw.cache_read_input_tokens || 0;
+ const inputWriteCacheTokens = raw.cache_creation_input_tokens || 0;
+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens + inputWriteCacheTokens;
+ const totalOutputTokens = raw.output_tokens || 0;
+ if (totalInputTokens + totalOutputTokens === 0) return undefined;
+ return {
+ inputCacheMissTokens,
+ ...(inputCachedTokens ? { inputCachedTokens } : {}),
+ ...(inputWriteCacheTokens ? { inputWriteCacheTokens } : {}),
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens: totalInputTokens + totalOutputTokens,
+ };
+};
+
+/**
+ * Convert a Codex `token_count` usage object (`info.last_token_usage`) into
+ * the LobeHub `ModelUsage` shape. Codex `input_tokens` INCLUDES the cached
+ * portion, unlike Anthropic's cache-miss-only `input_tokens`.
+ */
+export const toModelUsageFromCodex = (
+ raw:
+ | {
+ cached_input_tokens?: number;
+ input_tokens?: number;
+ output_tokens?: number;
+ reasoning_output_tokens?: number;
+ total_tokens?: number;
+ }
+ | null
+ | undefined,
+): Record<string, number> | undefined => {
+ if (!raw) return undefined;
+ const totalInputTokens = raw.input_tokens || 0;
+ const inputCachedTokens = raw.cached_input_tokens || 0;
+ const totalOutputTokens = raw.output_tokens || 0;
+ if (totalInputTokens + totalOutputTokens === 0) return undefined;
+ const outputReasoningTokens = raw.reasoning_output_tokens || 0;
+ return {
+ ...(inputCachedTokens
+ ? { inputCacheMissTokens: totalInputTokens - inputCachedTokens, inputCachedTokens }
+ : {}),
+ ...(outputReasoningTokens ? { outputReasoningTokens } : {}),
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens: raw.total_tokens || totalInputTokens + totalOutputTokens,
+ };
+};
diff --git a/packages/types/src/heteroSessionImport.ts b/packages/types/src/heteroSessionImport.ts
new file mode 100644
index 00000000000..e34e4fe9fb3
--- /dev/null
+++ b/packages/types/src/heteroSessionImport.ts
@@ -0,0 +1,205 @@
+import { z } from 'zod';
+
+/**
+ * Normalized payload for importing an external CLI agent session
+ * (Claude Code / Codex local transcript) into LobeHub.
+ *
+ * Produced by the transcript parsers in `@lobechat/heterogeneous-agents/transcript`,
+ * consumed by `HeteroSessionImporterRepo` in `@lobechat/database`.
+ *
+ * All entities carry a deterministic `clientId` derived from the source transcript,
+ * so re-importing the same session is idempotent (existing rows are skipped) and
+ * a grown transcript imports incrementally.
+ */
+
+export type HeteroSessionImportSource = 'claude-code' | 'codex';
+
+export interface HeteroSessionImportToolCall {
+ /** tool name, e.g. `Bash` / `exec_command` */
+ apiName: string;
+ /** JSON string of the tool arguments */
+ arguments: string;
+ /** tool_use id / call_id from the source transcript */
+ id: string;
+ /** builtin tool identifier, e.g. `claude-code` / `codex` */
+ identifier: string;
+ type: 'default';
+}
+
+export interface HeteroSessionImportMessage {
+ /** deterministic id derived from the source transcript, unique within the user scope */
+ clientId: string;
+ content: string;
+ /** ISO timestamp from the source transcript */
+ createdAt?: string;
+ metadata?: Record<string, any>;
+ model?: string;
+ /** clientId of the parent message (conversation chain) */
+ parentClientId?: string | null;
+ /** tool message plugin payload (role: 'tool' only) */
+ plugin?: {
+ apiName: string;
+ arguments: string;
+ identifier: string;
+ type: string;
+ };
+ pluginState?: Record<string, any>;
+ provider?: string;
+ reasoning?: { content: string } & Record<string, any>;
+ role: 'user' | 'assistant' | 'tool';
+ /** tool_use id this tool message answers (role: 'tool' only) */
+ toolCallId?: string;
+ /** tool calls issued by this assistant message */
+ tools?: HeteroSessionImportToolCall[];
+ usage?: Record<string, any>;
+}
+
+export interface HeteroSessionImportThread {
+ /** deterministic id derived from the source transcript */
+ clientId: string;
+ messages: HeteroSessionImportMessage[];
+ /** clientId of the main-chain message this thread hangs on (e.g. the Task tool message) */
+ sourceMessageClientId?: string;
+ status?: 'active' | 'completed' | 'failed';
+ title?: string;
+ type: 'continuation' | 'standalone' | 'isolation';
+}
+
+export interface HeteroSessionImportPayload {
+ /** main conversation chain */
+ messages: HeteroSessionImportMessage[];
+ /** extra metadata merged into the topic metadata */
+ metadata?: Record<string, any>;
+ /** native session id from the source CLI (Claude Code sessionId / Codex rollout id) */
+ sessionId: string;
+ source: HeteroSessionImportSource;
+ /** subagent / sidechain transcripts, imported as threads */
+ threads?: HeteroSessionImportThread[];
+ title?: string;
+ /** deterministic topic clientId, e.g. `claude-code-session-<sessionId>` */
+ topicClientId: string;
+ /** cwd the session was recorded under (used for resume binding) */
+ workingDirectory?: string;
+}
+
+export interface HeteroSessionImportResult {
+ /** whether a new topic was created (false = incremental into an existing one) */
+ created: boolean;
+ insertedMessages: number;
+ insertedThreads: number;
+ sessionId: string;
+ skippedMessages: number;
+ topicId: string;
+}
+
+/** import status of scanned sessions, for the picker UI badges */
+export interface HeteroSessionImportStatus {
+ imported: {
+ messageCount: number;
+ /** last source-transcript timestamp at import time — digest.endAt > this ⇒ syncable */
+ sourceEndAt?: string;
+ topicClientId: string;
+ topicId: string;
+ }[];
+ /** sessionIds that originated from LobeHub live runs (importing would duplicate) */
+ linked: string[];
+}
+
+/** Lightweight digest of a local session, for the import-picker list UI */
+export interface HeteroSessionDigest {
+ endAt?: string;
+ filePath: string;
+ firstPrompt?: string;
+ gitBranch?: string;
+ messageCount: number;
+ sessionId: string;
+ source: HeteroSessionImportSource;
+ startAt?: string;
+ title?: string;
+ /** cumulative tokens (fresh input + output) across the session */
+ tokens?: number;
+ workingDirectory?: string;
+}
+
+// ===== desktop scan surface (HeteroSessionCtr IPC) =====
+
+/**
+ * Per-directory user preference, persisted in the desktop main-process store.
+ * `none` is only ever STORED (never returned in scan results): it records that
+ * the user explicitly restored a directory that would otherwise be ignored by
+ * default (e.g. temp dirs), so the default doesn't re-apply on the next scan.
+ */
+export type HeteroSessionDirPref = 'ignored' | 'none' | 'watched';
+
+/** sessions of one working directory, aggregated across storage folders */
+export interface HeteroSessionDirGroup {
+ dirPref?: HeteroSessionDirPref;
+ /** any session in the dir carries a git branch */
+ isGit: boolean;
+ sessionCount: number;
+ /** digests sorted by endAt desc */
+ sessions: HeteroSessionDigest[];
+ source: HeteroSessionImportSource;
+ totalTokens: number;
+ workingDirectory: string;
+}
+
+export interface HeteroSessionScanResult {
+ /** per-file parse failures, for diagnostics — scan never throws on bad files */
+ errors: string[];
+ groups: HeteroSessionDirGroup[];
+}
+
+// ===== zod schemas (tRPC input validation), mirroring the interfaces above =====
+
+export const heteroSessionImportToolCallSchema = z.object({
+ apiName: z.string(),
+ arguments: z.string(),
+ id: z.string(),
+ identifier: z.string(),
+ type: z.literal('default'),
+});
+
+export const heteroSessionImportMessageSchema = z.object({
+ clientId: z.string(),
+ content: z.string(),
+ createdAt: z.string().optional(),
+ metadata: z.record(z.string(), z.any()).optional(),
+ model: z.string().optional(),
+ parentClientId: z.string().nullish(),
+ plugin: z
+ .object({
+ apiName: z.string(),
+ arguments: z.string(),
+ identifier: z.string(),
+ type: z.string(),
+ })
+ .optional(),
+ pluginState: z.record(z.string(), z.any()).optional(),
+ provider: z.string().optional(),
+ reasoning: z.object({ content: z.string() }).passthrough().optional(),
+ role: z.enum(['user', 'assistant', 'tool']),
+ toolCallId: z.string().optional(),
+ tools: z.array(heteroSessionImportToolCallSchema).optional(),
+ usage: z.record(z.string(), z.any()).optional(),
+});
+
+export const heteroSessionImportThreadSchema = z.object({
+ clientId: z.string(),
+ messages: z.array(heteroSessionImportMessageSchema),
+ sourceMessageClientId: z.string().optional(),
+ status: z.enum(['active', 'completed', 'failed']).optional(),
+ title: z.string().optional(),
+ type: z.enum(['continuation', 'standalone', 'isolation']),
+});
+
+export const heteroSessionImportPayloadSchema = z.object({
+ messages: z.array(heteroSessionImportMessageSchema),
+ metadata: z.record(z.string(), z.any()).optional(),
+ sessionId: z.string(),
+ source: z.enum(['claude-code', 'codex']),
+ threads: z.array(heteroSessionImportThreadSchema).optional(),
+ title: z.string().optional(),
+ topicClientId: z.string(),
+ workingDirectory: z.string().optional(),
+});
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 58041b2f174..bc0a90aec1a 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -21,6 +21,7 @@ export * from './fetch';
export * from './files';
export * from './followUpAction';
export * from './generation';
+export * from './heteroSessionImport';
export * from './home';
export * from './hotkey';
export * from './importer';
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index eab66a68ef6..4914684435f 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -276,10 +276,14 @@ export interface MessageMetadata {
duration?: number;
finishType?: string;
/**
- * The CC-native `message.id` of the hetero-agent (Claude Code) turn that
- * produced this message. Forensic provenance stamped by both the server
- * persistence handler and the renderer executor, so a diff can tie a row
- * back to its CC turn.
+ * The native id of this message inside the hetero agent (Claude Code /
+ * Codex) that produced it — forensic provenance tying a row back to its
+ * source.
+ *
+ * - live runs: the CC API `message.id` of the turn (all the stream exposes),
+ * stamped by the server persistence handler and the renderer executor
+ * - imported transcripts: the record's own id in the source file (CC session
+ * record `uuid`; codex call item `fc_...` / `ctc_...` id)
*/
heteroMessageId?: string;
/**
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 1637d41e02f..e24867a89f7 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -142,6 +142,15 @@ export interface ChatTopicMetadata {
* readers; this map lets the UI restore the right id when switching back.
*/
heteroSessionIdByWorkingDirectory?: Record<string, string>;
+ /**
+ * For topics imported from local CLI transcripts: the source transcript's
+ * last message timestamp at import time. The import picker compares it with
+ * a fresh scan's endAt to detect "the transcript grew since last import"
+ * (message counts are not comparable across transcript records and DB rows).
+ */
+ heteroSourceEndAt?: string;
+ /** origin marker for imported topics, e.g. `claude-code-local` / `codex-local` */
+ importedFrom?: string;
model?: string;
/**
* Free-form feedback collected after agent onboarding completion.