Skip to content
Merged
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
1 change: 1 addition & 0 deletions reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ billion-context/
│ │ ├── context-window.ts # Context-window resolution (launcher model channel, beta headers)
│ │ ├── dsh-compaction-guard.ts # Rejects dsh whole-prefix compaction replays (#1729)
│ │ ├── handle.ts # Proxy request pipeline (route triage, compat relay, compress orchestration) (#1440 P2 cut 3)
│ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots
│ │ ├── headers.ts # Client-provided id sanitization for dump filenames (#286)
│ │ ├── inject.ts # Per-wire tool-injection wrappers + FORCE_TEXT_PROTOCOL switch (#1440)
│ │ ├── observability.ts # Body dumps (dumps/req-*.json, raw/*), unrecognized-path stats
Expand Down
34 changes: 29 additions & 5 deletions src/export.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { matchSession as matchSessionKernel, parseStoredPlaceholder, renderHandoff as renderHandoffKernel, type MessageContentStore } from "acp-kernel";
import { matchSession as matchSessionKernel, parseStoredPlaceholder, renderHandoff as renderHandoffKernel, renderMessage, type MessageContentStore, type CoreMessage } from "acp-kernel";
import type { Session } from "./session.js";
import { SessionStore } from "./persist.js";
import { SqliteBackend, backendSelectionNotice, listBackendNames, openBackend, resolveBackendName, resolveMysqlDsn, selectedBackendRaw, type StorageBackend } from "./storage/backend.js";
Expand Down Expand Up @@ -82,12 +82,34 @@ function latestBlockTime(s: Session): number {
return latest;
}

/** Ends the reasoning cell inside a single assistant block. `renderMessage`
* emits `_reasoning_: …` with no terminator, so without it the handoff
* renderer folds the answer that follows into the collapsed thinking box.
* An HTML comment keeps the marker invisible in rendered Markdown. */
export const HANDOFF_THINK_END = "<!-- /reasoning -->";

function handoffCells(messages: CoreMessage[]): CoreMessage[] {
return messages.map((m) => m.contentType === "reasoning"
? { ...m, text: (m.text ?? "").split("\n").map((line, index) =>
index > 0 && line.trim() === HANDOFF_THINK_END ? line + "\n" + line : line
).join("\n").trimEnd() + "\n" + HANDOFF_THINK_END }
: m);
}

export function renderHandoff(s: Session, full: boolean): string {
const response = s.metadata.handoffResponse as { request?: unknown; messages?: unknown } | undefined;
const reply = response?.request === s.stats.requests && Array.isArray(response.messages) && response.messages.every((m): m is CoreMessage =>
m !== null && typeof m === "object" && typeof m.id === "string" && m.role === "assistant"
&& ["text", "reasoning", "tool-call"].includes(m.contentType)
&& [m.text, m.toolName, m.toolCallId].every((value) => value === undefined || typeof value === "string")
) ? response.messages : [];
const messages = s.lastMessages;
// Keep one assistant turn in arrival order, with explicit reasoning boundaries.
const latestReply = reply.length ? "\n### assistant\n\n" + handoffCells(reply).map(renderMessage).join("\n") + "\n" : "";
if (messages && messages.length > 0) {
const folded = s.lastMessagesFolded === true;
const base = renderHandoffKernel({
coreMessages: messages,
coreMessages: handoffCells(messages),
state: s.state,
full,
folded,
Expand All @@ -103,7 +125,7 @@ export function renderHandoff(s: Session, full: boolean): string {
],
},
});
return base + blockSummariesSection(s, full && folded, base);
return base + latestReply + blockSummariesSection(s, full && folded, base);
}

// v2 fallback: no snapshot persisted. Block summaries (+ originals with
Expand All @@ -122,7 +144,9 @@ export function renderHandoff(s: Session, full: boolean): string {
lines.push("");
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.");
lines.push(reply.length
? "No persisted request snapshot is available. Only the latest assistant response is included below."
: "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.");
lines.push("");
}
for (const b of active) {
Expand All @@ -146,7 +170,7 @@ export function renderHandoff(s: Session, full: boolean): string {
lines.push("Paste the block summaries above into a new session to continue without the proxy.");
lines.push("");
}
return lines.join("\n");
return lines.join("\n") + latestReply;
}

