Skip to content

Commit 356abaf

Browse files
leehom0123jim
andauthored
fix: support a host-owned idle steering fallback (agentclientprotocol#593)
If a Codex turn finishes just before `_session/steering` reaches it, the adapter starts another turn and returns `startedNewTurn`. The client never receives that new prompt's final response. If the original prompt is still waiting for plan approval, steering waits too, which can block clients that process steering and permission replies serially. This adds the opt-in requested in agentclientprotocol#440: ```json {"_meta":{"steering":{"idleBehavior":"promptRequired"}}} ``` Live turns still receive the input through native steering. When no turn can accept it, the adapter returns `promptRequired` with `reason: "noRunningTurn"`, leaving the input unconsumed and starting no new turn. The client can answer any pending approval, wait for the original prompt to finish, then send the input through a normal `session/prompt`. Calls without the option behave as before. This builds on @fontanierh's patch in agentclientprotocol#441, cherry-picked with the original author and source reference preserved. I added regression tests for pending plan approval, malformed metadata tests, and usage documentation. Fixes agentclientprotocol#440. ## Testing - 33 targeted tests passed. The pending-plan-approval steering tests timed out before the fix. - Typecheck, build, and all six standalone binary targets passed. - Tested idle, live-turn steering, and pending plan approval with real Codex. Steering returned in 1 ms while approval was pending; rejecting implementation completed the original prompt with its stop reason, usage, and quota. - Full suite on Windows: 1,205 passed, 19 failed, 36 skipped. All 19 failures reproduced on unmodified main at `4583cb3`, in history, attachment, and path assertions. The real Codex tests used temporary local runners, adapted for the removed `authRequired()` call in the repository's test script. Cancellation dispatch has unit coverage; the real test used the reject-plan path. For clients: `promptRequired` is a steering result, not completion of the original prompt or its approval request. The existing `_meta.steering.supported` flag also does not distinguish support for this option, so clients need to check the adapter version. --------- Co-authored-by: jim <[email protected]>
1 parent c1c6943 commit 356abaf

8 files changed

Lines changed: 217 additions & 13 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Use [OpenAI Codex](https://github.com/openai/codex) from [Agent Client Protocol]
1616
- Compact file changes through the negotiated [AIR diff patch extension](docs/air-extensions.md#diff-patch).
1717
- For AIR, one tool call shape with each fact in one field, as the [tool call contract](docs/air-extensions.md#tool-call-contract) defines. Other clients keep the earlier fields.
1818
- [Native ACP subagent sessions](docs/subagent-sessions.md) (after capability negotiation) with separate child histories and root-routed permissions; a legacy tool-call fallback otherwise.
19+
- Mid-turn input through the [_session/steering extension](docs/steering.md), with an opt-in host-owned fallback when no turn can accept it.
1920
- [Background terminal tasks](docs/air-extensions.md#async-tasks) in AIR, with task status and targeted stop support after capability negotiation.
2021
- Session-scoped long-running goals in AIR through the [goal extension](docs/air-extensions.md#goal).
2122
- Typed warnings and errors through the opt-in [AIR session failure extension](docs/air-extensions.md#session-failure).

‎docs/air-extensions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ The adapter keeps them where they are.
243243
| `mcp_output_delta` | tool call `_meta.mcp_output_delta = {data}` | MCP progress text to append, trimmed. AIR does not get it. |
244244
| `is_mcp_tool_call` | tool call `_meta.is_mcp_tool_call: true` | The tool call is an MCP tool call. |
245245
| `is_mcp_tool_approval` | `session/request_permission` request `_meta.is_mcp_tool_approval: true` | The permission request approves an MCP tool call. |
246-
| `steering` | `initialize` response `_meta.steering = {supported: true}` | The agent accepts `_session/steering` for a running turn. |
246+
| `steering` | `initialize` response `_meta.steering = {supported: true}` | The agent accepts `_session/steering` for a running turn; see [session steering](steering.md). |
247247
| `quota` | `PromptResponse._meta.quota` | Token usage of the whole turn, the same counts as `PromptResponse.usage`: `token_count` and one `model_usage` entry for the current model, or `null` and `[]` when Codex reported no usage for the prompt, as for a prompt that started no turn. |
248248
| `authStatus` | `initialize` response `agentCapabilities._meta.authStatus` | The agent pushes `_auth/status_update`. The object carries no payload. |
249249

‎docs/steering.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Session steering
2+
3+
Steering delivers a message into a running Codex turn, so a client can adjust the agent
4+
mid-task instead of queueing until the turn ends or cancelling it. The method is
5+
`_session/steering`, a pre-standard ACP extension also shipped by claude-agent-acp; the
6+
standardization proposal is
7+
[agent-client-protocol PR #1261](https://github.com/agentclientprotocol/agent-client-protocol/pull/1261).
8+
9+
## Capability
10+
11+
The adapter advertises steering in the `initialize` response as
12+
`_meta.steering = {supported: true}`. The flag covers the method in general; it does not
13+
distinguish support for a specific optional behavior, so clients check the adapter version.
14+
15+
## Request
16+
17+
```json
18+
{
19+
"sessionId": "session-id",
20+
"prompt": [{ "type": "text", "text": "Adjust the plan" }],
21+
"_meta": { "steering": { "idleBehavior": "promptRequired" } }
22+
}
23+
```
24+
25+
- `prompt` uses the same content blocks as `session/prompt`. Image blocks are rejected with
26+
`invalidRequest` when the active model has no image input support.
27+
- `_meta` is optional and may be `null`.
28+
- An `idleBehavior` value other than `"promptRequired"` is rejected with `invalidParams`.
29+
- Steers for one session are serialized in arrival order; steers for different sessions run
30+
concurrently.
31+
32+
## Outcomes
33+
34+
| Outcome | Meaning |
35+
| --- | --- |
36+
| `injected` | The prompt joined the running turn. |
37+
| `startedNewTurn` | No turn was running, and the adapter started one with the steer content. The response arrives once the turn is running; the turn's output follows the usual session updates, and its completion, usage, and failure reporting belong to that turn, not to this response. |
38+
| `promptRequired` | Returned with `reason: "noRunningTurn"` when the client opted into `idleBehavior: "promptRequired"` and no turn can accept the input, including while the original prompt is waiting for plan approval. The input is not consumed and no turn is started. |
39+
| `failed` | The steer could not be applied due to an unexpected error. Errors the protocol defines are thrown as JSON-RPC errors instead. |
40+
41+
## Host-owned idle fallback
42+
43+
Without the opt-in, a steer that finds no running turn falls back to `startedNewTurn`: the
44+
adapter starts the turn itself. A client that wants to keep the normal prompt lifecycle
45+
opts in:
46+
47+
```json
48+
{ "_meta": { "steering": { "idleBehavior": "promptRequired" } } }
49+
```
50+
51+
With the opt-in, an idle steer returns `promptRequired` and leaves the input with the
52+
client. The client keeps the input queued, answers any pending permission request, and
53+
waits for the original `session/prompt` response before sending the queued input through
54+
its normal `session/prompt` lifecycle. That request owns completion, usage, and failure
55+
reporting. `promptRequired` does not cancel an active prompt or answer its permission
56+
requests.
57+
58+
## Examples
59+
60+
`examples/steering.ts` drives a multi-step turn and injects a steer part-way through it.

‎src/AcpExtensions.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,17 @@ export async function legacySetSessionModel(
122122
export type SessionSteerRequest = {
123123
sessionId: SessionId;
124124
prompt: ContentBlock[];
125+
_meta?: {
126+
steering?: {
127+
/** Leave idle input unconsumed so the host can own a normal prompt lifecycle. */
128+
idleBehavior?: "promptRequired";
129+
};
130+
};
125131
}
126132

127-
export type SessionSteeringResponse = {
128-
outcome: "injected" | "startedNewTurn" | "failed";
129-
}
133+
export type SessionSteeringResponse =
134+
| {outcome: "injected" | "startedNewTurn" | "failed"}
135+
| {outcome: "promptRequired", reason: "noRunningTurn"}
130136

131137
export type SessionSteeringExtRequest = {
132138
method: typeof SESSION_STEERING_METHOD;

‎src/CodexAcpServer.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {RequestError, type SessionId, type SessionModeState} from "@agentclientp
33
import {CodexEventHandler, type CompletedPlan, failureWasShownAsMessage} from "./CodexEventHandler";
44
import {attachmentFileUri, desktopAttachmentHistory} from "./DesktopAttachmentHistory";
55
import {CodexApprovalHandler} from "./permissions/CodexApprovalHandler";
6+
import {isRecord} from "./permissions/json";
67
import {PermissionLifecycleContext} from "./permissions/lifecycle";
78
import {CodexElicitationHandler} from "./CodexElicitationHandler";
89
import {type CodexAuthRequest, getCodexAuthMethods, getCodexAuthMethodsV2, isCodexAuthRequest} from "./CodexAuthMethod";
@@ -2858,8 +2859,9 @@ export class CodexAcpServer {
28582859
* check guards against deleting a queue a later request has since reused).
28592860
*
28602861
* @param params The target session id and the prompt to steer with.
2861-
* @returns Whether the prompt joined the active turn ("injected"), started a
2862-
* new one ("startedNewTurn"), or could not be applied ("failed"); see
2862+
* @returns Whether the prompt joined the active turn ("injected"), needs a
2863+
* host-owned prompt ("promptRequired"), started a new one
2864+
* ("startedNewTurn"), or could not be applied ("failed"); see
28632865
* {@link performSteeringRequest}.
28642866
*/
28652867
async executeOrQueueSteeringRequest(params: SessionSteerRequest): Promise<SessionSteeringResponse> {
@@ -2898,11 +2900,13 @@ export class CodexAcpServer {
28982900

28992901
/**
29002902
* Delivers a steering prompt to the session: injects it into the live turn
2901-
* when there is one, otherwise starts a new turn.
2903+
* when there is one. On an idle race, an opted-in host keeps ownership of
2904+
* the content; legacy clients retain the adapter-started turn behavior.
29022905
*
29032906
* @param params The target session id and the prompt to steer with.
2904-
* @returns "injected" when the prompt joined an existing turn, otherwise the
2905-
* outcome of starting a new turn.
2907+
* @returns "injected" when the prompt joined an existing turn,
2908+
* "promptRequired" when the host requested an owned idle fallback, or
2909+
* the outcome of starting a legacy fallback turn.
29062910
*/
29072911
private async performSteeringRequest(params: SessionSteerRequest): Promise<SessionSteeringResponse> {
29082912
logger.log("Steering session requested", {
@@ -2925,6 +2929,9 @@ export class CodexAcpServer {
29252929
return {outcome: "injected"};
29262930
}
29272931
}
2932+
if (params._meta?.steering?.idleBehavior === "promptRequired") {
2933+
return {outcome: "promptRequired", reason: "noRunningTurn"};
2934+
}
29282935
return await this.startNewTurnFromSteering(params, clientUserMessageId);
29292936
}
29302937

@@ -2945,10 +2952,10 @@ export class CodexAcpServer {
29452952
* A failed injection is fatal only when the turn is still the session's
29462953
* current turn and Codex reported something other than "no active turn to
29472954
* steer". Otherwise the turn has already ended underneath us and the caller
2948-
* should start a new turn instead.
2955+
* should use its configured idle fallback instead.
29492956
*
29502957
* @returns true when the prompt was injected; false when the caller should
2951-
* fall back to starting a new turn.
2958+
* return "promptRequired" or use the legacy new-turn fallback.
29522959
*/
29532960
private async injectSteerIntoActiveTurn(
29542961
params: SessionSteerRequest,
@@ -3107,9 +3114,25 @@ export class CodexAcpServer {
31073114
if (typeof sessionId !== "string" || !Array.isArray(prompt)) {
31083115
throw RequestError.invalidParams();
31093116
}
3117+
const meta = params["_meta"];
3118+
// The ACP type allows `_meta: null`; treat it like an absent `_meta`.
3119+
if (meta !== undefined && meta !== null && !isRecord(meta)) {
3120+
throw RequestError.invalidParams(undefined, "steering _meta must be an object");
3121+
}
3122+
const steering = meta?.["steering"];
3123+
if (steering !== undefined && !isRecord(steering)) {
3124+
throw RequestError.invalidParams(undefined, "steering _meta.steering must be an object");
3125+
}
3126+
const idleBehavior = steering?.["idleBehavior"];
3127+
if (idleBehavior !== undefined && idleBehavior !== "promptRequired") {
3128+
throw RequestError.invalidParams(undefined, "unsupported steering idleBehavior");
3129+
}
31103130
return {
31113131
sessionId: sessionId,
31123132
prompt: prompt as acp.ContentBlock[],
3133+
...(idleBehavior === "promptRequired" ? {
3134+
_meta: {steering: {idleBehavior}},
3135+
} : {}),
31133136
};
31143137
}
31153138

‎src/__tests__/CodexACPAgent/plan-review-events.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as acp from "@agentclientprotocol/sdk/unstable";
22
import {beforeEach, describe, expect, it, vi} from "vitest";
33
import {PLAN_COLLABORATION_MODE} from "../../CollaborationModeConfig";
44
import {ClientCapabilities} from "../../tool-calls/ClientCapabilities";
5+
import {SESSION_STEERING_METHOD} from "../../AcpExtensions";
56
import {
67
createCodexMockTestFixture,
78
createTestSessionState,
@@ -165,6 +166,43 @@ describe("CodexACPAgent - plan review", () => {
165166
return {promptPromise, sessionState, turnStart, implementationTurn};
166167
}
167168

169+
it.each(["revise", "cancel"])("returns host-owned steering immediately during plan approval, allowing %s", async (action) => {
170+
const permission = deferred<acp.RequestPermissionResponse>();
171+
const {promptPromise, turnStart} = await startPlanPrompt(null, {
172+
permissionResponse: permission.promise,
173+
emitCompletionNotification: true,
174+
});
175+
await vi.waitFor(() => expect(fixture.getAcpConnectionEvents([])
176+
.some(event => event.method === "requestPermission")).toBe(true));
177+
// The plan turn has finished, but its prompt still owns the approval.
178+
// Codex rejects steering even if the adapter's cached turn id remains.
179+
vi.spyOn(fixture.getCodexAppServerClient(), "turnSteer")
180+
.mockRejectedValue(new Error("no active turn to steer"));
181+
let promptFinished = false;
182+
void promptPromise.then(() => { promptFinished = true; });
183+
try {
184+
await expect(fixture.getCodexAcpAgent().extMethod(SESSION_STEERING_METHOD, {
185+
sessionId,
186+
prompt: [{type: "text", text: "revise this plan"}],
187+
_meta: {steering: {idleBehavior: "promptRequired"}},
188+
})).resolves.toEqual({outcome: "promptRequired", reason: "noRunningTurn"});
189+
expect(promptFinished).toBe(false);
190+
expect(turnStart).toHaveBeenCalledTimes(1);
191+
if (action === "cancel") {
192+
await fixture.getCodexAcpAgent().cancel({sessionId});
193+
// Cancelling the completed turn does not answer its pending permission request.
194+
permission.resolve({outcome: {outcome: "cancelled"}});
195+
await expect(promptPromise).resolves.toMatchObject({stopReason: "end_turn"});
196+
} else {
197+
permission.resolve({outcome: {outcome: "selected", optionId: "revise_plan"}});
198+
await expect(promptPromise).resolves.toMatchObject({stopReason: "end_turn"});
199+
}
200+
expect(turnStart).toHaveBeenCalledTimes(1);
201+
} finally {
202+
permission.resolve({outcome: {outcome: "cancelled"}});
203+
}
204+
}, 2000);
205+
168206
it("requests plan permission and starts one implementation turn when approved", async () => {
169207
const {promptPromise, sessionState, turnStart, implementationTurn} = await startPlanPrompt("implement_plan");
170208

‎src/__tests__/CodexACPAgent/steer-events.test.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ describe('_session/steering', () => {
5050
vi.clearAllMocks();
5151
});
5252

53-
it('reports injected when the input joins the active turn', async () => {
53+
it.each([null, undefined, {steering: {idleBehavior: "promptRequired"}}])('reports injected when the input joins the active turn (metadata: %j)', async (_meta) => {
5454
const {mockFixture, sessionState, turnCompleted} = startActiveTurn();
5555
const turnSteerSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnSteer")
5656
.mockResolvedValue({turnId: "turn-id"});
@@ -66,6 +66,7 @@ describe('_session/steering', () => {
6666
await expect(mockFixture.getCodexAcpAgent().extMethod(SESSION_STEERING_METHOD, {
6767
sessionId: "session-id",
6868
prompt: [{type: "text", text: "also keep backward compatibility"}],
69+
_meta,
6970
})).resolves.toEqual({outcome: "injected"});
7071

7172
// Every steer mints a fresh `clientUserMessageId` (Codex-side param only; no ACP wire
@@ -113,6 +114,23 @@ describe('_session/steering', () => {
113114
});
114115
});
115116

117+
it('leaves idle input unconsumed when the host requests an owned prompt fallback', async () => {
118+
const mockFixture = createCodexMockTestFixture();
119+
const sessionState = createTestSessionState();
120+
vi.spyOn(mockFixture.getCodexAcpAgent(), "getSessionState").mockReturnValue(sessionState);
121+
const turnStartSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnStart");
122+
const turnSteerSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnSteer");
123+
124+
await expect(mockFixture.getCodexAcpAgent().extMethod(SESSION_STEERING_METHOD, {
125+
sessionId: "session-id",
126+
prompt: [{type: "text", text: "host-owned follow-up"}],
127+
_meta: {steering: {idleBehavior: "promptRequired"}},
128+
})).resolves.toEqual({outcome: "promptRequired", reason: "noRunningTurn"});
129+
130+
expect(turnStartSpy).not.toHaveBeenCalled();
131+
expect(turnSteerSpy).not.toHaveBeenCalled();
132+
});
133+
116134
it('starts a new turn when Codex reports that the tracked turn is no longer active', async () => {
117135
const {mockFixture, sessionState, turnCompleted} = startActiveTurn();
118136
const nextTurnCompleted = deferred<TurnCompletedNotification>();
@@ -156,6 +174,38 @@ describe('_session/steering', () => {
156174
});
157175
});
158176

177+
it('returns the host-owned fallback when the tracked turn wins the idle race', async () => {
178+
const {mockFixture, sessionState, turnCompleted} = startActiveTurn();
179+
const turnStartSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnStart");
180+
vi.spyOn(mockFixture.getCodexAppServerClient(), "turnSteer").mockImplementation(async () => {
181+
turnCompleted.resolve({
182+
threadId: "session-id",
183+
turn: createTurn("turn-id", "completed"),
184+
});
185+
throw Object.assign(new Error("Internal error"), {
186+
data: {details: "no active turn to steer"},
187+
});
188+
});
189+
190+
const promptPromise = mockFixture.getCodexAcpAgent().prompt({
191+
sessionId: "session-id",
192+
prompt: [{type: "text", text: "long running prompt"}],
193+
});
194+
await vi.waitFor(() => {
195+
expect(sessionState.currentTurnId).toBe("turn-id");
196+
});
197+
198+
await expect(mockFixture.getCodexAcpAgent().extMethod(SESSION_STEERING_METHOD, {
199+
sessionId: "session-id",
200+
prompt: [{type: "text", text: "racing follow-up"}],
201+
_meta: {steering: {idleBehavior: "promptRequired"}},
202+
})).resolves.toEqual({outcome: "promptRequired", reason: "noRunningTurn"});
203+
204+
await expect(promptPromise).resolves.toMatchObject({stopReason: "end_turn"});
205+
expect(turnStartSpy).toHaveBeenCalledTimes(1);
206+
expect(sessionState.currentTurnId).toBeNull();
207+
});
208+
159209
it('serializes concurrent late steering requests without dropping either prompt', async () => {
160210
const mockFixture = createCodexMockTestFixture();
161211
const sessionState = createTestSessionState();
@@ -217,6 +267,28 @@ describe('_session/steering', () => {
217267
})).rejects.toThrow(RequestError);
218268
});
219269

270+
it.each([
271+
[],
272+
false,
273+
"invalid",
274+
{steering: null},
275+
{steering: []},
276+
{steering: "invalid"},
277+
{steering: {idleBehavior: null}},
278+
{steering: {idleBehavior: "startDetachedTurn"}},
279+
])('rejects malformed steering metadata without starting or injecting a turn (%j)', async (_meta) => {
280+
const mockFixture = createCodexMockTestFixture();
281+
const turnStartSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnStart");
282+
const turnSteerSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnSteer");
283+
await expect(mockFixture.getCodexAcpAgent().extMethod(SESSION_STEERING_METHOD, {
284+
sessionId: "session-id",
285+
prompt: [{type: "text", text: "do not consume this"}],
286+
_meta,
287+
})).rejects.toThrow(RequestError);
288+
expect(turnStartSpy).not.toHaveBeenCalled();
289+
expect(turnSteerSpy).not.toHaveBeenCalled();
290+
});
291+
220292
it('rejects image input when the model does not support it', async () => {
221293
const {mockFixture} = startActiveTurn({supportedInputModalities: ["text"]});
222294
const turnSteerSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnSteer");

‎src/__tests__/SteeringQueue.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,11 @@ describe("SteeringQueue", () => {
5858
});
5959

6060
it("delivers each handler result to its own caller", async () => {
61-
const outcomes: SessionSteeringResponse["outcome"][] = ["injected", "startedNewTurn", "injected"];
61+
const outcomes: Array<Exclude<SessionSteeringResponse["outcome"], "promptRequired">> = [
62+
"injected",
63+
"startedNewTurn",
64+
"injected",
65+
];
6266
let call = 0;
6367
const queue = new SteeringQueue(async () => ({outcome: outcomes[call++]!}));
6468

0 commit comments

Comments
 (0)