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
10 changes: 10 additions & 0 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,13 @@ const MARKER_INTEGRITY_NOTE =
export function withMarkerIntegrityNote(text: string): string {
return text + MARKER_INTEGRITY_NOTE;
}

// #760: per-call conversation_id for MCP tools. Hosts that share ONE MCP shim
// process across several concurrent conversations (kimi web et al.) have no
// env/meta session channel, so the proxy prints its own resolved session id
// and the model echoes it back as the conversation_id argument of every
// mcp__bili__ call. Session-stable, so it rides the static system-prompt part
// (prefix-cache safe) next to MARKER_INTEGRITY_NOTE, in BOTH modes.
export function withConversationIdNote(text: string, conversationId: string): string {
return text + `\n\n[Your bili conversation id: ${conversationId}. When calling the bili compression tools, pass this value as the conversation_id argument so a shared MCP process can route the call to THIS session.]`;
}
43 changes: 31 additions & 12 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
// POST /__bili/plugin/tool. Claude Code passes its session id via the MCP
// initialize request's _meta.ui.sessionId (documented SessionStart context);
// we also accept BILI_CONVERSATION_ID env (codex spawn-time registration).
// #760: a fourth channel for hosts that share ONE shim across several
// concurrent conversations (no env/meta session at all): every tool accepts an
// optional conversation_id argument the model copies from the proxy's notes,
// which overrides the default binding for that one call only. No registration
// is issued for per-call ids — the proxy resolves them directly and flips the
// target session to plugin mode on successful execution.