// #845: the kernel handoff never emits state.blocks[].summary, and the persisted
Expand Down
21 changes: 21 additions & 0 deletions src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type Config,
type CoreMessage,
} from "acp-kernel";
import type { HandoffReply } from "../server/handoff-response.js";
import { estimateCoreMessages } from "../preflight.js";
import { estimateWireOverhead } from "../server/budget.js";
import { handleAcpStatus } from "../acp-status.js";
Expand Down Expand Up @@ -185,6 +186,7 @@ export interface LoopCtx {
/** View handed to applyCompression (see RewriteCtx.compressMessages). */
compressMessages?: CoreMessage[];
session: Session;
reply?: HandoffReply;
log: (msg: string) => void;
proxyUrl?: string;
/** #2809: diagnostic-only — the proxy the auto chain would have picked
Expand Down Expand Up @@ -437,6 +439,13 @@ export async function* runCompressLoop(
systemPrompt: string,
signal?: AbortSignal,
): AsyncGenerator<Buffer> {
let replyPart = 0;
let replyKind: "text" | "reasoning" | undefined;
const recordReplyText = (kind: "text" | "reasoning", text: string) => {
if (replyKind !== kind) replyPart++;
replyKind = kind;
ctx.reply?.append(`part_${replyPart}`, kind, text);
};
let activeClearTimer: (() => void) | null = null;
let currentUpstream = upstream;
let roundBody: Record<string, unknown> = requestBody;
Expand Down Expand Up @@ -757,8 +766,10 @@ export async function* runCompressLoop(
}
tp.text += ev.delta;
if (!ctx.textProtocol && ev.raw) {
recordReplyText("text", ev.delta);
yield fwd(ev.raw, true);
} else if (!ctx.textProtocol && round > 1 && ev.delta.length > 0) {
recordReplyText("text", ev.delta);
yield fwd(adapter.emitText(ev.delta), true);
}
} else if (ev.kind === "reasoning") {
Expand All @@ -781,8 +792,10 @@ export async function* runCompressLoop(
if (ev.blockEnd) reasoningSealed = true;
if (!ctx.textProtocol) {
if (ev.raw) {
recordReplyText("reasoning", ev.delta);
yield fwd(ev.raw);
} else if (round > 1 && ev.delta.length > 0 && adapter.emitReasoning) {
recordReplyText("reasoning", ev.delta);
yield fwd(adapter.emitReasoning(ev.delta));
}
}
Expand All @@ -792,6 +805,10 @@ export async function* runCompressLoop(
roundParts.push({ kind: "standalone_signature", signature: ev.signature });
} else if (ev.kind === "tool_call") {
calls.push({ name: ev.name, callId: ev.callId, arguments: ev.arguments, passthrough: ev.passthrough, signature: ev.signature });
if (ev.passthrough) {
replyKind = undefined;
ctx.reply?.tool(`tool_${++replyPart}`, ev.name, ev.callId, ev.arguments);
}
} else if (ev.kind === "usage") {
usage = {
inputTokens: ev.inputTokens,
Expand Down Expand Up @@ -1139,6 +1156,7 @@ export async function* runCompressLoop(
const functionCallIds = new Set(allCalls.map(c => c.callId));

if (ctx.textProtocol && resolvedText.length > 0) {
recordReplyText("text", resolvedText);
yield adapter.emitText(resolvedText);
}

Expand Down Expand Up @@ -1389,6 +1407,8 @@ export async function* runCompressLoop(

for (const tc of realToolCalls) {
if (tc.passthrough) continue;
replyKind = undefined;
ctx.reply?.tool(`tool_${++replyPart}`, tc.name, tc.callId, tc.arguments);
yield adapter.emitToolCall(tc);
}

Expand All @@ -1414,6 +1434,7 @@ export async function* runCompressLoop(
yield adapter.emitError(msg);
return;
}
if (!truncatedDone && streamError === undefined && finishReason !== "failed" && finishReason !== "incomplete" && finishReason !== "error" && !signal?.aborted) ctx.reply?.save();
// A passthrough round already streamed the upstream's own finish
// chunk + [DONE] verbatim (original id + order); re-emitting a
// regenerated completion would duplicate them.
Expand Down
Loading
Loading