Files
claude-agent-acp/src/fork-session.ts
Ben Brandt 1dadbfa68a feat: announce session cursors on v2 and fork at a cursor
The session cursors RFD lets an Agent name the positions of a session that a
method can act at, and `session/fork` takes one as `cursorId`. The adapter
announced none and refused every `cursorId`.

On v2, each user message that follows another entry of the conversation now
gets a `cursor_update` right after it, live and in a replay. The cursor is
anchored `before` the message and has the `fork` capability. `session/fork`
with its `cursorId` copies the history before that message, so a client can
edit a message or ask again from there.

- `src/session-cursors.ts` owns the rules. The `cursorId` is derived from
  the uuid of the user message, which Claude Code stores, so it is the same
  live, in every replay and after a restart, and the adapter keeps no
  cursors of its own.
- A fork reads the stored history as a replay reads it, and ends the copy at
  the entry before the cursor's message (`upToMessageId`). Any other
  `cursorId` fails with -32602 before anything is copied.
- The first entry of a history has no cursor: nothing is before it. A slash
  command gets none live, because a replay shows no user message for it. A
  subagent's session gets none: a client cannot fork it.

A v1 client gets no cursors yet. A fork takes a `cursorId` on both versions.
2026-11-18 17:14:11 +01:00

279 lines
9.6 KiB
TypeScript

