Skip to content

Commit 5e9b7c5

Browse files
authored
feat: return initial ACP v2 session commands (#652)
## Summary - Return initial `availableCommands` in ACP v2 `session/new`, `session/resume` (omitted/null/full replay), and `session/fork` responses instead of sending an initial commands notification. - Reuse the existing command builder and a shared v2 input converter. Preserve AIR command-action and skill-path metadata, and leave v1 behavior unchanged. - List skills once per setup using that session's cwd and additional directories, including forks. Seed change detection from the response; subsequent command changes still use replacement notifications. - Keep initial discovery best-effort: setup succeeds without `availableCommands` if discovery fails. Preserve newer command snapshots when overlapping reads finish out of order, and reject stale setup when the session closes or is replaced during discovery. - Document the v2 client contract and update lifecycle snapshots/fixtures. System prompts and standard subagent support remain separate work packages; the current AIR subagent contract is untouched. ## Validation - `npm run typecheck` — passed, including examples. - `npm test` — 1,821 passed, 36 skipped. - `npm run build` — passed. - `npm run test:integration` — 5 passed against real Codex app-server with a local mock model. V2 coverage verifies initial commands on new, all resume modes, and fork, with no redundant initial command notifications. - Focused wire tests cover AIR/non-AIR metadata, fork-specific skill discovery, unchanged and changed command lists, discovery failure/recovery, overlapping reads, and closure during discovery. - Live-model smoke test via `npm run codex-test` — passed. - `git diff --check` — passed. The full live-model E2E suite was not run. Specification checked at `agent-client-protocol@4034a8cbc99bc48fd4579f70a3407b07907e0eb6`, notably `docs/protocol/v2/slash-commands.mdx` and the unstable v2 setup response schemas.
1 parent 5377bfe commit 5e9b7c5

16 files changed

Lines changed: 804 additions & 282 deletions

‎readme-dev.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ to v2; it reuses the runtime environment variables above.
157157
These are behaviors the AIR (JetBrains) ACP client relies on that aren't obvious from the wire
158158
schema alone:
159159

160+
- Initial commands come from `availableCommands` in v2 `session/new`, `session/resume`, and
161+
`session/fork` responses, not an initial `available_commands_update`. Later command changes still
162+
use notifications. Text inputs use `type: "text"`, and AIR command actions and skill paths are
163+
preserved. Skill discovery is best-effort: setup succeeds without initial commands if it fails.
160164
- Failed foreground work ends with `state: "idle"`, `stopReason: "error"` and a standard `error`
161165
object containing `code` and a user-facing `message`. Before insertion, the prompt also fails
162166
with a JSON-RPC error; after insertion, its successful `messageId` response is not revoked.

‎src/AcpV2SessionUpdate.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@ import {stripShellPrefix} from "./CommandUtils";
1212
*/
1313
export const STRUCTURED_PLAN_ID = "codex-structured-plan";
1414

15+
export function toV2AvailableCommands(commands: acp.AvailableCommand[]): acpV2.AvailableCommand[] {
16+
return commands.map((command) => {
17+
const {input, ...withoutInput} = command;
18+
return input === undefined
19+
? withoutInput
20+
: {...command, input: input && {...input, type: "text" as const}};
21+
});
22+
}
23+
1524
/**
1625
* Renders an internal (v1-shaped) session update as the ACP v2 updates to send, in order.
1726
*
@@ -74,12 +83,7 @@ export function toV2SessionUpdate(update: AcpSessionUpdate): acpV2.SessionUpdate
7483
case "available_commands_update":
7584
return {
7685
...update,
77-
availableCommands: update.availableCommands.map((command) => {
78-
const {input, ...withoutInput} = command;
79-
return input === undefined
80-
? withoutInput
81-
: {...command, input: input && {...input, type: "text" as const}};
82-
}),
86+
availableCommands: toV2AvailableCommands(update.availableCommands),
8387
};
8488
// v2 removed the modes API. codex-acp never emits this (mode changes go out as
8589
// `config_option_update`), so there is no v2 rendering to give it.

‎src/CodexAcpServer.ts‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
import type * as acpV2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
5353
import {toV1ClientCapabilitiesView} from "./AcpV2ClientCapabilities";
5454
import {toV1SetSessionConfigOptionRequest, toV2ConfigOptions} from "./AcpV2ConfigOptions";
55+
import {toV2AvailableCommands} from "./AcpV2SessionUpdate";
5556
import {
5657
isInsertedUserMessage,
5758
postInsertionFailureText,
@@ -1213,7 +1214,9 @@ export class CodexAcpServer {
12131214
}
12141215
}
12151216

1216-
if (canPublishSessionUpdates) {
1217+
if (this.protocolVersion === 2) {
1218+
await this.initializeAvailableCommandsV2(sessionState, sessionGeneration);
1219+
} else if (canPublishSessionUpdates) {
12171220
this.publishAvailableCommandsAsync(sessionState, sessionGeneration);
12181221
}
12191222
if (operation === "resume") {
@@ -1704,14 +1707,14 @@ export class CodexAcpServer {
17041707
if (replayFrom == null) {
17051708
await this.resumeSession(request);
17061709
await this.snapshotForegroundState(params.sessionId);
1707-
return this.createSessionConfigOptionsResponseV2(this.getSessionState(params.sessionId));
1710+
return this.createSessionSetupResponseV2(this.getSessionState(params.sessionId));
17081711
}
17091712
if (replayFrom.type !== "start") {
17101713
throw RequestError.invalidParams(undefined, `Unsupported replayFrom type: ${replayFrom.type}`);
17111714
}
17121715
const {sessionId} = await this.loadSessionAndReplayHistory(request);
17131716
await this.snapshotForegroundState(sessionId);
1714-
return this.createSessionConfigOptionsResponseV2(this.getSessionState(sessionId));
1717+
return this.createSessionSetupResponseV2(this.getSessionState(sessionId));
17151718
}
17161719

17171720
private async snapshotForegroundState(sessionId: string): Promise<void> {
@@ -1752,7 +1755,7 @@ export class CodexAcpServer {
17521755
const {sessionId} = await this.forkSession(request);
17531756
return {
17541757
sessionId,
1755-
...this.createSessionConfigOptionsResponseV2(this.getSessionState(sessionId)),
1758+
...this.createSessionSetupResponseV2(this.getSessionState(sessionId)),
17561759
};
17571760
}
17581761

@@ -1904,7 +1907,7 @@ export class CodexAcpServer {
19041907
const {sessionId} = await this.newSession(request);
19051908
return {
19061909
sessionId,
1907-
...this.createSessionConfigOptionsResponseV2(this.getSessionState(sessionId)),
1910+
...this.createSessionSetupResponseV2(this.getSessionState(sessionId)),
19081911
};
19091912
}
19101913

@@ -2945,12 +2948,17 @@ export class CodexAcpServer {
29452948
};
29462949
}
29472950

2948-
/** The v2 `configOptions` field for session responses (`session/new`, `session/resume`). */
2949-
private createSessionConfigOptionsResponseV2(sessionState: SessionState): {
2951+
/** Initial v2 configuration and commands for new, resumed, and forked sessions. */
2952+
private createSessionSetupResponseV2(sessionState: SessionState): {
29502953
configOptions?: Array<acpV2.SessionConfigOption>;
2954+
availableCommands?: Array<acpV2.AvailableCommand>;
29512955
} {
29522956
const {configOptions} = this.createSessionConfigOptionsResponse(sessionState);
2953-
return configOptions ? {configOptions: toV2ConfigOptions(configOptions)} : {};
2957+
const commands = this.availableCommands.initialCommands(sessionState);
2958+
return {
2959+
...(configOptions ? {configOptions: toV2ConfigOptions(configOptions)} : {}),
2960+
...(commands.length > 0 ? {availableCommands: toV2AvailableCommands(commands)} : {}),
2961+
};
29542962
}
29552963

29562964
private isSessionConfigEnabled(): boolean {
@@ -2962,6 +2970,16 @@ export class CodexAcpServer {
29622970
void this.publishAvailableCommands(sessionState, sessionGeneration);
29632971
}
29642972

2973+
private async initializeAvailableCommandsV2(sessionState: SessionState, sessionGeneration: number): Promise<void> {
2974+
await this.availableCommands.initialize(
2975+
sessionState,
2976+
() => this.sessionPublishIsCurrent(sessionState, sessionGeneration),
2977+
);
2978+
if (!this.sessionPublishIsCurrent(sessionState, sessionGeneration)) {
2979+
throw RequestError.invalidRequest(undefined, `Session ${sessionState.sessionId} was closed or replaced during setup`);
2980+
}
2981+
}
2982+
29652983
private async publishAvailableCommands(sessionState: SessionState, sessionGeneration: number): Promise<void> {
29662984
await this.availableCommands.publish(
29672985
sessionState,
@@ -3221,7 +3239,11 @@ export class CodexAcpServer {
32213239
});
32223240
}
32233241

3224-
await this.publishAvailableCommands(sessionState, requestedSessionGeneration);
3242+
if (this.protocolVersion === 2) {
3243+
await this.initializeAvailableCommandsV2(sessionState, requestedSessionGeneration);
3244+
} else {
3245+
await this.publishAvailableCommands(sessionState, requestedSessionGeneration);
3246+
}
32253247
await this.publishCurrentGoalBestEffort(sessionState, requestedSessionGeneration, true);
32263248
const sessionModelState: LegacySessionModelState = this.createModelState(models, currentModelId);
32273249
const sessionModeState: SessionModeState =

‎src/CodexCommands.ts‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ export class CodexCommands {
6767
private readonly pendingSkillsPublishes = new WeakMap<SessionState, PendingSkillsPublish>();
6868
/** The publish each session started last, so a slower earlier one does not overwrite its list. */
6969
private readonly publishRevisions = new WeakMap<SessionState, number>();
70+
/** Latest completed list, also used by v2 setup responses after history replay. */
71+
private readonly snapshots = new WeakMap<SessionState, {revision: number; commands: AvailableCommand[]}>();
7072

7173
constructor(
7274
connection: AcpClientConnection,
@@ -115,6 +117,41 @@ export class CodexCommands {
115117
this.pendingSkillsPublishes.delete(sessionState);
116118
}
117119

120+
/** Loads v2's initial commands without sending an initial notification. */
121+
async initialize(sessionState: SessionState, shouldPublish: () => boolean): Promise<void> {
122+
try {
123+
if (shouldPublish()) {
124+
await this.loadCommands(sessionState);
125+
}
126+
} catch (err) {
127+
if (shouldPublish()) {
128+
logger.error(`Failed to load initial commands for session ${sessionState.sessionId}`, err);
129+
}
130+
}
131+
}
132+
133+
/** Takes the response snapshot and seeds change detection for later notifications. */
134+
initialCommands(sessionState: SessionState): AvailableCommand[] {
135+
const commands = this.snapshots.get(sessionState)?.commands ?? [];
136+
this.published.set(sessionState, JSON.stringify(commands));
137+
return commands;
138+
}
139+
140+
private async loadCommands(sessionState: SessionState): Promise<{revision: number; commands: AvailableCommand[]}> {
141+
const revision = (this.publishRevisions.get(sessionState) ?? 0) + 1;
142+
this.publishRevisions.set(sessionState, revision);
143+
const skillsResponse = await this.runWithProcessCheck(() => this.codexAcpClient.listSkills(this.createSkillsListParams(sessionState)));
144+
const commands = this.buildAvailableCommands(
145+
skillsResponse?.data ?? [],
146+
sessionState.clientCapabilities.airClient,
147+
);
148+
// A slower initial read must not replace a newer list published during setup or replay.
149+
if ((this.snapshots.get(sessionState)?.revision ?? 0) < revision) {
150+
this.snapshots.set(sessionState, {revision, commands});
151+
}
152+
return {revision, commands};
153+
}
154+
118155
/** Sends the available commands. With `onlyChanges`, it sends nothing when the commands did not change. */
119156
async publish(
120157
sessionState: SessionState,
@@ -125,13 +162,7 @@ export class CodexCommands {
125162
if (!shouldPublish()) {
126163
return;
127164
}
128-
const revision = (this.publishRevisions.get(sessionState) ?? 0) + 1;
129-
this.publishRevisions.set(sessionState, revision);
130-
const skillsResponse = await this.runWithProcessCheck(() => this.codexAcpClient.listSkills(this.createSkillsListParams(sessionState)));
131-
const availableCommands = this.buildAvailableCommands(
132-
skillsResponse?.data ?? [],
133-
sessionState.clientCapabilities.airClient,
134-
);
165+
const {revision, commands: availableCommands} = await this.loadCommands(sessionState);
135166
// A publish that started later already listed the skills, and its list is the newer one.
136167
if (this.publishRevisions.get(sessionState) !== revision) {
137168
return;
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
[
2+
{
3+
"name": "plan",
4+
"description": "Turn plan mode on.",
5+
"input": null,
6+
"_meta": {
7+
"jetbrains": {
8+
"air": {
9+
"version": 1,
10+
"commandAction": {
11+
"kind": "setConfigOption",
12+
"configId": "collaboration_mode",
13+
"value": "plan",
14+
"resetValue": "default",
15+
"presentation": "state"
16+
}
17+
}
18+
}
19+
}
20+
},
21+
{
22+
"name": "mcp",
23+
"description": "Show the status of the MCP servers, or reconnect them.",
24+
"input": {
25+
"hint": "[reconnect]",
26+
"type": "text"
27+
}
28+
},
29+
{
30+
"name": "skills",
31+
"description": "List available skills.",
32+
"input": null
33+
},
34+
{
35+
"name": "status",
36+
"description": "Display session configuration and token usage.",
37+
"input": null
38+
},
39+
{
40+
"name": "review",
41+
"description": "Review uncommitted changes, or review with custom instructions.",
42+
"input": {
43+
"hint": "optional review instructions",
44+
"type": "text"
45+
}
46+
},
47+
{
48+
"name": "review-branch",
49+
"description": "Review changes relative to a base branch.",
50+
"input": {
51+
"hint": "branch name",
52+
"type": "text"
53+
}
54+
},
55+
{
56+
"name": "review-commit",
57+
"description": "Review a specific commit.",
58+
"input": {
59+
"hint": "commit sha",
60+
"type": "text"
61+
}
62+
},
63+
{
64+
"name": "compact",
65+
"description": "Summarize conversation to avoid hitting the context limit.",
66+
"input": null
67+
},
68+
{
69+
"name": "goal",
70+
"description": "Set a goal to keep pursuing.",
71+
"input": {
72+
"hint": "[<objective>|clear|pause|resume]",
73+
"type": "text"
74+
},
75+
"_meta": {
76+
"jetbrains": {
77+
"air": {
78+
"version": 1,
79+
"commandAction": {
80+
"kind": "prefixPrompt",
81+
"presentation": "state"
82+
}
83+
}
84+
}
85+
}
86+
},
87+
{
88+
"name": "rename",
89+
"description": "Rename the current session.",
90+
"input": {
91+
"hint": "new name",
92+
"type": "text"
93+
}
94+
},
95+
{
96+
"name": "logout",
97+
"description": "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
98+
"input": null
99+
},
100+
{
101+
"name": "$deploy",
102+
"description": "Run deploy",
103+
"input": null,
104+
"_meta": {
105+
"jetbrains": {
106+
"air": {
107+
"version": 1,
108+
"skillPath": "/workspace/.agents/skills/deploy/SKILL.md"
109+
}
110+
}
111+
}
112+
}
113+
]

0 commit comments

Comments
 (0)