Skip to content

Commit c0e41b9

Browse files
committed
fix(hooks): adapt goal-turn and provider fences to v2.3.0
Upstream v2.3.0 (agentclientprotocol#620) removed adapter-started goal continuation turns (Codex continues an active goal itself) and gave external prompts a turn-start reservation: startNewTurnFromExternalPrompt now hands its reservation to prompt() together with the insertion. No upstream PR absorbs this patch. Keep upstream's reservation call and move the downstream continueOperation into promptAfterReservation, so a turn started inside a reviewed operation still continues that review and any other prompt starts one as before. Goal set/resume control, the active thread/goal/set gate, provider inputs and the authentication invalidation apply unchanged. The fallback goal tests now expect no adapter turn/start, and the dispatch-history test moves from the removed goal fallback turn to a prompt after a crash, whose lazy thread/resume and turn/start still dispatch twice. Mutating the dispatch mark, the goal gate or the goal control review fails the tests. Adapted from 960f779.
1 parent 6c4a292 commit c0e41b9

8 files changed

Lines changed: 265 additions & 36 deletions

File tree

‎docs/codex-hook-review.md‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,35 @@ projects using that home. Accepting another hash replaces a key's prior trust.
4848
## Execution and recovery
4949

5050
Every opted-in `session/new`, `session/load`, `session/resume`, `session/fork`,
51-
and `session/prompt` supplies:
51+
and `session/prompt` supplies the metadata below. Active `_session/goal` actions
52+
`set` and `resume` also require it because Codex may start a native model turn.
53+
A steering request (`_session/steering`) that starts a new turn supplies the
54+
same metadata. Read-only goal requests and pause/clear on a live thread do not
55+
require a review token:
5256

5357
```json
5458
{"_meta": {"codexHooks": {"reviewToken": "opaque-token-from-list"}}}
5559
```
5660

5761
The adapter carries the token in request-local asynchronous context. It checks
5862
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
63+
`thread/fork`, `turn/start`, `review/start`, and active `thread/goal/set` dispatch
64+
boundaries, including queued rollout loads, lazy recovery, and internal
65+
first-turn work. A final
6166
synchronous fence rejects a process or provider change after validation and
6267
before dispatch. No hook-capable request is sent by a failed fence.
6368

6469
Tokens are adapter-local and do not survive an adapter restart, app-server
6570
replacement, provider update, or authentication that can change routing.
6671
Changing captured launch hooks requires a replacement process and fresh review.
72+
Authentication invalidates both when it starts and when it settles, including
73+
failed/cancelled login, so reviews issued during the transition cannot survive
74+
it. Reviews also bind the persisted provider selection and the selected
75+
provider's routing definition (merged with launch/gateway overrides), without
76+
binding unrelated settings or provider display metadata. The final gate checks
77+
the resolved provider carried by an opening request as well as freshly read
78+
provider inputs.
79+
6780
A provider replacement still initializes the new process, but leaves opted-in
6881
threads unopened until a reviewed lifecycle request or prompt resumes them.
6982
Recovery preserves structured review errors instead of wrapping them as process
@@ -77,8 +90,15 @@ The adapter uses JSON-RPC error code `-32044` with `data.kind`:
7790
- `codex_hook_changed`: changed definitions or an invalid/ambiguous selected
7891
identity. Refresh the displayed list and selection before trusting again.
7992

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
93+
The adapter reserves `-32044` for an ACP operation that has sent no hook-capable
94+
work. Once an operation dispatches a potentially turn-starting request, a later
95+
review failure returns an ordinary `-32603` failure instead. Clients must not
96+
automatically replay earlier work. Generated goal and steering continuations
97+
retain the current request's reviewed context and dispatch history; they do not
98+
silently begin a new retry boundary.
99+
100+
A failed pre-dispatch review does not write trust or send the blocked operation.
101+
Trust writes are not transactional: a transport failure or failed readback after a write
82102
must be reconciled with a fresh list. Likewise, an application retry must use
83103
a new idempotency key after review changes if its transport caches errors.
84104

‎src/AcpExtensions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ export async function legacySetSessionModel(
120120
}
121121

122122
export type SessionSteerRequest = {
123+
_meta?: Record<string, unknown> | null;
123124
sessionId: SessionId;
124125
prompt: ContentBlock[];
125126
}

‎src/CodexAcpClient.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,22 @@ export class CodexAcpClient {
610610
return providerId === CUSTOM_GATEWAY_PROVIDER_ID && this.gatewayConfigSource === "acpProviders";
611611
}
612612

613+
/** Provider inputs that can change the routing of a subsequent open or turn. Never returned over ACP. */
614+
async hookReviewProviderInputs(): Promise<{modelProvider: string; config: JsonObject}> {
615+
const persisted = (await this.codexClient.configRead({includeLayers: false})).config;
616+
const modelProvider = this.getModelProvider() ?? persisted.model_provider ?? "openai";
617+
const selected = (providers: unknown): JsonObject => {
618+
if (providers === null || typeof providers !== "object" || Array.isArray(providers)) return {};
619+
const value = (providers as Record<string, unknown>)[modelProvider];
620+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as JsonObject : {};
621+
};
622+
const merged: JsonObject = this.gatewayConfig?.modelProvider === modelProvider ? this.gatewayConfig.config
623+
: {...selected(persisted["model_providers"]), ...selected(this.config["model_providers"])};
624+
// A provider's display name/instructions do not affect execution. Other persisted app settings are excluded.
625+
const {name: _name, env_key_instructions: _instructions, ...config} = merged;
626+
return {modelProvider, config};
627+
}
628+
613629
/**
614630
* The model provider the agent itself is configured with (launch option or
615631
* Codex config), ignoring any ACP-configured gateway routing. The

‎src/CodexAcpServer.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -835,6 +835,15 @@ export class CodexAcpServer {
835835
}
836836

837837
async extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
838+
if ((method === GOAL_CONTROL_METHOD || method === LEGACY_GOAL_CONTROL_METHOD)
839+
&& (params["action"] === "set" || params["action"] === "resume")) {
840+
const session = this.sessions.get(params["sessionId"] as string);
841+
if (session !== undefined) return this.hookReview.run(session.cwd, params["_meta"], () => this.extMethodReviewed(method, params));
842+
}
843+
return this.extMethodReviewed(method, params);
844+
}
845+
846+
private async extMethodReviewed(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
838847
const methodRequest = { method: method, params: params };
839848
if (!isExtMethodRequest(methodRequest)) {
840849
return {};
@@ -2033,14 +2042,19 @@ export class CodexAcpServer {
20332042
if (appServer) await appServer;
20342043
const elicitationRequester = this.createUrlElicitationRequester(requestId);
20352044
this.hookReview.invalidate();
2036-
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params, elicitationRequester));
2037-
if (!isAuthenticated) {
2038-
logger.log("Authenticate request failed");
2039-
throw RequestError.authRequired({methodId: _params.methodId}, "Sign-in did not complete");
2045+
try {
2046+
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params, elicitationRequester));
2047+
if (!isAuthenticated) {
2048+
logger.log("Authenticate request failed");
2049+
throw RequestError.authRequired({methodId: _params.methodId}, "Sign-in did not complete");
2050+
}
2051+
await this.refreshAuthState(this.getAuthProviderForAuthenticateRequest(_params));
2052+
logger.log("Authenticate request completed");
2053+
return { };
2054+
} finally {
2055+
// A list may have completed while login waited for its completion/cancellation notification.
2056+
this.hookReview.invalidate();
20402057
}
2041-
await this.refreshAuthState(this.getAuthProviderForAuthenticateRequest(_params));
2042-
logger.log("Authenticate request completed");
2043-
return { };
20442058
}
20452059

20462060
private createUrlElicitationRequester(requestId?: acp.JsonRpcId): UrlElicitationRequester | undefined {
@@ -3112,6 +3126,7 @@ export class CodexAcpServer {
31123126
return {
31133127
sessionId: sessionId,
31143128
prompt: prompt as acp.ContentBlock[],
3129+
...(params["_meta"] === undefined ? {} : {_meta: params["_meta"] as Record<string, unknown> | null}),
31153130
};
31163131
}
31173132

@@ -4578,7 +4593,8 @@ export class CodexAcpServer {
45784593
onTurnStarted?: () => void,
45794594
insertion?: UserMessageInsertion,
45804595
): Promise<acp.PromptResponse> {
4581-
return this.hookReview.run(this.getSessionState(params.sessionId).cwd, params._meta,
4596+
// A turn started from inside a reviewed operation (a steer or goal control) continues its review.
4597+
return this.hookReview.continueOperation(this.getSessionState(params.sessionId).cwd, params._meta,
45824598
() => this.promptReviewed(params, signal, onTurnStarted, insertion));
45834599
}
45844600

‎src/CodexAppServerClient.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1281,19 +1281,20 @@ export class CodexAppServerClient {
12811281
}
12821282

12831283
/** Validates a reviewed process/configuration and returns the final synchronous dispatch fence. */
1284-
hookExecutionGate: ((cwd?: string) => Promise<() => void>) | undefined;
1284+
hookExecutionGate: ((cwd?: string, modelProvider?: string | null) => Promise<() => void>) | undefined;
12851285

12861286
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)) {
1287+
const activeGoal = request.method === "thread/goal/set" && request.params.status !== "paused";
1288+
if (this.hookExecutionGate !== undefined && (activeGoal || ["thread/start", "thread/resume", "thread/fork", "turn/start", "review/start"].includes(request.method))) {
12881289
return this.dispatchReviewedRequest(request, this.hookExecutionGate);
12891290
}
12901291
return request.params ? this.connection.sendRequest<R>(request.method, request.params)
12911292
: this.connection.sendRequest<R>(request.method);
12921293
}
12931294

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);
1295+
private async dispatchReviewedRequest<R>(request: CodexRequest, gate: (cwd?: string, modelProvider?: string | null) => Promise<() => void>): Promise<R> {
1296+
const params = request.params as {cwd?: string | null; modelProvider?: string | null};
1297+
const fence = await gate(params.cwd ?? undefined, params.modelProvider);
12971298
fence();
12981299
return await this.connection.sendRequest<R>(request.method, request.params);
12991300
}

