Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"devDependencies": {
"@types/node": "^22.0.0",
"@types/node-forge": "^1.3.14",
"acp-kernel": "0.0.47",
"acp-kernel": "0.0.49",
"fzstd": "0.1.1",
"node-forge": "^1.4.0",
"tar": "^7.5.22",
Expand Down
84 changes: 28 additions & 56 deletions src/export.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { prune, type CoreMessage } from "acp-kernel";
import { renderHandoff as kernelRenderHandoff, matchSession as kernelMatchSession } from "acp-kernel";
import type { Session } from "./session.js";
import { SessionStore } from "./persist.js";

Expand Down Expand Up @@ -48,6 +48,32 @@ function latestBlockTime(s: Session): number {
}

export function renderHandoff(s: Session, full: boolean): string {
const messages = s.lastMessages;
if (messages && messages.length > 0) {
// Full-conversation snapshot (v3 files): delegate the whole doc —
// metadata header + folded (prune) / full conversation — to the
// kernel's shared renderer so proxy and billion-context-pi carry one
// copy, not two.
const extraBullets: string[] = [];
if (s.meta.protocol) extraBullets.push(`- protocol: ${s.meta.protocol}`);
if (s.meta.upstreamOrigin) extraBullets.push(`- upstream: ${s.meta.upstreamOrigin}`);
extraBullets.push(`- requests: ${s.stats.requests}`);
return kernelRenderHandoff({
coreMessages: messages,
state: s.state,
full,
meta: {
title: s.meta.title,
label: s.meta.label,
sessionId: s.id,
contextTokens: s.stats.contextTokens,
extraBullets,
},
});
}

// v2 fallback: no snapshot persisted. Block summaries (+ originals with
// --full from the blockContents cache) are all that is recoverable offline.
const lines: string[] = [];
lines.push(`# billion-context session handoff`);
lines.push("");
Expand All @@ -61,29 +87,6 @@ export function renderHandoff(s: Session, full: boolean): string {
lines.push(`- compression blocks: ${s.state.blocks.length} (active ${s.state.blocks.filter((b) => b.active).length})`);
lines.push("");

const messages = s.lastMessages;
if (messages && messages.length > 0) {
// Full-conversation snapshot (v3 files): render exactly what the model
// saw. Default = folded view via the kernel's own renderer (summaries
// in place of compressed ranges); --full = every original message.
lines.push(full ? `## Full conversation (${messages.length} messages)` : `## Conversation (folded view as the model saw it, ${messages.length} client messages)`);
lines.push("");
let lastRole = "";
const view = full ? messages : prune(messages, s.state);
for (const m of view) {
if (m.role !== lastRole) {
lines.push(`### ${m.role}`);
lines.push("");
lastRole = m.role;
}
lines.push(renderMessage(m));
}
lines.push("");
return lines.join("\n");
}

// v2 fallback: no snapshot persisted. Block summaries (+ originals with
// --full from the blockContents cache) are all that is recoverable offline.
const active = s.state.blocks.filter((b) => b.active);
if (active.length === 0) {
lines.push("No active compression blocks and no persisted conversation snapshot (v2 session file). Original messages are only persisted when they are compressed into a block, so this session's conversation content is not available for export.");
Expand Down Expand Up @@ -113,37 +116,6 @@ export function renderHandoff(s: Session, full: boolean): string {
return lines.join("\n");
}

/** Render one CoreMessage as markdown. tool-call / tool-result / reasoning
* carry their structured fields; text carries the body. */
function renderMessage(m: CoreMessage): string {
const parts: string[] = [];
switch (m.contentType) {
case "text":
parts.push(m.text ?? "");
break;
case "tool-call":
parts.push(`\`${m.toolName ?? "?"}(${m.toolCallId ?? ""})\` args: ${m.text ?? ""}`);
break;
case "tool-result":
parts.push(`\`${m.toolName ?? "?"}(${m.toolCallId ?? ""})\` → ${m.text ?? ""}`);
break;
case "reasoning":
parts.push(`_reasoning_: ${m.text ?? ""}`);
break;
}
const body = parts.join("\n").trim();
return body === "" ? "_(empty)_" : body + "\n";
}

function matchSession(sessions: Session[], selector: string): Session[] {
const exact = sessions.filter((s) => s.id === selector);
if (exact.length > 0) return exact;
const byLabel = sessions.filter((s) => s.meta.label === selector);
if (byLabel.length > 0) return byLabel;
const byPrefix = sessions.filter((s) => s.id.startsWith(selector) || (s.meta.label ?? "").startsWith(selector));
return byPrefix;
}

export async function exportSession(selector: string | undefined, opts: ExportOptions = {}): Promise<string> {
const store = new SessionStore({ dir: opts.dir, enabled: true });
const all = [...(await store.loadAll()).values()];
Expand All @@ -157,7 +129,7 @@ export async function exportSession(selector: string | undefined, opts: ExportOp
);
return ["Persisted sessions:", "", ...rows.map((r) => ` ${r}`), "", "Usage: bili export <session-id|label> [--output handoff.md] [--full]"].join("\n");
}
const matches = matchSession(all, selector);
const matches = kernelMatchSession(all, selector, (s) => s.meta.label);
if (matches.length === 0) {
throw new Error(`no session matches "${selector}" (run "bili export" to list sessions)`);
}
Expand Down
Loading