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
54 changes: 6 additions & 48 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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
81 changes: 24 additions & 57 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 } from "acp-kernel";
import type { Session } from "./session.js";
import { SessionStore } from "./persist.js";

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

export function renderHandoff(s: Session, full: boolean): string {
const messages = s.lastMessages;
if (messages && messages.length > 0) {
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: [
s.meta.protocol ? `- protocol: ${s.meta.protocol}` : null,
s.meta.upstreamOrigin ? `- upstream: ${s.meta.upstreamOrigin}` : null,
`- requests: ${s.stats.requests}`,
].filter((x): x is string => x !== null),
},
});
}

// 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 @@ -60,30 +82,6 @@ export function renderHandoff(s: Session, full: boolean): string {
if (s.stats.contextTokens) lines.push(`- last context tokens: ~${s.stats.contextTokens}`);
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 +111,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 +124,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 = matchSession(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