Skip to content

Commit c07bc0f

Browse files
committed
feat(hooks): adapt process-bound hook review to v2.3.0
Upstream v2.3.0 moved the ACP request routing from index.ts into AcpAgentRouter.ts (agentclientprotocol#620), wraps app-server request errors with explainCodexError (agentclientprotocol#626), adds insertion-aware prompts for steering (agentclientprotocol#620), a provider request ordering for providers/set (agentclientprotocol#627), and registers a baseline turn tracker before a provider restart resumes a session. None of this absorbs the downstream hook review (no upstream PR). Keep the downstream behaviour: the hook execution gate still fences thread/start, thread/resume, thread/fork, turn/start and review/start inside the new error wrapper; session/new, load, resume, fork and prompt still run under the review (prompt now forwards upstream's insertion); providers/set still invalidates the review after the routing changes; a provider restart still leaves a reviewed session for its reviewed lazy resume, before any baseline tracker is registered for it. The codexHooks initialize capability moves into initializeExtensionsMeta and stays ACP v1 only (the review is configured only by the v1 initialize). _codex/hooks/trust must keep accepting reviewToken, and its route now lives in AcpAgentRouter.ts, which the ledger lists among this patch's files. A new router test fails without it. Adapted from 4d43405.
1 parent 3294c45 commit c07bc0f

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
@@ -180,6 +180,9 @@ The agent advertises the `goal` object, and the client uses the control method w
180180

181181
### Hook trust
182182

183+
Clients that are not AIR can opt into [process-bound hook review](codex-hook-review.md) without changing their identity or tool/subagent contract.
184+
185+
183186
The adapter passes `CODEX_CONFIG.hooks` to Codex App Server at startup as a TOML override and removes them from the later thread config.
184187
This lets AIR review the same process that will open the session. The adapter keeps other session config fields unchanged.
185188
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
@@ -55,6 +55,7 @@ const asyncTaskStopParamsParser = z.object({
5555

5656
const hooksListParamsParser = z.object({cwd: z.string().trim().min(1)});
5757
const hooksTrustParamsParser = z.object({
58+
reviewToken: z.string().min(1).optional(),
5859
cwd: z.string().trim().min(1),
5960
hooks: z.array(z.object({key: z.string().min(1), currentHash: z.string().min(1)})).min(1),
6061
});
@@ -108,7 +109,7 @@ export function createAcpAgentRouter(
108109
.onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent().extMethod(SESSION_STEERING_METHOD, ctx.params))
109110
.onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent().extMethod(ASYNC_TASK_STOP_METHOD, ctx.params))
110111
.onRequest(CODEX_HOOKS_LIST_METHOD, hooksListParamsParser, (ctx) => getAgent().listHooks(ctx.params.cwd))
111-
.onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks))
112+
.onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks, ctx.params.reviewToken))
112113
.onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent().extMethod(GOAL_CONTROL_METHOD, ctx.params))
113114
.onRequest(SESSION_RENAME_METHOD, sessionRenameParamsParser, (ctx) => getAgent().sessionIndex.rename(ctx.params))
114115
.onRequest(SESSION_ARCHIVE_METHOD, sessionArchiveParamsParser, (ctx) => getAgent().sessionIndex.setArchived(ctx.params, true))

