Skip to content

Commit 2341b05

Browse files
committed
feat(hooks): adapt process-bound hook review to v2.4.0
Upstream v2.4.0 (agentclientprotocol#682, agentclientprotocol#688) routes the session-scoped ACP v1 requests through getAgent(ctx.params), so a standard subagent session rejects client mutations, and imports the standard subagent modules next to the hook trust imports in CodexAcpServer.ts. No upstream PR absorbs the downstream hook review. The two conflicts are context only. The _codex/hooks/trust route keeps upstream's routing of the neighbouring requests and still forwards reviewToken; CodexAcpServer.ts keeps upstream's new imports and replaces the hook trust imports with the review's, as before. The sorted +/- lines of this commit are identical to the original's. Reviewed against v2.4.0: the execution gate still fences thread/start, thread/resume, thread/fork, turn/start and review/start by method, so upstream's new child thread/resume (restoreChild, during session/load inside the reviewed operation) is fenced too; a provider restart still recreates the standard subagent router before the reviewed session skips the baseline tracker; the route is registered once, on the ACP v1 chain, where the review is configured. Adapted from c07bc0f (original 4d43405).
1 parent a612a33 commit 2341b05

11 files changed

Lines changed: 539 additions & 19 deletions

File tree

‎docs/air-extensions.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ The agent advertises the `goal` object, and the client uses the control method w
181181

182182
### Hook trust
183183

184+
Clients that are not AIR can opt into [process-bound hook review](codex-hook-review.md) without changing their identity or tool/subagent contract.
185+
186+
184187
The adapter passes `CODEX_CONFIG.hooks` to Codex App Server at startup as a TOML override and removes them from the later thread config.
185188
This lets AIR review the same process that will open the session. The adapter keeps other session config fields unchanged.
186189
Codex validates the hooks itself. If they are malformed, App Server exits at startup and `initialize` fails with the Codex error.

‎docs/codex-hook-review.md‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Client-neutral Codex hook review
2+
3+
A client keeps its own identity and opts in through
4+
`initialize.clientCapabilities._meta.codexHooks = {"version": 1}`.
5+
Only version `1` is supported. Missing, non-object, array, or unknown-version
6+
values enable nothing. The initialize answer advertises
7+
`_meta.codexHooks = {"version": 1, "reviewToken": true}`. This opt-in does not
8+
change tool calls or subagent reports. Actual AIR clients retain the existing
9+
AIR hook contract even if they also supply this opt-in.
10+
11+
## List and trust
12+
13+
`_codex/hooks/list {"cwd": "/project"}` returns the existing
14+
`{cwd, hooks, warnings, errors}` fields, restricted to `sessionFlags`, and adds:
15+
16+
- `reviewToken`: an opaque, non-empty string for this live app-server, cwd,
17+
effective hook definitions and diagnostics, and provider configuration.
18+
- `codexHome`: the actual home reported by the app-server initialize handshake,
19+
omitted if unavailable. This is a directory, not an inferred local path.
20+
21+
Listing never writes configuration. A review with warnings or path-specific
22+
errors remains a valid snapshot; it does not approve any hook. The client may
23+
continue with the hooks left untrusted. A failed list supplies no review.
24+
25+
`_codex/hooks/trust` accepts:
26+
27+
```json
28+
{
29+
"cwd": "/project",
30+
"reviewToken": "opaque-token-from-list",
31+
"hooks": [{"key": "session_flags:session_start:0:0", "currentHash": "reviewed-hash"}]
32+
}
33+
```
34+
35+
The response is `{"trusted": true}` only if readback reports every selected
36+
key/hash as trusted. A false readback returns `{"trusted": false}`; write and
37+
readback failures retain their errors. Clients must not treat any of these as
38+
successful consent, and should list again to determine what persisted.
39+
40+
Before writing, the adapter requires the current token, the same full snapshot,
41+
a non-empty selection, unique selected keys, and exactly one listed hook with
42+
each selected key and hash. It writes only the selected `trusted_hash` entries
43+
with `reloadUserConfig: true`, then reads Codex again. Trust-state updates alone
44+
do not invalidate the review; definition changes do. Trust is Codex-owned
45+
persistent state under the reported CODEX_HOME, shared with Codex CLI and other
46+
projects using that home. Accepting another hash replaces a key's prior trust.
47+
48+
## Execution and recovery
49+
50+
Every opted-in `session/new`, `session/load`, `session/resume`, `session/fork`,
51+
and `session/prompt` supplies:
52+
53+
```json
54+
{"_meta": {"codexHooks": {"reviewToken": "opaque-token-from-list"}}}
55+
```
56+
57+
The adapter carries the token in request-local asynchronous context. It checks
58+
fresh hooks at the actual app-server `thread/start`, `thread/resume`,
59+
`thread/fork`, `turn/start`, and `review/start` dispatch boundaries, including
60+
a queued rollout load, lazy recovery, and internal first-turn work. A final
61+
synchronous fence rejects a process or provider change after validation and
62+
before dispatch. No hook-capable request is sent by a failed fence.
63+
64+
Tokens are adapter-local and do not survive an adapter restart, app-server
65+
replacement, provider update, or authentication that can change routing.
66+
Changing captured launch hooks requires a replacement process and fresh review.
67+
A provider replacement still initializes the new process, but leaves opted-in
68+
threads unopened until a reviewed lifecycle request or prompt resumes them.
69+
Recovery preserves structured review errors instead of wrapping them as process
70+
failures. A replacement-process first prompt with an old token stops before
71+
`thread/resume` or `turn/start`.
72+
73+
The adapter uses JSON-RPC error code `-32044` with `data.kind`:
74+
75+
- `codex_hook_review_required`: missing, invalid, superseded, or wrong-process/
76+
provider/cwd review. List again before retrying.
77+
- `codex_hook_changed`: changed definitions or an invalid/ambiguous selected
78+
identity. Refresh the displayed list and selection before trusting again.
79+
80+
These errors do not write trust or dispatch the blocked operation. Trust writes
81+
are not transactional: a transport failure or failed readback after a write
82+
must be reconciled with a fresh list. Likewise, an application retry must use
83+
a new idempotency key after review changes if its transport caches errors.
84+
85+
Clients without the neutral opt-in keep their previous request/response shapes
86+
and execution behavior. The original AIR capability and hook methods remain
87+
compatible.

‎src/AcpAgentRouter.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const asyncTaskStopParamsParser = z.object({
5858

5959
const hooksListParamsParser = z.object({cwd: z.string().trim().min(1)});
6060
const hooksTrustParamsParser = z.object({
61+
reviewToken: z.string().min(1).optional(),
6162
cwd: z.string().trim().min(1),
6263
hooks: z.array(z.object({key: z.string().min(1), currentHash: z.string().min(1)})).min(1),
6364
});
@@ -172,7 +173,7 @@ function createRouter(
172173
.onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params))
173174
.onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params))
174175
.onRequest(CODEX_HOOKS_LIST_METHOD, hooksListParamsParser, (ctx) => getAgent().listHooks(ctx.params.cwd))
175-
.onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks))
176+
.onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks, ctx.params.reviewToken))
176177
.onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params))
177178
.onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent(ctx.params).sessionIndex.rename(ctx.params))
178179
.onRequest(SESSION_BATCH_GET_METHOD, sessionBatchGetParamsParser, (ctx) => getAgent().sessionIndex.batchGet(ctx.params))

