Skip to content

Commit fc9a61e

Browse files
committed
feat: negotiate a client-neutral fork point
A client that opts in with initialize clientCapabilities._meta.forkPoint gets _meta.forkPoint {version: 1, boundary: "turn"} and can fork a session at a message with session/fork _meta.forkPoint {messageId, messageFingerprint?, messageOccurrence?}. The fingerprint is taken over the agent message text as the client received it, with file citations rendered. Invalid fields, unknown messages and fork points from clients that did not opt in fail with invalidParams and structured data. The fork response reports the turn boundary it kept. The AIR fork point is unchanged.
1 parent 0f50c0b commit fc9a61e

8 files changed

Lines changed: 412 additions & 25 deletions

File tree

‎docs/air-extensions.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1444,6 +1444,53 @@ It adds this object to the `session/fork` request:
14441444
- When no message matches, the request fails with `invalidParams`.
14451445
- The fork keeps the history up to the turn that holds the message.
14461446

1447+
### Client-neutral fork point
1448+
1449+
A client that is not AIR can fork at a message without the `_meta.jetbrains.air` namespace.
1450+
It opts in with `initialize.clientCapabilities._meta`:
1451+
1452+
```json
1453+
{ "forkPoint": { "version": 1 } }
1454+
```
1455+
1456+
- Accepted only when `forkPoint` is an object whose `version` is an integer of at least 1. Anything else
1457+
enables nothing.
1458+
- The opt-in works on ACP v1 and v2. The `initialize` answer of an opted-in client has the top-level
1459+
`_meta.forkPoint: {"version": 1, "boundary": "turn"}`. `boundary: "turn"` means that a fork keeps the whole
1460+
turn that holds the message, the items after the message included.
1461+
1462+
The `session/fork` request carries the fork point in its top-level `_meta`:
1463+
1464+
```json
1465+
{ "_meta": { "forkPoint": { "messageId": "item-12", "messageFingerprint": "sha256:<64 hex>", "messageOccurrence": 1 } } }
1466+
```
1467+
1468+
- Without `_meta.forkPoint`, the fork copies the whole session, as before.
1469+
- A client that did not opt in gets `invalidParams` with the data `{"forkPoint": {"reason": "notNegotiated"}}`.
1470+
- `version` is optional; when present it must be `1`.
1471+
- `messageId` must be a non-empty string. It matches the id of any Codex item, the `messageId` of the
1472+
session update chunks. The `:segment:<n>` suffix of the AIR form is not read.
1473+
- `messageFingerprint` is optional: `sha256:` and 64 lowercase hex digits. It is the SHA-256 digest of the
1474+
agent message text as the client received it, so with file citations already rendered as Markdown links,
1475+
against the cwd of the source thread. The adapter uses it when no item has the id.
1476+
- `messageOccurrence` is optional, a positive integer, and `1` by default.
1477+
It selects among the agent messages of the whole thread with the same fingerprint.
1478+
- An invalid field fails the request with `invalidParams` and the data `{"forkPoint": {"field": "<name>"}}`,
1479+
where the name is `forkPoint` when the value is not an object.
1480+
- When no message matches, the request fails with `invalidParams` and the data
1481+
`{"forkPoint": {"messageId": "<requested id>", "reason": "notFound"}}`.
1482+
- When a request has both `_meta.forkPoint` and `_meta.jetbrains.air.fork`, only `_meta.forkPoint` is read.
1483+
1484+
The `session/fork` answer, on ACP v1 and v2, then says where the fork ends:
1485+
1486+
```json
1487+
{ "_meta": { "forkPoint": { "boundary": "turn", "messageId": "item-12", "turnId": "turn-4", "lastItemId": "item-15", "matchedBy": "id" } } }
1488+
```
1489+
1490+
- `messageId` is the id of the matched Codex item, `turnId` the last turn the fork keeps, and `lastItemId`
1491+
the last item of that turn.
1492+
- `matchedBy` is `id` or `fingerprint`.
1493+
14471494
## Presentation hints
14481495