‎src/CodexAcpServer.ts‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,8 @@ import {
177177
type SubagentModels,
178178
} from "./subagents/CodexSubagentEventRouter";
179179
import {nameFromAgentPath} from "./subagents/CodexAgentPath";
180-
import {listCodexHooks, trustCodexHooks, type CodexHookIdentity} from "./CodexHookTrust";
181-
import type {HooksListEntry} from "./app-server/v2/HooksListEntry";
180+
import {type CodexHookIdentity} from "./CodexHookTrust";
181+
import {CodexHookReview, type ReviewedCodexHooks} from "./CodexHookReview";
182182
import {
183183
accountFromUpdated,
184184
agentConfiguredProviderStatus,
@@ -548,6 +548,7 @@ export class CodexAcpServer {
548548
*/
549549
private providerRequests = 0;
550550
private appliedProviderRequest = 0;
551+
private readonly hookReview = new CodexHookReview(() => this.codexAcpClient);
551552
/** The `sessionIndex` extension, for AIR or a client-neutral opt-in, see `SessionIndexService.ts`. */
552553
readonly sessionIndex = new SessionIndexService({
553554
connection: () => this.connection,
@@ -649,6 +650,7 @@ export class CodexAcpServer {
649650
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
650651
this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
651652
this.sessionIndex.configure(_params.clientCapabilities);
653+
this.hookReview.configure(_params.clientCapabilities?._meta?.["codexHooks"], this.capabilities.airClient);
652654
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
653655
this.sessionIndex.observe(this.codexAcpClient);
654656
this.publishFirstAuthStatusAfterResponse();
@@ -797,6 +799,7 @@ export class CodexAcpServer {
797799
...(this.capabilities.asyncTasks && !this.capabilities.airClient ? {
798800
"async-tasks": asyncTaskCapability(),
799801
} : {}),
802+
...(this.hookReview.enabled ? {codexHooks: {version: 1, reviewToken: true}} : {}),
800803
// The session index for a client that opted in without AIR, see `docs/air-extensions.md`.
801804
...(neutralSessionIndex ? {
802805
[NEUTRAL_SESSION_INDEX_META_KEY]: neutralSessionIndex,
@@ -817,18 +820,18 @@ export class CodexAcpServer {
817820
};
818821
}
819822

820-
async listHooks(cwd: string): Promise<HooksListEntry> {
823+
async listHooks(cwd: string): Promise<ReviewedCodexHooks> {
821824
if (this.providerUpdate !== null) await this.waitForProviderUpdate();
822825
const appServer = this.ensureAppServer();
823826
if (appServer) await appServer;
824-
return await this.runWithProcessCheck(() => listCodexHooks(this.codexAcpClient.appServerClient, cwd));
827+
return await this.runWithProcessCheck(() => this.hookReview.list(cwd));
825828
}
826829

827-
async trustHooks(cwd: string, hooks: CodexHookIdentity[]): Promise<{trusted: boolean}> {
830+
async trustHooks(cwd: string, hooks: CodexHookIdentity[], reviewToken?: string): Promise<{trusted: boolean}> {
828831
if (this.providerUpdate !== null) await this.waitForProviderUpdate();
829832
const appServer = this.ensureAppServer();
830833
if (appServer) await appServer;
831-
return {trusted: await this.runWithProcessCheck(() => trustCodexHooks(this.codexAcpClient.appServerClient, cwd, hooks))};
834+
return {trusted: await this.runWithProcessCheck(() => this.hookReview.trust(cwd, hooks, reviewToken))};
832835
}
833836

834837
async extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -1679,6 +1682,10 @@ export class CodexAcpServer {
16791682

16801683
async loadSession(params: acp.LoadSessionRequest): Promise<LegacyLoadSessionResponse> {
16811684
params = this.withV1SessionInstructionAppend(params);
1685+
return this.hookReview.run(params.cwd, params._meta, () => this.loadSessionReviewed(params));
1686+
}
1687+
1688+
private async loadSessionReviewed(params: acp.LoadSessionRequest): Promise<LegacyLoadSessionResponse> {
16821689
return this.recovery === null
16831690
? await this.loadSessionOnce(params)
16841691
: await this.recovery.trackOpen(params.sessionId, () => this.loadSessionOnce(params));
@@ -1766,6 +1773,10 @@ export class CodexAcpServer {
17661773

17671774
async resumeSession(params: WithAcpMcpServers<acp.ResumeSessionRequest>): Promise<LegacyResumeSessionResponse> {
17681775
params = this.withV1SessionInstructionAppend(params);
1776+
return this.hookReview.run(params.cwd, params._meta, () => this.resumeSessionReviewed(params));
1777+
}
1778+
1779+
private async resumeSessionReviewed(params: WithAcpMcpServers<acp.ResumeSessionRequest>): Promise<LegacyResumeSessionResponse> {
17691780
return this.withSystemPromptUpdate(params, async () => this.recovery === null
17701781
? await this.resumeSessionOnce(params)
17711782
: await this.recovery.trackOpen(params.sessionId, () => this.resumeSessionOnce(params)));
@@ -1819,7 +1830,8 @@ export class CodexAcpServer {
18191830
params = this.withV1SessionInstructionAppend(params);
18201831
clientSystemPromptText(params.systemPrompt);
18211832
this.assertInstructionsReady(params.sessionId);
1822-
return this.sessionIndex.forking(params.sessionId, () => this.createFork(params));
1833+
return this.hookReview.run(params.cwd, params._meta,
1834+
() => this.sessionIndex.forking(params.sessionId, () => this.createFork(params)));
18231835
}
18241836

18251837
private async createFork(params: WithAcpMcpServers<acp.ForkSessionRequest>): Promise<acp.ForkSessionResponse> {
@@ -1976,6 +1988,10 @@ export class CodexAcpServer {
19761988
params: WithAcpMcpServers<acp.NewSessionRequest>,
19771989
): Promise<LegacyNewSessionResponse> {
19781990
params = this.withV1SessionInstructionAppend(params);
1991+
return this.hookReview.run(params.cwd, params._meta, () => this.newSessionReviewed(params));
1992+
}
1993+
1994+
private async newSessionReviewed(params: WithAcpMcpServers<acp.NewSessionRequest>): Promise<LegacyNewSessionResponse> {
19791995
if (this.providerUpdate !== null) {
19801996
await this.waitForProviderUpdate();
19811997
}
@@ -2016,6 +2032,7 @@ export class CodexAcpServer {
20162032
const appServer = this.ensureAppServer();
20172033
if (appServer) await appServer;
20182034
const elicitationRequester = this.createUrlElicitationRequester(requestId);
2035+
this.hookReview.invalidate();
20192036
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params, elicitationRequester));
20202037
if (!isAuthenticated) {
20212038
logger.log("Authenticate request failed");
@@ -2088,13 +2105,15 @@ export class CodexAcpServer {
20882105
}
20892106
this.appliedProviderRequest = request;
20902107
this.codexAcpClient.setProvider(gatewayConfig);
2108+
this.hookReview.invalidate();
20912109
// The restarted app-server takes the listing too and does not list the models again.
20922110
await this.enqueueProviderUpdate((client) => client.setProvider(gatewayConfig));
20932111
return { };
20942112
}
20952113

20962114
async disableProvider(params: acp.DisableProviderRequest): Promise<acp.DisableProviderResponse> {
20972115
this.codexAcpClient.disableProvider(params);
2116+
if (params.providerId === OPENAI_PROVIDER_ID) this.hookReview.invalidate();
20982117
if (params.providerId !== OPENAI_PROVIDER_ID) {
20992118
return { };
21002119
}
@@ -2132,6 +2151,7 @@ export class CodexAcpServer {
21322151
throw new Error("Cannot restart Codex app-server before ACP initialization");
21332152
}
21342153
await replacement.initialize(this.initializeRequest);
2154+
this.hookReview.bind(replacement);
21352155
this.codexAcpClient = replacement;
21362156
this.sessionIndex.observe(replacement);
21372157
this.availableCommands = this.createAvailableCommands(replacement);
@@ -2168,6 +2188,7 @@ export class CodexAcpServer {
21682188
// The new app-server died: the next use of each session resumes it in the restarted one.
21692189
break;
21702190
}
2191+
if (this.hookReview.enabled) continue;
21712192
// Registered before `resumeSession`, so a goal turn Codex auto-starts within a
21722193
// few ms of `thread/resume`'s response can't slip past an empty subscription
21732194
// registry on the new client (10(f1) `startCodexTurnTracker`).
@@ -2298,7 +2319,9 @@ export class CodexAcpServer {
22982319
currentClient: () => this.codexAcpClient,
22992320
createClient: (connection) => {
23002321
this.captureStderr();
2301-
return this.codexAcpClient.withAppServer(new CodexAppServerClient(connection.connection));
2322+
const client = this.codexAcpClient.withAppServer(new CodexAppServerClient(connection.connection));
2323+
this.hookReview.bind(client);
2324+
return client;
23022325
},
23032326
handshake: (client) => this.initializeRequest !== null && this.codexAcpClient.initialized
23042327
? client.initialize(this.initializeRequest)
@@ -2341,6 +2364,7 @@ export class CodexAcpServer {
23412364
// A `providers/set` can have changed the routing of the old client while the restart ran.
23422365
client.adoptRoutingFrom(this.codexAcpClient);
23432366
this.codexAcpClient = client;
2367+
this.hookReview.bind(client);
23442368
// The session index watches the thread notifications of the app-server that runs now.
23452369
this.sessionIndex.observe(client);
23462370
this.availableCommands = this.createAvailableCommands(client);
@@ -4553,6 +4577,16 @@ export class CodexAcpServer {
45534577
signal?: AbortSignal,
45544578
onTurnStarted?: () => void,
45554579
insertion?: UserMessageInsertion,
4580+
): Promise<acp.PromptResponse> {
4581+
return this.hookReview.run(this.getSessionState(params.sessionId).cwd, params._meta,
4582+
() => this.promptReviewed(params, signal, onTurnStarted, insertion));
4583+
}
4584+
4585+
private async promptReviewed(
4586+
params: acp.PromptRequest,
4587+
signal?: AbortSignal,
4588+
onTurnStarted?: () => void,
4589+
insertion?: UserMessageInsertion,
45564590
): Promise<acp.PromptResponse> {
45574591
if (this.providerUpdate !== null) {
45584592
await this.waitForProviderUpdate();

‎src/CodexAppServerClient.ts‎

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

1283+
/** Validates a reviewed process/configuration and returns the final synchronous dispatch fence. */
1284+
hookExecutionGate: ((cwd?: string) => Promise<() => void>) | undefined;
1285+
1286+
private dispatchRequest<R>(request: CodexRequest): Promise<R> {
1287+
if (this.hookExecutionGate !== undefined && ["thread/start", "thread/resume", "thread/fork", "turn/start", "review/start"].includes(request.method)) {
1288+
return this.dispatchReviewedRequest(request, this.hookExecutionGate);
1289+
}
1290+
return request.params ? this.connection.sendRequest<R>(request.method, request.params)
1291+
: this.connection.sendRequest<R>(request.method);
1292+
}
1293+
1294+
private async dispatchReviewedRequest<R>(request: CodexRequest, gate: (cwd?: string) => Promise<() => void>): Promise<R> {
1295+
const params = request.params as {cwd?: string | null};
1296+
const fence = await gate(params.cwd ?? undefined);
1297+
fence();
1298+
return await this.connection.sendRequest<R>(request.method, request.params);
1299+
}
1300+
12831301
private async sendRequest<R>(request: CodexRequest): Promise<R> {
12841302
for (const callback of this.codexEventHandlers) {
12851303
callback({ eventType: "request", ...request});
@@ -1288,12 +1306,7 @@ export class CodexAppServerClient {
12881306
let result: any;
12891307
try {
12901308
if (loadedThreadId === null) {
1291-
if (request.params) {
1292-
result = await this.connection.sendRequest<R>(request.method, request.params)
1293-
}
1294-
else {
1295-
result = await this.connection.sendRequest<R>(request.method);
1296-
}
1309+
result = await this.dispatchRequest<R>(request);
12971310
} else {
12981311
result = await this.threadLoadGate(loadedThreadId, () => this.sendThreadLoad<R>(loadedThreadId, request));
12991312
}
@@ -1309,7 +1322,7 @@ export class CodexAppServerClient {
13091322
private async sendThreadLoad<R>(threadId: string, request: CodexRequest): Promise<R> {
13101323
this.threadLoads.set(threadId, (this.threadLoads.get(threadId) ?? 0) + 1);
13111324
try {
1312-
return await this.connection.sendRequest<R>(request.method, (request as {params?: unknown}).params);
1325+
return await this.dispatchRequest<R>(request);
13131326
} finally {
13141327
const count = (this.threadLoads.get(threadId) ?? 1) - 1;
13151328
if (count > 0) this.threadLoads.set(threadId, count);

0 commit comments

Comments
 (0)