Skip to content

Commit bcf0e92

Browse files
authored
fix: report hooks that block or stop Codex (#767)
A Codex hook that blocks or stops the prompt ended the turn with a bare `end_turn`: no answer, no error, no reason. codex-acp ignored `hook/completed`, which carries the hook's status and output. ## Changes - **`hook/completed` with status `blocked` or `stopped` becomes a warning**, sent the same way as other Codex warnings: a session `notice`, an AIR `sessionFailure` advisory, or agent text. - The title names the event and what it blocked, for example `UserPromptSubmit hook blocked the prompt` or `PreToolUse hook blocked the tool call`. - The reason is the hook's output, without `context` entries. - Hooks that complete or fail without blocking send nothing. - **Advisory ids no longer repeat across prompts.** The id counter lived in the per-prompt event handler, so the first advisory of every prompt had the same id and revision. It is now shared, in `SessionFailureIds`. - `readme-dev.md` documents hook notices. ## Testing - Reproduced against real Codex with a blocking `UserPromptSubmit` hook. After the fix, each prompt shows the reason with a distinct id. - Tests cover all three warning paths, ACP v2, and distinct ids across prompts. The wording for events other than `UserPromptSubmit` was not checked against real Codex.
1 parent 6567651 commit bcf0e92

14 files changed

Lines changed: 352 additions & 24 deletions

‎readme-dev.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ npm run package:all
101101
### Session notices
102102

103103
The adapter implements [Session Notices](https://agentclientprotocol.com/rfds/session-notices)
104-
for Codex warnings, configuration warnings, deprecation notices, model rerouting, and the legacy
104+
for Codex warnings, configuration warnings, deprecation notices, model rerouting, hooks that block or stop Codex, and the legacy
105105
`thread/compacted` advisory when the client advertises `clientCapabilities.session.notices: {}`.
106106
These are live `session/update` notifications with
107107
`sessionUpdate: "notice"`, a severity, a plain-text title, and optional description.
@@ -112,6 +112,10 @@ the existing assistant/thought text or AIR `sessionFailure` advisory records. Wh
112112
enabled, they take precedence over AIR advisory records. Clients control their presentation;
113113
the adapter does not rely on notices being displayed.
114114

115+
A hook notice is a warning titled with the hook event and what it did (for example `UserPromptSubmit hook blocked
116+
the prompt` or `PreToolUse hook blocked the tool call`); its description holds the hook's `stop`, `feedback`, `error` and `warning` output. Hooks that complete
117+
or fail without blocking send nothing, because Codex carries on as usual.
118+
115119
Command replies, review results, and terminal/retrying errors retain their existing response or
116120
failure channels. Clients advertising session compaction support continue to receive the dedicated
117121
compaction lifecycle instead of the legacy completion advisory.

‎src/CodexAcpServer.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as acp from "@agentclientprotocol/sdk/unstable";
22
import {RequestError, type SessionId, type SessionModeState} from "@agentclientprotocol/sdk/unstable";
3-
import {CodexEventHandler, type CompletedPlan, failureWasShownAsMessage} from "./CodexEventHandler";
3+
import {CodexEventHandler, type CompletedPlan, failureWasShownAsMessage, SessionFailureIds} from "./CodexEventHandler";
44
import {attachmentFileUri, desktopAttachmentHistory} from "./DesktopAttachmentHistory";
55
import {CodexApprovalHandler} from "./permissions/CodexApprovalHandler";
66
import {isRecord} from "./permissions/json";
@@ -505,7 +505,7 @@ export class CodexAcpServer {
505505
private readonly defaultAuthRequest: CodexAuthRequest | null;
506506
private readonly getExitCode: () => number | null;
507507
private readonly getRecentStderr: () => string;
508-
private readonly sessionFailureEpoch: string;
508+
private readonly sessionFailureIds: SessionFailureIds;
509509
private availableCommands: CodexCommands;
510510
private clientInfo: acp.Implementation | null;
511511
private clientCapabilities: acp.ClientCapabilities | null;
@@ -641,7 +641,7 @@ export class CodexAcpServer {
641641
this.captureStderr();
642642
this.getExitCode = getExitCode ?? (() => this.codexProcessState?.connection.process.exitCode ?? null);
643643
this.getRecentStderr = getRecentStderr ?? (() => this.codexProcessState?.stderr ?? "");
644-
this.sessionFailureEpoch = randomUUID();
644+
this.sessionFailureIds = new SessionFailureIds(randomUUID());
645645
this.clientInfo = null;
646646
this.clientCapabilities = null;
647647
this.capabilities = ClientCapabilities.DEFAULT;
@@ -1676,7 +1676,7 @@ export class CodexAcpServer {
16761676
this.connection,
16771677
sessionState,
16781678
clientSupportsTypedSessionFailures(this.clientCapabilities),
1679-
this.sessionFailureEpoch,
1679+
this.sessionFailureIds,
16801680
sessionState.subagents,
16811681
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
16821682
false,
@@ -5008,7 +5008,7 @@ export class CodexAcpServer {
50085008
this.connection,
50095009
sessionState,
50105010
clientSupportsTypedSessionFailures(this.clientCapabilities),
5011-
this.sessionFailureEpoch,
5011+
this.sessionFailureIds,
50125012
sessionState.subagents,
50135013
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
50145014
agentFileChangeReportRequest !== null,

‎src/CodexEventHandler.ts‎

Lines changed: 71 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import type {
1818
ConfigWarningNotification,
1919
DeprecationNoticeNotification,
2020
ErrorNotification,
21+
HookCompletedNotification,
22+
HookEventName,
2123
ItemCompletedNotification,
2224
ItemStartedNotification,
2325
ThreadItem,
@@ -193,18 +195,58 @@ export function failureWasShownAsMessage(error: unknown): boolean {
193195
return error instanceof RequestError && failuresShownAsMessages.has(error);
194196
}
195197

198+
/** What a hook of the event blocks, for the title of its notice. */
199+
function hookBlockTarget(eventName: HookEventName): string {
200+
switch (eventName) {
201+
case "userPromptSubmit":
202+
return "the prompt";
203+
case "preToolUse":
204+
case "permissionRequest":
205+
return "the tool call";
206+
case "postToolUse":
207+
return "the tool result";
208+
case "preModelRequest":
209+
return "the model request";
210+
case "preCompact":
211+
return "the compaction";
212+
case "subagentStart":
213+
return "the subagent";
214+
case "postModelRequest":
215+
case "postCompact":
216+
case "sessionStart":
217+
case "sessionEnd":
218+
case "subagentStop":
219+
case "stop":
220+
case "interrupt":
221+
return "the request";
222+
}
223+
}
224+
225+
/**
226+
* Numbers failure and advisory ids for the adapter process. Each prompt gets its own event handler, so the counter
227+
* must outlive a handler: otherwise the first advisory of every prompt gets the same id and revision.
228+
*/
229+
export class SessionFailureIds {
230+
private next = 1;
231+
232+
constructor(private readonly epoch: string) {}
233+
234+
allocate(): string {
235+
return `${this.epoch}:${this.next++}`;
236+
}
237+
}
238+
196239
export class CodexEventHandler {
197240

198241
private readonly sessionState: SessionState;
199242
private readonly supportsTypedSessionFailures: boolean;
200-
private readonly sessionFailureEpoch: string;
243+
private readonly sessionFailureIds: SessionFailureIds;
201244
private readonly pendingErrors: ErrorNotification[] = [];
202245
private readonly failuresById = new Map<string, SessionFailure>();
203246
private readonly activeFailureIdByScope = new Map<string, string>();
204247
private readonly failureTurnIdById = new Map<string, string | undefined>();
205248
private readonly allocatedFailureScopes = new Set<string>();
206249
private lastSessionNotice: {key: string; failure: SessionFailure} | undefined;
207-
private nextNoticeId = 1;
208250
private failure: RequestError | null = null;
209251
private terminalTurnError: {turnId: string; error: ErrorNotification["error"]} | null = null;
210252
private completedPlan: CompletedPlan | null = null;
@@ -228,7 +270,7 @@ export class CodexEventHandler {
228270
connection: AcpClientConnection,
229271
sessionState: SessionState,
230272
supportsTypedSessionFailures: boolean,
231-
sessionFailureEpoch: string,
273+
sessionFailureIds: SessionFailureIds,
232274
subagents: SubagentEventRouter,
233275
onAccountUpdated: ((notification: AccountUpdatedNotification) => void) | undefined,
234276
collectTurnDiffs: boolean,
@@ -238,7 +280,7 @@ export class CodexEventHandler {
238280
this.onAccountUpdated = onAccountUpdated;
239281
this.sessionState = sessionState;
240282
this.supportsTypedSessionFailures = supportsTypedSessionFailures;
241-
this.sessionFailureEpoch = sessionFailureEpoch;
283+
this.sessionFailureIds = sessionFailureIds;
242284
this.session = new ACPSessionConnection(connection, sessionState.sessionId);
243285
this.renderer = new AcpToolCallRenderer(sessionState.clientCapabilities);
244286
this.plans = new CodexPlanStream(this.session, sessionState.clientCapabilities);
@@ -688,6 +730,8 @@ export class CodexEventHandler {
688730
return await this.createConfigWarningEvent(notification.params);
689731
case "warning":
690732
return this.createWarningEvent(notification.params);
733+
case "hook/completed":
734+
return this.createHookCompletedEvent(notification.params);
691735
case "guardianWarning":
692736
return null;
693737
case "deprecationNotice":
@@ -748,7 +792,6 @@ export class CodexEventHandler {
748792
case "thread/environment/disconnected":
749793
case "command/exec/outputDelta":
750794
case "hook/started":
751-
case "hook/completed":
752795
case "turn/moderationMetadata":
753796
case "item/fileChange/outputDelta":
754797
case "item/fileChange/patchUpdated":
@@ -876,6 +919,27 @@ export class CodexEventHandler {
876919
return createAgentTextMessageChunk(`Warning: ${event.message}\n\n`);
877920
}
878921

922+
/**
923+
* A hook that blocks or stops Codex can end the turn before the model runs. Without this the client sees
924+
* an empty turn and no reason. Other hook results do not change what Codex does, so they stay silent.
925+
*/
926+
private createHookCompletedEvent({run}: HookCompletedNotification): UpdateSessionEvent | null {
927+
if (run.status !== "blocked" && run.status !== "stopped") return null;
928+
const eventName = run.eventName.charAt(0).toUpperCase() + run.eventName.slice(1);
929+
const title = `${eventName} hook ${run.status === "blocked" ? `blocked ${hookBlockTarget(run.eventName)}` : "stopped the turn"}`;
930+
// Context entries are text the hook adds to the model input, not a reason.
931+
const reason = run.entries
932+
.filter(entry => entry.kind !== "context")
933+
.map(entry => entry.text.trim())
934+
.filter(text => text.length > 0)
935+
.join("\n") || null;
936+
if (this.supportsNotices) return createSessionNotice("warning", title, reason);
937+
if (this.supportsTypedSessionFailures) {
938+
return this.createSessionFailureUpdate(this.recordSessionNotice(...this.sessionNoticeContent(title, reason)));
939+
}
940+
return createAgentTextMessageChunk(reason === null ? `${title}.\n\n` : `${title}: ${reason}\n\n`);
941+
}
942+
879943
private createModelReroutedEvent(event: ModelReroutedNotification): UpdateSessionEvent {
880944
if (!this.supportsNotices) {
881945
return createAgentTextThoughtChunk(`Model rerouted from ${event.fromModel} to ${event.toModel} (${event.reason}).\n\n`);
@@ -1196,7 +1260,7 @@ export class CodexEventHandler {
11961260
return `${turnId}:error`;
11971261
}
11981262
this.allocatedFailureScopes.add(scope);
1199-
return `${scope}:error:${this.sessionFailureEpoch}:${this.nextNoticeId++}`;
1263+
return `${scope}:error:${this.sessionFailureIds.allocate()}`;
12001264
}
12011265

12021266
/**
@@ -1238,7 +1302,7 @@ export class CodexEventHandler {
12381302
? this.lastSessionNotice.failure
12391303
: undefined;
12401304
const id = previous?.id
1241-
?? `${this.sessionState.sessionId}:notice:${this.sessionFailureEpoch}:${this.nextNoticeId++}`;
1305+
?? `${this.sessionState.sessionId}:notice:${this.sessionFailureIds.allocate()}`;
12421306
const notice: SessionFailure = {
12431307
id,
12441308
revision: nextSessionFailureRevision(previous, id),

‎src/__tests__/AcpV2SessionInfo.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import {describe, expect, it, vi} from "vitest";
22
import {AcpV2SessionInfo} from "../AcpV2SessionInfo";
33
import {AcpV2Connection, type AcpV2ClientConnection} from "../ACPSessionConnection";
4-
import {CodexEventHandler} from "../CodexEventHandler";
4+
import {CodexEventHandler, SessionFailureIds} from "../CodexEventHandler";
55
import {createTestSessionState} from "./acp-test-utils";
66
import type {SessionFailure} from "../CodexAcpServer";
77

@@ -118,7 +118,7 @@ describe("V2 session metadata", () => {
118118
const v2 = new AcpV2Connection(client);
119119
const failure: SessionFailure = {id: "incident", revision: 1, category: "service", severity: "warning", title: "Retrying", actions: ["retry"]};
120120
const state = createTestSessionState({sessionId: "session", sessionFailure: failure});
121-
const handler = new CodexEventHandler(v2.extensionOnlyV1View(), state, true, "epoch", state.subagents, undefined, false, false, false);
121+
const handler = new CodexEventHandler(v2.extensionOnlyV1View(), state, true, new SessionFailureIds("epoch"), state.subagents, undefined, false, false, false);
122122
await v2.client.notify("session/update", {sessionId: "session", update: {
123123
sessionUpdate: "session_info_update",
124124
_meta: {jetbrains: {other: true, air: {version: 1, sibling: {value: null}, sessionFailure: {...failure, revision}}}},

‎src/__tests__/CodexACPAgent/data/plans-v2-compaction-and-notice.json‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,14 @@
2222
"title": "Optional integration unavailable",
2323
"sessionUpdate": "notice"
2424
}
25+
},
26+
{
27+
"sessionId": "session-1",
28+
"update": {
29+
"severity": "warning",
30+
"title": "UserPromptSubmit hook blocked the prompt",
31+
"description": "blocked by policy",
32+
"sessionUpdate": "notice"
33+
}
2534
}
2635
]
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
{
2+
"method": "sessionUpdate",
3+
"args": [
4+
{
5+
"sessionId": "notice-session",
6+
"update": {
7+
"sessionUpdate": "session_info_update",
8+
"_meta": {
9+
"jetbrains": {
10+
"air": {
11+
"version": 1,
12+
"sessionFailure": {
13+
"id": "id",
14+
"revision": 1,
15+
"category": "unknown",
16+
"severity": "warning",
17+
"title": "UserPromptSubmit hook blocked the prompt — blocked by policy",
18+
"actions": []
19+
}
20+
}
21+
}
22+
}
23+
}
24+
}
25+
]
26+
}
27+
{
28+
"method": "sessionUpdate",
29+
"args": [
30+
{
31+
"sessionId": "notice-session",
32+
"update": {
33+
"sessionUpdate": "session_info_update",
34+
"_meta": {
35+
"jetbrains": {
36+
"air": {
37+
"version": 1,
38+
"sessionFailure": {
39+
"id": "id",
40+
"revision": 1,
41+
"category": "unknown",
42+
"severity": "warning",
43+
"title": "SessionStart hook stopped the turn — stopped by hook\nhook error",
44+
"actions": []
45+
}
46+
}
47+
}
48+
}
49+
}
50+
}
51+
]
52+
}
53+
{
54+
"method": "sessionUpdate",
55+
"args": [
56+
{
57+
"sessionId": "notice-session",
58+
"update": {
59+
"sessionUpdate": "session_info_update",
60+
"_meta": {
61+
"jetbrains": {
62+
"air": {
63+
"version": 1,
64+
"sessionFailure": {
65+
"id": "id",
66+
"revision": 1,
67+
"category": "unknown",
68+
"severity": "warning",
69+
"title": "PreToolUse hook blocked the tool call",
70+
"actions": []
71+
}
72+
}
73+
}
74+
}
75+
}
76+
}
77+
]
78+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
{
2+
"method": "sessionUpdate",
3+
"args": [
4+
{
5+
"sessionId": "notice-session",
6+
"update": {
7+
"sessionUpdate": "agent_message_chunk",
8+
"content": {
9+
"type": "text",
10+
"text": "UserPromptSubmit hook blocked the prompt: blocked by policy\n\n"
11+
}
12+
}
13+
}
14+
]
15+
}
16+
{
17+
"method": "sessionUpdate",
18+
"args": [
19+
{
20+
"sessionId": "notice-session",
21+
"update": {
22+
"sessionUpdate": "agent_message_chunk",
23+
"content": {
24+
"type": "text",
25+
"text": "SessionStart hook stopped the turn: stopped by hook\nhook error\n\n"
26+
}
27+
}
28+
}
29+
]
30+
}
31+
{
32+
"method": "sessionUpdate",
33+
"args": [
34+
{
35+
"sessionId": "notice-session",
36+
"update": {
37+
"sessionUpdate": "agent_message_chunk",
38+
"content": {
39+
"type": "text",
40+
"text": "PreToolUse hook blocked the tool call.\n\n"
41+
}
42+
}
43+
}
44+
]
45+
}

0 commit comments

Comments
 (0)