‎src/CodexAcpServer.ts‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,8 @@ import {SubagentAssociations} from "./subagents/SubagentAssociations";
185185
import {SubagentInteractionHandlers} from "./subagents/SubagentInteractionHandlers";
186186
import type {SubagentEventRouter} from "./subagents/SubagentEventRouter";
187187
import {subagentConfigurationOptions, type ObservedSubagentConfiguration} from "./subagents/SubagentConfiguration";
188-
import {listCodexHooks, trustCodexHooks, type CodexHookIdentity} from "./CodexHookTrust";
189-
import type {HooksListEntry} from "./app-server/v2/HooksListEntry";
188+
import {type CodexHookIdentity} from "./CodexHookTrust";
189+
import {CodexHookReview, type ReviewedCodexHooks} from "./CodexHookReview";
190190
import {
191191
accountFromUpdated,
192192
agentConfiguredProviderStatus,
@@ -559,6 +559,7 @@ export class CodexAcpServer {
559559
*/
560560
private providerRequests = 0;
561561
private appliedProviderRequest = 0;
562+
private readonly hookReview = new CodexHookReview(() => this.codexAcpClient);
562563
/** The `sessionIndex` extension, for AIR or a client-neutral opt-in, see `SessionIndexService.ts`. */
563564
readonly sessionIndex = new SessionIndexService({
564565
connection: () => this.connection,
@@ -783,6 +784,7 @@ export class CodexAcpServer {
783784
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
784785
this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
785786
this.sessionIndex.configure(_params.clientCapabilities);
787+
this.hookReview.configure(_params.clientCapabilities?._meta?.["codexHooks"], this.capabilities.airClient);
786788
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
787789
this.sessionIndex.observe(this.codexAcpClient);
788790
this.publishFirstAuthStatusAfterResponse();
@@ -931,6 +933,7 @@ export class CodexAcpServer {
931933
...(this.capabilities.asyncTasks && !this.capabilities.airClient ? {
932934
"async-tasks": asyncTaskCapability(),
933935
} : {}),
936+
...(this.hookReview.enabled ? {codexHooks: {version: 1, reviewToken: true}} : {}),
934937
// The session index for a client that opted in without AIR, see `docs/air-extensions.md`.
935938
...(neutralSessionIndex ? {
936939
[NEUTRAL_SESSION_INDEX_META_KEY]: neutralSessionIndex,
@@ -951,18 +954,18 @@ export class CodexAcpServer {
951954
};
952955
}
953956

954-
async listHooks(cwd: string): Promise<HooksListEntry> {
957+
async listHooks(cwd: string): Promise<ReviewedCodexHooks> {
955958
if (this.providerUpdate !== null) await this.waitForProviderUpdate();
956959
const appServer = this.ensureAppServer();
957960
if (appServer) await appServer;
958-
return await this.runWithProcessCheck(() => listCodexHooks(this.codexAcpClient.appServerClient, cwd));
961+
return await this.runWithProcessCheck(() => this.hookReview.list(cwd));
959962
}
960963

961-
async trustHooks(cwd: string, hooks: CodexHookIdentity[]): Promise<{trusted: boolean}> {
964+
async trustHooks(cwd: string, hooks: CodexHookIdentity[], reviewToken?: string): Promise<{trusted: boolean}> {
962965
if (this.providerUpdate !== null) await this.waitForProviderUpdate();
963966
const appServer = this.ensureAppServer();
964967
if (appServer) await appServer;
965-
return {trusted: await this.runWithProcessCheck(() => trustCodexHooks(this.codexAcpClient.appServerClient, cwd, hooks))};
968+
return {trusted: await this.runWithProcessCheck(() => this.hookReview.trust(cwd, hooks, reviewToken))};
966969
}
967970

968971
async extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -1820,6 +1823,10 @@ export class CodexAcpServer {
18201823

18211824
async loadSession(params: acp.LoadSessionRequest): Promise<LegacyLoadSessionResponse> {
18221825
params = this.withV1SessionInstructionAppend(params);
1826+
return this.hookReview.run(params.cwd, params._meta, () => this.loadSessionReviewed(params));
1827+
}
1828+
1829+
private async loadSessionReviewed(params: acp.LoadSessionRequest): Promise<LegacyLoadSessionResponse> {
18231830
return this.recovery === null
18241831
? await this.loadSessionOnce(params)
18251832
: await this.recovery.trackOpen(params.sessionId, () => this.loadSessionOnce(params));
@@ -1907,6 +1914,10 @@ export class CodexAcpServer {
19071914

19081915
async resumeSession(params: WithAcpMcpServers<acp.ResumeSessionRequest>): Promise<LegacyResumeSessionResponse> {
19091916
params = this.withV1SessionInstructionAppend(params);
1917+
return this.hookReview.run(params.cwd, params._meta, () => this.resumeSessionReviewed(params));
1918+
}
1919+
1920+
private async resumeSessionReviewed(params: WithAcpMcpServers<acp.ResumeSessionRequest>): Promise<LegacyResumeSessionResponse> {
19101921
return this.withSystemPromptUpdate(params, async () => this.recovery === null
19111922
? await this.resumeSessionOnce(params)
19121923
: await this.recovery.trackOpen(params.sessionId, () => this.resumeSessionOnce(params)));
@@ -1960,7 +1971,8 @@ export class CodexAcpServer {
19601971
params = this.withV1SessionInstructionAppend(params);
19611972
clientSystemPromptText(params.systemPrompt);
19621973
this.assertInstructionsReady(params.sessionId);
1963-
return this.sessionIndex.forking(params.sessionId, () => this.createFork(params));
1974+
return this.hookReview.run(params.cwd, params._meta,
1975+
() => this.sessionIndex.forking(params.sessionId, () => this.createFork(params)));
19641976
}
19651977

19661978
private async createFork(params: WithAcpMcpServers<acp.ForkSessionRequest>): Promise<acp.ForkSessionResponse> {
@@ -2119,6 +2131,10 @@ export class CodexAcpServer {
21192131
params: WithAcpMcpServers<acp.NewSessionRequest>,
21202132
): Promise<LegacyNewSessionResponse> {
21212133
params = this.withV1SessionInstructionAppend(params);
2134+
return this.hookReview.run(params.cwd, params._meta, () => this.newSessionReviewed(params));
2135+
}
2136+
2137+
private async newSessionReviewed(params: WithAcpMcpServers<acp.NewSessionRequest>): Promise<LegacyNewSessionResponse> {
21222138
if (this.providerUpdate !== null) {
21232139
await this.waitForProviderUpdate();
21242140
}
@@ -2159,6 +2175,7 @@ export class CodexAcpServer {
21592175
const appServer = this.ensureAppServer();
21602176
if (appServer) await appServer;
21612177
const elicitationRequester = this.createUrlElicitationRequester(requestId);
2178+
this.hookReview.invalidate();
21622179
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params, elicitationRequester));
21632180
if (!isAuthenticated) {
21642181
logger.log("Authenticate request failed");
@@ -2231,13 +2248,15 @@ export class CodexAcpServer {
22312248
}
22322249
this.appliedProviderRequest = request;
22332250
this.codexAcpClient.setProvider(gatewayConfig);
2251+
this.hookReview.invalidate();
22342252
// The restarted app-server takes the listing too and does not list the models again.
22352253
await this.enqueueProviderUpdate((client) => client.setProvider(gatewayConfig));
22362254
return { };
22372255
}
22382256

22392257
async disableProvider(params: acp.DisableProviderRequest): Promise<acp.DisableProviderResponse> {
22402258
this.codexAcpClient.disableProvider(params);
2259+
if (params.providerId === OPENAI_PROVIDER_ID) this.hookReview.invalidate();
22412260
if (params.providerId !== OPENAI_PROVIDER_ID) {
22422261
return { };
22432262
}
@@ -2278,6 +2297,7 @@ export class CodexAcpServer {
22782297
throw new Error("Cannot restart Codex app-server before ACP initialization");
22792298
}
22802299
await replacement.initialize(this.initializeRequest);
2300+
this.hookReview.bind(replacement);
22812301
this.codexAcpClient = replacement;
22822302
this.sessionIndex.observe(replacement);
22832303
this.availableCommands = this.createAvailableCommands(replacement);
@@ -2315,6 +2335,7 @@ export class CodexAcpServer {
23152335
// The new app-server died: the next use of each session resumes it in the restarted one.
23162336
break;
23172337
}
2338+
if (this.hookReview.enabled) continue;
23182339
// Registered before `resumeSession`, so a goal turn Codex auto-starts within a
23192340
// few ms of `thread/resume`'s response can't slip past an empty subscription
23202341
// registry on the new client (10(f1) `startCodexTurnTracker`).
@@ -2445,7 +2466,9 @@ export class CodexAcpServer {
24452466
currentClient: () => this.codexAcpClient,
24462467
createClient: (connection) => {
24472468
this.captureStderr();
2448-
return this.codexAcpClient.withAppServer(new CodexAppServerClient(connection.connection));
2469+
const client = this.codexAcpClient.withAppServer(new CodexAppServerClient(connection.connection));
2470+
this.hookReview.bind(client);
2471+
return client;
24492472
},
24502473
handshake: (client) => this.initializeRequest !== null && this.codexAcpClient.initialized
24512474
? client.initialize(this.initializeRequest)
@@ -2493,6 +2516,7 @@ export class CodexAcpServer {
24932516
// A `providers/set` can have changed the routing of the old client while the restart ran.
24942517
client.adoptRoutingFrom(this.codexAcpClient);
24952518
this.codexAcpClient = client;
2519+
this.hookReview.bind(client);
24962520
// The session index watches the thread notifications of the app-server that runs now.
24972521
this.sessionIndex.observe(client);
24982522
this.availableCommands = this.createAvailableCommands(client);
@@ -4828,6 +4852,16 @@ export class CodexAcpServer {
48284852
signal?: AbortSignal,
48294853
onTurnStarted?: () => void,
48304854
insertion?: UserMessageInsertion,
4855+
): Promise<acp.PromptResponse> {
4856+
return this.hookReview.run(this.getSessionState(params.sessionId).cwd, params._meta,
4857+
() => this.promptReviewed(params, signal, onTurnStarted, insertion));
4858+
}
4859+
4860+
private async promptReviewed(
4861+
params: acp.PromptRequest,
4862+
signal?: AbortSignal,
4863+
onTurnStarted?: () => void,
4864+
insertion?: UserMessageInsertion,
48314865
): Promise<acp.PromptResponse> {
48324866
if (this.providerUpdate !== null) {
48334867
await this.waitForProviderUpdate();

‎src/CodexAppServerClient.ts‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,6 +1290,24 @@ export class CodexAppServerClient {
12901290
return [...this.threadLoads.keys()];
12911291
}
12921292

1293+
/** Validates a reviewed process/configuration and returns the final synchronous dispatch fence. */
1294+
hookExecutionGate: ((cwd?: string) => Promise<() => void>) | undefined;
1295+
1296+
private dispatchRequest<R>(request: CodexRequest): Promise<R> {
1297+
if (this.hookExecutionGate !== undefined && ["thread/start", "thread/resume", "thread/fork", "turn/start", "review/start"].includes(request.method)) {
1298+
return this.dispatchReviewedRequest(request, this.hookExecutionGate);
1299+
}
1300+
return request.params ? this.connection.sendRequest<R>(request.method, request.params)
1301+
: this.connection.sendRequest<R>(request.method);
1302+
}
1303+
1304+
private async dispatchReviewedRequest<R>(request: CodexRequest, gate: (cwd?: string) => Promise<() => void>): Promise<R> {
1305+
const params = request.params as {cwd?: string | null};
1306+
const fence = await gate(params.cwd ?? undefined);
1307+
fence();
1308+
return await this.connection.sendRequest<R>(request.method, request.params);
1309+
}
1310+
12931311
private async sendRequest<R>(request: CodexRequest): Promise<R> {
12941312
for (const callback of this.codexEventHandlers) {
12951313
callback({ eventType: "request", ...request});
@@ -1298,12 +1316,7 @@ export class CodexAppServerClient {
12981316
let result: any;
12991317
try {
13001318
if (loadedThreadId === null) {
1301-
if (request.params) {
1302-
result = await this.connection.sendRequest<R>(request.method, request.params)
1303-
}
1304-
else {
1305-
result = await this.connection.sendRequest<R>(request.method);
1306-
}
1319+
result = await this.dispatchRequest<R>(request);
13071320
} else {
13081321
result = await this.threadLoadGate(loadedThreadId, () => this.sendThreadLoad<R>(loadedThreadId, request));
13091322
}
@@ -1319,7 +1332,7 @@ export class CodexAppServerClient {
13191332
private async sendThreadLoad<R>(threadId: string, request: CodexRequest): Promise<R> {
13201333
this.threadLoads.set(threadId, (this.threadLoads.get(threadId) ?? 0) + 1);
13211334
try {
1322-
return await this.connection.sendRequest<R>(request.method, (request as {params?: unknown}).params);
1335+
return await this.dispatchRequest<R>(request);
13231336
} finally {
13241337
const count = (this.threadLoads.get(threadId) ?? 1) - 1;
13251338
if (count > 0) this.threadLoads.set(threadId, count);

0 commit comments

Comments
 (0)