import {
ForkSessionRequest,
ForkSessionResponse,
RequestError,
} from "@agentclientprotocol/sdk/unstable";
import {
forkSession as forkClaudeSession,
getSessionMessages,
type SessionStoreEntry,
} from "@anthropic-ai/claude-agent-sdk";
import { createHash } from "node:crypto";
import { loadFullSessionHistory, readHistoryAcrossCompactions } from "./resumed-session.js";
import { forkPointOf } from "./session-cursors.js";
import { assistantMessageText } from "./session-failure-extension.js";
import { SessionTiming } from "./session-timing.js";
type ForkSessionMeta = {
[key: string]: unknown;
jetbrains?: {
air?: {
fork?: {
version?: number;
messageId?: string;
messageFingerprint?: string;
messageOccurrence?: number;
};
};
};
};
type ForkSessionDependencies = {
liveMessageIdToUuid?: ReadonlyMap<string, string>;
logger?: { log: (...args: unknown[]) => void };
messageIdForGrouping: (message: {
type?: string;
uuid?: string | null;
message?: unknown;
}) => string | undefined;
};
type ForkPoint = {
messageId: string;
messageFingerprint?: string;
messageOccurrence?: number;
};
function forkPoint(meta: unknown): ForkPoint | undefined {
const fork = (meta as ForkSessionMeta | null | undefined)?.jetbrains?.air?.fork;
if (fork?.version !== 1) return undefined;
const messageId = fork.messageId?.trim();
if (!messageId) return undefined;
const messageFingerprint = fork.messageFingerprint?.trim();
const messageOccurrence = fork.messageOccurrence;
return {
messageId,
...(messageFingerprint ? { messageFingerprint } : {}),
// AIR computes this with count(...) over the visible prefix, so it is 1-based.
...(typeof messageOccurrence === "number" &&
Number.isSafeInteger(messageOccurrence) &&
messageOccurrence > 0
? { messageOccurrence }
: {}),
};
}
function forkPointMessageIdCandidates(messageId: string): string[] {
// Older AIR builds sent their visible segment id. Prefer the exact id before its ACP source id.
const protocolMessageId = messageId.replace(/:segment:\d+$/, "");
return protocolMessageId === messageId ? [messageId] : [messageId, protocolMessageId];
}
function assistantGroups(
entries: SessionStoreEntry[],
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
) {
const groups = new Map<string, { uuid?: string; text: string }>();
for (const entry of entries) {
if (
entry.type !== "assistant" ||
entry.isSidechain === true ||
entry.parent_tool_use_id != null ||
entry.parent_agent_id != null
) {
continue;
}
const messageId = messageIdForGrouping(entry);
if (!messageId) continue;
const group = groups.get(messageId) ?? { text: "" };
if (typeof entry.uuid === "string" && entry.uuid.length > 0) group.uuid = entry.uuid;
group.text += assistantMessageText(entry.message) ?? "";
groups.set(messageId, group);
}
return groups;
}
function fingerprint(text: string): string {
return `sha256:${createHash("sha256").update(text).digest("hex")}`;
}
function fingerprintOccurrenceOnBranch(
targetUuid: string,
expectedFingerprint: string,
entries: SessionStoreEntry[],
groups: ReturnType<typeof assistantGroups>,
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
): number {
const entriesByUuid = new Map(
entries.flatMap((entry) => (typeof entry.uuid === "string" ? [[entry.uuid, entry]] : [])),
);
const seenGroups = new Set<string>();
let occurrence = 0;
let cursor: string | undefined = targetUuid;
while (cursor) {
const entry = entriesByUuid.get(cursor);
if (!entry) break;
if (
entry.type === "assistant" &&
entry.isSidechain !== true &&
entry.parent_tool_use_id == null &&
entry.parent_agent_id == null
) {
const messageId = messageIdForGrouping(entry);
if (messageId && !seenGroups.has(messageId)) {
seenGroups.add(messageId);
const group = groups.get(messageId);
if (group && fingerprint(group.text) === expectedFingerprint) occurrence++;
}
}
cursor = typeof entry.parentUuid === "string" ? entry.parentUuid : undefined;
}
return occurrence;
}
function resolveFromFullHistory(
entries: SessionStoreEntry[],
candidates: string[],
point: ForkPoint,
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
): string | undefined {
const groups = assistantGroups(entries, messageIdForGrouping);
const exact = candidates.map((candidate) => groups.get(candidate)?.uuid).find(Boolean);
if (exact) return exact;
if (!point.messageFingerprint || !point.messageOccurrence) return undefined;
const fingerprintMatches = [...groups.values()].filter(
(group) => group.uuid && fingerprint(group.text) === point.messageFingerprint,
);
// If only one persisted message has this content, the fingerprint already
// identifies it even when an older client supplied an incompatible index.
if (fingerprintMatches.length === 1) return fingerprintMatches[0]?.uuid;
const occurrenceMatches = fingerprintMatches.filter(
(group) =>
group.uuid &&
fingerprintOccurrenceOnBranch(
group.uuid,
point.messageFingerprint!,
entries,
groups,
messageIdForGrouping,
) === point.messageOccurrence,
);
return occurrenceMatches.length === 1 ? occurrenceMatches[0]?.uuid : undefined;
}
/**
* Whether `error` is the Claude SDK's report that `sessionId` has no
* transcript: `forkSession` and `importSessionToStore` throw
* `Error("Session <id> not found")`, and both throw
* `"Invalid sessionId: <id>"` for an id that is not a UUID.
*/
function isUnknownSessionError(error: unknown, sessionId: string): boolean {
if (!(error instanceof Error)) return false;
return (
error.message === `Session ${sessionId} not found` ||
error.message === `Invalid sessionId: ${sessionId}`
);
}
/**
* Copies the transcript of `params.sessionId` into a new session: all of it,
* or with a `cursorId` the history before that session cursor (see
* `session-cursors.ts`).
*
* Fails with invalid params (-32602) for a `cursorId` that is no cursor of
* the session's stored history. ACP forbids forking the whole session, or at
* another position, in its place.
*/
export async function forkSession(
params: ForkSessionRequest,
dependencies: ForkSessionDependencies,
): Promise<ForkSessionResponse> {
try {
return await forkTranscript(params, dependencies);
} catch (error) {
if (isUnknownSessionError(error, params.sessionId)) {
throw RequestError.sessionNotFound(params.sessionId);
}
throw error;
}
}
async function forkTranscript(
params: ForkSessionRequest,
dependencies: ForkSessionDependencies,
): Promise<ForkSessionResponse> {
const timing = new SessionTiming(dependencies.logger, "fork", params.sessionId);
if (params.cursorId != null) {
// The history as a replay reads it, which announces the cursors.
const history = await readHistoryAcrossCompactions(
params.sessionId,
await getSessionMessages(params.sessionId),
);
const upToMessageId = forkPointOf(params.cursorId, history);
timing.phase("cursor", ` resolution=${upToMessageId ? "found" : "missing"}`);
if (upToMessageId === undefined) {
throw RequestError.invalidParams(
{ cursorId: params.cursorId },
`Session ${params.sessionId} has no cursor ${params.cursorId} that a fork can start at. Use a cursor that the session announced with the \`fork\` capability, or send the request without \`cursorId\` to fork the whole session.`,
);
}
const forked = await forkClaudeSession(params.sessionId, { upToMessageId });
timing.phase("sdk-fork");
return { sessionId: forked.sessionId };
}
const point = forkPoint(params._meta);
// SDK `dir` scopes source lookup, not the fork's working directory. Search
// all projects: params.cwd can name a different workspace for the new session.
if (!point) {
const forked = await forkClaudeSession(params.sessionId);
timing.phase("sdk-fork", " resolution=latest");
return { sessionId: forked.sessionId };
}
const candidateIds = forkPointMessageIdCandidates(point.messageId);
const liveUuid = candidateIds
.map((candidateId) => dependencies.liveMessageIdToUuid?.get(candidateId))
.find(Boolean);
const history = liveUuid ? undefined : await getSessionMessages(params.sessionId);
timing.phase("active-history", ` resolution=${liveUuid ? "live" : "pending"}`);
const messageUuid =
liveUuid ??
candidateIds
.map(
(candidateId) =>
history
?.slice()
.reverse()
.find((message) => dependencies.messageIdForGrouping(message) === candidateId)?.uuid,
)
.find(Boolean);
// getSessionMessages returns only the active parentUuid chain. The full history keeps inactive branches that AIR can still reference.
const fullHistoryUuid = messageUuid
? undefined
: resolveFromFullHistory(
await loadFullSessionHistory(params.sessionId),
candidateIds,
point,
dependencies.messageIdForGrouping,
);
timing.phase(
"full-history",
` resolution=${liveUuid ? "live" : messageUuid ? "active" : fullHistoryUuid ? "full" : "missing"}`,
);
if (!messageUuid && !fullHistoryUuid) {
throw RequestError.invalidParams(
{ messageId: point.messageId },
`Fork point message ${point.messageId} was not found in session ${params.sessionId}`,
);
}
const forked = await forkClaudeSession(params.sessionId, {
upToMessageId: messageUuid ?? fullHistoryUuid,
});
timing.phase("sdk-fork");
return { sessionId: forked.sessionId };
}