1- import { randomUUID } from "node:crypto" ;
21import fs from "node:fs/promises" ;
3- import path from "node:path" ;
4- import { StringDecoder } from "node:string_decoder" ;
5- import { CURRENT_SESSION_VERSION , type SessionManager } from "@mariozechner/pi-coding-agent" ;
62import {
73 acquireSessionWriteLock ,
4+ appendSessionTranscriptMessage ,
85 emitSessionTranscriptUpdate ,
96 resolveSessionWriteLockAcquireTimeoutMs ,
107 runAgentHarnessBeforeMessageWriteHook ,
118 type AgentMessage ,
129 type SessionWriteLockAcquireTimeoutConfig ,
1310} from "openclaw/plugin-sdk/agent-harness-runtime" ;
1411
15- const TRANSCRIPT_APPEND_SCAN_CHUNK_BYTES = 64 * 1024 ;
16- const SESSION_MANAGER_APPEND_MAX_BYTES = 8 * 1024 * 1024 ;
17-
18- type TranscriptLeafInfo = {
19- leafId ?: string ;
20- hasParentLinkedEntries : boolean ;
21- nonSessionEntryCount : number ;
22- } ;
23-
2412export async function mirrorCodexAppServerTranscript ( params : {
2513 sessionFile : string ;
2614 sessionKey ?: string ;
@@ -36,7 +24,6 @@ export async function mirrorCodexAppServerTranscript(params: {
3624 return ;
3725 }
3826
39- await fs . mkdir ( path . dirname ( params . sessionFile ) , { recursive : true } ) ;
4027 const lock = await acquireSessionWriteLock ( {
4128 sessionFile : params . sessionFile ,
4229 timeoutMs : resolveSessionWriteLockAcquireTimeoutMs ( params . config ) ,
@@ -53,7 +40,7 @@ export async function mirrorCodexAppServerTranscript(params: {
5340 const transcriptMessage = {
5441 ...message ,
5542 ...( idempotencyKey ? { idempotencyKey } : { } ) ,
56- } as Parameters < SessionManager [ "appendMessage" ] > [ 0 ] ;
43+ } as AgentMessage ;
5744 const nextMessage = runAgentHarnessBeforeMessageWriteHook ( {
5845 message : transcriptMessage ,
5946 agentId : params . agentId ,
@@ -62,15 +49,18 @@ export async function mirrorCodexAppServerTranscript(params: {
6249 if ( ! nextMessage ) {
6350 continue ;
6451 }
65- const messageToAppend = ( idempotencyKey
66- ? {
67- ...( nextMessage as unknown as Record < string , unknown > ) ,
68- idempotencyKey,
69- }
70- : nextMessage ) as unknown as Parameters < SessionManager [ "appendMessage" ] > [ 0 ] ;
71- await appendCodexAppServerTranscriptMessage ( {
52+ const messageToAppend = (
53+ idempotencyKey
54+ ? {
55+ ...( nextMessage as unknown as Record < string , unknown > ) ,
56+ idempotencyKey,
57+ }
58+ : nextMessage
59+ ) as AgentMessage ;
60+ await appendSessionTranscriptMessage ( {
7261 transcriptPath : params . sessionFile ,
7362 message : messageToAppend ,
63+ config : params . config ,
7464 } ) ;
7565 if ( idempotencyKey ) {
7666 existingIdempotencyKeys . add ( idempotencyKey ) ;
@@ -87,202 +77,6 @@ export async function mirrorCodexAppServerTranscript(params: {
8777 }
8878}
8979
90- async function appendCodexAppServerTranscriptMessage ( params : {
91- transcriptPath : string ;
92- message : unknown ;
93- } ) : Promise < void > {
94- await ensureTranscriptHeader ( params . transcriptPath ) ;
95- const stat = await fs . stat ( params . transcriptPath ) . catch ( ( ) => null ) ;
96- let leafInfo : TranscriptLeafInfo = await readTranscriptLeafInfo ( params . transcriptPath ) . catch (
97- ( ) => ( {
98- hasParentLinkedEntries : false ,
99- nonSessionEntryCount : 0 ,
100- } ) ,
101- ) ;
102- const hasLinearEntries = ! leafInfo . hasParentLinkedEntries && leafInfo . nonSessionEntryCount > 0 ;
103- const shouldRawAppend = hasLinearEntries && ( stat ?. size ?? 0 ) > SESSION_MANAGER_APPEND_MAX_BYTES ;
104- if ( hasLinearEntries && ! shouldRawAppend ) {
105- const migrated = await migrateLinearTranscriptToParentLinked ( params . transcriptPath ) ;
106- leafInfo = {
107- ...( migrated . leafId ? { leafId : migrated . leafId } : { } ) ,
108- hasParentLinkedEntries : Boolean ( migrated . leafId ) ,
109- nonSessionEntryCount : leafInfo . nonSessionEntryCount ,
110- } ;
111- }
112- const entry = {
113- type : "message" ,
114- id : randomUUID ( ) ,
115- ...( shouldRawAppend ? { } : { parentId : leafInfo . leafId ?? null } ) ,
116- timestamp : new Date ( ) . toISOString ( ) ,
117- message : params . message ,
118- } ;
119- await fs . appendFile ( params . transcriptPath , `${ JSON . stringify ( entry ) } \n` , "utf-8" ) ;
120- }
121-
122- async function ensureTranscriptHeader ( transcriptPath : string ) : Promise < void > {
123- const stat = await fs . stat ( transcriptPath ) . catch ( ( ) => null ) ;
124- if ( stat ?. isFile ( ) && stat . size > 0 ) {
125- return ;
126- }
127- await fs . mkdir ( path . dirname ( transcriptPath ) , { recursive : true } ) ;
128- const header = {
129- type : "session" ,
130- version : CURRENT_SESSION_VERSION ,
131- id : randomUUID ( ) ,
132- timestamp : new Date ( ) . toISOString ( ) ,
133- cwd : process . cwd ( ) ,
134- } ;
135- await fs . writeFile ( transcriptPath , `${ JSON . stringify ( header ) } \n` , {
136- encoding : "utf-8" ,
137- mode : 0o600 ,
138- flag : stat ?. isFile ( ) ? "w" : "wx" ,
139- } ) ;
140- }
141-
142- async function readTranscriptLeafInfo ( transcriptPath : string ) : Promise < TranscriptLeafInfo > {
143- const handle = await fs . open ( transcriptPath , "r" ) ;
144- try {
145- const decoder = new StringDecoder ( "utf8" ) ;
146- const buffer = Buffer . allocUnsafe ( TRANSCRIPT_APPEND_SCAN_CHUNK_BYTES ) ;
147- let carry = "" ;
148- let leafId : string | undefined ;
149- let hasParentLinkedEntries = false ;
150- let nonSessionEntryCount = 0 ;
151- while ( true ) {
152- const { bytesRead } = await handle . read ( buffer , 0 , buffer . length , null ) ;
153- if ( bytesRead <= 0 ) {
154- break ;
155- }
156- const text = carry + decoder . write ( buffer . subarray ( 0 , bytesRead ) ) ;
157- const lines = text . split ( / \r ? \n / ) ;
158- carry = lines . pop ( ) ?? "" ;
159- for ( const line of lines ) {
160- if ( lineHasNonSessionEntry ( line ) ) {
161- nonSessionEntryCount += 1 ;
162- }
163- const id = lineParentLinkedEntryId ( line ) ;
164- if ( id ) {
165- leafId = id ;
166- hasParentLinkedEntries = true ;
167- }
168- }
169- await yieldTranscriptAppendScan ( ) ;
170- }
171- const tail = carry + decoder . end ( ) ;
172- if ( lineHasNonSessionEntry ( tail ) ) {
173- nonSessionEntryCount += 1 ;
174- }
175- const id = lineParentLinkedEntryId ( tail ) ;
176- if ( id ) {
177- leafId = id ;
178- hasParentLinkedEntries = true ;
179- }
180- return {
181- ...( leafId ? { leafId } : { } ) ,
182- hasParentLinkedEntries,
183- nonSessionEntryCount,
184- } ;
185- } finally {
186- await handle . close ( ) ;
187- }
188- }
189-
190- async function migrateLinearTranscriptToParentLinked ( transcriptPath : string ) : Promise < {
191- leafId ?: string ;
192- } > {
193- const raw = await fs . readFile ( transcriptPath , "utf-8" ) ;
194- const existingIds = new Set < string > ( ) ;
195- const output : string [ ] = [ ] ;
196- let previousId : string | null = null ;
197- let leafId : string | undefined ;
198- for ( const line of raw . split ( / \r ? \n / ) ) {
199- if ( ! line . trim ( ) ) {
200- continue ;
201- }
202- let parsed : unknown ;
203- try {
204- parsed = JSON . parse ( line ) ;
205- } catch {
206- output . push ( line ) ;
207- continue ;
208- }
209- if ( ! parsed || typeof parsed !== "object" || Array . isArray ( parsed ) ) {
210- output . push ( line ) ;
211- continue ;
212- }
213- const record = parsed as Record < string , unknown > ;
214- if ( record . type === "session" ) {
215- output . push ( JSON . stringify ( { ...record , version : CURRENT_SESSION_VERSION } ) ) ;
216- continue ;
217- }
218- const id = normalizeEntryId ( record . id ) ?? generateEntryId ( existingIds ) ;
219- existingIds . add ( id ) ;
220- record . id = id ;
221- if ( ! Object . hasOwn ( record , "parentId" ) ) {
222- record . parentId = previousId ;
223- }
224- previousId = id ;
225- leafId = id ;
226- output . push ( JSON . stringify ( record ) ) ;
227- }
228- await fs . writeFile ( transcriptPath , `${ output . join ( "\n" ) } \n` , {
229- encoding : "utf-8" ,
230- mode : 0o600 ,
231- } ) ;
232- const result : { leafId ?: string } = { } ;
233- if ( leafId ) {
234- result . leafId = leafId ;
235- }
236- return result ;
237- }
238-
239- function normalizeEntryId ( value : unknown ) : string | undefined {
240- return typeof value === "string" && value . trim ( ) . length > 0 ? value : undefined ;
241- }
242-
243- function generateEntryId ( existingIds : Set < string > ) : string {
244- for ( let attempt = 0 ; attempt < 100 ; attempt += 1 ) {
245- const id = randomUUID ( ) . slice ( 0 , 8 ) ;
246- if ( ! existingIds . has ( id ) ) {
247- existingIds . add ( id ) ;
248- return id ;
249- }
250- }
251- const id = randomUUID ( ) ;
252- existingIds . add ( id ) ;
253- return id ;
254- }
255-
256- function lineHasNonSessionEntry ( line : string ) : boolean {
257- if ( ! line . trim ( ) ) {
258- return false ;
259- }
260- try {
261- const parsed = JSON . parse ( line ) as { type ?: unknown } ;
262- return parsed . type !== "session" ;
263- } catch {
264- return false ;
265- }
266- }
267-
268- function lineParentLinkedEntryId ( line : string ) : string | undefined {
269- if ( ! line . trim ( ) ) {
270- return undefined ;
271- }
272- try {
273- const parsed = JSON . parse ( line ) as { type ?: unknown ; id ?: unknown ; parentId ?: unknown } ;
274- return parsed . type !== "session" && typeof parsed . id === "string" && "parentId" in parsed
275- ? parsed . id
276- : undefined ;
277- } catch {
278- return undefined ;
279- }
280- }
281-
282- async function yieldTranscriptAppendScan ( ) : Promise < void > {
283- await new Promise < void > ( ( resolve ) => setImmediate ( resolve ) ) ;
284- }
285-
28680async function readTranscriptIdempotencyKeys ( sessionFile : string ) : Promise < Set < string > > {
28781 const keys = new Set < string > ( ) ;
28882 let raw : string ;
0 commit comments