Skip to content

Commit 6f96fbe

Browse files
authored
fix: update ACP SDK to 2.2 and align protocol behavior (#710)
## Summary Upgrade `@agentclientprotocol/sdk` from 2.1.0 to 2.2.0 (schemas v1.28.0 and v2.0.0-alpha.11) and align the adapter with the intervening schema and protocol-documentation clarifications. - Remove JSON-RPC batching and release setup publication after individual response writes. - Reuse the Codex handshake across repeated ACP initialization and retain the previous capabilities after a failed repeat. - Validate absolute workspace paths and reject duplicate MCP server names, including sanitized-name collisions. - Reject v2 configuration value types that do not match advertised options. - Emit native absolute paths in v2 Git patches while preserving v1/AIR formatting. - Preserve arbitrary JSON in accepted v2 MCP form responses and validate built-in question answers per property. - Add regression coverage across both ACP versions where applicable. ## Protocol review and follow-ups This change does not claim full v2 conformance. Active-session teardown, resume snapshots, subagent directory reporting, authentication/MCP delegation, and extension/security work remain separately reviewable follow-ups. ## Validation - `npm run typecheck` — passed, including examples. - `npm test` — 2,263 passed, 39 skipped. - `npm run build` — passed. - `git diff --check` — passed. - Real Codex smoke: `npm run codex-test -- -p "Reply with exactly OK. Do not use tools or modify any files." -o summary` — completed with `end_turn`. - Separate integration and opt-in E2E suites were not run.
1 parent 82ad58f commit 6f96fbe

34 files changed

Lines changed: 359 additions & 199 deletions

‎package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
"vitest": "^5.0.1"
6969
},
7070
"dependencies": {
71-
"@agentclientprotocol/sdk": "~2.1.0",
71+
"@agentclientprotocol/sdk": "~2.2.0",
7272
"@openai/codex": "^0.165.0",
7373
"cross-spawn": "^7.0.6",
7474
"diff": "^9.0.0",

‎src/AcpAgentRouter.ts‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {CodexAcpServer} from "./CodexAcpServer";
55
import {type AcpClientConnection, AcpV2Connection} from "./ACPSessionConnection";
66
import packageJson from "../package.json";
77
import {AcpResponseDelivery} from "./AcpResponseDelivery";
8+
import {isAbsoluteProtocolPath} from "./PathUtils";
89
import {
910
GOAL_CONTROL_METHOD, LEGACY_SET_SESSION_MODEL_METHOD,
1011
SESSION_STEERING_METHOD,
@@ -91,6 +92,15 @@ function createRouter(
9192
if (typeof params?.sessionId === "string") codexAcpServer.assertSessionMutationAllowed(params.sessionId);
9293
return codexAcpServer;
9394
};
95+
const getAgentForPaths = (params: {sessionId?: string; cwd?: string | null; additionalDirectories?: string[] | null}): CodexAcpServer => {
96+
if (params.cwd != null && !isAbsoluteProtocolPath(params.cwd)) {
97+
throw acp.RequestError.invalidParams(undefined, "cwd must be an absolute path");
98+
}
99+
if (params.additionalDirectories?.some(directory => !isAbsoluteProtocolPath(directory))) {
100+
throw acp.RequestError.invalidParams(undefined, "additionalDirectories entries must be absolute paths");
101+
}
102+
return getAgent(params);
103+
};
94104
type SetupState = {tail: Promise<void>; publication: Promise<void>; epoch: number; pending: number};
95105
const setups = new Map<string, SetupState>();
96106
const setup = <T>(sessionId: string, requestId: acpV2.JsonRpcId, operation: () => Promise<T>, signal: AbortSignal): Promise<T> => {
@@ -133,7 +143,7 @@ function createRouter(
133143
if (!registered) finish();
134144
}
135145
});
136-
// Waiting for delivery here would deadlock two setup requests in the same batch.
146+
// The next setup waits for delivery, not the request handler that produces the response.
137147
return response;
138148
};
139149
const attachAgent = (agent: CodexAcpServer, signal: AbortSignal) => {
@@ -150,12 +160,12 @@ function createRouter(
150160
const v1Agent = acp.agent({name: packageJson.name})
151161
.onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal))
152162
.onRequest(acp.methods.agent.initialize, (ctx) => getAgent().initialize(ctx.params))
153-
.onRequest(acp.methods.agent.session.new, (ctx) => getAgent().newSession(ctx.params))
154-
.onRequest(acp.methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).loadSession(ctx.params), ctx.signal))
155-
.onRequest(acp.methods.agent.session.fork, (ctx) => getAgent(ctx.params).forkSession(ctx.params))
156-
.onRequest(acp.methods.agent.session.list, (ctx) => getAgent().listSessions(ctx.params))
163+
.onRequest(acp.methods.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSession(ctx.params))
164+
.onRequest(acp.methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).loadSession(ctx.params), ctx.signal))
165+
.onRequest(acp.methods.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSession(ctx.params))
166+
.onRequest(acp.methods.agent.session.list, (ctx) => getAgentForPaths({cwd: ctx.params.cwd ?? null}).listSessions(ctx.params))
157167
.onRequest(acp.methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params))
158-
.onRequest(acp.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).resumeSession(ctx.params), ctx.signal))
168+
.onRequest(acp.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSession(ctx.params), ctx.signal))
159169
.onRequest(acp.methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params))
160170
.onRequest(acp.methods.agent.session.setMode, (ctx) => getAgent(ctx.params).setSessionMode(ctx.params))
161171
.onRequest(acp.methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOption(ctx.params))
@@ -185,11 +195,11 @@ function createRouter(
185195
.onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal))
186196
.onRequest(acpV2.methods.agent.initialize, (ctx) => getAgent().initializeV2(ctx.params))
187197
// No `session/load`: v2 folds it into `session/resume` with `replayFrom`.
188-
.onRequest(acpV2.methods.agent.session.new, (ctx) => getAgent().newSessionV2(ctx.params))
189-
.onRequest(acpV2.methods.agent.session.list, (ctx) => getAgent().listSessions(ctx.params))
198+
.onRequest(acpV2.methods.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSessionV2(ctx.params))
199+
.onRequest(acpV2.methods.agent.session.list, (ctx) => getAgentForPaths({cwd: ctx.params.cwd ?? null}).listSessions(ctx.params))
190200
.onRequest(acpV2.methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params))
191-
.onRequest(acpV2.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgent(ctx.params).resumeSessionV2(ctx.params), ctx.signal))
192-
.onRequest(acpV2.methods.agent.session.fork, (ctx) => getAgent(ctx.params).forkSessionV2(ctx.params))
201+
.onRequest(acpV2.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSessionV2(ctx.params), ctx.signal))
202+
.onRequest(acpV2.methods.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSessionV2(ctx.params))
193203
.onRequest(acpV2.methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params))
194204
// No `session/set_mode`: v2 removed the modes API; modes are config options.
195205
.onRequest(acpV2.methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOptionV2(ctx.params))

