Skip to content

Commit 2a1384e

Browse files
committed
feat: negotiate a client-neutral session failure
1 parent 8af13bd commit 2a1384e

13 files changed

Lines changed: 638 additions & 16 deletions

‎docs/air-extensions.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,8 @@ A client can also declare the ACP `clientCapabilities.session.notices`.
953953
Then a `warning`, `configWarning`, or `deprecationNotice` notification goes out as an ACP `notice` session update.
954954
It does not go out as a `sessionFailure` record. Errors still use `sessionFailure`.
955955

956+
A client that is not AIR can opt in without the AIR namespace, see [Client-neutral session failure](#client-neutral-session-failure).
957+
956958
### Record
957959

958960
```json
@@ -1040,6 +1042,68 @@ A retry warning stops being active when Codex produces turn content again.
10401042
A successful turn ends an active warning of that turn.
10411043
Recovery never removes the transcript record.
10421044

1045+
### Client-neutral session failure
1046+
1047+
A client that is not AIR can get the same typed lane without the `_meta.jetbrains.air` namespace.
1048+
It opts in with `initialize.clientCapabilities._meta`:
1049+
1050+
```json
1051+
{ "sessionFailure": { "version": 1 } }
1052+
```
1053+
1054+
- Accepted only when `sessionFailure` is an object whose `version` is an integer of at least 1. Anything else
1055+
enables nothing.
1056+
- The opt-in is an ACP v1 extension. The `initialize` answer of an opted-in client has the top-level
1057+
`_meta.sessionFailure: {"version": 1}`.
1058+
- ACP v2 ignores the opt-in: a v2 terminal failure is reported with `state_update.error`.
1059+
1060+
The opt-in selects the whole lane, not just where the record goes. The [delivery](#delivery), the identity,
1061+
the [categories and actions](#categories-and-actions), the [title and details](#title-and-details), the
1062+
[recovery](#recovery) and the `session.notices` rule are those of the AIR form. In particular:
1063+
1064+
- A terminal failure of the running turn ends the prompt with `stopReason: end_turn` and the record, not with agent
1065+
text or a JSON-RPC error. A prompt that failed because the Codex process exited or the adapter failed
1066+
unexpectedly does the same.
1067+
- Records replace `_meta.codex.error`. Records or, with `session.notices`, ACP `notice` updates replace the
1068+
`Warning:` and `Config warning:` text chunks.
1069+
- `unauthorized` and HTTP 401 still end the prompt with the ACP `authRequired` error and no record.
1070+
1071+
The record goes in the top-level `_meta.sessionFailure` of a `session_info_update` or of the `PromptResponse`:
1072+
1073+
```json
1074+
{
1075+
"stopReason": "end_turn",
1076+
"_meta": {
1077+
"sessionFailure": {
1078+
"version": 1,
1079+
"id": "turn-7:error",
1080+
"revision": 1,
1081+
"category": "limit",
1082+
"severity": "error",
1083+
"title": "You've hit your usage limit.",
1084+
"actions": [],
1085+
"kind": "quota_exhausted"
1086+
}
1087+
}
1088+
}
1089+
```
1090+
1091+
It has the fields of the [AIR record](#record), plus `version` and:
1092+
1093+
| Field | Required | Type | Meaning |
1094+
| --- | --- | --- | --- |
1095+
| `kind` | yes | open string | The adapter's internal kind of the failure. Ignore a value that you do not know. |
1096+
1097+
The current kinds are `transport_lost`, `rate_limited`, `quota_exhausted`, `overloaded`, `context_exhausted`,
1098+
`budget_exhausted`, `policy_denied`, `bad_request`, `provider_error`, `internal_error`, and `notice` for a warning
1099+
record that comes from a Codex notice. A retry warning has the kind of its failure.
1100+
1101+
- Revisions of an id only increase for the whole connection, also across prompts and `session/load`, and a new
1102+
session-scoped incident always gets a new id. A new adapter process starts over.
1103+
- A client that declares both the AIR `sessionFailure` capability and the client-neutral opt-in gets only the
1104+
client-neutral form. Its AIR capability list still names `sessionFailure`.
1105+
- AIR clients that do not send the client-neutral opt-in get the AIR form, unchanged. The AIR record has no `kind`.
1106+
10431107
## Native subagent sessions
10441108

10451109
The adapter implements the draft [ACP subagent RFD](https://github.com/agentclientprotocol/agent-client-protocol/pull/1992).

‎src/CodexAcpServer.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,11 @@ import {
229229
neutralForkPointCapability,
230230
} from "./SessionFork";
231231
import {NEUTRAL_DIFF_PATCH_META_KEY, neutralDiffPatchCapability} from "./GitPatch";
232+
import {
233+
NEUTRAL_SESSION_FAILURE_META_KEY,
234+
NeutralSessionFailureLedger,
235+
neutralSessionFailureCapability,
236+
} from "./SessionFailureExtension";
232237
import {SessionIndexService} from "./SessionIndexService";
233238
import type {SessionIndexTitleState} from "./SessionIndexTitles";
234239
import {ASYNC_TASK_STOP_METHOD, asyncTaskCapability} from "./async-tasks/AsyncTaskExtension";
@@ -337,6 +342,11 @@ export interface SessionFailure {
337342
title: string;
338343
details?: string;
339344
actions: SessionFailureAction[];
345+
/**
346+
* The adapter's internal kind of the failure. Only the client-neutral form sends it:
347+
* `CodexEventHandler.createSessionFailureMeta` removes it from the AIR record.
348+
*/
349+
kind: string;
340350
}
341351

342352
/**
@@ -415,10 +425,6 @@ const DENY_ALL_ELICITATIONS: ElicitationHandler = {
415425
handleUserInput: async () => ({answers: {}}),
416426
};
417427

418-
function clientSupportsTypedSessionFailures(capabilities: acp.ClientCapabilities | null): boolean {
419-
return clientSupportsAirCapability(capabilities, AIR_SESSION_FAILURE_KEY);
420-
}
421-
422428
function clientSupportsAgentFileChangeReports(capabilities: acp.ClientCapabilities | null): boolean {
423429
return clientSupportsAirCapability(capabilities, AIR_AGENT_FILE_CHANGE_REPORT_KEY);
424430
}
@@ -512,6 +518,7 @@ export class CodexAcpServer {
512518
private readonly getExitCode: () => number | null;
513519
private readonly getRecentStderr: () => string;
514520
private readonly sessionFailureEpoch: string;
521+
private readonly neutralSessionFailures = new NeutralSessionFailureLedger();
515522
private availableCommands: CodexCommands;
516523
private clientInfo: acp.Implementation | null;
517524
private clientCapabilities: acp.ClientCapabilities | null;
@@ -962,6 +969,11 @@ export class CodexAcpServer {
962969
...(protocolVersion === 1 && this.capabilities.diffPatchFormat === "neutral" ? {
963970
[NEUTRAL_DIFF_PATCH_META_KEY]: neutralDiffPatchCapability(),
964971
} : {}),
972+
// The client-neutral session failure, see `docs/air-extensions.md`. ACP v2 has its own terminal
973+
// failure state, so `ClientCapabilities.fromV2` never selects it.
974+
...(protocolVersion === 1 && this.capabilities.sessionFailureFormat === "neutral" ? {
975+
[NEUTRAL_SESSION_FAILURE_META_KEY]: neutralSessionFailureCapability(),
976+
} : {}),
965977
// The session index for a client that opted in without AIR, see `docs/air-extensions.md`.
966978
...(neutralSessionIndex ? {
967979
[NEUTRAL_SESSION_INDEX_META_KEY]: neutralSessionIndex,
@@ -1659,13 +1671,14 @@ export class CodexAcpServer {
16591671
baselineEventHandler = new CodexEventHandler(
16601672
this.connection,
16611673
sessionState,
1662-
clientSupportsTypedSessionFailures(this.clientCapabilities),
1674+
this.capabilities.sessionFailureFormat,
16631675
this.sessionFailureEpoch,
16641676
sessionState.subagents,
16651677
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
16661678
false,
16671679
clientSupportsCompaction(this.clientCapabilities),
16681680
clientSupportsNotices(this.clientCapabilities),
1681+
this.neutralSessionFailures,
16691682
);
16701683
}
16711684
await this.trackCodexForegroundWork(sessionState, event);
@@ -3181,13 +3194,14 @@ export class CodexAcpServer {
31813194
const eventHandler = new CodexEventHandler(
31823195
this.connection,
31833196
sessionState,
3184-
clientSupportsTypedSessionFailures(this.clientCapabilities),
3197+
this.capabilities.sessionFailureFormat,
31853198
this.sessionFailureEpoch,
31863199
sessionState.subagents,
31873200
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
31883201
false,
31893202
clientSupportsCompaction(this.clientCapabilities),
31903203
clientSupportsNotices(this.clientCapabilities),
3204+
this.neutralSessionFailures,
31913205
);
31923206
const permissionContext = this.permissionLifecycleContext(sessionState).beginPrompt();
31933207
const toolCallRenderer = new AcpToolCallRenderer(this.capabilities);
@@ -5054,13 +5068,14 @@ export class CodexAcpServer {
50545068
const promptEventHandler = new CodexEventHandler(
50555069
this.connection,
50565070
sessionState,
5057-
clientSupportsTypedSessionFailures(this.clientCapabilities),
5071+
this.capabilities.sessionFailureFormat,
50585072
this.sessionFailureEpoch,
50595073
sessionState.subagents,
50605074
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
50615075
agentFileChangeReportRequest !== null,
50625076
clientSupportsCompaction(this.clientCapabilities),
50635077
clientSupportsNotices(this.clientCapabilities),
5078+
this.neutralSessionFailures,
50645079
);
50655080
eventHandler = promptEventHandler;
50665081
const permissionLifecycle = this.permissionLifecycleContext(sessionState);
@@ -5542,7 +5557,7 @@ export class CodexAcpServer {
55425557
insertion?.onFailure?.(toV2Failure(err));
55435558
const isUnexpectedFailure = !(err instanceof RequestError);
55445559
if (eventHandler !== null
5545-
&& clientSupportsTypedSessionFailures(this.clientCapabilities)
5560+
&& this.capabilities.sessionFailureFormat !== "none"
55465561
&& (isProcessExit || isUnexpectedFailure)) {
55475562
eventHandler.recordSyntheticTerminalFailure(
55485563
isProcessExit ? "transport_lost" : "internal_error",

‎src/CodexEventHandler.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ import {
6363
AIR_SESSION_FAILURE_KEY,
6464
JETBRAINS_META_KEY,
6565
} from "./AirExtension";
66+
import {
67+
NEUTRAL_SESSION_FAILURE_META_KEY,
68+
type NeutralSessionFailureLedger,
69+
SESSION_FAILURE_VERSION,
70+
type SessionFailureFormat,
71+
} from "./SessionFailureExtension";
6672
import type {SubagentEventRouter} from "./subagents/SubagentEventRouter";
6773
import {StandardSubagentEventRouter} from "./subagents/StandardSubagentEventRouter";
6874
import type {SubagentState} from "./subagents/AcpSubagents";
@@ -91,6 +97,9 @@ type SessionFailurePolicy = {
9197

9298
const MAX_SESSION_FAILURE_TITLE_LENGTH = 240;
9399

100+
/** The `kind` of a warning record that comes from a Codex notice, not from a failure. */
101+
const SESSION_NOTICE_KIND = "notice";
102+
94103
const SESSION_FAILURE_POLICY: Record<CodexFailureKind, SessionFailurePolicy> = {
95104
transport_lost: {
96105
category: "connection",
@@ -194,6 +203,7 @@ export function failureWasShownAsMessage(error: unknown): boolean {
194203
export class CodexEventHandler {
195204

196205
private readonly sessionState: SessionState;
206+
/** The typed failure lane, in either form. Only {@link createSessionFailureMeta} reads the form itself. */
197207
private readonly supportsTypedSessionFailures: boolean;
198208
private readonly sessionFailureEpoch: string;
199209
private readonly pendingErrors: ErrorNotification[] = [];
@@ -226,17 +236,18 @@ export class CodexEventHandler {
226236
constructor(
227237
connection: AcpClientConnection,
228238
sessionState: SessionState,
229-
supportsTypedSessionFailures: boolean,
239+
private readonly sessionFailureFormat: SessionFailureFormat,
230240
sessionFailureEpoch: string,
231241
subagents: SubagentEventRouter,
232242
onAccountUpdated: ((notification: AccountUpdatedNotification) => void) | undefined,
233243
collectTurnDiffs: boolean,
234244
private readonly supportsCompaction: boolean,
235245
private readonly supportsNotices: boolean,
246+
private readonly neutralFailures: NeutralSessionFailureLedger,
236247
) {
237248
this.onAccountUpdated = onAccountUpdated;
238249
this.sessionState = sessionState;
239-
this.supportsTypedSessionFailures = supportsTypedSessionFailures;
250+
this.supportsTypedSessionFailures = sessionFailureFormat !== "none";
240251
this.sessionFailureEpoch = sessionFailureEpoch;
241252
this.session = new ACPSessionConnection(connection, sessionState.sessionId);
242253
this.renderer = new AcpToolCallRenderer(sessionState.clientCapabilities);
@@ -1162,11 +1173,12 @@ export class CodexEventHandler {
11621173
const previous = this.failuresById.get(id);
11631174
const failure: NonNullable<SessionState["sessionFailure"]> = {
11641175
id,
1165-
revision: nextSessionFailureRevision(previous, id),
1176+
revision: this.sessionFailureRevision(previous, id),
11661177
category: policy.category,
11671178
severity,
11681179
title: readableServiceErrorMessage(title),
11691180
actions: actionsOverride ?? policy.actions,
1181+
kind,
11701182
};
11711183
this.failuresById.set(id, failure);
11721184
this.failureTurnIdById.set(id, attributeToTurn ? turnId : undefined);
@@ -1182,7 +1194,16 @@ export class CodexEventHandler {
11821194
return `${turnId}:error`;
11831195
}
11841196
this.allocatedFailureScopes.add(scope);
1185-
return `${scope}:error:${this.sessionFailureEpoch}:${this.nextNoticeId++}`;
1197+
return `${scope}:error:${this.sessionFailureEpoch}:${this.nextIncidentNumber()}`;
1198+
}
1199+
1200+
private nextIncidentNumber(): number {
1201+
return this.sessionFailureFormat === "neutral" ? this.neutralFailures.incidentNumber() : this.nextNoticeId++;
1202+
}
1203+
1204+
private sessionFailureRevision(previous: SessionFailure | undefined, id: string): number {
1205+
const revision = nextSessionFailureRevision(previous, id);
1206+
return this.sessionFailureFormat === "neutral" ? this.neutralFailures.revision(id, revision) : revision;
11861207
}
11871208

11881209
/**
@@ -1221,15 +1242,16 @@ export class CodexEventHandler {
12211242
? this.lastSessionNotice.failure
12221243
: undefined;
12231244
const id = previous?.id
1224-
?? `${this.sessionState.sessionId}:notice:${this.sessionFailureEpoch}:${this.nextNoticeId++}`;
1245+
?? `${this.sessionState.sessionId}:notice:${this.sessionFailureEpoch}:${this.nextIncidentNumber()}`;
12251246
const notice: SessionFailure = {
12261247
id,
1227-
revision: nextSessionFailureRevision(previous, id),
1248+
revision: this.sessionFailureRevision(previous, id),
12281249
category: "unknown",
12291250
severity: "warning",
12301251
title,
12311252
...(details === undefined ? {} : {details}),
12321253
actions: [],
1254+
kind: SESSION_NOTICE_KIND,
12331255
};
12341256
this.lastSessionNotice = {key, failure: notice};
12351257
return notice;
@@ -1246,11 +1268,16 @@ export class CodexEventHandler {
12461268
private createSessionFailureMeta(
12471269
failure: NonNullable<SessionState["sessionFailure"]>,
12481270
): Record<string, unknown> {
1271+
if (this.sessionFailureFormat === "neutral") {
1272+
return {[NEUTRAL_SESSION_FAILURE_META_KEY]: {version: SESSION_FAILURE_VERSION, ...failure}};
1273+
}
1274+
// The AIR record has no `kind`.
1275+
const {kind: _kind, ...airFailure} = failure;
12491276
return {
12501277
[JETBRAINS_META_KEY]: {
12511278
[AIR_META_KEY]: {
12521279
[AIR_EXTENSION_VERSION_KEY]: AIR_EXTENSION_VERSION,
1253-
[AIR_SESSION_FAILURE_KEY]: failure,
1280+
[AIR_SESSION_FAILURE_KEY]: airFailure,
12541281
},
12551282
},
12561283
};

‎src/SessionFailureExtension.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* The client-neutral session failure extension, see `docs/air-extensions.md#client-neutral-session-failure`.
3+
*/
4+
5+
import type * as acp from "@agentclientprotocol/sdk/unstable";
6+
7+
/** The top-level `_meta` key of the client-neutral session failure. */
8+
export const NEUTRAL_SESSION_FAILURE_META_KEY = "sessionFailure";
9+
export const SESSION_FAILURE_VERSION = 1;
10+
11+
/**
12+
* How the adapter reports failures to the client: on the legacy lane (`none`), or as typed records in the AIR
13+
* `sessionFailure` extension or in the client-neutral top-level `_meta.sessionFailure`.
14+
* Both typed forms are the same lane. They differ only in where the record goes and in its `kind`.
15+
*/
16+
export type SessionFailureFormat = "none" | "air" | "neutral";
17+
18+
/** The `initialize` answer `_meta.sessionFailure` for a client that opted into the client-neutral form. */
19+
export function neutralSessionFailureCapability(): {version: number} {
20+
return {version: SESSION_FAILURE_VERSION};
21+
}
22+
23+
/**
24+
* Whether the client opted into the client-neutral session failure with
25+
* `clientCapabilities._meta.sessionFailure: {version}`, an integer of at least 1.
26+
*/
27+
export function clientRequestsNeutralSessionFailure(capabilities: acp.ClientCapabilities | null | undefined): boolean {
28+
const declared: unknown = capabilities?._meta?.[NEUTRAL_SESSION_FAILURE_META_KEY];
29+
if (declared === null || typeof declared !== "object" || Array.isArray(declared)) return false;
30+
const version = (declared as Record<string, unknown>)["version"];
31+
return typeof version === "number" && Number.isInteger(version) && version >= 1;
32+
}
33+
34+
/**
35+
* The incident numbers and revisions of the client-neutral form, shared by every event handler of a connection.
36+
*
37+
* A session gets a new handler for each prompt, and each `session/load` gets a new session state, while the client
38+
* keeps its records. Without this, a later handler can send a known id at revision 1, which the client drops,
39+
* or reuse the number of an unrelated incident. The AIR form keeps its per-handler numbering.
40+
*/
41+
export class NeutralSessionFailureLedger {
42+
private readonly revisions = new Map<string, number>();
43+
private nextIncident = 1;
44+
45+
incidentNumber(): number {
46+
return this.nextIncident++;
47+
}
48+
49+
/** The lowest revision of `id` that is at least `proposed` and above every revision already sent. */
50+
revision(id: string, proposed: number): number {
51+
const revision = Math.max(proposed, (this.revisions.get(id) ?? 0) + 1);
52+
this.revisions.set(id, revision);
53+
return revision;
54+
}
55+
}

0 commit comments

Comments
 (0)