@@ -93,6 +93,28 @@ function formatHookRunWarningConsoleMessage(params: {
9393 return parts . join ( " " ) ;
9494}
9595
96+ function createSessionKeyedHookDispatchQueue ( ) {
97+ const hookAgentDispatchTails = new Map < string , Promise < void > > ( ) ;
98+
99+ return ( sessionKey : string , operation : ( ) => Promise < void > ) => {
100+ const previousTail = hookAgentDispatchTails . get ( sessionKey ) ;
101+ const run = previousTail ? previousTail . catch ( ( ) => undefined ) . then ( operation ) : operation ( ) ;
102+ const tail = run . then (
103+ ( ) => undefined ,
104+ ( ) => undefined ,
105+ ) ;
106+ hookAgentDispatchTails . set ( sessionKey , tail ) ;
107+ // Same-session hook agent runs append to one Codex session. Serializing avoids
108+ // optimistic lifecycle-claim races while preserving parallelism across sessions.
109+ void tail . finally ( ( ) => {
110+ if ( hookAgentDispatchTails . get ( sessionKey ) === tail ) {
111+ hookAgentDispatchTails . delete ( sessionKey ) ;
112+ }
113+ } ) ;
114+ return run ;
115+ } ;
116+ }
117+
96118/** Creates the HTTP handler used by gateway hook endpoints. */
97119export function createGatewayHooksRequestHandler ( params : {
98120 deps : CliDeps ;
@@ -103,6 +125,7 @@ export function createGatewayHooksRequestHandler(params: {
103125 logHooks : SubsystemLogger ;
104126} ) {
105127 const { deps, getHooksConfig, getClientIpConfig, bindHost, port, logHooks } = params ;
128+ const enqueueHookAgentDispatch = createSessionKeyedHookDispatchQueue ( ) ;
106129
107130 const dispatchWakeHook = ( value : { text : string ; mode : "now" | "next-heartbeat" } ) => {
108131 const sessionKey = resolveMainSessionKeyFromConfig ( ) ;
@@ -151,79 +174,81 @@ export function createGatewayHooksRequestHandler(params: {
151174 } ;
152175
153176 let hookEventSessionKey : string | undefined ;
154- void runWithGatewayIndependentRootWorkContinuation ( async ( ) => {
155- try {
156- // Agent hooks run after the HTTP response path has returned, so failure
157- // handling must record a system event instead of throwing to the caller.
158- const cfg = getRuntimeConfig ( ) ;
159- hookEventSessionKey = resolveHookEventSessionKey ( {
160- cfg,
161- agentId : value . agentId ,
162- } ) ;
163- const { runCronIsolatedAgentTurn } = await import ( "../../cron/isolated-agent.js" ) ;
164- const result = await runCronIsolatedAgentTurn ( {
165- cfg,
166- deps,
167- job,
168- message : value . message ,
169- sessionKey,
170- lane : "cron" ,
171- } ) ;
172- const summary = resolveHookRunSummary ( result ) ;
173- const prefix =
174- result . status === "ok" ? `Hook ${ safeName } ` : `Hook ${ safeName } (${ result . status } )` ;
175- const shouldAnnounce = shouldAnnounceHookRunResult ( { deliver : value . deliver , result } ) ;
176- if ( result . status !== "ok" ) {
177- logHooks . warn ( "hook agent run returned non-ok status" , {
178- sourcePath : value . sourcePath ,
179- name : safeName ,
180- runId,
181- jobId,
177+ void runWithGatewayIndependentRootWorkContinuation ( ( ) =>
178+ enqueueHookAgentDispatch ( sessionKey , async ( ) => {
179+ try {
180+ // Agent hooks run after the HTTP response path has returned, so failure
181+ // handling must record a system event instead of throwing to the caller.
182+ const cfg = getRuntimeConfig ( ) ;
183+ hookEventSessionKey = resolveHookEventSessionKey ( {
184+ cfg,
182185 agentId : value . agentId ,
186+ } ) ;
187+ const { runCronIsolatedAgentTurn } = await import ( "../../cron/isolated-agent.js" ) ;
188+ const result = await runCronIsolatedAgentTurn ( {
189+ cfg,
190+ deps,
191+ job,
192+ message : value . message ,
183193 sessionKey,
184- status : result . status ,
185- model : value . model ,
186- summary,
187- consoleMessage : formatHookRunWarningConsoleMessage ( {
194+ lane : "cron" ,
195+ } ) ;
196+ const summary = resolveHookRunSummary ( result ) ;
197+ const prefix =
198+ result . status === "ok" ? `Hook ${ safeName } ` : `Hook ${ safeName } (${ result . status } )` ;
199+ const shouldAnnounce = shouldAnnounceHookRunResult ( { deliver : value . deliver , result } ) ;
200+ if ( result . status !== "ok" ) {
201+ logHooks . warn ( "hook agent run returned non-ok status" , {
202+ sourcePath : value . sourcePath ,
203+ name : safeName ,
204+ runId,
205+ jobId,
206+ agentId : value . agentId ,
207+ sessionKey,
188208 status : result . status ,
189209 model : value . model ,
190210 summary,
191- } ) ,
192- } ) ;
193- }
194- if ( shouldAnnounce ) {
195- const eventSessionKey = hookEventSessionKey ?? resolveMainSessionKeyFromConfig ( ) ;
196- enqueueSystemEvent ( `${ prefix } : ${ summary } ` . trim ( ) , {
197- sessionKey : eventSessionKey ,
211+ consoleMessage : formatHookRunWarningConsoleMessage ( {
212+ status : result . status ,
213+ model : value . model ,
214+ summary,
215+ } ) ,
216+ } ) ;
217+ }
218+ if ( shouldAnnounce ) {
219+ const eventSessionKey = hookEventSessionKey ?? resolveMainSessionKeyFromConfig ( ) ;
220+ enqueueSystemEvent ( `${ prefix } : ${ summary } ` . trim ( ) , {
221+ sessionKey : eventSessionKey ,
222+ } ) ;
223+ if ( value . wakeMode === "now" ) {
224+ requestHeartbeat ( { source : "hook" , intent : "immediate" , reason : `hook:${ jobId } ` } ) ;
225+ }
226+ } else if ( result . status === "ok" && ! value . deliver ) {
227+ logHooks . info ( "hook agent run completed without announcement" , {
228+ sourcePath : value . sourcePath ,
229+ name : safeName ,
230+ runId,
231+ jobId,
232+ agentId : value . agentId ,
233+ sessionKey,
234+ completedAt : new Date ( ) . toISOString ( ) ,
235+ } ) ;
236+ }
237+ } catch ( err ) {
238+ logHooks . warn ( `hook agent failed: ${ String ( err ) } ` ) ;
239+ enqueueSystemEvent ( `Hook ${ safeName } (error): ${ String ( err ) } ` , {
240+ sessionKey : hookEventSessionKey ?? resolveMainSessionKeyFromConfig ( ) ,
198241 } ) ;
199242 if ( value . wakeMode === "now" ) {
200- requestHeartbeat ( { source : "hook" , intent : "immediate" , reason : `hook:${ jobId } ` } ) ;
243+ requestHeartbeat ( {
244+ source : "hook" ,
245+ intent : "immediate" ,
246+ reason : `hook:${ jobId } :error` ,
247+ } ) ;
201248 }
202- } else if ( result . status === "ok" && ! value . deliver ) {
203- logHooks . info ( "hook agent run completed without announcement" , {
204- sourcePath : value . sourcePath ,
205- name : safeName ,
206- runId,
207- jobId,
208- agentId : value . agentId ,
209- sessionKey,
210- completedAt : new Date ( ) . toISOString ( ) ,
211- } ) ;
212249 }
213- } catch ( err ) {
214- logHooks . warn ( `hook agent failed: ${ String ( err ) } ` ) ;
215- enqueueSystemEvent ( `Hook ${ safeName } (error): ${ String ( err ) } ` , {
216- sessionKey : hookEventSessionKey ?? resolveMainSessionKeyFromConfig ( ) ,
217- } ) ;
218- if ( value . wakeMode === "now" ) {
219- requestHeartbeat ( {
220- source : "hook" ,
221- intent : "immediate" ,
222- reason : `hook:${ jobId } :error` ,
223- } ) ;
224- }
225- }
226- } ) ;
250+ } ) ,
251+ ) ;
227252
228253 return runId ;
229254 } ;
0 commit comments