import fs from "node:fs";
import path from "node:path";
Expand Down Expand Up @@ -70,7 +76,9 @@ const IDENTITY_BINDING = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim());
const ORPHAN_ADOPT = IDENTITY_BINDING && process.env.BILI_MCP_NO_ORPHAN_ADOPT !== "1";
let manifestTools: McpToolDef[] = [];
let conversationId = CONVERSATION_FROM_ENV;
let registered = false;
// #760: every conversation this shim has ever registered — the default
// binding plus any per-call ids seen so far (issue-once each).
const registeredConversations = new Set<string>();
let initialized = false;
function send(msg: unknown): void {
process.stdout.write(JSON.stringify(msg) + "\n");
Expand Down Expand Up @@ -105,14 +113,15 @@ function ensureManifest(): Promise<void> {
return manifestPromise;
}

export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS): Promise<string> {
export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS, conversationIdOverride: string | undefined = undefined): Promise<string> {
const effectiveConversationId = conversationIdOverride ?? conversationId;
for (let attempt = 0; ; attempt++) {
let res: Response;
try {
res = await fetch(`${resolveProxyOrigin()}/__bili/plugin/tool`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId, tool, args }),
body: JSON.stringify({ conversationId: effectiveConversationId, tool, args }),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (err) {
Expand All @@ -123,9 +132,11 @@ export async function forwardTool(tool: string, args: unknown, timeoutMs: number
if (res.ok && data.ok) return data.result ?? "";
// #656: the shim's captured id was never registered — the host likely
// resumed its session and forked a new id after this shim spawned.
// Adopt the proxy's latest active conversation and retry once.
// Adopt the proxy's latest active conversation and retry once. Armed
// for DEFAULT-bound calls only: a per-call (#760) id naming an unknown
// session must fail loudly, never adopt a sibling conversation.
if (
res.status === 404 && attempt === 0 && ORPHAN_ADOPT && conversationId &&
res.status === 404 && attempt === 0 && ORPHAN_ADOPT && conversationIdOverride === undefined && conversationId &&
typeof data.error === "string" && data.error.includes("no model request has arrived")
) {
if (await adoptLatestActiveConversation()) continue;
Expand Down Expand Up @@ -181,14 +192,14 @@ async function handleMessage(msg: {
const fromMeta = params._meta?.ui?.sessionId?.trim();
if (fromMeta) conversationId ??= fromMeta;
initialized = true;
if (conversationId && !registered) {
if (conversationId && !registeredConversations.has(conversationId)) {
const registerFetch = fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId, agent: "mcp", identity: IDENTITY_BINDING }),
signal: AbortSignal.timeout(5000),
});
registered = true; // issue-once: a repeated initialize must not re-register
registeredConversations.add(conversationId); // issue-once: a repeated initialize must not re-register
if (IDENTITY_BINDING) {
// Identity-mode binding survives any arrival order —
// respond immediately so pipelined hosts are not stuck
Expand Down Expand Up @@ -225,20 +236,28 @@ async function handleMessage(msg: {
}
case "tools/call": {
const tool = typeof params.name === "string" ? params.name : "";
const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {};
const rawArgs: Record<string, unknown> = params.arguments && typeof params.arguments === "object" ? (params.arguments as Record<string, unknown>) : {};
if (!tool) {
sendError(id, ERR_TOOL, "params.name is required");
return;
}
if (!conversationId) {
sendError(id, ERR_TOOL, "no conversation id (set BILI_CONVERSATION_ID or connect via Claude Code MCP session meta)");
// #760: per-call conversation_id — the model copies the id the
// proxy printed in its notes ("your bili conversation id: …").
// Overrides the default binding (env/meta); stripped before
// forwarding since the proxy routes on the body-level field.
const perCallRaw = rawArgs.conversation_id;
const perCall = typeof perCallRaw === "string" ? perCallRaw.trim() : "";
const args = { ...rawArgs };
delete args.conversation_id;
if (!perCall && !conversationId) {
sendError(id, ERR_TOOL, "no conversation id (pass the conversation_id argument — see the 'your bili conversation id' line in the proxy notes — or set BILI_CONVERSATION_ID or connect via Claude Code MCP session meta)");
return;
}
try {
const text = await forwardTool(tool, args);
const text = await forwardTool(tool, args, TOOL_TIMEOUT_MS, perCall || undefined);
sendResult(id, { content: [{ type: "text", text }], isError: false });
} catch (err) {
// Tool-level failures are results (isError), not JSON-RPC
// Protocol failures are results (isError), not JSON-RPC
// errors, so the host surfaces them to the model.
sendResult(id, { content: [{ type: "text", text: `bili tool error: ${err instanceof Error ? err.message : String(err)}` }], isError: true });
}
Expand Down
103 changes: 86 additions & 17 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { buildStatusPanel } from "acp-kernel/panel";
import { fileURLToPath } from "node:url";
import fs from "node:fs";
import path from "node:path";
import { acquireInFlight, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.js";
import { acquireInFlight, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.js";
import { ABSORB_TOOL, ABSORB_TOOL_NAME, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, ACP_TOOLS_ANTHROPIC, ACP_TOOLS_OPENAI, ACP_TOOLS_RESPONSES, PROXY_TOOL_NAMES } from "./compress-tool.js";
import { effectiveAbsorbConfig, isProxyToolFor } from "./absorb.js";
import { executeProxyTool } from "./loop/core.js";
Expand Down Expand Up @@ -319,18 +319,56 @@ export function handlePluginCompact(payload: string, res: import("node:http").Se
res.end(JSON.stringify({ ok: false, error: "conversationId is required" }));
return;
}
const entry = conversations.get(conversationId);
const session = entry ? peekSession(entry.sessionId) : undefined;
if (!entry || !session) {
const { session, entry } = resolveConversation(conversationId);
// #760: the verbatim-id fallback above can resolve a session with NO map
// entry (first call), so only the session itself gates execution.
if (!session) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation (no model request has arrived with this conversation id yet)" }));
res.end(JSON.stringify({
ok: false,
error: entry
? `unknown plugin conversation id "${conversationId}" (id registered but session not resident)`
: `unknown plugin conversation id "${conversationId}" (no model request has arrived with this conversation id yet)`,
}));
return;
}
markCompactionBoundary(session);
entry.lastSeen = Date.now();
if (entry) entry.lastSeen = Date.now();
res.end(JSON.stringify({ ok: true, conversationId }));
}

// #760: per-call conversation_id for MCP tools. Hosts that share ONE shim
// process across several concurrent conversations have no env/meta session
// channel, so the model supplies the target conversation per call (the proxy
// prints its own session id in the wire notes). The param is added to CLONED
// schemas only — wire-mode injection serves the kernel constants directly and
// those models are routed by request identity, not arguments.
const CONVERSATION_ID_PARAM = {
type: "string" as const,
description:
"Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). " +
"Pass it on every call when your host shares one MCP process across several concurrent conversations; " +
"omit it when the host bound the session itself.",
};

function withConversationIdParam(tool: unknown): unknown {
const copy = structuredClone(tool);
if (!copy || typeof copy !== "object") return copy;
const t = copy as Record<string, unknown>;
const add = (schema: unknown): void => {
if (!schema || typeof schema !== "object") return;
const s = schema as { properties?: Record<string, unknown> };
s.properties = { ...(s.properties ?? {}), conversation_id: CONVERSATION_ID_PARAM };
};
if (t.input_schema !== undefined) add(t.input_schema);
else {
const fn = t.function;
if (fn && typeof fn === "object") add((fn as { parameters?: unknown }).parameters);
else add(t.parameters);
}
return copy;
}

export function handlePluginManifest(res: import("node:http").ServerResponse): void {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({
Expand All @@ -345,9 +383,9 @@ export function handlePluginManifest(res: import("node:http").ServerResponse): v
// manifest has no request context to know which route will win.
toolNames: [...PROXY_TOOL_NAMES, ABSORB_TOOL_NAME],
tools: {
anthropic: [...ACP_TOOLS_ANTHROPIC, ABSORB_TOOL],
openai: [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI],
responses: [...ACP_TOOLS_RESPONSES, ABSORB_TOOL_RESPONSES],
anthropic: [...ACP_TOOLS_ANTHROPIC, ABSORB_TOOL].map(withConversationIdParam),
openai: [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI].map(withConversationIdParam),
responses: [...ACP_TOOLS_RESPONSES, ABSORB_TOOL_RESPONSES].map(withConversationIdParam),
},
headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER },
toolEndpoint: "/__bili/plugin/tool",
Expand Down Expand Up @@ -379,14 +417,32 @@ function conversationIdForSession(sessionId: string): string | undefined {
return bestId;
}

/** Resolve a caller-supplied conversation id to a resident session through every
* known channel, in precedence order: (1) the persisted conversation→session map
* (plugin binding / prior calls), (2) the verbatim session id (#760 — the id IS
* the client-provided conversation value), (3) the proxy-derived canonical pfa-*
* alias (#760b — every session exposes a stable canonical id the model echoes
* back from the wire notes). Paths 2/3 record the resolved mapping so later
* calls hit path 1 directly. Read-only w.r.t. creation: an unknown id finds
* nothing and creates nothing. */
function resolveConversation(conversationId: string): { session: Session | undefined; entry?: ConversationEntry } {
const entry = conversations.get(conversationId);
let session = entry ? peekSession(entry.sessionId) : undefined;
if (!session) {
session = peekSession(conversationId) ?? findSessionByCanonicalId(conversationId);
if (session) recordPluginSession(conversationId, session.id);
}
return { session, entry };
}

/** Context-level visibility for plugin UIs (status bars / slash commands):
* the same usage the nudge decision sees, keyed by conversation id. */
export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false): void {
let entry = conversations.get(conversationId);
let session = entry ? peekSession(entry.sessionId) : undefined;
const { session: resolvedSession, entry } = resolveConversation(conversationId);
let session = resolvedSession;
let viaFallback = false;
let resolvedConversationId = conversationId;
if ((!entry || !session) && fallbackLatest) {
if (!session && fallbackLatest) {
// #404: only sessions with real activity in THIS process qualify.
// Before the fix every boot-restored session carried lastSeen =
// restore time, so a 245-way tie resolved by insertion (readdir)
Expand Down Expand Up @@ -501,9 +557,10 @@ export async function handlePluginTool(
res.end(JSON.stringify({ ok: false, error: `conversationId is required (send the same value as the ${PLUGIN_CONVERSATION_HEADER} header)` }));
return;
}
const entry = conversations.get(conversationId);
const session = entry ? peekSession(entry.sessionId) : undefined;
if (!entry || !session) {
const { session, entry } = resolveConversation(conversationId);
// #760: the verbatim-id fallback above can resolve a session with NO map
// entry (first call), so only the session itself gates execution.
if (!session) {
// #656: two distinct failures shared one message before. An id that was
// NEVER registered is the classic stale-shim-id case (host resumed its
// session after the MCP shim captured CLAUDE_CODE_SESSION_ID) — say so,
Expand All @@ -528,8 +585,12 @@ export async function handlePluginTool(
res.end(JSON.stringify({ ok: false, error: `unknown tool "${tool}" (expected one of: ${allowed.join(", ")})` }));
return;
}
entry.lastSeen = Date.now();
const args = parsed.args && typeof parsed.args === "object" ? (parsed.args as Record<string, unknown>) : {};
if (entry) entry.lastSeen = Date.now();
const args = parsed.args && typeof parsed.args === "object" ? { ...(parsed.args as Record<string, unknown>) } : {};
// #760: the MCP manifest advertises an optional conversation_id argument
// for per-call routing; routing itself uses the body-level conversationId
// field, so strip it before kernel arg parsing sees it.
delete args.conversation_id;
const callId = `plugin_${Date.now().toString(36)}`;
acquireInFlight(session);
let result: string;
Expand Down Expand Up @@ -557,6 +618,14 @@ export async function handlePluginTool(
return;
}
releaseInFlight(session);
// #760b: evidence-based plugin-mode flip. A successful MCP tool execution proves
// this session's host owns the bili compression tools, so bind it to plugin mode
// (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") {
session.metadata.pluginAgent = "mcp";
}
markDirty(session);
deps.log("info", `[${session.id}] [plugin] tool ${tool} executed via plugin (${result.length} chars)`);
res.writeHead(200, { "content-type": "application/json" });
Expand Down
Loading
Loading