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
11 changes: 9 additions & 2 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BLOCKED_REF, COMPRESS_TOOL_NAME, type CompressionCore, type Config, type CoreMessage, type NudgeDecision, countMessageTokens, parseStoredPlaceholder, prune } from "acp-kernel";
import { BLOCKED_REF, COMPRESS_TOOL_NAME, type CompressionCore, type Config, type CoreMessage, type NudgeDecision, type RetrievalExport, applyRetrieve, countMessageTokens, parseStoredPlaceholder, prune } from "acp-kernel";
import { publicSnapshotCapBytes } from "./knobs.js";
import { buildStatusPanel } from "acp-kernel/panel";
import { fileURLToPath } from "node:url";
Expand Down Expand Up @@ -1711,6 +1711,7 @@ export async function handlePluginTool(
const callId = `${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`;
acquireInFlight(session);
let result: ProxyToolResult | undefined;
let retrievalExport: RetrievalExport | undefined;
try {
result = await withSessionLock(session, async () => {
if (parsed.expectedRevision !== undefined) {
Expand Down Expand Up @@ -1750,6 +1751,11 @@ export async function handlePluginTool(
session,
log: (m) => deps.log("info", `[${session.id}] [plugin] ${m}`),
}, callId, undefined, deps.signal);
if (nativeCaller && tool === retrieveToolName(session) && typeof args.ref === "string") {
// Preserve the session's export before a same-ref concurrent lookup.
const retrieved = applyRetrieve({ store: contentStoreOf(session), ref: args.ref, exportDir: path.join(stateDir(), "retrieve") });
if (retrieved.ok && retrieved.toolResultText === toolResult.text) retrievalExport = retrieved.export;
}
const creditDelta = (session.stats.compressCreditTokens ?? 0) - creditBefore;
const restoredInjections = session.pendingRetrievals.filter((p) => !pendingBefore.has(p.ref));
// The string tool protocol has distinct success headers for whole/derived and range restores.
Expand All @@ -1775,7 +1781,7 @@ export async function handlePluginTool(
// (sticky) — the next model request stops injecting the duplicate ephemeral wire
// tools. Guarded: only flips a session with NO existing agent binding, never
// overriding a pi/omp/opencode plugin or a launcher-registered agent.
if (typeof session.metadata.pluginAgent !== "string") {
if (typeof session.metadata.pluginAgent !== "string" && tool !== retrieveToolName(session)) {
session.metadata.pluginAgent = "mcp";
}
markDirty(session);
Expand All @@ -1796,6 +1802,7 @@ export async function handlePluginTool(
if (result.outcome !== undefined) body.outcome = result.outcome;
if (result.blocksCreated !== undefined) body.blocksCreated = result.blocksCreated;
body.result = sentResult;
if (retrievalExport !== undefined) body.retrievalExport = retrievalExport;
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(body));
}
Expand Down
78 changes: 77 additions & 1 deletion tests/ccr-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { startServer } from "../src/server.ts";
import { findCcrPluginDivergences, loadOptions, type ProxyOptions } from "../src/config.ts";
import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { _setForTest as setRegistryForTest } from "../src/registry.ts";
import { listSessions } from "../src/session.ts";
import { _resetSessionsForTest, listSessions } from "../src/session.ts";
import { ccrEnabled, ccrPluginWireOk, contentStoreOf, PLUGIN_CCR_WIRES, retrieveToolName } from "../src/store.ts";
import { handlePluginManifest } from "../src/plugin.ts";
import { setLogCapture } from "../src/logger.ts";
Expand Down Expand Up @@ -208,13 +208,89 @@ const BASE_MSGS = (): unknown[] => [
{ role: "tool", tool_call_id: "call_1", content: BIG_TEXT },
];

test("native retrieval bridge preserves proxy compression ownership", async () => {
const rig = await startRig();
const conversationId = "ccr-native-retrieval-bridge";
const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`;
const send = async (messages: unknown[]): Promise<void> => {
const response = await fetch(url, {
method: "POST",
// Isolate retrieval ownership from the separate native identity fix (#2779).
headers: { "content-type": "application/json", "x-session-id": conversationId },
body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages }),
});
assert.equal(response.status, 200, await response.text());
};
try {
await send(BASE_MSGS());
const session = listSessions().find((s) => s.metadata.pluginAgent === undefined && ccrEnabled(s));
assert.ok(session, "proxy session was armed without claiming plugin ownership");
const ref = Object.keys(contentStoreOf(session).byRef)[0];
assert.ok(ref, "original tool output has a stored ref");
const response = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId, nativeCaller: true, tool: "acp_retrieve", args: { ref } }),
});
const result = await response.json() as { ok: boolean; result?: string };
assert.equal(response.status, 200);
assert.equal(result.ok, true);
assert.match(result.result ?? "", /acp-retrieved/);
assert.ok(result.result?.includes(BIG_TEXT.slice(0, 120)), "retrieval returns the original");
assert.equal(session.metadata.pluginAgent, undefined, "read-only retrieval does not prove ownership of compression tools");
await send([...BASE_MSGS(), { role: "user", content: "Continue the build." }]);
const next = JSON.parse(rig.forwards.at(-1)!) as { tools?: Array<{ function?: { name?: string } }> };
assert.ok(next.tools?.some((t) => t.function?.name === "compress"), "proxy must keep injecting compression tools");
} finally {
await closeRig(rig);
_resetSessionsForTest();
}
});

async function closeRig(rig: Rig): Promise<void> {
rig.proxy.close();
await once(rig.proxy, "close");
rig.upstream.close();
await once(rig.upstream, "close");
}

test("native retrieval exports preserve each session's original when refs collide", async () => {
const rig = await startRig();
const originals = ["Alpha original\r\n".repeat(1800), "Beta original\r\n".repeat(1800)];
const identities = ["ses_ExportAlpha", "ses_ExportBeta"];
try {
for (let i = 0; i < identities.length; i++) {
const messages = BASE_MSGS();
messages[2] = { role: "tool", tool_call_id: "call_1", content: originals[i] };
const response = await fetch(`http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`, {
method: "POST", headers: { "content-type": "application/json", "x-session-id": identities[i] },
body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages }),
});
assert.equal(response.status, 200, await response.text());
}
const refs = rig.forwards.map(body => /\[acp-stored #(m\d+)/.exec(body)?.[1]);
assert.ok(refs[0]);
assert.equal(refs[0], refs[1], "independent sessions can reuse the same message ref");
const results = await Promise.all(identities.map(async (conversationId, i) => {
const response = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId, nativeCaller: true, tool: "acp_retrieve", args: { ref: refs[i] } }),
});
assert.equal(response.status, 200);
return await response.json() as { ok: boolean; retrievalExport?: { path: string; text: string }; result: string };
}));
for (let i = 0; i < results.length; i++) {
assert.equal(results[i].ok, true);
assert.equal(results[i].retrievalExport?.text, originals[i], "export snapshot retains exact CRLF bytes from its own session");
assert.ok(results[i].result.includes(results[i].retrievalExport?.path ?? "MISSING"));
}
assert.ok(listSessions().filter(ccrEnabled).every(session => session.metadata.pluginAgent === undefined));
} finally {
await closeRig(rig);
_resetSessionsForTest();
}
});

test("e2e plugin lane: CCR arms, stores+placeholderes, and acp_retrieve rides full text back", async () => {
const rig = await startRig();
try {
Expand Down
Loading