@@ -5,10 +5,59 @@ import type {SessionConfig} from "./CodexAcpClient";
55import type { CodexAppServerClient } from "./CodexAppServerClient" ;
66import type { ModeKind } from "./app-server/ModeKind" ;
77import type { ServiceTier } from "./app-server/ServiceTier" ;
8- import type { Model } from "./app-server/v2" ;
8+ import type { Model , Turn } from "./app-server/v2" ;
99import type { SessionMetadata } from "./SessionMetadata" ;
1010import type { AcpMcpServer , WithAcpMcpServers } from "./McpServerConfig" ;
1111import 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
1362export 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 = / ^ s h a 2 5 6 : [ 0 - 9 a - 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" || ! / ^ s h a 2 5 6 : [ 0 - 9 a - 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