‎src/AcpResponseDelivery.ts‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import type {AnyWireMessage, JsonRpcId, WireStream} from "@agentclientprotocol/sdk/experimental/v2/unstable";
1+
import type {AnyMessage, JsonRpcId, Stream} from "@agentclientprotocol/sdk/experimental/v2/unstable";
22

3-
/** Observe completed writes, including batches, without changing SDK framing. */
3+
/** Observe completed response writes without changing SDK framing. */
44
export class AcpResponseDelivery {
55
private readonly callbacks = new Map<JsonRpcId, () => void>();
66
private disposed = false;
@@ -9,20 +9,18 @@ export class AcpResponseDelivery {
99
if (!this.disposed) this.callbacks.set(requestId, callback);
1010
}
1111

12-
observe(stream: WireStream): WireStream {
12+
observe(stream: Stream): Stream {
1313
return {
1414
readable: stream.readable,
15-
writable: new WritableStream<AnyWireMessage>({
15+
writable: new WritableStream<AnyMessage>({
1616
write: async message => {
1717
const writer = stream.writable.getWriter();
1818
try { await writer.write(message); }
1919
finally { writer.releaseLock(); }
20-
for (const entry of Array.isArray(message) ? message : [message]) {
21-
if ("method" in entry || entry.id === null) continue;
22-
const callback = this.callbacks.get(entry.id);
23-
this.callbacks.delete(entry.id);
24-
callback?.();
25-
}
20+
if ("method" in message || message.id === null) return;
21+
const callback = this.callbacks.get(message.id);
22+
this.callbacks.delete(message.id);
23+
callback?.();
2624
},
2725
close: async () => {
2826
const writer = stream.writable.getWriter();

‎src/AcpV2Elicitation.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import type * as acpV2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
33

44
/**
55
* `elicitation/create`'s request/response, and `elicitation/complete`'s notification, are
6-
* wire-identical between v1 and v2 (same fields, same method names) -- unlike
6+
* share field and method names between v1 and v2 -- unlike
77
* `session/request_permission`, there is no shape to render, only the type import differs per
8-
* version. These are identity casts kept as named conversion points so the rest of the codebase
9-
* never has to reach into the v2 namespace directly.
8+
* version. v2 responses allow arbitrary JSON content values. Keep them intact through the
9+
* v1-typed view and validate with the v2 response guards in shared consumers.
1010
*/
1111
export function toV2CreateElicitationRequest(request: acp.CreateElicitationRequest): acpV2.CreateElicitationRequest {
1212
return request as unknown as acpV2.CreateElicitationRequest;
@@ -16,6 +16,11 @@ export function toV1CreateElicitationResponse(response: acpV2.CreateElicitationR
1616
return response as unknown as acp.CreateElicitationResponse;
1717
}
1818

19+
/** Use the broader response contract when consuming responses through the shared typed view. */
20+
export function toV2CreateElicitationResponse(response: acp.CreateElicitationResponse): acpV2.CreateElicitationResponse {
21+
return response as unknown as acpV2.CreateElicitationResponse;
22+
}
23+
1924
/** A session-scoped elicitation carries `sessionId`; a request-scoped one carries `requestId` instead. */
2025
export function elicitationSessionId(request: acp.CreateElicitationRequest): string | undefined {
2126
const sessionId = (request as {sessionId?: unknown}).sessionId;

‎src/CodexAcpClient.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,8 @@ import {AgentMode} from "./AgentMode";
2929
import path from "node:path";
3030
import {logger} from "./Logger";
3131
import {isAccountReadAuthFailureError, isAccountReadUnavailableError} from "./CodexThreadErrors";
32-
import {sanitizeMcpServerName} from "./McpServerName";
3332
import {listedSessionTitle} from "./SessionTitle";
34-
import {type AcpMcpServer, type WithAcpMcpServers, getMcpServerName, normalizeMcpServer, toCodexMcpServerConfig} from "./McpServerConfig";
33+
import {type AcpMcpServer, type WithAcpMcpServers, normalizeMcpServers, toCodexMcpServerConfig} from "./McpServerConfig";
3534
import type {
3635
AccountLoginCompletedNotification,
3736
AccountUpdatedNotification,
@@ -63,7 +62,7 @@ import packageJson from "../package.json";
6362
import type {AuthenticationStatusResponse} from "./AcpExtensions";
6463
import {createCodexCollaborationMode} from "./CollaborationModeConfig";
6564
import type {ModeKind} from "./app-server/ModeKind";
66-
import {arePathBasenamesEqual, arePathsEqual, isAbsolutePathLike} from "./PathUtils";
65+
import {arePathBasenamesEqual, arePathsEqual, isAbsolutePathLike, isAbsoluteProtocolPath} from "./PathUtils";
6766
import {CodexSubagentSubscriptions} from "./subagents/CodexSubagentSubscriptions";
6867
import {forkSession as runForkSession} from "./SessionFork";
6968
import type {SessionMetadata, SessionMetadataWithThread} from "./SessionMetadata";
@@ -203,6 +202,8 @@ export class CodexAcpClient {
203202
};
204203

205204
async initialize(request: Pick<acp.InitializeRequest, "clientInfo">): Promise<void> {
205+
// ACP can repeat initialize, but a Codex app-server connection handshakes only once.
206+
if (this.isInitialized) return;
206207
const response = await this.codexClient.initialize({
207208
capabilities: {
208209
experimentalApi: true,
@@ -1135,10 +1136,7 @@ export class CodexAcpClient {
11351136
return {config: configWithWorkspaceRoots, skippedMcpServers: []};
11361137
}
11371138

1138-
const requestedServers = mcpServers.map(mcp => ({
1139-
name: sanitizeMcpServerName(getMcpServerName(mcp)),
1140-
server: normalizeMcpServer(mcp),
1141-
}));
1139+
const requestedServers = normalizeMcpServers(mcpServers).map(server => ({name: server.name, server}));
11421140
let serversToConfigure = requestedServers;
11431141
if (shouldDeduplicateMcpConflicts()) {
11441142
// Prevents Codex from deep-merging incompatible field types, such as url and stdio schemas.
@@ -1713,7 +1711,7 @@ function readAdditionalDirectories(cwd: string, additionalDirectories?: string[]
17131711
if (directory.length === 0) {
17141712
throw RequestError.invalidParams(undefined, "additionalDirectories entries must not be empty");
17151713
}
1716-
if (!path.isAbsolute(directory)) {
1714+
if (!isAbsoluteProtocolPath(directory)) {
17171715
throw RequestError.invalidParams(undefined, "additionalDirectories entries must be absolute paths");
17181716
}
17191717
if (!seen.has(directory)) {

‎src/CodexAcpServer.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -774,16 +774,16 @@ export class CodexAcpServer {
774774
_params: acp.InitializeRequest,
775775
): Promise<acp.InitializeResponse> {
776776
logger.log("Initialize request received");
777+
const appServer = this.ensureAppServer();
778+
if (appServer) await appServer;
779+
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
777780
this.clientInfo = _params.clientInfo ?? null;
778781
this.clientCapabilities = _params.clientCapabilities ?? null;
779782
this.initializeRequest = _params;
780783
this.capabilities = ClientCapabilities.from(_params.clientCapabilities);
781-
const appServer = this.ensureAppServer();
782-
if (appServer) await appServer;
783784
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
784785
this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
785786
this.sessionIndex.configure(_params.clientCapabilities);
786-
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
787787
this.sessionIndex.observe(this.codexAcpClient);
788788
this.publishFirstAuthStatusAfterResponse();
789789
const sessionCapabilities: SubagentAwareSessionCapabilities = {
@@ -836,17 +836,17 @@ export class CodexAcpServer {
836836
logger.log("Initialize request received", {protocolVersion: params.protocolVersion});
837837
// Existing capability readers take the v1 shape; v2 fields they read keep their relative path.
838838
const clientCapabilities = toV1ClientCapabilitiesView(params.capabilities);
839+
const appServer = this.ensureAppServer();
840+
if (appServer) await appServer;
841+
await this.runWithProcessCheck(() => this.codexAcpClient.initialize({clientInfo: params.info}));
839842
this.clientInfo = params.info;
840843
this.clientCapabilities = clientCapabilities;
841844
this.initializeRequest = {clientInfo: params.info};
842845
this.capabilities = ClientCapabilities.fromV2(clientCapabilities);
843-
const appServer = this.ensureAppServer();
844-
if (appServer) await appServer;
845846
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
846847
// Boolean config options are baseline on v2, so there is nothing to probe.
847848
this.booleanConfigOptionsSupported = true;
848849
this.sessionIndex.configure(clientCapabilities);
849-
await this.runWithProcessCheck(() => this.codexAcpClient.initialize({clientInfo: params.info}));
850850
this.sessionIndex.observe(this.codexAcpClient);
851851
this.publishFirstAuthStatusAfterResponse();
852852
return {
@@ -2699,6 +2699,11 @@ export class CodexAcpServer {
26992699
async setSessionConfigOptionV2(
27002700
params: acpV2.SetSessionConfigOptionRequest,
27012701
): Promise<acpV2.SetSessionConfigOptionResponse> {
2702+
const option = this.createSessionConfigOptions(this.getSessionState(params.sessionId))
2703+
.find(option => option.id === params.configId);
2704+
if (!option || params.type !== (option.type === "boolean" ? "boolean" : "id")) {
2705+
throw RequestError.invalidParams();
2706+
}
27022707
const response = await this.setSessionConfigOption(toV1SetSessionConfigOptionRequest(params));
27032708
return {configOptions: toV2ConfigOptions(response.configOptions)};
27042709
}

0 commit comments

Comments
 (0)