‎src/CodexHookReview.ts‎

Lines changed: 55 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@ export class CodexHookReviewError extends RequestError {
1616
}
1717

1818
export type ReviewedCodexHooks = HooksListEntry & {reviewToken?: string; codexHome?: string};
19-
type Review = {cwd: string; token: string; fingerprint: string; revision: number; client: CodexAppServerClient};
19+
type Review = {cwd: string; token: string; fingerprint: string; revision: number; client: CodexAppServerClient; provider: string; providerFingerprint: string};
2020

2121
/** Owns ephemeral reviews. Request context also reaches lazy recovery and internal first-turn operations. */
2222
export class CodexHookReview {
2323
enabled = false;
2424
private revision = 0;
2525
private readonly reviews = new Map<string, Review>();
26-
private readonly context = new AsyncLocalStorage<{cwd: string; token: unknown}>();
26+
private readonly context = new AsyncLocalStorage<{cwd: string; token: unknown; dispatched: boolean}>();
2727

2828
constructor(private readonly client: () => CodexAcpClient) {}
2929

@@ -40,29 +40,49 @@ export class CodexHookReview {
4040
}
4141

4242
bind(client: CodexAcpClient): void {
43-
client.appServerClient.hookExecutionGate = this.enabled ? async cwd => {
43+
client.appServerClient.hookExecutionGate = this.enabled ? async (cwd, provider) => {
4444
const context = this.context.getStore();
45-
if (context === undefined || (cwd !== undefined && cwd !== context.cwd)) throw new CodexHookReviewError("codex_hook_review_required");
46-
return await this.validate(client.appServerClient, context.cwd, context.token);
45+
const fail = (error: unknown): never => {
46+
if (context?.dispatched && error instanceof CodexHookReviewError) {
47+
throw RequestError.internalError(undefined,
48+
"Codex hook review changed after this operation began executing. Review again before sending new work; do not retry the completed work automatically.");
49+
}
50+
throw error;
51+
};
52+
try {
53+
if (context === undefined || (cwd !== undefined && cwd !== context.cwd)) throw new CodexHookReviewError("codex_hook_review_required");
54+
const fence = await this.validate(client, context.cwd, context.token, provider);
55+
return () => {
56+
try {fence();} catch (error) {fail(error);}
57+
context.dispatched = true;
58+
};
59+
} catch (error) {return fail(error);}
4760
} : undefined;
4861
}
4962

5063
run<T>(cwd: string, meta: unknown, operation: () => Promise<T>): Promise<T> {
5164
if (!this.enabled) return operation();
5265
const hooks = (meta as {codexHooks?: {reviewToken?: unknown}} | undefined)?.codexHooks;
53-
return this.context.run({cwd, token: hooks?.reviewToken}, operation);
66+
return this.context.run({cwd, token: hooks?.reviewToken, dispatched: false}, operation);
67+
}
68+
69+
continueOperation<T>(cwd: string, meta: unknown, operation: () => Promise<T>): Promise<T> {
70+
return this.context.getStore() === undefined ? this.run(cwd, meta, operation) : operation();
5471
}
5572

5673
async list(cwd: string): Promise<ReviewedCodexHooks> {
5774
const client = this.client();
5875
const revision = this.revision;
59-
const entry = await listCodexHooks(client.appServerClient, cwd);
60-
if (!this.enabled) return entry;
76+
if (!this.enabled) return await listCodexHooks(client.appServerClient, cwd);
77+
const [entry, provider] = await Promise.all([
78+
listCodexHooks(client.appServerClient, cwd), client.hookReviewProviderInputs(),
79+
]);
6180
this.assertCurrent(client.appServerClient, revision);
62-
const fingerprint = definitionFingerprint(entry);
81+
const definitions = definitionFingerprint(entry);
82+
const providerFingerprint = fingerprint(provider);
6383
const previous = this.reviews.get(cwd);
64-
const review = previous?.client === client.appServerClient && previous.revision === revision && previous.fingerprint === fingerprint
65-
? previous : {cwd, token: randomUUID(), fingerprint, revision, client: client.appServerClient};
84+
const review = previous?.client === client.appServerClient && previous.revision === revision && previous.fingerprint === definitions && previous.providerFingerprint === providerFingerprint
85+
? previous : {cwd, token: randomUUID(), fingerprint: definitions, revision, client: client.appServerClient, provider: provider.modelProvider, providerFingerprint};
6686
this.reviews.set(cwd, review);
6787
const home = client.getHomePath();
6888
return {...entry, reviewToken: review.token, ...(home === null ? {} : {codexHome: home})};
@@ -72,6 +92,8 @@ export class CodexHookReview {
7292
const client = this.client().appServerClient;
7393
if (!this.enabled) return await trustCodexHooks(client, cwd, requested);
7494
const review = this.requireReview(client, cwd, token);
95+
const fence = await this.validate(this.client(), cwd, token);
96+
fence();
7597
if (requested.length === 0 || new Set(requested.map(hook => hook.key)).size !== requested.length
7698
|| requested.some(hook => !hook.key || !hook.currentHash)) throw new CodexHookReviewError("codex_hook_changed");
7799
return await trustCodexHooks(client, cwd, requested, entry => {
@@ -85,12 +107,18 @@ export class CodexHookReview {
85107
}, () => {this.requireReview(client, cwd, token);});
86108
}
87109

88-
private async validate(client: CodexAppServerClient, cwd: string, token: unknown): Promise<() => void> {
89-
const review = this.requireReview(client, cwd, token);
90-
const entry = await listCodexHooks(client, cwd);
91-
this.checkDefinition(client, review, entry);
110+
private async validate(client: CodexAcpClient, cwd: string, token: unknown, requestedProvider?: string | null): Promise<() => void> {
111+
const review = this.requireReview(client.appServerClient, cwd, token);
112+
const [entry, provider] = await Promise.all([
113+
listCodexHooks(client.appServerClient, cwd), client.hookReviewProviderInputs(),
114+
]);
115+
this.checkDefinition(client.appServerClient, review, entry);
116+
if (fingerprint(provider) !== review.providerFingerprint
117+
|| (requestedProvider != null && requestedProvider !== review.provider)) {
118+
throw new CodexHookReviewError("codex_hook_changed");
119+
}
92120
// The caller invokes this synchronously at dispatch, after the await and any thread-load queue.
93-
return () => {this.requireReview(client, cwd, token);};
121+
return () => {this.requireReview(client.appServerClient, cwd, token);};
94122
}
95123

96124
private requireReview(client: CodexAppServerClient, cwd: string, token: unknown): Review {
@@ -117,5 +145,15 @@ export class CodexHookReview {
117145
function definitionFingerprint(entry: HooksListEntry): string {
118146
// Trust-state changes are expected after consent; every definition field and diagnostic remains bound.
119147
const value = {...entry, hooks: entry.hooks.map(({trustStatus: _trust, ...definition}) => definition)};
120-
return createHash("sha256").update(JSON.stringify(value, (_key, value) => typeof value === "bigint" ? value.toString() : value)).digest("hex");
148+
return fingerprint(value);
149+
}
150+
151+
function fingerprint(value: unknown): string {
152+
return createHash("sha256").update(JSON.stringify(value, (_key, value) => {
153+
if (typeof value === "bigint") return value.toString();
154+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
155+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
156+
}
157+
return value;
158+
})).digest("hex");
121159
}

‎src/GoalExtension.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export type GoalSnapshot = {
2828
controlMethod: typeof GOAL_CONTROL_METHOD;
2929
}
3030

31-
export type GoalControlRequest =
31+
export type GoalControlRequest = { _meta?: Record<string, unknown> | null } & (
3232
| { sessionId: SessionId; action: "set"; objective: string }
3333
| { sessionId: SessionId; action: Exclude<GoalControlAction, "set"> }
34+
);

0 commit comments

Comments
 (0)