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
2 changes: 2 additions & 0 deletions PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ New success is `201`; exact payload replay is `200` with `replayed: true`, even

Boundary handling is `exact` when complete blocks fit inside the prefix, `expanded` when a block crosses it (crossing summaries are omitted, affected nested descendants are expanded, matched originals are retained), and `unavailable` when safe reconstruction is impossible. Blocks, nested caches, raw messages, issued ref namespace, token snapshots, rules and prefix CCR payloads are independent copies. Note that the child inherits the parent's ENTIRE issued-ref namespace (dead refs included): refs are never reused, so forks keep allocating fresh refs without colliding with ids a sibling may still hold. The child never reads its parent's later state as a fallback. Registration and first-request resume heuristics do not replace its copied state. With existing persistence enabled, raw snapshots, receipts, nested originals and the child's CCR payloads survive restart; with persistence disabled, durability is not promised. Atomic child publication/idempotency covers concurrent requests to one proxy process; concurrent writers sharing one state directory across processes are not supported by this protocol.

Lineage-only declaration (#2408): a host that cannot drive the full fork protocol (no snapshot matching, e.g. claude `--fork-session`) may still declare the parent by sending a plain identity register — `POST /__bili/plugin/register` with `conversationId` (the fresh child id), `identity: true` and `parentConversationId` — from its SessionStart hook. The declaration scopes the proxy's content-match resume inheritance (#1486) to that parent chain, so a byte-exact replay of the parent's wire history seeds refs/blocks on the child's first request, and a non-matching replay falls back to the read-only parent link (#1333). A later register without `parentConversationId` never erases the declared parent. This is strictly weaker than §8 (no dead-ref namespace, no nudge inheritance, no receipt verification) but needs no snapshot access.

中文集成要点:协议仍为 1;先读取 manifest 能力及 snapshot,按原文、role、工具身份确认匹配前缀,仅提交该前缀的 orderedMessages,不猜测多模态分支点。父 revision 变化必须重新取快照并重新匹配。子会话使用独立稳定 id,首次请求可追加尚未出站的模型回复,不能重置继承的 refs/blocks。手动摘要使用 snapshot 的 refs 和 `expectedRevision: snapshot.parentRevision` 调用公开 tool;摘要期间历史发生变化时返回 409,不执行旧摘要。状态栏读取 `contextTokens`、`contextTokensSource`、`contextTokensAt`、`model`、`contextLimit`、`contextGeneration`、`sessionId` 与 `sessionRevision`,不得用累计账单 input/cache 冒充有效上下文。手动 compress/decompress 后为独立时间及 generation 的 estimate,不改累计账单或 last-usage 基线;下一次正数 usage 才恢复 usage,零值或缺失 usage 不得复活旧观测。未知来源返回 unavailable,tokens/time/generation 为 null。

## Security
Expand Down
129 changes: 118 additions & 11 deletions src/claude-native-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "./launcher.js";
import { resolveClaudeNativePort } from "./config.js";
import { postIdentityRegister } from "./agent/shared.js";
import { lanePreferredPort } from "./instance.js";
import { claudeNativeInstalled, isBiliClaudeBaseUrl, repinClaudeManagedBaseUrl } from "./plugin-install.js";
import { claudeRoutingWarningFile } from "./paths.js";
Expand Down Expand Up @@ -314,19 +315,45 @@ export function isClaudeHostArgv(argv: string[]): boolean {
* callers then fall back to the legacy direct parent (strictly no worse
* than before). Exported for tests (inject `read` to stub the process
* table). */
export function resolveClaudeHostPid(opts: { read?: ProcReader; startPid?: number } = {}): number | undefined {
function findClaudeHost(opts: { read?: ProcReader; startPid?: number } = {}): { pid: number; argv: string[] } | undefined {
const read = opts.read ?? defaultProcReader();
let pid = opts.startPid ?? process.pid;
for (let hop = 0; hop < CLAUDE_HOST_MAX_WALK; hop++) {
const info = read(pid);
if (info === null) return undefined;
if (info.argv !== null && isClaudeHostArgv(info.argv)) return pid;
if (info.argv !== null && isClaudeHostArgv(info.argv)) return { pid, argv: info.argv };
if (info.ppid === null || info.ppid <= 1) return undefined;
pid = info.ppid;
}
return undefined;
}

export function resolveClaudeHostArgv(opts: { read?: ProcReader; startPid?: number } = {}): string[] | undefined {
return findClaudeHost(opts)?.argv;
}

export function resolveClaudeHostPid(opts: { read?: ProcReader; startPid?: number } = {}): number | undefined {
return findClaudeHost(opts)?.pid;
}

/** #2408: the parent session id of a `claude --resume <id> --fork-session`
* launch, parsed off the claude host's argv (`--resume <uuid>`,
* `--resume=<uuid>`, `-r <uuid>`). UUID-tight on purpose: a loose token
* match could adopt an unrelated flag value as the parent. `--continue
* --fork-session` carries no id and returns undefined (no declaration, the
* proxy's content matching decides on its own). Exported for tests. */
export function claudeForkParentFromArgv(argv: string[]): string | undefined {
const isSessionToken = (token: string): boolean => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(token);
for (let i = 0; i < argv.length; i++) {
const arg = stripQuotes(argv[i] ?? "");
let candidate: string | undefined;
if (arg === "--resume" || arg === "-r") candidate = stripQuotes(argv[i + 1] ?? "");
else if (arg.startsWith("--resume=")) candidate = stripQuotes(arg.slice("--resume=".length));
if (candidate !== undefined && isSessionToken(candidate)) return candidate;
}
return undefined;
}

/** Is this argv a shell running a run-and-exit one-shot — the transient hook
* wrapper shape? Covers POSIX `sh -c` (also -lc/-ic flag clusters), Windows
* `cmd /c` (/k stays open — not transient), and `powershell -Command`
Expand Down Expand Up @@ -368,7 +395,36 @@ export function chooseWatchdogParentPid(opts: { read?: ProcReader; parentPid?: n
return parentPid;
}

async function run(): Promise<void> {
/** #2408: declare fork lineage to the proxy. A `claude --resume <parent>
* --fork-session` launch fires SessionStart with source:"fork" and a FRESH
* session_id while replaying the parent's wire history on it. The
* declaration scopes the proxy's #1486 resume-inheritance to the declared
* parent chain (refs/blocks seed when the replay matches) and otherwise
* leaves the #1333 read-only parent link as fallback. Best-effort by
* design — never fails the hook. */
async function declareForkLineage(payloadJson: string, origin: string): Promise<void> {
try {
let payload: Record<string, unknown>;
try {
payload = JSON.parse(payloadJson) as Record<string, unknown>;
} catch {
return;
}
if (payload.source !== "fork") return;
const child = typeof payload.session_id === "string" ? payload.session_id : "";
if (child.length === 0) return;
const argv = resolveClaudeHostArgv();
if (argv === undefined) return;
const parent = claudeForkParentFromArgv(argv);
if (parent === undefined || parent === child) return;
await postIdentityRegister(origin, child, "claude", parent);
log(`fork session ${child.slice(0, 8)} declared parent ${parent.slice(0, 8)} (#2408)`);
} catch (err) {
log(`fork lineage declaration failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
}
}

async function run(payloadJson: string): Promise<void> {
const plan = planClaudeNativeBootstrap(process.env);
if (plan.action === "exit") return;
// #2290: detect a host that will not honor the managed base URL BEFORE
Expand Down Expand Up @@ -427,6 +483,9 @@ async function run(): Promise<void> {
`WARNING: proxy at ${handle.origin} has NO session-lifecycle watchdog (it was started without BILI_PARENT_PID, e.g. manually on this port) — it will outlive every session, and config edits only apply after that process is restarted. Kill it or start a session-owned proxy to restore the lifecycle contract (#1322).`,
);
}
// #2408: fork lineage only matters when the proxy compresses — a
// passthrough proxy ignores lineage entirely.
if (plan.action === "start") await declareForkLineage(payloadJson, handle.origin);
} catch (err) {
log(
`proxy bring-up failed on port ${plan.port} — ${err instanceof Error ? err.message : String(err)}` +
Expand All @@ -435,15 +494,63 @@ async function run(): Promise<void> {
}
}

function hookMain(): void {
// Drain the hook's stdin payload (session_id etc.) — claude waits for
// this process to exit; we never read the payload, but draining avoids a
// blocked writer if the payload ever exceeds the socket buffer.
process.stdin.resume();
void run().finally(() => {
process.stdin.destroy();
process.exit(0);
/** Safety net for the stdin drain below: claude writes the SessionStart
* JSON and closes the pipe, so 'end' fires within milliseconds — but a
* never-closed or exotic pipe must not hang the hook (claude blocks session
* start until this process exits). Two seconds is far above any real
* SessionStart payload latency while staying invisible to the user. */
export const HOOK_STDIN_DRAIN_TIMEOUT_MS = 2_000;

/** The hook entrypoint's stdin wiring, isolated for tests (#2408 review):
* collect the SessionStart payload chunks, call `runImpl` with the FULL
* payload exactly once — only after the stream has drained ('end'/'error',
* or the timeout safety net) — then exit 0. Node delivers 'data'
* asynchronously: calling run with the accumulator before drain would ship
* an empty string on every session (the bug the entrypoint tests pin).
* Exported with injectable deps so the real wiring — not a re-implementation
* — is what the tests drive. */
export function hookMainWithDeps(deps: {
input?: NodeJS.ReadableStream;
runImpl?: (payload: string) => Promise<void>;
exit?: (code: number) => void;
drainTimeoutMs?: number;
} = {}): void {
const input = deps.input ?? process.stdin;
const runImpl = deps.runImpl ?? run;
const exit = deps.exit ?? ((code: number) => process.exit(code));
const destroyInput = (): void => {
try {
(input as { destroy?: () => void }).destroy?.();
} catch {
// already closed
}
};
let payload = "";
let started = false;
const start = (): void => {
if (started) return;
started = true;
clearTimeout(timer);
void runImpl(payload).finally(() => {
destroyInput();
exit(0);
});
};
const timer = setTimeout(start, deps.drainTimeoutMs ?? HOOK_STDIN_DRAIN_TIMEOUT_MS);
if (typeof (input as { setEncoding?: (e: string) => void }).setEncoding === "function") {
(input as { setEncoding: (e: string) => void }).setEncoding("utf8");
}
input.on("data", (chunk: string) => {
payload += chunk;
});
input.on("end", start);
input.on("error", start);
}

function hookMain(): void {
// claude waits for this process to exit, and draining avoids a blocked
// writer if the payload ever exceeds the socket buffer.
hookMainWithDeps();
}

// Direct entry (dist/claude-native-bootstrap.js spawned by claude's hook, or
Expand Down
6 changes: 5 additions & 1 deletion src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,11 @@ export function queuePluginRegister(conversationId: string, agent: string, ident
pendingRegisters.push({ conversationId, agent, ts: Date.now(), ...(parentConversationId ? { parentConversationId } : {}) });
while (pendingRegisters.length > MAX_PENDING_REGISTERS) pendingRegisters.shift();
} else {
registeredIds.set(conversationId, { agent, ...(parentConversationId ? { parentConversationId } : {}) });
// #2408: a parent declaration is sticky for a conversation — a
// follow-up register WITHOUT one (claude's MCP shim re-registering the
// session the fork hook already declared) must not erase it.
const parent = parentConversationId ?? registeredIds.get(conversationId)?.parentConversationId;
registeredIds.set(conversationId, { agent, ...(parent ? { parentConversationId: parent } : {}) });
while (registeredIds.size > MAX_PENDING_REGISTERS) {
const oldest = registeredIds.keys().next().value;
if (oldest !== undefined) registeredIds.delete(oldest);
Expand Down
22 changes: 22 additions & 0 deletions src/prefix-affinity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,28 @@ export class PrefixAffinityResolver {
return best ? { sessionId: best.sessionId, sharedDepth: best.sharedDepth } : null;
}

/** #2408: the DECLARED-parent variant of findResumeParent — an explicit
* lineage declaration (claude --fork-session SessionStart register,
* opencode derived register) scopes the content match to that parent's
* chain only, killing the multi-chain ambiguity the unscoped scan
* refuses to guess on. Same head-anchored byte-exact judgement as
* findResumeParent (strictly deeper than the parent, >=
* MIN_RESUME_PREFIX). Null when the parent chain is untracked or its
* replay does not match — the caller then falls back to the read-only
* derived link (#1333). */
findResumeParentWithin(parentId: string, messages: unknown[], selfSessionId: string): { sessionId: string; sharedDepth: number } | null {
if (parentId === selfSessionId) return null;
const entry = this.trackedChains.get(parentId);
if (entry === undefined || entry.depth < MIN_RESUME_PREFIX) return null;
const msgs = normalizeAffinityMessages(messages);
if (!hasUserMessage(msgs)) return null;
const hashes = chainHashes(msgs);
if (hashes.length < MIN_RESUME_PREFIX) return null;
if (msgs.length <= entry.depth) return null;
if (hashes[entry.depth - 1] !== entry.tailHash) return null;
return { sessionId: parentId, sharedDepth: entry.depth };
}

/** #2241: does `messages` continue the tracked chain of `sessionId`?
* True when the session's stored chain is a byte-exact head-anchored
* prefix of the incoming list — the progressive hash at the stored
Expand Down
Loading
Loading