14491496
The adapter sends these keys only to AIR:

‎src/CodexAcpServer.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,13 @@ import {
221221
JETBRAINS_META_KEY,
222222
} from "./AirExtension";
223223
import {NEUTRAL_SESSION_INDEX_META_KEY} from "./SessionIndex";
224+
import {
225+
clientRequestsNeutralForkPoint,
226+
forkPointNotNegotiatedError,
227+
hasNeutralForkPoint,
228+
NEUTRAL_FORK_POINT_META_KEY,
229+
neutralForkPointCapability,
230+
} from "./SessionFork";
224231
import {SessionIndexService} from "./SessionIndexService";
225232
import type {SessionIndexTitleState} from "./SessionIndexTitles";
226233
import {ASYNC_TASK_STOP_METHOD, asyncTaskCapability} from "./async-tasks/AsyncTaskExtension";
@@ -510,6 +517,8 @@ export class CodexAcpServer {
510517
/** The capability choices of the client for tool call and plan reports. */
511518
private capabilities: ClientCapabilities;
512519
private booleanConfigOptionsSupported: boolean;
520+
/** Whether the client opted into the client-neutral `session/fork` `_meta.forkPoint`. */
521+
private neutralForkPointSupported = false;
513522
/** Last `authStatus` pushed to the client; used to suppress duplicates. */
514523
private currentAuthStatus: AuthStatus | null;
515524
/**
@@ -790,6 +799,7 @@ export class CodexAcpServer {
790799
if (appServer) await appServer;
791800
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
792801
this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
802+
this.neutralForkPointSupported = clientRequestsNeutralForkPoint(_params.clientCapabilities);
793803
this.sessionIndex.configure(_params.clientCapabilities);
794804
this.hookReview.configure(_params.clientCapabilities?._meta?.["codexHooks"], this.capabilities.airClient);
795805
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
@@ -854,6 +864,7 @@ export class CodexAcpServer {
854864
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
855865
// Boolean config options are baseline on v2, so there is nothing to probe.
856866
this.booleanConfigOptionsSupported = true;
867+
this.neutralForkPointSupported = clientRequestsNeutralForkPoint(clientCapabilities);
857868
this.sessionIndex.configure(clientCapabilities, {neutral: false});
858869
await this.runWithProcessCheck(() => this.codexAcpClient.initialize({clientInfo: params.info}));
859870
this.sessionIndex.observe(this.codexAcpClient);
@@ -941,6 +952,10 @@ export class CodexAcpServer {
941952
"async-tasks": asyncTaskCapability(),
942953
} : {}),
943954
...(this.hookReview.enabled ? {codexHooks: {version: 1, reviewToken: true}} : {}),
955+
// The client-neutral fork point, see `docs/air-extensions.md`.
956+
...(this.neutralForkPointSupported ? {
957+
[NEUTRAL_FORK_POINT_META_KEY]: neutralForkPointCapability(),
958+
} : {}),
944959
// The session index for a client that opted in without AIR, see `docs/air-extensions.md`.
945960
...(neutralSessionIndex ? {
946961
[NEUTRAL_SESSION_INDEX_META_KEY]: neutralSessionIndex,
@@ -1270,6 +1285,7 @@ export class CodexAcpServer {
12701285
| WithAcpMcpServers<acp.ResumeSessionRequest>
12711286
| WithAcpMcpServers<acp.ForkSessionRequest>,
12721287
operation: "new" | "resume" | "fork" = "sessionId" in request ? "resume" : "new",
1288+
onForked?: (metadata: SessionMetadata) => void,
12731289
): Promise<[SessionId, LegacySessionModelState, SessionModeState]> {
12741290
clientSystemPromptText(request.systemPrompt);
12751291
const existingSessionRequest = request as WithAcpMcpServers<acp.ResumeSessionRequest> | WithAcpMcpServers<acp.ForkSessionRequest>;
@@ -1332,6 +1348,7 @@ export class CodexAcpServer {
13321348
previousInstructions,
13331349
);
13341350
});
1351+
onForked?.(sessionMetadata);
13351352
} else {
13361353
logger.log(`Create new session...`);
13371354
sessionMetadata = await this.runWithProcessCheck(() => {
@@ -1990,6 +2007,9 @@ export class CodexAcpServer {
19902007
async forkSession(params: WithAcpMcpServers<acp.ForkSessionRequest>): Promise<acp.ForkSessionResponse> {
19912008
params = this.withV1SessionInstructionAppend(params);
19922009
clientSystemPromptText(params.systemPrompt);
2010+
if (hasNeutralForkPoint(params._meta) && !this.neutralForkPointSupported) {
2011+
throw forkPointNotNegotiatedError();
2012+
}
19932013
this.assertInstructionsReady(params.sessionId);
19942014
return this.hookReview.run(params.cwd, params._meta,
19952015
() => this.sessionIndex.forking(params.sessionId, () => this.createFork(params)));
@@ -2003,12 +2023,16 @@ export class CodexAcpServer {
20032023
if (appServer) await appServer;
20042024
logger.log("Forking session...", {sessionId: params.sessionId});
20052025
try {
2006-
const [sessionId, , modeState] = await this.tryCreateSession(params, "fork");
2026+
let forkPoint: SessionMetadata["forkPoint"];
2027+
const [sessionId, , modeState] = await this.tryCreateSession(params, "fork", metadata => {
2028+
forkPoint = metadata.forkPoint;
2029+
});
20072030
logger.log("Session forked", {sourceSessionId: params.sessionId, sessionId});
20082031
return {
20092032
sessionId,
20102033
modes: modeState,
20112034
...this.createSessionConfigOptionsResponse(this.getSessionState(sessionId)),
2035+
...(forkPoint ? {_meta: {[NEUTRAL_FORK_POINT_META_KEY]: forkPoint}} : {}),
20122036
};
20132037
} catch (e) {
20142038
const error = e instanceof Error ? e : new Error(String(e));
@@ -2020,10 +2044,11 @@ export class CodexAcpServer {
20202044
async forkSessionV2(params: acpV2.ForkSessionRequest): Promise<acpV2.ForkSessionResponse> {
20212045
const {systemPrompt, ...rest} = params;
20222046
const request = {...rest, systemPrompt: toV1SystemPrompt(systemPrompt)};
2023-
const {sessionId} = await this.forkSession(request);
2047+
const {sessionId, _meta} = await this.forkSession(request);
20242048
return {
20252049
sessionId,
20262050
...this.createSessionSetupResponseV2(this.getSessionState(sessionId)),
2051+
...(_meta ? {_meta} : {}),
20272052
};
20282053
}
20292054

‎src/SessionFork.ts‎

Lines changed: 147 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,59 @@ import type {SessionConfig} from "./CodexAcpClient";
55
import type {CodexAppServerClient} from "./CodexAppServerClient";
66
import type {ModeKind} from "./app-server/ModeKind";
77
import type {ServiceTier} from "./app-server/ServiceTier";
8-
import type {Model} from "./app-server/v2";
8+
import type {Model, Turn} from "./app-server/v2";
99
import type {SessionMetadata} from "./SessionMetadata";
1010
import type {AcpMcpServer, WithAcpMcpServers} from "./McpServerConfig";
1111
import type {SessionInstructions} from "./ClientSystemPrompt";
12+
import {renderFileCitations} from "./CodexFileCitations";
13+
14+
/** The top-level `_meta` key of the client-neutral fork point, see `docs/air-extensions.md`. */
15+
export const NEUTRAL_FORK_POINT_META_KEY = "forkPoint";
16+
export const NEUTRAL_FORK_POINT_VERSION = 1;
17+
18+
/** Where the history of a fork at a message ends: after the whole turn that holds the message. */
19+
export type ForkPointBoundary = "turn";
20+
21+
/** The fork point that a client-neutral `session/fork` resolved, returned in the response `_meta.forkPoint`. */
22+
export type ForkPointResult = {
23+
boundary: ForkPointBoundary;
24+
/** The id of the matched Codex item. */
25+
messageId: string;
26+
/** The last turn that the fork keeps. */
27+
turnId: string;
28+
/** The last item of that turn, the last item that the fork keeps. */
29+
lastItemId: string;
30+
matchedBy: "id" | "fingerprint";
31+
};
32+
33+
/** The initialize `_meta.forkPoint` advert for a client that opted in. */
34+
export function neutralForkPointCapability(): {version: number; boundary: ForkPointBoundary} {
35+
return {version: NEUTRAL_FORK_POINT_VERSION, boundary: "turn"};
36+
}
37+
38+
/**
39+
* Whether the client opted into the client-neutral fork point with `clientCapabilities._meta.forkPoint: {version}`,
40+
* an integer of at least 1.
41+
*/
42+
export function clientRequestsNeutralForkPoint(capabilities: acp.ClientCapabilities | null | undefined): boolean {
43+
const declared = capabilities?._meta?.[NEUTRAL_FORK_POINT_META_KEY];
44+
if (!isUnknownRecord(declared)) return false;
45+
const version = declared["version"];
46+
return typeof version === "number" && Number.isInteger(version) && version >= 1;
47+
}
48+
49+
/** Whether a `session/fork` request carries the client-neutral fork point. */
50+
export function hasNeutralForkPoint(meta: Record<string, unknown> | null | undefined): boolean {
51+
return meta != null && meta[NEUTRAL_FORK_POINT_META_KEY] !== undefined;
52+
}
53+
54+
/** The error for a client-neutral fork point from a client that did not opt in. */
55+
export function forkPointNotNegotiatedError(): RequestError {
56+
return RequestError.invalidParams(
57+
{[NEUTRAL_FORK_POINT_META_KEY]: {reason: "notNegotiated"}},
58+
"session/fork _meta.forkPoint needs initialize clientCapabilities._meta.forkPoint",
59+
);
60+
}
1261

1362
export type SessionForkDependencies = {
1463
codexClient: CodexAppServerClient;
@@ -34,8 +83,10 @@ export async function forkSession(
3483
dependencies: SessionForkDependencies,
3584
instructions?: SessionInstructions,
3685
): Promise<SessionMetadata> {
86+
const forkPoint = readForkPoint(request._meta);
3787
await dependencies.refreshSkills(request.cwd, additionalDirectories);
38-
const lastTurnId = await resolveForkTurnId(request, dependencies.codexClient);
88+
const match = forkPoint ? await resolveForkPoint(request, forkPoint, dependencies.codexClient) : undefined;
89+
const lastTurnId = match?.turnId;
3990
const sessionConfig = await dependencies.createSessionConfig(
4091
request.cwd,
4192
additionalDirectories,
@@ -72,45 +123,120 @@ export async function forkSession(
72123
additionalDirectories,
73124
skippedMcpServers: sessionConfig.skippedMcpServers,
74125
...(instructions ? {instructions} : {}),
126+
...(forkPoint?.kind === "neutral" && match ? {
127+
forkPoint: {
128+
boundary: "turn",
129+
messageId: match.messageId,
130+
turnId: match.turnId,
131+
lastItemId: match.lastItemId,
132+
matchedBy: match.matchedBy,
133+
},
134+
} : {}),
75135
};
76136
}
77137

78-
async function resolveForkTurnId(
79-
request: Pick<acp.ForkSessionRequest, "sessionId" | "_meta">,
80-
codexClient: CodexAppServerClient,
81-
): Promise<string | undefined> {
82-
const forkPoint = readAirForkPoint(request._meta);
83-
if (!forkPoint) return undefined;
138+
type ForkPointRequest = {kind: "air" | "neutral"} & MessageForkPoint;
84139

140+
type ForkPointMatch = Omit<ForkPointResult, "boundary">;
141+
142+
/**
143+
* The fork point of a request. The client-neutral `_meta.forkPoint` wins over the AIR one; the caller rejects it
144+
* for a client that did not opt in.
145+
*/
146+
function readForkPoint(meta?: Record<string, unknown> | null): ForkPointRequest | undefined {
147+
if (hasNeutralForkPoint(meta)) return {kind: "neutral", ...readNeutralForkPoint(meta![NEUTRAL_FORK_POINT_META_KEY])};
148+
const air = readAirForkPoint(meta);
149+
return air ? {kind: "air", ...air} : undefined;
150+
}
151+
152+
async function resolveForkPoint(
153+
request: Pick<acp.ForkSessionRequest, "sessionId" | "cwd">,
154+
forkPoint: ForkPointRequest,
155+
codexClient: CodexAppServerClient,
156+
): Promise<ForkPointMatch> {
85157
const history = await codexClient.threadReadWithHistory(request.sessionId);
86-
const candidateIds = airForkMessageIdCandidates(forkPoint.messageId);
87-
const itemTurnId = candidateIds
88-
.map(candidateId => history.thread.turns.find(turn => turn.items.some(item => item.id === candidateId))?.id)
89-
.find(turnId => turnId !== undefined);
90-
if (itemTurnId) return itemTurnId;
158+
const turns = history.thread.turns;
159+
const matchById = (candidateId: string): ForkPointMatch | undefined => {
160+
const turn = turns.find(turn => turn.items.some(item => item.id === candidateId));
161+
return turn ? toMatch(turn, candidateId, "id") : undefined;
162+
};
163+
// The AIR form also accepts the visible segment id of older AIR builds; the neutral form takes the item id.
164+
const candidateIds = forkPoint.kind === "air"
165+
? airForkMessageIdCandidates(forkPoint.messageId)
166+
: [forkPoint.messageId];
167+
const idMatch = candidateIds.map(matchById).find(match => match !== undefined);
168+
if (idMatch) return idMatch;
91169

92170
if (forkPoint.messageFingerprint) {
93-
const matchingTurns = history.thread.turns.flatMap(turn => turn.items
171+
// The client saw the text with file citations rendered, as the source session sent it.
172+
const renderCwd = history.thread.cwd ?? request.cwd;
173+
const clientText = forkPoint.kind === "neutral"
174+
? (text: string) => renderFileCitations(text, renderCwd)
175+
: (text: string) => text;
176+
const matches = turns.flatMap(turn => turn.items
94177
.filter(item => item.type === "agentMessage"
95-
&& fingerprintAgentMessage(item.text) === forkPoint.messageFingerprint)
96-
.map(() => turn.id));
97-
const fingerprintTurnId = matchingTurns[forkPoint.messageOccurrence - 1];
98-
if (fingerprintTurnId) return fingerprintTurnId;
178+
&& fingerprintAgentMessage(clientText(item.text)) === forkPoint.messageFingerprint)
179+
.map(item => toMatch(turn, item.id, "fingerprint")));
180+
const fingerprintMatch = matches[forkPoint.messageOccurrence - 1];
181+
if (fingerprintMatch) return fingerprintMatch;
99182
}
100183

184+
if (forkPoint.kind === "neutral") {
185+
throw RequestError.invalidParams(
186+
{[NEUTRAL_FORK_POINT_META_KEY]: {messageId: forkPoint.messageId, reason: "notFound"}},
187+
`Fork point message ${forkPoint.messageId} was not found in session ${request.sessionId}`,
188+
);
189+
}
101190
throw RequestError.invalidParams(
102191
{messageId: forkPoint.messageId},
103192
`Fork point message ${forkPoint.messageId} was not found in session ${request.sessionId}`,
104193
);
105194
}
106195

107-
type AirForkPoint = {
196+
function toMatch(turn: Turn, messageId: string, matchedBy: ForkPointMatch["matchedBy"]): ForkPointMatch {
197+
return {messageId, turnId: turn.id, lastItemId: turn.items.at(-1)!.id, matchedBy};
198+
}
199+
200+
/** Reads the client-neutral `_meta.forkPoint`. An invalid field fails with `{forkPoint: {field}}` as the error data. */
201+
function readNeutralForkPoint(forkPoint: unknown): MessageForkPoint {
202+
const invalid = (field: string, message: string) => RequestError.invalidParams(
203+
{[NEUTRAL_FORK_POINT_META_KEY]: {field}},
204+
`session/fork _meta.forkPoint: ${message}`,
205+
);
206+
if (!isUnknownRecord(forkPoint)) throw invalid(NEUTRAL_FORK_POINT_META_KEY, "must be an object");
207+
const version = forkPoint["version"];
208+
if (version !== undefined && version !== NEUTRAL_FORK_POINT_VERSION) {
209+
throw invalid("version", `version must be ${NEUTRAL_FORK_POINT_VERSION} when present`);
210+
}
211+
const messageId = forkPoint["messageId"];
212+
if (typeof messageId !== "string" || messageId.trim().length === 0) {
213+
throw invalid("messageId", "messageId must be a non-empty string");
214+
}
215+
const messageFingerprint = forkPoint["messageFingerprint"];
216+
if (messageFingerprint !== undefined
217+
&& (typeof messageFingerprint !== "string" || !SHA256_FINGERPRINT.test(messageFingerprint))) {
218+
throw invalid("messageFingerprint", "messageFingerprint must be sha256: and 64 lowercase hex digits");
219+
}
220+
const messageOccurrence = forkPoint["messageOccurrence"] ?? 1;
221+
if (!Number.isSafeInteger(messageOccurrence) || (messageOccurrence as number) < 1) {
222+
throw invalid("messageOccurrence", "messageOccurrence must be a positive integer");
223+
}
224+
return {
225+
messageId: messageId.trim(),
226+
...(typeof messageFingerprint === "string" && {messageFingerprint}),
227+
messageOccurrence: messageOccurrence as number,
228+
};
229+
}
230+
231+
const SHA256_FINGERPRINT = /^sha256:[0-9a-f]{64}$/;
232+
233+
type MessageForkPoint = {
108234
messageId: string;
109235
messageFingerprint?: string;
110236
messageOccurrence: number;
111237
};
112238

113-
function readAirForkPoint(meta?: Record<string, unknown> | null): AirForkPoint | undefined {
239+
function readAirForkPoint(meta?: Record<string, unknown> | null): MessageForkPoint | undefined {
114240
const jetbrains = meta?.["jetbrains"];
115241
if (!isUnknownRecord(jetbrains)) return undefined;
116242
const air = jetbrains["air"];
@@ -123,7 +249,7 @@ function readAirForkPoint(meta?: Record<string, unknown> | null): AirForkPoint |
123249
}
124250
const messageFingerprint = fork["messageFingerprint"];
125251
if (messageFingerprint !== undefined
126-
&& (typeof messageFingerprint !== "string" || !/^sha256:[0-9a-f]{64}$/.test(messageFingerprint))) {
252+
&& (typeof messageFingerprint !== "string" || !SHA256_FINGERPRINT.test(messageFingerprint))) {
127253
throw RequestError.invalidParams(undefined, "AIR fork messageFingerprint must be a SHA-256 fingerprint");
128254
}
129255
const messageOccurrence = fork["messageOccurrence"] ?? 1;

0 commit comments

Comments
 (0)