From 755a6cd2cd0e48ec1a03613d7b93b607c7856bfc Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Sat, 28 Nov 2026 22:09:21 +0100 Subject: [PATCH 1/3] feat: read the history of a stored session after a cursor with `_session/history_tail` AIR follows sessions that another Codex client writes, such as the Codex CLI. A `session/load` of such a thread fails: `thread/resume` takes the writer lock. The new request reads the thread with `thread/read`, `thread/items/list` and `thread/turns/list` only. It takes no lock and opens no session. - `CodexAcpClient.readSessionHistory` gives the stored history without `thread/resume`, close to the change of PR #815. A legacy thread uses one `thread/read`. - `streamThreadHistory` replays into a target: a state, a connection and a sink. A load uses the open session. The tail uses a detached state and its own delivery, so the `_meta` filter is the filter of a load. - The tail replays the whole history into a recorder and cuts it after the cursor item of each session, as the Claude adapter does. `unchanged` reads only the newest item and turn of the root thread and the newest item of each open subagent. `rewritten` comes when the cursor item is gone, as after `thread/revert`. `turnOpen` tells that the newest turn has no end. - A v1 client with `loadReplayEnd` gets one `session_info_update` after the load replay. With `historyTail` it carries `historyCursor`. - The `thread_active_writer` refusal carries an empty `data.held` object, the form of the Claude adapter. Codex does not name the holder, and the tail cannot tell a held thread without `thread/resume`, so its answer has no `held`. A live test with two app-servers on one temporary Codex home shows that the second one reads the held thread, and that it sees the running turn of the first one as interrupted with no `completedAt`. So `turnOpen` is true while that turn runs. --- README.md | 1 + docs/air-extensions.md | 147 ++- src/AcpAgentRouter.ts | 3 + src/AirExtension.ts | 14 + src/CodexAcpClient.ts | 136 +- src/CodexAcpServer.ts | 312 ++++- src/CodexAppServerClient.ts | 2 +- src/CodexThreadErrors.ts | 20 +- src/HistoryTail.ts | 741 +++++++++++ .../data/session-index-capabilities.json | 4 +- .../CodexACPAgent/history-tail.test.ts | 1092 +++++++++++++++++ .../CodexACPAgent/initialize.test.ts | 2 +- .../thread-active-writer.test.ts | 1 + .../integration/history-tail.test.ts | 92 ++ .../air/agent-message-and-reasoning.jsonl | 2 +- .../data/air/background-terminal.jsonl | 2 +- .../scenarios/data/air/collab-agent.jsonl | 2 +- .../scenarios/data/air/collab-controls.jsonl | 2 +- .../scenarios/data/air/command-approval.jsonl | 2 +- .../scenarios/data/air/command-failed.jsonl | 2 +- .../data/air/command-output-stdin.jsonl | 2 +- .../air/command-without-streamed-output.jsonl | 2 +- .../data/air/context-compaction.jsonl | 2 +- .../scenarios/data/air/dynamic-tool.jsonl | 2 +- .../data/air/file-change-approval.jsonl | 2 +- .../scenarios/data/air/file-changes.jsonl | 2 +- .../data/air/fuzzy-file-search.jsonl | 2 +- .../scenarios/data/air/goal-update.jsonl | 2 +- .../scenarios/data/air/guardian-review.jsonl | 2 +- .../scenarios/data/air/history-replay.jsonl | 2 +- .../scenarios/data/air/image-generation.jsonl | 2 +- .../scenarios/data/air/image-view.jsonl | 2 +- .../data/air/late-subagent-update.jsonl | 2 +- .../scenarios/data/air/mcp-elicitation.jsonl | 2 +- .../data/air/mcp-startup-failure.jsonl | 2 +- .../data/air/mcp-tool-approval.jsonl | 2 +- .../scenarios/data/air/mcp-tool.jsonl | 2 +- .../data/air/mcp-url-elicitation.jsonl | 2 +- .../data/air/native-subagent-session.jsonl | 2 +- .../data/air/nested-subagent-session.jsonl | 2 +- .../air/network-and-sandbox-approval.jsonl | 2 +- .../data/air/plan-deltas-and-turn-plan.jsonl | 2 +- .../data/air/plan-review-permission.jsonl | 2 +- .../scenarios/data/air/plan-stream.jsonl | 2 +- .../scenarios/data/air/read-search-list.jsonl | 2 +- .../data/air/subagent-activity.jsonl | 2 +- .../scenarios/data/air/web-search.jsonl | 2 +- src/__tests__/scenarios/scenario-harness.ts | 1 + 48 files changed, 2551 insertions(+), 83 deletions(-) create mode 100644 src/HistoryTail.ts create mode 100644 src/__tests__/CodexACPAgent/history-tail.test.ts create mode 100644 src/__tests__/integration/history-tail.test.ts diff --git a/README.md b/README.md index a8af072a0..3796182ce 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Use [OpenAI Codex](https://github.com/openai/codex) from [Agent Client Protocol] - [Native ACP subagent sessions](docs/subagent-sessions.md) with separate child histories and permissions. ACP v2 selects the standard route without capability negotiation. - [Session cursors](docs/session-cursors.md): `cursor_update` positions and `session/fork` at a cursor. - Editing a user message in place with [`_session/rewind`](docs/air-extensions.md#session-rewind) for AIR. +- A read-only [history tail](docs/air-extensions.md#history-tail) for AIR: the history of a stored session after a cursor, also of a session that another Codex client holds. - Mid-turn input through the [_session/steering extension](docs/steering.md), with an opt-in host-owned fallback when no turn can accept it. - [Async Codex questions](docs/async-questions.md) as non-blocking form elicitations, with answers steered into the turn that asked them. - [Background terminal tasks](docs/background-work.md) with standard ACP v2 state and terminal Stop. ACP v1 retains the Air extension. diff --git a/docs/air-extensions.md b/docs/air-extensions.md index 75e6a8d62..fa37de282 100644 --- a/docs/air-extensions.md +++ b/docs/air-extensions.md @@ -29,6 +29,8 @@ It describes only this adapter. - [Context compaction](#context-compaction) - [Session fork point](#session-fork-point) - [Session rewind](#session-rewind) +- [Load replay end](#load-replay-end) +- [History tail](#history-tail) - [Presentation hints](#presentation-hints) - [Predicted follow-up prompt](#predicted-follow-up-prompt) - [Removed keys](#removed-keys) @@ -143,7 +145,8 @@ The `initialize` response carries the agent side of the extension only when the "recommendedValue", "rawInputRendering", "planContentDelta", - "codexHooks" + "codexHooks", + "historyTail" ] } } @@ -174,6 +177,8 @@ A client that is not AIR gets no `jetbrains` key and no `goal` key in the `initi | `codexHooks` | Lets AIR review and trust startup hooks before it opens a session. | [Hook trust](#hook-trust) | | `sessionIndex` | Serves `session/list` as the session index of AIR, as the ACP session list extensions RFD and RFD #2161 describe, adds rename and archive requests, and pushes the changed rows of a cwd to a subscription. | [Session index](#session-index) | | `sessionRewind` | Accepts `_session/rewind`, and announces its session cursors with the `rewind` capability. ACP v1 only. | [Session rewind](#session-rewind) | +| `loadReplayEnd` | Sends one `session_info_update` after the whole history replay of a `session/load`. ACP v1 only. The agent does not advertise it. | [Load replay end](#load-replay-end) | +| `historyTail` | Adds the cursor of the replayed history to the load replay end. The agent advertises it and serves `_session/history_tail` to every v1 client. | [History tail](#history-tail) | Five agent capabilities come with `sessionIndex` and are listed exactly when it is. The client does not declare them: @@ -1240,7 +1245,8 @@ A thread that is not loaded here has no `state`. A change of `state` is a row ch `_meta.jetbrains.air.archived`. For an archive it comes after the close, as the last update of the session. - `session/load` and `session/resume` of an archived thread fail, and do not unarchive it. - Errors: - - A thread that another Codex process holds fails with the `thread_active_writer` reason in `data.reason`. + - A thread that another Codex process holds fails with the `thread_active_writer` reason in `data.reason` + and an empty `data.held` object (see [History tail](#history-tail)). - A thread that Codex does not have, or has deleted, fails with `-32002`, as does a thread that `thread/read` shows without a rollout. V2 `session/delete` succeeds if the thread is already gone. Unarchive never brings back a deleted thread. - Without `sessionIndex` the three `_session/*` methods answer method-not-found, and `session/delete` keeps @@ -1506,6 +1512,143 @@ Every `thread/revert` call, even a failing one, reloads the thread: that interru So the adapter decides `busy` and `backgroundWork` before it calls. File changes are not reverted. The files stay as the removed turns left them. +## Load replay end + +ACP v1 has no signal that the history replay of `session/load` is over, other than the response. +The client declares `loadReplayEnd` in its capabilities. The agent does not advertise it. +After the history replay of the loaded session, the agent then sends one more update for that session: + +```json +{ + "sessionId": "", + "update": { + "sessionUpdate": "session_info_update", + "_meta": { "jetbrains": { "air": { "version": 1, "loadReplayEnd": true } } } + } +} +``` + +- The update has no `title`. A `null` there would clear the title. +- It comes after every replayed update, the subagent history included, and before the `session/load` response. +- It comes also for an empty history. +- It does not come when the replay fails. A failed replay closes the session again. +- It does not come on ACP v2. The v2 `replay_complete` marks the same point there. +- For a client that also declares `historyTail`, it carries `historyCursor`, the cursor of the replayed history (see [History tail](#history-tail)). + A load that failed to read a subagent lacks its history, so its load replay end has no `historyCursor`. The next tail then reads the whole history. + +## History tail + +AIR shows sessions that another Codex client writes, such as the Codex CLI in a terminal. +A `session/load` of such a thread fails, because `thread/resume` takes the writer lock of the thread. +`_session/history_tail` gives the history of a stored thread after a cursor. +It reads the thread with `thread/read`, `thread/items/list` and `thread/turns/list`, and never calls `thread/resume`. +So it takes no writer lock, opens no session, and also reads a thread that another process holds. + +The agent advertises `historyTail` to every AIR client on ACP v1, and serves the method there. +ACP v2 gets no `historyTail` and the method not found. +AIR on ACP v1 never uses standard subagent sessions. Another client with them gets `-32600`. + +Request: + +```json +{ "sessionId": "…", "cwd": "/Users/me/repo", "cursor": { "v": 1, "…": "…" }, "limit": 2000 } +``` + +- `sessionId` is required. A thread that Codex does not have is `-32002`. +- `cwd` is required and must be an absolute path. The tool calls of the history render against it, as in a load. +- `cursor` is optional. No cursor, or `null`, reads the whole history. The client sends back a cursor of an earlier answer or of a load replay end as it is. +- `limit` is optional and must be a positive integer. An answer holds about `limit` updates: it ends at the end of a thread item. Without `limit`, the agent uses 2000. + +Answer: + +```json +{ + "status": "ok", + "updates": [{ "sessionId": "…", "update": { "…": "…" } }], + "cursor": { "…": "…" }, + "turnOpen": false +} +``` + +- `ok`: `updates` holds the `session/update` notifications that the replay of a `session/load` sends after the cursor, with the same converter and the same `_meta` filter. + The updates come in replay order, the order of a load: the frames of a child session come where the load replays them, before the end state of the child. + The `disconnected` states of the subagents that have not ended come last, in each last answer, also when no item changed. +- With `more: true`, more updates follow: the client asks again with the new `cursor`. The pages keep the replay order, and together they give what one answer with no `limit` gives. Only the last answer has `turnOpen`. +- `turnOpen` tells that the newest turn of the root thread can still run: it has no end time (`completedAt`), and its status is not `completed` or `failed`. + An `interrupted` turn with no end time counts as open, see the known gaps. +- `unchanged`: the newest item and the newest turn of the root thread, and the newest item of each subagent in `c`, are the same as at the read of the whole history that gave the cursor. + The answer has the same `cursor`, no updates, and the `turnOpen` of the newest turn now, also in its `cursor`. + A turn can end with no end time and no new item, so `turnOpen` does not come from the cursor. +- A child session that the cursor does not name gets its `subagent_spawned` update before its first update, also when the spawn comes before the cursor of its parent. + This happens when the turn of a queued interaction with an ended subagent starts: the root thread gets no new item, and the next session of the subagent starts. + The spawn also comes before a state of such a session. The answer gives each state of it that comes before the cursor of its parent, such as the `disconnected` state that a subagent gives its own subagent. + The new cursor names each child session whose spawn the client has, so no answer gives a spawn twice. +- `rewritten`: the cursor names an item that the history no longer holds in its session, or it is not a cursor of this version. + This happens after `thread/revert`. The answer has no updates and no cursor. The client reads again with no cursor and replaces the transcript. + Only a replay that started after the request answers `rewritten`. When an older kept replay lacks the item of the cursor, the agent replays again and answers from the new replay. +- A failed read fails the whole tail with `-32603` and `data` `{"reason": "history_read_failed", "retryable": true, "sessionId": "…", "threadIds": ["…"]}`. + This covers each read of the root thread, of a subagent thread, and of `model/list`. `threadIds` names the subagent threads whose read failed. + A failed `model/list` adds `"models": true`: the model reports of the subagents need the models. + A root thread that Codex does not have is not such a failure: the tail answers `-32002`. + The error has no updates and no cursor. The client keeps its cursor and asks again later. The agent keeps no replay of a failed read. + A load does not fail: it leaves out the history of such a subagent and logs the failure. +- The answer has no `held`. Codex tells the holder of the writer lock only when `thread/resume` fails, and the tail does not call it. + The refusal of `session/load` for such a thread carries `data.held` as an empty object, next to `data.reason` `thread_active_writer`. + The holder is not known, so the object has no `entrypoint` and no `status`. +- The tail sends no `session/update` and no load replay end. + +The cursor is opaque to the client: + +```json +{ "v": 1, "s": { "": [12, ""] }, "end": "", "turn": "@", "c": { "": "" }, "turnOpen": false } +``` + +- `s` names, for each session of the replay, the count of its updates and the last thread item of the session that the client has. `#0` names the updates before the first item, such as the title. + An update belongs to the current item of its own session, also when it comes while the replay of a child session runs. + An item that sends no update, such as a reasoning item with no text, also has its place in the session. + `""` names a child session whose `subagent_spawned` update the client has, but none of its updates. An answer and a load replay end give it. + A legacy thread names its items `item-` and counts them again after a rollback. + So there `s` names an item by its id and a rolling hash of the items of the session up to it: `item-7:`. + A rollback that leaves an item with the same id and content then gives another name, and the answer is `rewritten`. +- `end`, `turn` and `c` are the signature of a read of the whole history. A load replay end has no signature, so the first tail after a load reads the whole history. + `c` holds each subagent that had not ended, and each ended subagent with a queued interaction that started no turn yet. + On a legacy thread, `end` and `c` name an item by its id and a hash of its content: Codex appends to the last reasoning item in place. + Such an append makes the next tail `rewritten`. +- `p` names the kept replay of a page with `more`. `q` holds where the page ended in that replay and the positions of the first page. + So the next page goes on in the same replay, and the pages together give what one answer with no `limit` gives. + A page goes on only in the replay that `p` names. When the agent no longer keeps that replay, the page answers `rewritten`, and the client reads the whole history again. + This happens when the replay is idle for 5 minutes, when four other replays push it out, or when another read of the same session and `cwd` replaces it. + The agent pushes out a replay in the middle of a paged read only after the other replays. +- The agent ignores the `h` field of a cursor of an older build. + +A thread item keeps its id when the thread grows, so the cursor of a load stays valid. +`unchanged` costs one `thread/read`, one `thread/turns/list` and one `thread/items/list` with `limit: 1`, and one more `thread/items/list` for each subagent that had not ended. +A legacy thread has no `thread/items/list`: its newest item comes from `thread/turns/list` with the items of the newest turn, and its history from one `thread/read` with `includeTurns`. +Any other read replays the whole history again and cuts it after the cursor: the converter of a load has state across the items, such as the open tool calls. +The agent keeps the replay of each read, so a page does not replay the whole history again. +The pages of one read come from the same replay, also when the thread changes between two pages. +A read after a cursor uses the kept replay while its signature holds. A read with no cursor always replays. +The agent keeps one replay for each session and `cwd`, four at most, and drops a replay that no read uses for 5 minutes. +Reads of one session and `cwd` that overlap share one replay. A read joins only a replay that reads the newest turn after the start of the read. +At most two replays run at one time, and the others wait. +A cancelled read stops to wait, and a waiting replay that no read waits for does not start. +A replay that ends after its reads were cancelled is kept for the next read. +Each read of Codex in a tail fails after 60 seconds with no answer, so a hung read does not block the other tails. +A subagent thread that Codex does not have yet has no items, and it does not fail the tail. +Codex tells this only with the text of an `invalid_request` that names the thread: `thread is not materialized yet`, `no rollout found for thread id `, or `thread not found: `. +The agent accepts this text only at the first read of the first run of a subagent, and at the first page of the root thread. +Any other failed read of a subagent thread fails the tail with the retryable error above. +A thread with no rollout has `""` as its newest item, as in `c`. A failed read of the newest item of a subagent in `c` matches no item, also not `""`. +So the tail replays, and the replay gives the error. +The agent drops the kept replays when the connection closes. + +Known gaps: + +- Another process sees the running turn of the holder as `interrupted` with no `completedAt`, because Codex marks an in-progress turn of a thread that it has not loaded as interrupted. + So `turnOpen` is `true` while the turn runs. It also stays `true` after the holder crashed in the turn, until a new turn starts. +- Codex persists an item only when it completes. A running command or message of the holder is not in the tail until it ends. +- The title comes only in a read with no cursor. A tail after a cursor does not carry a title change: the session list and `session_info_update` of a live session carry it. +- `unchanged` does not see a change of a subagent of a subagent. ## Presentation hints The adapter sends these keys only to AIR: diff --git a/src/AcpAgentRouter.ts b/src/AcpAgentRouter.ts index 3a1b494de..289b85362 100644 --- a/src/AcpAgentRouter.ts +++ b/src/AcpAgentRouter.ts @@ -17,6 +17,7 @@ import { } from "./AcpExtensions"; import {ASYNC_TASK_STOP_METHOD} from "./async-tasks/AsyncTaskExtension"; import {SESSION_REWIND_METHOD} from "./SessionRewind"; +import {HISTORY_TAIL_METHOD, historyTailParamsParser} from "./HistoryTail"; import {CODEX_HOOKS_LIST_METHOD, CODEX_HOOKS_TRUST_METHOD} from "./CodexHookTrust"; import { SESSION_ARCHIVE_METHOD, @@ -194,6 +195,7 @@ function createRouter( setups.clear(); stopSetupPublication(); agent.sessionIndex.dispose(); + agent.disposeHistoryTails(); if (codexAcpServer === agent) { codexAcpServer = null; } @@ -236,6 +238,7 @@ function createRouter( .onRequest(SESSION_STEERING_METHOD, sessionSteerParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_STEERING_METHOD, ctx.params)) .onRequest(ASYNC_TASK_STOP_METHOD, asyncTaskStopParamsParser, (ctx) => getAgent(ctx.params).extMethod(ASYNC_TASK_STOP_METHOD, ctx.params)) .onRequest(SESSION_REWIND_METHOD, sessionRewindParamsParser, (ctx) => getAgent(ctx.params).extMethod(SESSION_REWIND_METHOD, ctx.params)) + .onRequest(HISTORY_TAIL_METHOD, historyTailParamsParser, (ctx) => getAgentForPaths(ctx.params).historyTail(ctx.params, ctx.signal)) .onRequest(CODEX_HOOKS_LIST_METHOD, hooksListParamsParser, (ctx) => getAgent().listHooks(ctx.params.cwd)) .onRequest(CODEX_HOOKS_TRUST_METHOD, hooksTrustParamsParser, (ctx) => getAgent().trustHooks(ctx.params.cwd, ctx.params.hooks)) .onRequest(GOAL_CONTROL_METHOD, goalControlParamsParser, (ctx) => getAgent(ctx.params).extMethod(GOAL_CONTROL_METHOD, ctx.params)) diff --git a/src/AirExtension.ts b/src/AirExtension.ts index cde045b21..bfcafaffb 100644 --- a/src/AirExtension.ts +++ b/src/AirExtension.ts @@ -36,6 +36,20 @@ export const AIR_CODEX_HOOKS_KEY = "codexHooks"; export const AIR_CONTENT_DELTA_KEY = "contentDelta"; export const AIR_SUBAGENT_KEY = "subagent"; export const AIR_SESSION_REWIND_KEY = "sessionRewind"; +/** + * The client wants to know when the history replay of a loaded session is whole. After the + * last replayed update, the agent sends one `session_info_update` with + * `_meta.jetbrains.air.loadReplayEnd: true`. The client declares it; the agent does not + * advertise it. + */ +export const AIR_LOAD_REPLAY_END_KEY = "loadReplayEnd"; +/** + * The agent answers `_session/history_tail` and advertises it. A client that declares it gets + * the cursor of a load in the load replay end, under {@link AIR_HISTORY_CURSOR_KEY}. + */ +export const AIR_HISTORY_TAIL_KEY = "historyTail"; +/** The `_meta.jetbrains.air` key of the load replay end that holds the cursor of the replayed history. */ +export const AIR_HISTORY_CURSOR_KEY = "historyCursor"; export const AIR_CUSTOM_ANSWER_KEY = "customAnswer"; export const AIR_CUSTOM_ANSWER_FIELDS_KEY = "customAnswerFields"; /** diff --git a/src/CodexAcpClient.ts b/src/CodexAcpClient.ts index a637eaf25..65573145d 100644 --- a/src/CodexAcpClient.ts +++ b/src/CodexAcpClient.ts @@ -16,6 +16,8 @@ import type { ElicitationHandler, ExperimentalTurnStartParams, } from "./CodexAppServerClient"; +import {withHistoryTimeout} from "./CodexAppServerClient"; +import {itemIdentity} from "./HistoryTail"; import type {McpServerStartupWaitOptions, McpStartupResult} from "./mcp/McpStartupTracker"; import open from "open"; import type {Disposable} from "vscode-jsonrpc"; @@ -80,6 +82,7 @@ import {throwIfRequestCancelled, withRequestCancellation} from "./RequestCancell import {isKeyedPromptId} from "./AcpV2Prompt"; import { isMissingRolloutError, + isNoRolloutOfThreadError, isNonSteerableTurnError, isThreadNotMaterializedError, isThreadActiveWriterError, @@ -839,14 +842,131 @@ export class CodexAcpClient { }; } + /** + * Reads the stored history of a session through the read-only Codex app-server API: + * `thread/read` and `thread/items/list`, never `thread/resume`. It takes no writer lock, + * so it also reads a thread that another Codex process holds. + * + * A paginated thread gives its items in pages up to the newest item at the start of the read. + * A legacy thread gives all its items in one `thread/read`. + */ + async readSessionHistory(sessionId: string): Promise<{ + thread: Thread; + history: AsyncIterable; + }> { + const {thread: metadata} = await withHistoryTimeout(this.codexClient.threadRead({threadId: sessionId}), "thread/read", sessionId); + if (metadata.id !== sessionId) throw sessionNotFoundRequestError(sessionId); + if (metadata.historyMode === "paginated") { + const client = this.codexClient; + const history: AsyncIterable = { + async *[Symbol.asyncIterator]() { + // Only the first page tells a thread with no rollout yet. A later failure is a failure. + let paged = false; + try { + for await (const page of client.threadItemEntryPages(metadata.id)) { + paged = true; + yield page; + } + } catch (error) { + if (paged || !isNoRolloutOfThreadError(error, metadata.id)) throw error; + } + }, + }; + return {thread: {...metadata, turns: []}, history}; + } + try { + const legacy = (await withHistoryTimeout(this.codexClient.threadReadWithHistory(metadata.id), "thread/read", metadata.id)).thread; + const thread: Thread = {...legacy, turns: []}; + const history = oneItemPage(legacy.turns.flatMap(turn => turn.items.map(item => ({ + turnId: turn.id, + item, + startedAtMs: null, + completedAtMs: null, + })))); + return {thread, history}; + } catch (error) { + if (!isNoRolloutOfThreadError(error, metadata.id)) throw error; + return {thread: {...metadata, turns: []}, history: noItems()}; + } + } + + /** + * The models and the current model id of a stored thread, as a load of the thread gives + * them, for the subagent model reports of a read-only replay. + */ + async readSessionModels(thread: Pick): Promise<{models: Model[]; currentModelId: string}> { + const models = await this.fetchAvailableModels(); + return {models, currentModelId: this.createModelId(models, thread.model, thread.reasoningEffort).toString()}; + } + + /** + * The newest item and the newest turn of a thread, read with one small request each. + * `item` is the `itemIdentity` of the newest item, or "" for a thread with no item. `turn` is the + * id of the newest turn and its end time, or "" for a thread with no turn. `turnOpen` + * tells that the newest turn can still run, see {@link isTurnOpen}. + * + * A legacy thread has no `thread/items/list`, so its newest item comes from the newest + * turn with its items. Each request fails when Codex does not answer in time. + * + * A thread that Codex cannot read, such as a subagent thread with no rollout yet, has no + * item and no turn, as {@link readSessionHistory} and the replay of a subagent give none. + */ + async readSessionHead(threadId: string, legacy: boolean): Promise<{item: string; turn: string; turnOpen: boolean}> { + try { + return await this.readSessionHeadOnce(threadId, legacy); + } catch (error) { + if (!isNoRolloutOfThreadError(error, threadId)) throw error; + return {item: "", turn: "", turnOpen: false}; + } + } + + private async readSessionHeadOnce(threadId: string, legacy: boolean): Promise<{item: string; turn: string; turnOpen: boolean}> { + const turns = await withHistoryTimeout(this.codexClient.threadTurnsList({ + threadId, + cursor: null, + limit: 1, + sortDirection: "desc", + itemsView: legacy ? "full" : "notLoaded", + }), "thread/turns/list", threadId); + const turn = turns.data[0]; + let item = ""; + if (legacy) { + const last = turn?.items.at(-1); + item = last ? itemIdentity(last, true) : ""; + } else { + const items = await withHistoryTimeout( + this.codexClient.threadItemsList({threadId, cursor: null, limit: 1, sortDirection: "desc"}), + "thread/items/list", + threadId, + ); + item = items.data[0]?.item.id ?? ""; + } + return { + item, + turn: turn ? `${turn.id}@${turn.completedAt ?? ""}` : "", + turnOpen: turn !== undefined && isTurnOpen(turn), + }; + } + /** * The items of the turn at `index` of a session, oldest first, in pages. - * Returns null when the session has fewer turns. + * Returns null when the session has fewer turns, or when Codex has no rollout of it for the first turn. */ async readSessionTurnItems(sessionId: string, index: number): Promise | null> { - const metadata = await this.codexClient.threadRead({threadId: sessionId}); + try { + return await this.readSessionTurnItemsOnce(sessionId, index); + } catch (error) { + // A subagent thread with no rollout yet has no turn, as {@link readSessionHead} gives none. Only its first + // turn can tell it: a thread with a turn has a rollout. The pages of the items fail as they come. + if (index !== 0 || !isNoRolloutOfThreadError(error, sessionId)) throw error; + return null; + } + } + + private async readSessionTurnItemsOnce(sessionId: string, index: number): Promise | null> { + const metadata = await withHistoryTimeout(this.codexClient.threadRead({threadId: sessionId}), "thread/read", sessionId); if (metadata.thread.historyMode === "legacy") { - const legacy = await this.codexClient.threadRead({threadId: sessionId, includeTurns: true}); + const legacy = await withHistoryTimeout(this.codexClient.threadRead({threadId: sessionId, includeTurns: true}), "thread/read", sessionId); const turn = legacy.thread.turns[index]; return turn ? oneItemPage(turn.items) : null; } @@ -2134,3 +2254,13 @@ function recordedItemCompleted(item: ThreadItem, completed: boolean): boolean { return completed; } } + +/** + * Whether a turn can still run: it has no end time, and its status is not `completed` or + * `failed`. A Codex process that has not loaded the thread shows a running turn of another + * process as `interrupted` with no end time. A turn that a crash ended looks the same, so an + * `interrupted` turn with no end time counts as open. + */ +function isTurnOpen(turn: Pick): boolean { + return turn.completedAt === null && turn.status !== "completed" && turn.status !== "failed"; +} diff --git a/src/CodexAcpServer.ts b/src/CodexAcpServer.ts index f5efc7889..c3bd6bacb 100644 --- a/src/CodexAcpServer.ts +++ b/src/CodexAcpServer.ts @@ -27,6 +27,7 @@ import { type ApprovalHandler, CodexAppServerClient, type ElicitationHandler, + withHistoryTimeout, } from "./CodexAppServerClient"; import { isAccountReadAccountChangedError, @@ -178,11 +179,23 @@ import { resolveCursorTurn, clientSupportsCursors, forkCursorUpdate, + type LastReportedEntity, ReplayCursors, withRewindCapability, type CursorUpdate, } from "./SessionCursors"; import { + HISTORY_TAIL_METHOD, + HistoryRecorder, + HistoryTails, + historyReadFailedError, + parseHistoryTailParams, + type HistoryTailRequest, + type HistoryTailResponse, + type ReplaySink, +} from "./HistoryTail"; +import { + isRewindableThread, rewindSession, SESSION_REWIND_METHOD, type SessionRewindRequest, @@ -248,10 +261,14 @@ import { AIR_META_KEY, AIR_SESSION_FAILURE_KEY, AIR_SESSION_REWIND_KEY, + AIR_HISTORY_CURSOR_KEY, + AIR_HISTORY_TAIL_KEY, + AIR_LOAD_REPLAY_END_KEY, clientSupportsAirCapability, isAirClient, JETBRAINS_META_KEY, publishAirSessionMetadata, + withAirMeta, } from "./AirExtension"; import type {SessionOptionMetadata} from "./SessionMetadata"; import {SessionIndexService} from "./SessionIndexService"; @@ -288,6 +305,37 @@ interface SessionOptionState { clientCapabilities: ClientCapabilities; } +/** + * The part of a session state that a history replay reads and writes. A load replays into the + * state of the open session. A `_session/history_tail` replays into a detached state: it has no + * background tasks and no title generator, and it is dropped after the replay. + */ +type HistoryReplayState = { + sessionId: string; + cwd: string; + clientCapabilities: ClientCapabilities; + rewindable: boolean; + hasTurn: boolean; + sessionTitle: string | null; + sessionTitleSource: SessionState["sessionTitleSource"]; + titleGen?: TitleGenerator; + subagents: SubagentEventRouter; + /** Absent in a detached state: the replay then restores no background terminal. */ + asyncTasks?: CodexBackgroundTasks; + availableModels?: Array; + currentModelId?: string; +}; + +/** Where a history replay goes: the state, the connection of its updates, and the sink that counts them. */ +type HistoryReplayTarget = { + state: HistoryReplayState; + connection: AcpClientConnection; + /** What a v1 live cursor anchors to, see `AcpClientDelivery.entities`. */ + entities: LastReportedEntity; + isOpen: () => boolean; + sink?: ReplaySink; +}; + export interface SessionState extends SessionIndexTitleState, SessionOptionState { sessionId: string, instructions?: SessionInstructions; @@ -556,6 +604,7 @@ export class CodexAcpServer { private authStatusVersion = 0; private readonly sessions: Map; + private readonly historyTails = new HistoryTails(); private readonly subagentAssociations = new SubagentAssociations(); private readonly subagentInteractionHandlers = new WeakMap(); private readonly mcpSessionStartup: McpSessionStartup; @@ -1006,6 +1055,7 @@ export class CodexAcpServer { AIR_RAW_INPUT_RENDERING_KEY, AIR_PLAN_CONTENT_DELTA_KEY, AIR_CODEX_HOOKS_KEY, + AIR_HISTORY_TAIL_KEY, ...(this.supportsSessionRewind() ? [AIR_SESSION_REWIND_KEY] : []), ...this.sessionIndex.agentCapabilities(), ] @@ -2036,15 +2086,22 @@ export class CodexAcpServer { try { try { + const recorder = this.loadReplayRecorder(sessionId); const readHistory = async () => { - await this.streamThreadHistory(sessionId, thread, history); + const target = this.loadReplayTarget(sessionId); + await this.streamThreadHistory(sessionId, thread, history, recorder + ? {...target, connection: recorder.connection(target.connection), sink: recorder} + : target); if (sessionState.subagents instanceof StandardSubagentEventRouter) { await sessionState.subagents.announceLiveChildrenForReplay(); } }; const v2 = AcpV2Connection.of(this.connection); if (v2) await v2.replay.withHistory(sessionId, readHistory); - else await readHistory(); + else { + await readHistory(); + await this.sendLoadReplayEnd(sessionId, recorder); + } } finally { // Only after replay is fully streamed does the baseline tracker start dispatching // live events, so a live goal-turn frame can never race ahead of history. @@ -2070,6 +2127,137 @@ export class CodexAcpServer { return {sessionId, modelState, modeState}; } + /** + * For a v1 client that declared both `loadReplayEnd` and `historyTail`, the recorder that + * counts the updates of a load replay for the cursor of its load replay end. + */ + private loadReplayRecorder(sessionId: string): HistoryRecorder | undefined { + if (this.protocolVersion !== 1 + || !clientSupportsAirCapability(this.clientCapabilities, AIR_LOAD_REPLAY_END_KEY) + || !clientSupportsAirCapability(this.clientCapabilities, AIR_HISTORY_TAIL_KEY)) { + return undefined; + } + return new HistoryRecorder(sessionId); + } + + /** + * For a v1 client that declared `loadReplayEnd`, the update after the whole history replay + * of a load. It carries the cursor of the replayed history when `recorder` counted it. A + * replay that failed to read a subagent lacks its history, so it gives no cursor: the next + * tail reads the whole history. It has no `title`: a `null` there would clear the title. + */ + private async sendLoadReplayEnd(sessionId: string, recorder: HistoryRecorder | undefined): Promise { + if (!clientSupportsAirCapability(this.clientCapabilities, AIR_LOAD_REPLAY_END_KEY)) return; + const cursor = recorder && recorder.failedChildren.size === 0 ? recorder.cursor() : undefined; + await new ACPSessionConnection(this.connection, sessionId).update({ + sessionUpdate: "session_info_update", + _meta: withAirMeta( + cursor ? withAirMeta(undefined, AIR_HISTORY_CURSOR_KEY, cursor) : undefined, + AIR_LOAD_REPLAY_END_KEY, + true, + ), + }); + } + + /** + * `_session/history_tail`: the updates that the replay of a `session/load` gives after the + * cursor of the request, see `HistoryTails`. It reads the thread with the read-only Codex + * API, sends no `session/update`, and opens no session. A thread that another Codex process + * holds reads the same way. + * + * Codex tells no holder of the writer lock without a `thread/resume`, so the answer has no + * `held`. The refusal of a `session/load` of such a thread carries `data.held`. + */ + async historyTail(request: HistoryTailRequest, signal?: AbortSignal): Promise { + const params = parseHistoryTailParams(request); + const {sessionId, cwd} = params; + if (this.protocolVersion !== 1) throw RequestError.methodNotFound(HISTORY_TAIL_METHOD); + if (this.usesStandardSubagents()) { + throw RequestError.invalidRequest(undefined, "The history tail does not support standard subagent sessions"); + } + if (this.providerUpdate !== null) await this.waitForProviderUpdate(); + const appServer = this.ensureAppServer(); + if (appServer) await appServer; + const startedAt = performance.now(); + const client = this.codexAcpClient; + try { + const answer = await this.runWithProcessCheck(() => this.historyTails.read(params, { + legacy: async () => { + const {thread} = await withHistoryTimeout(client.appServerClient.threadRead({threadId: sessionId}), "thread/read", sessionId); + if (thread.id !== sessionId) throw sessionNotFoundRequestError(sessionId); + return thread.historyMode === "legacy"; + }, + head: (threadId, legacy) => client.readSessionHead(threadId, legacy), + replay: recorder => this.replayDetachedHistory(sessionId, cwd, recorder), + }, signal)); + logger.log("History tail read", { + sessionId, + status: answer.status, + updates: answer.updates.length, + more: answer.status === "ok" && answer.more === true, + durationMs: Math.round(performance.now() - startedAt), + }); + return answer; + } catch (error) { + const refused = storedSessionError(sessionId, error, this.sessionIndex.enabled); + // A thread that Codex does not have is -32002. Each other failed read can pass on a later try. + if (refused instanceof RequestError) throw refused; + logger.error(`Failed to read the history tail of ${sessionId}`, error); + throw historyReadFailedError(sessionId, {}); + } + } + + /** Drops the kept replays of `_session/history_tail` when the connection closes. */ + disposeHistoryTails(): void { + this.historyTails.dispose(); + } + + /** + * Replays the stored history of `sessionId` as a `session/load` does, into `recorder`. The + * replay uses a detached state and its own delivery, so it changes no open session and + * sends nothing to the client. + */ + private async replayDetachedHistory(sessionId: string, cwd: string, recorder: HistoryRecorder): Promise { + const {thread, history} = await this.codexAcpClient.readSessionHistory(sessionId); + let models: {models: Model[]; currentModelId: string} | null = null; + if (this.supportsNativeSubagents() && this.isSessionConfigEnabled()) { + try { + models = await withHistoryTimeout(this.codexAcpClient.readSessionModels(thread), "model/list", sessionId); + } catch (error) { + // The model reports of the subagents need the models, so the tail fails as for a failed read of a subagent. + logger.error(`Failed to read the models for the history tail of ${sessionId}`, error); + throw historyReadFailedError(sessionId, {models: true}); + } + } + const delivery = new AcpClientDelivery(recorder.captureClient()); + delivery.reports.compareMeta = this.clientDelivery.reports.compareMeta; + const connection = recorder.connection(delivery.asClientConnection()); + const state: HistoryReplayState = { + sessionId, + cwd, + clientCapabilities: this.capabilities, + rewindable: isRewindableThread(thread), + hasTurn: false, + sessionTitle: null, + sessionTitleSource: "unset", + subagents: new CodexSubagentEventRouter( + sessionId, + this.supportsNativeSubagents(), + new ACPSessionConnection(connection, sessionId), + id => delivery.reports.releaseOpen(id), + () => this.replaySubagentModels(state), + ), + ...(models ? {availableModels: models.models, currentModelId: models.currentModelId} : {}), + }; + await this.streamThreadHistory(sessionId, thread, history, { + state, + connection, + entities: delivery.entities, + isOpen: () => true, + sink: recorder, + }); + } + async resumeSession(params: WithAcpMcpServers): Promise { return this.withSystemPromptUpdate(params, async () => this.recovery === null ? await this.resumeSessionOnce(params) @@ -3945,7 +4133,7 @@ export class CodexAcpServer { } /** The models of a root session, for the configuration of its native subagent sessions. */ - private subagentModels(sessionState: SessionState): SubagentModels | null { + private subagentModels(sessionState: Pick): SubagentModels | null { if (!this.isSessionConfigEnabled()) return null; let currentModel: string | null = null; try { @@ -4145,24 +4333,39 @@ export class CodexAcpServer { }; } + /** The target of the replay of a loaded session: its state, the client connection, and its generation. */ + private loadReplayTarget(sessionId: string): HistoryReplayTarget { + const generation = this.getSessionGeneration(sessionId); + return { + state: this.getSessionState(sessionId), + connection: this.connection, + entities: this.clientDelivery.entities, + isOpen: () => this.getSessionGeneration(sessionId) === generation, + }; + } + /** - * Sends the history of a loaded session one page of items at a time. The + * Sends the history of a session one page of items at a time. The * adapter keeps only the current page, not the whole history. + * + * A load replays into the state of the loaded session. `_session/history_tail` replays + * into a detached `target`, which the standard subagent form does not support. */ private async streamThreadHistory( sessionId: string, thread: Thread, history: AsyncIterable, + target: HistoryReplayTarget = this.loadReplayTarget(sessionId), ): Promise { - const session = new ACPSessionConnection(this.connection, sessionId); - const sessionState = this.getSessionState(sessionId); - const generation = this.getSessionGeneration(sessionId); - const isOpen = () => this.getSessionGeneration(sessionId) === generation; + const session = new ACPSessionConnection(target.connection, sessionId); + const sessionState = target.state; + const {isOpen, sink} = target; + sink?.beginThread(thread.historyMode === "legacy"); const pages = history[Symbol.asyncIterator](); const first = await pages.next(); const firstPage = first.done ? [] : first.value; // A replay rebuilds the entities that the client holds, so a live cursor anchors to those of this replay. - this.clientDelivery.entities.forget(sessionId); + target.entities.forget(sessionId); if (firstPage.length > 0) sessionState.hasTurn = true; const cursors = new ReplayCursors(); // The first user message of the first page names the session. @@ -4175,17 +4378,16 @@ export class CodexAcpServer { isOpen, ); if (this.usesStandardSubagents()) { - await this.streamStandardHistory(sessionId, standardHistoryItems(itemPages), sessionState, isOpen, cursors); + await this.streamStandardHistory(sessionId, standardHistoryItems(itemPages), this.getSessionState(sessionId), isOpen, cursors); return; } if (this.supportsNativeSubagents()) { await this.streamNativeThreadHistory( sessionId, itemPages, - sessionState, + target, new Set([sessionId]), new Set(), - isOpen, cursors, ); return; @@ -4194,30 +4396,40 @@ export class CodexAcpServer { for await (const items of itemPages) { for (const item of items) { if (!isOpen()) throw new SessionClosedDuringLoadError(); - await this.replayHistoryItem(item, sessionState, session, replayedEntities, cursors); + sink?.beginItem(sessionId, item); + await this.replayHistoryItem(item, sessionState, session, replayedEntities, cursors, target.entities); } } } + /** The models that the subagent model reports of a replay offer, or null when the state has none. */ + private replaySubagentModels(state: HistoryReplayState): SubagentModels | null { + if (!state.availableModels || state.currentModelId === undefined) return null; + return this.subagentModels({availableModels: state.availableModels, currentModelId: state.currentModelId}); + } + private async streamNativeThreadHistory( sessionId: string, itemPages: AsyncIterable, - sessionState: SessionState, + target: HistoryReplayTarget, ancestry: Set, unreadableChildren: Set, - isOpen: () => boolean, cursors: ReplayCursors, ): Promise { - const session = new ACPSessionConnection(this.connection, sessionId); + const {state: sessionState, isOpen, sink} = target; + const session = new ACPSessionConnection(target.connection, sessionId); const announced = new Map(); + // The ended children with an interaction that started no child turn yet. + const queuedInteractions = new Set(); // v1 load includes recorded model changes. v2 replay contains conversation history, not past settings. const reportModel = async (childSessionId: string, model: string | undefined) => { - if (session.protocolVersion === 1) await reportSubagentModel(session, childSessionId, this.subagentModels(sessionState), model); + if (session.protocolVersion === 1) await reportSubagentModel(session, childSessionId, this.replaySubagentModels(sessionState), model); }; const replayedEntities: ReplayedEntities = new Map(); for await (const items of itemPages) { for (const item of items) { if (!isOpen()) throw new SessionClosedDuringLoadError(); + sink?.beginItem(sessionId, item); if (item.type === "subAgentActivity") { const activityKind = item.kind as string; if (activityKind === "started" || activityKind === "interacted") { @@ -4238,11 +4450,18 @@ export class CodexAcpServer { } catch (error) { unreadableChildren.add(item.agentThreadId); + sink?.childFailed(item.agentThreadId); logger.error(`Failed to read subagent history ${item.agentThreadId}`, error); } } // An interaction that started no child turn is not a new generation. - if (activityKind === "interacted" && !childItems) continue; + if (activityKind === "interacted" && !childItems) { + if (!ancestry.has(item.agentThreadId) && !unreadableChildren.has(item.agentThreadId)) { + queuedInteractions.add(item.agentThreadId); + } + continue; + } + queuedInteractions.delete(item.agentThreadId); const name = nameFromAgentPath(item.agentPath, `Agent ${item.agentThreadId.slice(-8)}`); const model = item.model || previous?.model; await session.update({ @@ -4265,10 +4484,9 @@ export class CodexAcpServer { await this.streamNativeThreadHistory( childSessionId, withCommandIds(untilSessionClose(childItems, isOpen), commandIds), - sessionState, + target, new Set([...ancestry, item.agentThreadId]), unreadableChildren, - isOpen, cursors, ); } @@ -4276,16 +4494,20 @@ export class CodexAcpServer { if (error instanceof SessionClosedDuringLoadError) throw error; // The child pages are read lazily. A child that fails midway keeps what it sent. unreadableChildren.add(item.agentThreadId); + sink?.childFailed(item.agentThreadId); logger.error(`Failed to read subagent history ${item.agentThreadId}`, error); } - try { - await sessionState.asyncTasks.recover( - item.agentThreadId, - childSessionId, - commandIds, - ); - } catch (error) { - logger.error(`Failed to restore background terminals for ${item.agentThreadId}`, error); + // A detached replay has no background terminals to restore. + if (sessionState.asyncTasks) { + try { + await sessionState.asyncTasks.recover( + item.agentThreadId, + childSessionId, + commandIds, + ); + } catch (error) { + logger.error(`Failed to restore background terminals for ${item.agentThreadId}`, error); + } } } } @@ -4322,11 +4544,18 @@ export class CodexAcpServer { } // The activity items above replay the lifecycle of a spawn. A control call is a tool call, as in the live session. if (item.type === "collabAgentToolCall" && item.tool === "spawnAgent") continue; - await this.replayHistoryItem(item, sessionState, session, replayedEntities, cursors); + await this.replayHistoryItem(item, sessionState, session, replayedEntities, cursors, target.entities); } } - for (const child of announced.values()) { - if (child.terminal) continue; + // The states of the children that have not ended close the history of the root: the trailer of the replay. + if (sessionId === sessionState.sessionId) sink?.bodyEnded(); + for (const [threadId, child] of announced) { + if (child.terminal) { + // The turn of a queued interaction starts the next session of the child later, with no new item of the root. + if (sessionId === sessionState.sessionId && queuedInteractions.has(threadId)) sink?.watchChild(threadId, child.sessionId); + continue; + } + if (sessionId === sessionState.sessionId) sink?.watchChild(threadId, child.sessionId); await session.update({ sessionUpdate: "subagent_state_update", subagentSessionId: child.sessionId, @@ -4424,7 +4653,7 @@ export class CodexAcpServer { // Agent-owned input is a message between sessions, not an ordinary human message. if (item.type === "userMessage") { await router.reportIncomingMessage(threadId, item); continue; } } - await this.replayHistoryItem(item, state, session, replayedEntities, cursors); + await this.replayHistoryItem(item, state, session, replayedEntities, cursors, this.clientDelivery.entities); } } while (unresolved.length > 0) { @@ -4447,7 +4676,7 @@ export class CodexAcpServer { private async publishThreadHistoryTitle( session: ACPSessionConnection, - sessionState: SessionState, + sessionState: HistoryReplayState, thread: Thread, firstItems: ThreadItem[], ): Promise { @@ -4466,7 +4695,7 @@ export class CodexAcpServer { if (sessionState.titleGen?.isGenerating) return; const historyTitle = this.findFirstUserMessageTitle(firstItems) ?? normalizeSessionTitle(thread.preview); - await this.publishFallbackSessionTitle(sessionState, historyTitle); + await this.publishFallbackSessionTitle(sessionState, historyTitle, session); } private findFirstUserMessageTitle(items: ThreadItem[]): string | null { @@ -4517,13 +4746,13 @@ export class CodexAcpServer { } private async publishFallbackSessionTitle( - sessionState: SessionState, + sessionState: Pick, title: string | null, + session = new ACPSessionConnection(this.connection, sessionState.sessionId), ): Promise { if (sessionState.sessionTitleSource !== "unset" || !title) return; sessionState.sessionTitle = title; sessionState.sessionTitleSource = "fallback"; - const session = new ACPSessionConnection(this.connection, sessionState.sessionId); await session.update({ sessionUpdate: "session_info_update", title, @@ -4583,7 +4812,7 @@ export class CodexAcpServer { } /** The cursor as the client gets it: with `rewind` where `_session/rewind` can act. */ - private cursorForClient(cursor: CursorUpdate, sessionState: SessionState): CursorUpdate { + private cursorForClient(cursor: CursorUpdate, sessionState: Pick): CursorUpdate { return sessionState.rewindable && this.supportsSessionRewind() ? withRewindCapability(cursor) : cursor; } @@ -4600,24 +4829,25 @@ export class CodexAcpServer { /** Replays `item`, then the cursor before its turn if `item` is the first user message of the turn. */ private async replayHistoryItem( item: ThreadItem, - sessionState: SessionState, + sessionState: HistoryReplayState, session: ACPSessionConnection, replayedEntities: ReplayedEntities, cursors: ReplayCursors, + entities: LastReportedEntity, ): Promise { - const before = this.clientDelivery.entities.last(session.sessionId); + const before = entities.last(session.sessionId); const updates = await this.createHistoryUpdates(item, sessionState); for (const update of updates) { await session.replayUpdate(update, replayedEntities); } const cursor = cursors.cursorAfter(item, updates); if (cursor !== null && clientSupportsCursors(this.clientCapabilities)) { - this.clientDelivery.entities.recordCursor(session.sessionId, cursor.cursorId, before); + entities.recordCursor(session.sessionId, cursor.cursorId, before); await session.replayUpdate(this.cursorForClient(cursor, sessionState), replayedEntities); } } - private async createHistoryUpdates(item: ThreadItem, sessionState: SessionState): Promise { + private async createHistoryUpdates(item: ThreadItem, sessionState: HistoryReplayState): Promise { const renderer = new AcpToolCallRenderer(sessionState.clientCapabilities); switch (item.type) { case "userMessage": diff --git a/src/CodexAppServerClient.ts b/src/CodexAppServerClient.ts index 1bf0f6ff1..d0d9cf445 100644 --- a/src/CodexAppServerClient.ts +++ b/src/CodexAppServerClient.ts @@ -1578,7 +1578,7 @@ async function* historyPages( } /** The page, or an error when Codex does not answer within {@link HISTORY_PAGE_TIMEOUT_MS}. */ -async function withHistoryTimeout(page: Promise, method: string, threadId: string): Promise { +export async function withHistoryTimeout(page: Promise, method: string, threadId: string): Promise { let timer: ReturnType | undefined; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error( diff --git a/src/CodexThreadErrors.ts b/src/CodexThreadErrors.ts index 5cb1d01a8..4d1e22422 100644 --- a/src/CodexThreadErrors.ts +++ b/src/CodexThreadErrors.ts @@ -28,6 +28,20 @@ export function isMissingRolloutError(err: unknown): boolean { return errorText(err).includes("no rollout found for thread id"); } +/** + * Codex has no rollout of `threadId` yet: a thread with no first user message, or one that it + * does not have. Codex gives these as `invalid_request` with no reason, so the match names the + * thread in the texts of codex-rs `thread_processor.rs`. + */ +export function isNoRolloutOfThreadError(err: unknown, threadId: string): boolean { + const code = err !== null && typeof err === "object" && "code" in err ? (err as {code: unknown}).code : undefined; + if (code !== undefined && code !== -32600) return false; + const text = errorText(err); + return text.includes(`thread ${threadId} is not materialized yet`) + || text.includes(`no rollout found for thread id ${threadId}`) + || text.includes(`thread not found: ${threadId}`); +} + /** History paging rejects a live thread whose rollout has not been written yet. */ export function isThreadNotMaterializedError(err: unknown): boolean { return errorText(err).includes("not materialized"); @@ -117,10 +131,14 @@ export function isThreadActiveWriterError(err: unknown): boolean { * The ACP error for a thread that another Codex client has loaded. The * `reason` field is stable, so a client can recognise the case without * parsing the message. + * + * `held` has the form of the `held` object of the Claude adapter, so a client + * can follow the session read-only with `_session/history_tail`. Codex does + * not tell which process holds the thread, so the object is empty. */ export function threadActiveWriterRequestError(threadId: string, err: unknown): RequestError { return RequestError.invalidRequest( - {reason: "thread_active_writer", threadId, details: errorText(err)}, + {reason: "thread_active_writer", threadId, held: {}, details: errorText(err)}, "This Codex session is in use by another Codex client (the Codex app, the CLI or an IDE extension). Close the session there or quit that client, then try again.", ); } diff --git a/src/HistoryTail.ts b/src/HistoryTail.ts new file mode 100644 index 000000000..f8ee41e67 --- /dev/null +++ b/src/HistoryTail.ts @@ -0,0 +1,741 @@ +import * as acp from "@agentclientprotocol/sdk/unstable"; +import {createHash, randomBytes} from "node:crypto"; +import {z} from "zod"; +import type {AcpClientConnection} from "./ACPSessionConnection"; +import type {AcpSessionNotification} from "./AcpSessionExtensions"; +import {logger} from "./Logger"; + +/** + * `_session/history_tail`: the updates of the history of a stored session after a cursor. + * It reads the thread with `thread/read`, `thread/items/list` and `thread/turns/list`. It + * calls no `thread/resume`, so it takes no writer lock and opens no session. See + * `docs/air-extensions.md#history-tail`. + */ +export const HISTORY_TAIL_METHOD = "_session/history_tail"; + +/** The version of {@link HistoryCursor}. A cursor of another version answers `rewritten`. */ +const CURSOR_VERSION = 1; + +/** + * The `limit` of a request that sets none. One message with the updates of a big session + * blocks the client while it parses. + */ +export const DEFAULT_HISTORY_TAIL_LIMIT = 2000; + +/** How many recorded replays {@link HistoryTails} keeps at one time. */ +const KEPT_REPLAYS = 4; + +/** How many replays of {@link HistoryTails} run at one time. */ +const MAX_RUNNING_REPLAYS = 2; + +/** How long {@link HistoryTails} keeps a recorded replay that no read uses. */ +const KEPT_REPLAY_IDLE_MS = 5 * 60 * 1000; + +/** + * Where a client is in the history of one stored thread. The client keeps it as it is and + * sends it back. + * + * `s` holds, for each session of the replay (the root session and each child session of a + * subagent), the count of its updates up to the last one that the client has, and the name + * of the last thread item of that session that the client has. `#0` names the updates + * before the first item, such as the title. A legacy thread names an item by its id and a + * rolling hash of the items of the session up to it. "" names a child session whose spawn + * the client has but none of its updates. + * + * `end` is the {@link itemIdentity} of the newest item of the root thread, and `turn` is the + * id and the end time of its newest turn, at the read of the whole history. `c` holds, for + * each subagent thread that had not ended then or that waits for the turn of a queued + * interaction, the {@link itemIdentity} of its last replayed item. `turnOpen` is the + * {@link HistoryTailResponse} `turnOpen` of that read. A load replay end has no `end` and no + * `turn`, so the first tail after a load reads the whole history. + * + * `p` names the recorded replay of an answer with `more`, so the next page comes from the + * same replay. `q` holds where that page ended in the replay and the positions of the first + * page of the read: the next page goes on there, and gives what an answer with no `limit` + * gives after it. A page whose replay is no longer kept answers `rewritten`. + */ +export type HistoryCursor = { + v: typeof CURSOR_VERSION; + s: Record; + end?: string; + turn?: string; + c?: Record; + turnOpen?: boolean; + p?: string; + q?: {at: number; from: Record}; +}; + +export type HistoryTailRequest = { + sessionId: string; + /** The working directory that the tool calls of the history render against. */ + cwd: string; + /** No cursor reads the whole history. */ + cursor?: unknown; + /** The most updates of one answer, rounded up to the end of an item. */ + limit?: number | undefined; + _meta?: Record | null | undefined; +}; + +export type HistoryTailResponse = + | {status: "unchanged"; cursor: HistoryCursor; turnOpen: boolean; updates: []} + | {status: "rewritten"; updates: []} + | { + status: "ok"; + cursor: HistoryCursor; + updates: AcpSessionNotification[]; + /** More updates follow: ask again with `cursor`. */ + more?: true; + /** The newest turn of the root thread has no end time. Only in the last answer of a read. */ + turnOpen?: boolean; + }; + +export const historyTailParamsParser = z.object({ + sessionId: z.string().trim().min(1), + cwd: z.string().min(1), + cursor: z.unknown().optional(), + limit: z.number().int().positive().optional(), + _meta: z.record(z.string(), z.unknown()).nullable().optional(), +}).passthrough(); + +/** The checked params of a request, or `invalid_params`. */ +export function parseHistoryTailParams(params: unknown): HistoryTailRequest { + const parsed = historyTailParamsParser.safeParse(params); + if (!parsed.success) { + throw acp.RequestError.invalidParams(undefined, parsed.error.issues[0]?.message ?? "Invalid history tail parameters"); + } + return parsed.data as HistoryTailRequest; +} + +/** + * Receives one history replay of `streamThreadHistory`. The replay tells the item that each + * update comes from, the subagent threads whose change the signature watches, the subagent + * threads that it failed to read, and the end of the body: what comes after it is the + * trailer, the states of the open subagents. + */ +export interface ReplaySink { + /** + * Starts a replay of a thread. A legacy thread names its items `item-` and counts them + * again after a rollback, so the recorder then names an item by its id and a hash of its + * content. + */ + beginThread(legacy: boolean): void; + beginItem(sessionId: string, item: {id: string}): void; + /** + * Watches the subagent thread `threadId`, whose last session is `sessionId`: a subagent + * that has not ended, or an ended subagent with an interaction that started no turn yet. + */ + watchChild(threadId: string, sessionId: string): void; + /** The replay failed to read the subagent thread `threadId`, so the replay lacks items. */ + childFailed(threadId: string): void; + bodyEnded(): void; + /** The connection that the replay sends its updates to. It counts each update, then gives it to `inner`. */ + connection(inner: AcpClientConnection): AcpClientConnection; +} + +type RecordedUpdate = { + session: string; + /** The cursor name of the item of the update. */ + item: string; + /** The count of the updates of the session up to this one. */ + count: number; + /** The index of the record in the records of its session. */ + index: number; + /** The index in the body of the last record of the same item of the same session. */ + itemEnd: number; + /** What the client gets of the update: null when the delivery drops it. */ + notification: AcpSessionNotification | null; + /** The start of an item. It is no update: it gives an item with no update a place in its session. */ + marker?: true; + /** The child session of a `subagent_spawned` update. */ + spawns?: string; + /** The child session of a `subagent_state_update` update. */ + stateOf?: string; +}; + +/** What one replay sent, as {@link HistoryRecorder} recorded it. */ +export type RecordedHistory = { + /** The body records of all sessions, in replay order. */ + body: RecordedUpdate[]; + /** The body records of each session. */ + sessions: Map; + /** The `subagent_spawned` record of each child session. */ + spawns: Map; + trailer: RecordedUpdate[]; + end: string; + turn: string; + children: Record; + turnOpen: boolean; +}; + +/** The newest item and turn of a thread, see `CodexAcpClient.readSessionHead`. */ +export type ThreadHead = {item: string; turn: string; turnOpen: boolean}; + +/** + * The head of a subagent thread whose read failed. It equals no head of a signature, also not + * the "" of a thread with no rollout, so the read replays and reports the failure. + */ +const NO_HEAD: ThreadHead = {item: "\u0000unreadable", turn: "\u0000unreadable", turnOpen: false}; + +/** The cursor name of a child session whose spawn the client has, but none of its updates. */ +const SPAWNED_ONLY = ""; + +/** + * The name of a thread item in the signature of a cursor, see {@link HistoryCursor}. A legacy + * thread names an item by its id and a hash of its content, because it counts the ids again + * after a rollback and appends to a reasoning item in place. + */ +export function itemIdentity(item: {id: string}, legacy: boolean): string { + return legacy ? `${item.id}:${contentHash(JSON.stringify(item))}` : item.id; +} + +/** + * A {@link ReplaySink} that counts the updates of each session by item. A load uses it to + * make the cursor of its load replay end. With `keep`, it also keeps each update and what + * the delivery made of it, for a tail. + */ +export class HistoryRecorder implements ReplaySink { + private legacy = false; + private inBody = true; + private pending: RecordedUpdate | null = null; + private readonly positions = new Map(); + /** + * The cursor name of the current item of each session. An update belongs to the current + * item of its own session. A legacy thread adds a hash of the item and of every item + * before it in the session, so a change before the item gives another name. + */ + private readonly currentItems = new Map(); + /** The rolling hash of the items of each session of a legacy thread. */ + private readonly chains = new Map(); + /** The {@link itemIdentity} of the last replayed item of each session, for the signature. */ + private readonly lastItems = new Map(); + private readonly watchedChildren = new Map(); + /** The subagent threads that the replay failed to read. */ + readonly failedChildren = new Set(); + private readonly body: RecordedUpdate[] = []; + private readonly sessions = new Map(); + private readonly spawns = new Map(); + /** The child sessions of the `subagent_spawned` updates, in replay order. */ + private readonly spawnedSessions = new Set(); + private readonly trailer: RecordedUpdate[] = []; + + constructor(private readonly rootSessionId: string, private readonly keep = false) {} + + beginThread(legacy: boolean): void { + this.legacy = legacy; + } + + beginItem(sessionId: string, item: {id: string}): void { + let name = item.id; + if (this.legacy) { + const chain = contentHash(`${this.chains.get(sessionId) ?? ""}\n${JSON.stringify(item)}`); + this.chains.set(sessionId, chain); + name = `${item.id}:${chain}`; + } + this.currentItems.set(sessionId, name); + this.lastItems.set(sessionId, itemIdentity(item, this.legacy)); + if (this.keep && this.inBody) { + this.record({session: sessionId, item: name, count: this.positions.get(sessionId)?.[0] ?? 0, marker: true}); + } + } + + watchChild(threadId: string, sessionId: string): void { + this.watchedChildren.set(threadId, sessionId); + } + + childFailed(threadId: string): void { + this.failedChildren.add(threadId); + } + + bodyEnded(): void { + this.inBody = false; + } + + connection(inner: AcpClientConnection): AcpClientConnection { + return { + notify: async (method: string, params?: unknown) => { + if (method !== acp.methods.client.session.update) return await inner.notify(method as never, params as never); + this.pending = this.count(params as AcpSessionNotification); + try { + await inner.notify(method, params as never); + } finally { + this.pending = null; + } + }, + request: (method: string, params?: unknown, options?: acp.SendRequestOptions) => + inner.request(method as never, params as never, options), + } as AcpClientConnection; + } + + /** The client behind the delivery of a tail: it keeps what the delivery sends for the update that the replay sends now. */ + captureClient(): AcpClientConnection { + return { + notify: async (method: string, params?: unknown) => { + if (method === acp.methods.client.session.update && this.pending) { + this.pending.notification = params as AcpSessionNotification; + } + }, + request: async (method: string) => { + throw acp.RequestError.internalError(undefined, `A history replay sends no '${method}' request`); + }, + } as AcpClientConnection; + } + + private record(fields: Pick): RecordedUpdate { + let records = this.sessions.get(fields.session); + if (!records) this.sessions.set(fields.session, (records = [])); + const recorded: RecordedUpdate = {...fields, index: records.length, itemEnd: this.body.length, notification: null}; + if (recorded.marker === undefined) delete recorded.marker; + if (recorded.spawns === undefined) delete recorded.spawns; + if (recorded.stateOf === undefined) delete recorded.stateOf; + records.push(recorded); + this.body.push(recorded); + return recorded; + } + + private count(notification: AcpSessionNotification): RecordedUpdate { + const session = notification.sessionId; + const item = this.currentItems.get(session) ?? "#0"; + const update = notification.update as {sessionUpdate: string; subagentSessionId?: string}; + const stateOf = update.sessionUpdate === "subagent_state_update" ? update.subagentSessionId : undefined; + if (!this.inBody) { + const recorded: RecordedUpdate = { + session, item, count: 0, index: -1, itemEnd: -1, notification: null, ...(stateOf !== undefined ? {stateOf} : {}), + }; + if (this.keep) this.trailer.push(recorded); + return recorded; + } + const count = (this.positions.get(session)?.[0] ?? 0) + 1; + this.positions.set(session, [count, item]); + const spawns = update.sessionUpdate === "subagent_spawned" ? update.subagentSessionId : undefined; + if (spawns !== undefined) this.spawnedSessions.add(spawns); + if (!this.keep) return {session, item, count, index: -1, itemEnd: -1, notification: null}; + const recorded = this.record({ + session, item, count, ...(spawns !== undefined ? {spawns} : {}), ...(stateOf !== undefined ? {stateOf} : {}), + }); + if (spawns !== undefined && !this.spawns.has(spawns)) this.spawns.set(spawns, recorded); + return recorded; + } + + /** + * The cursor of the whole replay, for the load replay end. A child session with a spawn + * and no update has the name {@link SPAWNED_ONLY}, so a tail does not give its spawn again. + */ + cursor(): HistoryCursor { + const positions: HistoryCursor["s"] = Object.fromEntries(this.positions); + for (const session of this.spawnedSessions) positions[session] ??= [0, SPAWNED_ONLY]; + return {v: CURSOR_VERSION, s: positions}; + } + + /** The kept replay. `head` is the newest turn of the root thread, read before the replay. */ + recorded(head: ThreadHead): RecordedHistory { + const ends = new Map(); + for (let index = this.body.length - 1; index >= 0; index--) { + const record = this.body[index]!; + const key = `${record.session}\n${record.item}`; + if (!ends.has(key)) ends.set(key, index); + record.itemEnd = ends.get(key)!; + } + const children: Record = {}; + for (const [threadId, sessionId] of this.watchedChildren) children[threadId] = this.lastItems.get(sessionId) ?? ""; + return { + body: this.body, + sessions: this.sessions, + spawns: this.spawns, + trailer: this.trailer, + end: this.lastItems.get(this.rootSessionId) ?? "", + turn: head.turn, + children, + turnOpen: head.turnOpen, + }; + } +} + +/** A short hash of `text`. */ +function contentHash(text: string): string { + return createHash("sha256").update(text).digest("base64url").slice(0, 12); +} + +/** + * One answer of `_session/history_tail` from the recorded replay of the whole history. + * + * The cursor names one item for each session. The answer has the updates of each session + * after the last record of that item, in replay order, as a load sends them. A cursor whose + * item the new history lacks in its session answers `rewritten`, as after `thread/revert`. So + * does a cursor of another version. The client then reads again with no cursor. + * + * Each session that the cursor did not name starts with its `subagent_spawned` update, also + * when the spawn comes before the cursor of its parent. A queued interaction with an ended + * subagent starts its next session in this way. The spawn also comes before a state of such a + * session, and the answer gives each state of it that comes before the cursor of its parent, + * as the `disconnected` state that a subagent gives its own subagent. The new cursor names + * each session whose spawn the answer gave. + * + * With `limit`, an answer ends where every session ended an item. The trailer, the signature + * and `turnOpen` come only with the last answer. + */ +export function historyTailAnswer( + history: RecordedHistory, + cursor: unknown, + limit: number | undefined, + samePage = false, +): HistoryTailResponse { + // The next page of a read goes on in the same replay with the positions of the first page. + // A page goes on only in the replay of its read: another replay gives other indexes. + const page = cursorPage(cursor); + if (page && !samePage) return {status: "rewritten", updates: []}; + const requested = page ? page.from : cursor === undefined || cursor === null ? {} : cursorPositions(cursor); + if (!requested) return {status: "rewritten", updates: []}; + const pageStart = page?.at ?? 0; + // The index of the first record of each session that the client lacks. + const starts = new Map(); + for (const [session, position] of Object.entries(requested)) { + if (position[1] === SPAWNED_ONLY) { + starts.set(session, 0); + continue; + } + const recorded = history.sessions.get(session) ?? []; + let last = recorded.length - 1; + while (last >= 0 && recorded[last]!.item !== position[1]) last--; + if (last < 0) return {status: "rewritten", updates: []}; + starts.set(session, last + 1); + } + const positions: HistoryCursor["s"] = {...requested}; + // The sessions that the client has the spawn of. + const known = new Set(Object.keys(requested)); + const spawned: string[] = []; + const markSpawned = () => { + for (const session of spawned) positions[session] ??= [0, SPAWNED_ONLY]; + }; + const updates: AcpSessionNotification[] = []; + // Gives the spawn of `session` first when the client does not have it. An earlier page gave the spawns before `pageStart`. + const announce = (session: string, emit: boolean) => { + if (known.has(session)) return; + known.add(session); + spawned.push(session); + const spawn = history.spawns.get(session)?.notification; + if (spawn && emit) updates.push(spawn); + }; + let count = 0; + // The end of the items that this answer started: a page can end only after it. + let itemsEnd = -1; + for (let index = 0; index < history.body.length; index++) { + const record = history.body[index]!; + const after = record.index >= (starts.get(record.session) ?? 0); + // A state of a session that the cursor does not name comes also from before the cursor of its parent. + if (!after && (record.stateOf === undefined || record.stateOf in requested)) continue; + const emit = index >= pageStart; + if (emit && limit !== undefined && count >= limit && itemsEnd < index) { + markSpawned(); + return {status: "ok", cursor: {v: CURSOR_VERSION, s: positions, q: {at: index, from: requested}}, updates, more: true}; + } + itemsEnd = Math.max(itemsEnd, record.itemEnd); + announce(record.session, emit); + if (record.stateOf !== undefined) announce(record.stateOf, emit); + if (after) positions[record.session] = [record.count, record.item]; + if (record.marker) continue; + if (emit && record.notification) updates.push(record.notification); + if (record.spawns !== undefined && !known.has(record.spawns)) { + known.add(record.spawns); + spawned.push(record.spawns); + } + if (emit) count++; + } + for (const record of history.trailer) { + if (record.stateOf !== undefined) announce(record.stateOf, true); + if (record.notification) updates.push(record.notification); + } + markSpawned(); + return { + status: "ok", + cursor: { + v: CURSOR_VERSION, + s: positions, + end: history.end, + turn: history.turn, + ...(Object.keys(history.children).length > 0 ? {c: history.children} : {}), + turnOpen: history.turnOpen, + }, + updates, + turnOpen: history.turnOpen, + }; +} + +/** + * The error of a tail whose replay failed to read a subagent thread or the models: `-32603` + * with `data.retryable` `true`. The client keeps its cursor and asks again later. + */ +export function historyReadFailedError(sessionId: string, failed: {threadIds?: string[]; models?: true}): acp.RequestError { + return acp.RequestError.internalError( + {reason: "history_read_failed", retryable: true, sessionId, threadIds: failed.threadIds ?? [], ...(failed.models ? {models: true} : {})}, + "The history tail failed to read the history. Ask again later.", + ); +} + +/** The positions of a cursor that a client sent back, or undefined when it is not a cursor of this version. */ +function cursorPositions(cursor: unknown): HistoryCursor["s"] | undefined { + if (!cursor || typeof cursor !== "object" || Array.isArray(cursor)) return undefined; + const {v, s} = cursor as Partial; + if (v !== CURSOR_VERSION || !s || typeof s !== "object" || Array.isArray(s)) return undefined; + for (const position of Object.values(s)) { + if (!Array.isArray(position) || position.length !== 2 + || typeof position[0] !== "number" || typeof position[1] !== "string") { + return undefined; + } + } + return s; +} + +/** Where the page of a cursor ended, see {@link HistoryCursor} `q`, or undefined for a malformed one. */ +function cursorPage(cursor: unknown): {at: number; from: HistoryCursor["s"]} | undefined { + const {q} = (cursor ?? {}) as Partial; + if (!q || typeof q !== "object" || !Number.isInteger(q.at) || q.at < 0) return undefined; + const from = cursorPositions({v: CURSOR_VERSION, s: q.from}); + return from ? {at: q.at, from} : undefined; +} + +/** The signature of a cursor: what the root thread and its open subagent threads held at the read. */ +function cursorSignature(cursor: unknown): Pick | undefined { + if (!cursorPositions(cursor)) return undefined; + const {end, turn, c} = cursor as Partial; + if (typeof end !== "string" || typeof turn !== "string") return undefined; + if (c !== undefined && (!c || typeof c !== "object" || Array.isArray(c) + || Object.values(c).some(item => typeof item !== "string"))) { + return undefined; + } + return {end, turn, children: c ?? {}}; +} + +/** The thread that one `_session/history_tail` request reads. */ +export type HistorySource = { + /** Reads the metadata of the thread: whether it has a legacy history. Fails for an unknown thread. */ + legacy(): Promise; + /** The newest item and turn of `threadId`. */ + head(threadId: string, legacy: boolean): Promise; + /** Runs the replay of a `session/load` of the thread into `recorder`, with no session. */ + replay(recorder: HistoryRecorder): Promise; +}; + +/** + * The `_session/history_tail` reads of one connection. + * + * A cursor whose signature still holds answers `unchanged` with one small read of the + * newest item and turn of the root thread, and of the newest item of each subagent in `c`. + * A subagent whose read fails has the head of no thread. Otherwise the read replays the whole + * history into a recorder and cuts it after the cursor. A replay that fails to read a subagent + * fails the read with {@link historyReadFailedError}, and it is not kept. + * + * Each read keeps its recorded replay. The cursor of a page with `more` names it (`p`), so + * the next pages do not replay the whole history again, also when the thread changed since. + * A read after a cursor with no `p` uses the kept replay when its signature still holds. Only + * a replay after the start of the read answers `rewritten`, so a kept replay that lacks the + * item of the cursor gives way to a new replay. A read with no cursor always replays. It keeps one + * replay for each session and working directory, {@link KEPT_REPLAYS} at most, and drops one + * that no read uses for {@link KEPT_REPLAY_IDLE_MS}. It drops a replay in the middle of a paged + * read only after the others. A replay that ends after its reads were + * cancelled is kept too, but none after {@link dispose}. + */ +export class HistoryTails { + /** The kept replays, oldest first. `paging` tells that the last answer from the replay had `more`. */ + private readonly kept = new Map; paging: boolean}>(); + private readonly running = new Map(); + private readonly waitingForSlot: Array<() => void> = []; + private runningReplays = 0; + private disposed = false; + /** A counter that orders the start of each read and the head read of each replay. */ + private ticks = 0; + + /** @param signal the cancellation of the request: the read then stops to wait for a replay. */ + async read(params: HistoryTailRequest, source: HistorySource, signal?: AbortSignal): Promise { + const startedAt = ++this.ticks; + const legacy = await source.legacy(); + const heads = new Map>(); + const head = (threadId: string): Promise => { + let read = heads.get(threadId); + if (!read) { + read = source.head(threadId, legacy); + // A failed read of a subagent gives the head of no thread: a changed head replays, and the replay reports the failure. + if (threadId !== params.sessionId) { + read = read.catch(error => { + logger.error(`Failed to read the newest item of subagent ${threadId}`, error); + return NO_HEAD; + }); + } + heads.set(threadId, read); + } + return read; + }; + const holds = async (signature: Pick): Promise => { + const root = await head(params.sessionId); + if (root.item !== signature.end || root.turn !== signature.turn) return false; + for (const [threadId, item] of Object.entries(signature.children)) { + if ((await head(threadId)).item !== item) return false; + } + return true; + }; + // A null cursor reads the whole history, as no cursor does. + const cursor = (params.cursor ?? undefined) as Partial | undefined; + const signature = cursorSignature(cursor); + if (signature && await holds(signature)) { + // The turn can end with no end time and no new item, so `turnOpen` comes from the head of now. + const {turnOpen} = await head(params.sessionId); + return {status: "unchanged", cursor: {...cursor as HistoryCursor, turnOpen}, turnOpen, updates: []}; + } + const key = JSON.stringify([params.sessionId, params.cwd]); + const fresh = () => this.sharedReplay(key, params.sessionId, () => source.head(params.sessionId, legacy), source, signal, startedAt); + const limit = params.limit ?? DEFAULT_HISTORY_TAIL_LIMIT; + const kept = this.kept.get(key); + // A page goes on in the replay of its read. A read after a cursor uses the kept replay while its signature holds. + // A read with no cursor replays. + let replay: KeptReplay | undefined; + const samePage = kept !== undefined && typeof cursor?.p === "string" && cursor.p === kept.id; + // A page whose replay is gone cannot go on in another replay. + if (!samePage && cursorPage(cursor)) return {status: "rewritten", updates: []}; + if (kept && (samePage || (cursor !== undefined && await holds(kept.history)))) replay = kept; + let answer: HistoryTailResponse; + if (replay) { + answer = historyTailAnswer(replay.history, cursor, limit, samePage); + // The kept replay can be older than the cursor. Only a replay after the start of the read answers `rewritten`. + if (answer.status === "rewritten" && cursorPositions(cursor)) { + replay = await fresh(); + answer = historyTailAnswer(replay.history, cursor, limit); + } else if (answer.status === "ok" && !answer.more) { + // The kept replay read the head earlier. The turn can end since with no end time and no new item. + const {turnOpen} = await head(params.sessionId); + answer = {...answer, turnOpen, cursor: {...answer.cursor, turnOpen}}; + } + } else { + replay = await fresh(); + answer = historyTailAnswer(replay.history, cursor, limit); + } + this.keep(key, replay.id, replay.history); + if (answer.status !== "ok" || !answer.more) return answer; + const paged = this.kept.get(key); + if (paged?.id === replay.id) paged.paging = true; + return {...answer, cursor: {...answer.cursor, p: replay.id}}; + } + + /** + * The replay of the session and working directory of `key`. Reads that overlap share one + * replay. At most {@link MAX_RUNNING_REPLAYS} replays run at one time, and the others wait. + * A cancelled read stops to wait. A waiting replay that no read waits for any more does not + * start. A replay that ends is kept, also when no read waits for it any more. + * + * A read joins only a replay that reads the head after the start of the read, so the replay + * is not older than the cursor of the read. + * + * @param rootHead reads the head of the root thread again, so a replay that waited does not use an old head. + * @param startedAt the {@link ticks} at the start of the read. + */ + private async sharedReplay( + key: string, + rootSessionId: string, + rootHead: () => Promise, + source: HistorySource, + signal: AbortSignal | undefined, + startedAt: number, + ): Promise { + if (signal?.aborted) throw acp.RequestError.requestCancelled(undefined, "The history tail was cancelled"); + let running = this.running.get(key); + if (running?.headAt !== undefined && running.headAt < startedAt) running = undefined; + if (!running) { + const job: RunningReplay = {waiting: 0, result: Promise.resolve(null as unknown as KeptReplay)}; + job.result = (async () => { + await this.acquireSlot(); + try { + if (job.waiting === 0 || this.disposed) throw acp.RequestError.requestCancelled(undefined, "The history tail was cancelled"); + // The head comes before the replay: a turn that ends during the replay then gives another signature. + job.headAt = ++this.ticks; + const head = await rootHead(); + const recorder = new HistoryRecorder(rootSessionId, true); + await source.replay(recorder); + // A replay that lacks a subagent is not kept, so the next read replays again. + if (recorder.failedChildren.size > 0) throw historyReadFailedError(rootSessionId, {threadIds: [...recorder.failedChildren]}); + const replay: KeptReplay = {id: randomBytes(6).toString("base64url"), history: recorder.recorded(head)}; + this.keep(key, replay.id, replay.history); + return replay; + } finally { + this.releaseSlot(); + if (this.running.get(key) === job) this.running.delete(key); + } + })(); + // A read that stopped to wait does not see the failure of the shared replay. + job.result.catch(() => {}); + this.running.set(key, (running = job)); + } + const job = running; + job.waiting++; + try { + return await untilAborted(job.result, signal); + } finally { + job.waiting--; + } + } + + private async acquireSlot(): Promise { + if (this.runningReplays < MAX_RUNNING_REPLAYS) { + this.runningReplays++; + return; + } + // The release gives its slot to the first waiting replay, so no new replay takes it in between. + await new Promise(resolve => this.waitingForSlot.push(resolve)); + } + + private releaseSlot(): void { + const next = this.waitingForSlot.shift(); + if (next) next(); + else this.runningReplays--; + } + + /** Keeps the replay of `key` for {@link KEPT_REPLAY_IDLE_MS} from now. It keeps nothing after {@link dispose}. */ + private keep(key: string, id: string, history: RecordedHistory): void { + if (this.disposed) return; + const previous = this.kept.get(key); + if (previous) { + clearTimeout(previous.timer); + this.kept.delete(key); + } + // A replay in the middle of a paged read goes last, because its next page needs it. + for (const paging of [false, true]) { + for (const [oldKey, old] of this.kept) { + if (this.kept.size < KEPT_REPLAYS) break; + if (old.paging !== paging) continue; + clearTimeout(old.timer); + this.kept.delete(oldKey); + } + } + const timer = setTimeout(() => { + if (this.kept.get(key)?.id === id) this.kept.delete(key); + }, KEPT_REPLAY_IDLE_MS); + timer.unref?.(); + this.kept.set(key, {id, history, timer, paging: false}); + } + + /** Drops every kept replay. A waiting replay does not start any more. */ + dispose(): void { + this.disposed = true; + for (const {timer} of this.kept.values()) clearTimeout(timer); + this.kept.clear(); + } +} + +type KeptReplay = {id: string; history: RecordedHistory}; + +/** A replay that runs or waits for a slot, and the count of the reads that wait for it. */ +type RunningReplay = { + waiting: number; + result: Promise; + /** The {@link HistoryTails} ticks when the replay read the head of the root thread. */ + headAt?: number; +}; + +/** `promise`, or a cancellation when `signal` aborts first. */ +function untilAborted(promise: Promise, signal: AbortSignal | undefined): Promise { + if (!signal) return promise; + const cancelled = () => acp.RequestError.requestCancelled(undefined, "The history tail was cancelled"); + if (signal.aborted) return Promise.reject(cancelled()); + return new Promise((resolve, reject) => { + const abort = () => reject(cancelled()); + signal.addEventListener("abort", abort, {once: true}); + promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)); + }); +} diff --git a/src/__tests__/CodexACPAgent/data/session-index-capabilities.json b/src/__tests__/CodexACPAgent/data/session-index-capabilities.json index 7489b9000..b1b2bf472 100644 --- a/src/__tests__/CodexACPAgent/data/session-index-capabilities.json +++ b/src/__tests__/CodexACPAgent/data/session-index-capabilities.json @@ -10,6 +10,7 @@ "rawInputRendering", "planContentDelta", "codexHooks", + "historyTail", "sessionIndex", "sessionBatchGet", "sessionArchive", @@ -27,7 +28,8 @@ "recommendedValue", "rawInputRendering", "planContentDelta", - "codexHooks" + "codexHooks", + "historyTail" ], "plain": null } diff --git a/src/__tests__/CodexACPAgent/history-tail.test.ts b/src/__tests__/CodexACPAgent/history-tail.test.ts new file mode 100644 index 000000000..651e244b5 --- /dev/null +++ b/src/__tests__/CodexACPAgent/history-tail.test.ts @@ -0,0 +1,1092 @@ +import {describe, expect, it, vi} from "vitest"; +import {isDeepStrictEqual} from "node:util"; +import * as acp from "@agentclientprotocol/sdk/unstable"; +import type { + Thread, + ThreadItem, + ThreadItemsListParams, + ThreadReadParams, + ThreadTurnsListParams, + Turn, +} from "../../app-server/v2"; +import {createCodexMockTestFixture, createTestModel} from "../acp-test-utils"; +import {HistoryRecorder, HistoryTails, type HistoryCursor, type HistorySource, type HistoryTailResponse} from "../../HistoryTail"; + +const threadId = "019c6e27-e55b-73d1-87d8-4e01f1f75043"; +const cwd = "/workspace"; +const airCapabilities = { + session: {cursors: {}}, + _meta: {jetbrains: {air: {version: 1, capabilities: ["loadReplayEnd", "historyTail", "sessionRewind"]}}}, +}; +const subagentCapabilities = { + session: {cursors: {}}, + _meta: {jetbrains: {air: {version: 1, capabilities: ["loadReplayEnd", "historyTail", "nativeSubagentSessions"]}}}, +}; + +type StoredTurn = {id: string; items: ThreadItem[]; completedAt: number | null; status?: Turn["status"]}; + +function userMessage(id: string, text: string): ThreadItem { + return {type: "userMessage", id, clientId: null, content: [{type: "text", text, text_elements: []}]}; +} + +function agentMessage(id: string, text: string): ThreadItem { + return {type: "agentMessage", id, text, phase: "final_answer", moderation: null, memoryCitation: null, delivery: null, questions: null}; +} + +function command(id: string, text: string): ThreadItem { + return { + type: "commandExecution", id, pluginId: null, scriptPath: null, command: text, cwd, processId: null, + source: "agent", status: "completed", commandActions: [], aggregatedOutput: `ran ${text}`, exitCode: 0, durationMs: 5, + } as ThreadItem; +} + +function subagentActivity(id: string, kind: "started" | "interacted" | "completed", agentThreadId: string): ThreadItem { + return {type: "subAgentActivity", id, kind, agentThreadId, agentPath: `/root/${agentThreadId}`, model: null, reasoningEffort: null}; +} + +function messageTurn(id: string, completedAt: number | null = 100): StoredTurn { + return {id, completedAt, items: [userMessage(`${id}-input`, `Question ${id}`), agentMessage(`${id}-answer`, `Answer ${id}`)]}; +} + +/** + * A fake of the read-only Codex thread API over one stored thread. A descending read of + * thread/items/list without a cursor starts at the newest item, and the cursor `item:` + * starts at that item. An ascending read gives pages of at most 100 items. + */ +class ThreadStore { + turns: StoredTurn[]; + + constructor(turns: StoredTurn[], readonly historyMode: "paginated" | "legacy" = "paginated", readonly id = threadId) { + this.turns = turns; + } + + /** What `thread/revert` leaves: the turns before `turnId`. */ + revert(turnId: string): void { + this.turns = this.turns.slice(0, this.turns.findIndex(turn => turn.id === turnId)); + } + + private entries(turnId?: string | null) { + return this.turns + .filter(turn => !turnId || turn.id === turnId) + .flatMap(turn => turn.items.map(item => ({turnId: turn.id, item, startedAtMs: null, completedAtMs: null}))); + } + + private turn(turn: StoredTurn, full: boolean): Turn { + return { + id: turn.id, rootTurnId: null, items: full ? turn.items : [], itemsView: full ? "full" : "notLoaded", + status: turn.status ?? (turn.completedAt === null ? "interrupted" : "completed"), error: null, + startedAt: 1, completedAt: turn.completedAt, durationMs: null, + }; + } + + thread(): Thread { + return { + id: this.id, sessionId: threadId, parentThreadId: this.id === threadId ? null : threadId, threadSource: null, originator: null, forkedFromId: null, + preview: "Question first", ephemeral: false, modelProvider: "openai", model: "gpt-5", reasoningEffort: "medium", + createdAt: 1, updatedAt: 2, recencyAt: null, status: {type: "notLoaded"}, path: null, cwd, cliVersion: "0", + section: null, sectionEnteredAt: null, projectId: null, historyMode: this.historyMode, source: "cli", + agentNickname: null, agentRole: null, gitInfo: null, name: "Saved conversation", turns: [], + }; + } + + newestItemId(): string | null { + return this.entries().at(-1)?.item.id ?? null; + } + + read = async ({includeTurns}: ThreadReadParams) => ({ + thread: {...this.thread(), turns: includeTurns ? this.turns.map(turn => this.turn(turn, true)) : []}, + }); + + itemsList = async ({turnId, cursor, limit, sortDirection}: ThreadItemsListParams) => { + if (this.historyMode === "legacy") throw new Error("thread/items/list is not supported yet"); + const entries = this.entries(turnId); + if (sortDirection === "desc") { + const index = cursor === null || cursor === undefined + ? entries.length - 1 + : entries.findIndex(entry => `item:${entry.item.id}` === cursor); + return {data: index < 0 ? [] : [entries[index]!], nextCursor: null, backwardsCursor: null}; + } + const start = typeof cursor === "string" ? Number(cursor.slice("asc:".length)) : 0; + const end = start + Math.min(limit ?? 100, 100); + return {data: entries.slice(start, end), nextCursor: end < entries.length ? `asc:${end}` : null, backwardsCursor: null}; + }; + + turnsList = async ({limit, sortDirection, itemsView}: ThreadTurnsListParams) => { + const full = itemsView === "full"; + if (sortDirection === "desc") { + const data = this.turns.slice(-(limit ?? 1)).reverse().map(turn => this.turn(turn, full)); + return {data, nextCursor: null, backwardsCursor: null}; + } + return {data: this.turns.map(turn => this.turn(turn, full)), nextCursor: null, backwardsCursor: null}; + }; +} + +function setUp(store: ThreadStore, ...children: ThreadStore[]) { + const stores = new Map([store, ...children].map(each => [each.id, each])); + const storeOf = (id: string): ThreadStore => { + const found = stores.get(id); + if (!found) throw new Error(`no rollout found for thread id ${id}`); + return found; + }; + const fixture = createCodexMockTestFixture(); + const agent = fixture.getCodexAcpAgent(); + const client = fixture.getCodexAcpClient(); + const appServer = fixture.getCodexAppServerClient(); + client.readAuthRequirement = vi.fn().mockResolvedValue({required: false, account: null}); + client.getAccount = vi.fn().mockResolvedValue({account: null, requiresOpenaiAuth: false}); + client.listSkills = vi.fn().mockResolvedValue({data: []}); + vi.spyOn(appServer, "skillsExtraRootsSet").mockResolvedValue(undefined); + vi.spyOn(appServer, "listModels").mockResolvedValue({data: [createTestModel({id: "gpt-5"})], nextCursor: null}); + const read = vi.spyOn(appServer, "threadRead").mockImplementation(params => storeOf(params.threadId).read(params)); + const items = vi.spyOn(appServer, "threadItemsList").mockImplementation(params => storeOf(params.threadId).itemsList(params)); + const turns = vi.spyOn(appServer, "threadTurnsList").mockImplementation(params => storeOf(params.threadId).turnsList(params)); + const resume = vi.spyOn(appServer, "threadResume").mockImplementation(async () => { + const newest = store.newestItemId(); + return { + thread: store.thread(), itemsBackwardsCursor: newest === null ? null : `item:${newest}`, + model: "gpt-5", modelProvider: "openai", reasoningEffort: "medium", serviceTier: null, cwd, + approvalPolicy: "never", sandbox: {type: "dangerFullAccess"}, + } as any; + }); + const tail = (cursor?: unknown, limit?: number): Promise => + agent.historyTail({sessionId: threadId, cwd, ...(cursor !== undefined ? {cursor} : {}), ...(limit !== undefined ? {limit} : {})}); + return {fixture, agent, appServer, read, items, turns, resume, tail}; +} + +/** The updates of a `session/load` from its first replayed update to its load replay end, and the cursor of the end. */ +async function loadReplay(setup: ReturnType): Promise<{updates: unknown[]; cursor: HistoryCursor}> { + setup.fixture.clearAcpConnectionDump(); + await setup.agent.loadSession({sessionId: threadId, cwd, mcpServers: []}); + const updates = setup.fixture.getAcpConnectionEvents([]) + .filter(event => event.method === "sessionUpdate") + .map(event => event.args[0]); + const end = updates.findIndex(notification => notification.update._meta?.jetbrains?.air?.loadReplayEnd === true); + expect(end).toBeGreaterThanOrEqual(0); + // The history replay starts with the title of the thread. + const start = updates.findIndex(notification => notification.update.sessionUpdate === "session_info_update" + && notification.update.title === "Saved conversation"); + const cursor = updates[end].update._meta.jetbrains.air.historyCursor as HistoryCursor; + await setup.agent.closeSession({sessionId: threadId}); + return {updates: updates.slice(start, end), cursor}; +} + +/** A short label of each update: the message id, the spawned session, or the session and state of a subagent state. */ +function labels(updates: unknown[]): string[] { + return (updates as Array<{sessionId: string; update: any}>).flatMap(({sessionId, update}) => { + if (update.sessionUpdate === "subagent_spawned") return [`spawn ${update.subagentSessionId}`]; + if (update.sessionUpdate === "subagent_state_update") return [`${update.subagentSessionId} ${update.state}`]; + return update.messageId ? [`${sessionId} ${update.messageId}`] : []; + }); +} + +/** + * The updates of the answers of a read in pages of `limit` updates. Each page must go on from the page before it, so a + * read that repeats a page fails. + */ +async function pagedUpdates(setup: ReturnType, cursor: unknown, limit: number): Promise { + const updates: unknown[] = []; + const cursors = new Set(); + for (;;) { + const page = await setup.tail(cursor, limit); + if (page.status !== "ok") throw new Error(`unexpected ${page.status}`); + updates.push(...page.updates); + if (!page.more) return updates; + const next = JSON.stringify(page.cursor); + if (cursors.has(next) || page.updates.length === 0) throw new Error(`the page after ${JSON.stringify(cursor)} does not go on`); + cursors.add(next); + cursor = page.cursor; + } +} + +/** Replays `items` of the root session into `recorder`, one update for each item. */ +async function replayItems(recorder: HistoryRecorder, items: string[]): Promise { + recorder.beginThread(false); + const connection = recorder.connection({notify: async () => {}, request: async () => { throw new Error("no request"); }} as any); + for (const id of items) { + recorder.beginItem(threadId, {id}); + await connection.notify(acp.methods.client.session.update, { + sessionId: threadId, update: {sessionUpdate: "agent_message_chunk", messageId: id, content: {type: "text", text: id}}, + } as never); + } +} + +/** The updates of each session, in their order. */ +function bySession(updates: unknown[]): Record { + const sessions: Record = {}; + for (const notification of updates as Array<{sessionId: string}>) (sessions[notification.sessionId] ??= []).push(notification); + return sessions; +} + +async function initialized(setup: ReturnType, clientCapabilities: acp.ClientCapabilities = airCapabilities) { + await setup.agent.initialize({protocolVersion: 1, clientCapabilities}); + return setup; +} + +describe("_session/history_tail", () => { + it("advertises historyTail to AIR on v1, and not to a client with standard subagent sessions, which it refuses", async () => { + const setup = setUp(new ThreadStore([])); + const response = await setup.agent.initialize({protocolVersion: 1, clientCapabilities: airCapabilities}); + expect((response._meta as any).jetbrains.air.capabilities).toContain("historyTail"); + + const standard = setUp(new ThreadStore([])); + const refused = await standard.agent.initialize({protocolVersion: 1, clientCapabilities: {subagents: {}} as acp.ClientCapabilities}); + // Only an AIR client gets AIR capabilities, and AIR on v1 never uses standard subagent sessions. + expect((refused._meta as any)?.jetbrains?.air?.capabilities ?? []).not.toContain("historyTail"); + await expect(standard.tail()).rejects.toMatchObject({code: -32600}); + }); + + it("gives the history replay of a load with no cursor, and the suffix of a later load after a load cursor", async () => { + const store = new ThreadStore([ + messageTurn("first"), + {id: "second", completedAt: 100, items: [userMessage("second-input", "Run it"), command("second-command", "ls"), agentMessage("second-answer", "Done")]}, + ]); + const setup = await initialized(setUp(store)); + + const firstLoad = await loadReplay(setup); + const whole = await setup.tail(); + expect(whole.status).toBe("ok"); + expect(whole.updates).toEqual(firstLoad.updates); + expect(firstLoad.cursor).toEqual({v: 1, s: {[threadId]: [expect.any(Number), "second-answer"]}}); + + store.turns.push({id: "third", completedAt: 100, items: [userMessage("third-input", "More"), command("third-command", "pwd"), agentMessage("third-answer", "Here")]}); + const secondLoad = await loadReplay(setup); + const tail = await setup.tail(firstLoad.cursor); + + expect(tail.status).toBe("ok"); + expect(tail.updates.length).toBeGreaterThan(0); + expect(tail.updates).toEqual(secondLoad.updates.slice(firstLoad.updates.length)); + expect(tail).toMatchObject({cursor: {v: 1, s: {[threadId]: [secondLoad.cursor.s[threadId]![0], "third-answer"]}, end: "third-answer", turn: "third@100", turnOpen: false}, turnOpen: false}); + expect(tail).not.toHaveProperty("held"); + }); + + it("answers unchanged with one small read when the thread did not change", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second")]); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + setup.items.mockClear(); + setup.turns.mockClear(); + + const unchanged = await setup.tail(whole.cursor); + + expect(unchanged).toEqual({status: "unchanged", cursor: whole.cursor, turnOpen: false, updates: []}); + expect(setup.items.mock.calls).toEqual([[{threadId, cursor: null, limit: 1, sortDirection: "desc"}]]); + expect(setup.turns.mock.calls).toEqual([[{threadId, cursor: null, limit: 1, sortDirection: "desc", itemsView: "notLoaded"}]]); + + store.turns.push(messageTurn("third")); + const grown = await setup.tail(whole.cursor); + expect(grown.status).toBe("ok"); + expect(grown.updates.map(notification => (notification.update as {messageId?: string}).messageId)) + .toEqual(expect.arrayContaining(["third-input", "third-answer"])); + expect(grown.updates.some(notification => (notification.update as {messageId?: string}).messageId === "second-answer")).toBe(false); + }); + + it("gives the subagent history of a load, ends with the states of open subagents, and follows a running subagent", async () => { + const activity = (id: string, kind: "started" | "completed", agentThreadId: string): ThreadItem => ({ + type: "subAgentActivity", id, kind, agentThreadId, agentPath: `/root/${agentThreadId}`, model: null, reasoningEffort: null, + }); + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), activity("a-started", "started", "child-a"), + agentMessage("first-answer", "Delegated"), activity("a-completed", "completed", "child-a"), + ]}, + {id: "second", completedAt: null, items: [ + userMessage("second-input", "Delegate more"), activity("b-started", "started", "child-b"), + ]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + const childB = new ThreadStore([{id: "b-turn", completedAt: null, items: [command("b-1", "make")]}], "paginated", "child-b"); + const setup = await initialized(setUp(store, childA, childB), subagentCapabilities); + + const load = await loadReplay(setup); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + // The tail gives the root session first, then each child session: the same updates of each session as the load. + expect(bySession(whole.updates)).toEqual(bySession(load.updates)); + expect(Object.keys(bySession(whole.updates))).toEqual([threadId, "child-a", "child-b"]); + expect(whole.updates.at(-1)).toEqual({sessionId: threadId, update: {sessionUpdate: "subagent_state_update", subagentSessionId: "child-b", state: "disconnected"}}); + expect(whole.cursor).toMatchObject({end: "b-started", turn: "second@", c: {"child-b": "b-1"}, turnOpen: true, s: {"child-a": [expect.any(Number), "a-1"], "child-b": [expect.any(Number), "b-1"]}}); + + setup.items.mockClear(); + expect(await setup.tail(whole.cursor)).toEqual({status: "unchanged", cursor: whole.cursor, turnOpen: true, updates: []}); + expect(setup.items.mock.calls.map(([params]) => params.threadId)).toEqual([threadId, "child-b"]); + + childB.turns[0]!.items.push(agentMessage("b-2", "Child B progress")); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + // The trailer comes again in each last answer: the subagent still has not ended. + expect(grown.updates).toEqual([ + {sessionId: "child-b", update: expect.objectContaining({sessionUpdate: "agent_message_chunk", messageId: "b-2"})}, + {sessionId: threadId, update: {sessionUpdate: "subagent_state_update", subagentSessionId: "child-b", state: "disconnected"}}, + ]); + expect(grown.cursor.c).toEqual({"child-b": "b-2"}); + + // Pages of one update give each spawn once. + const pages: unknown[] = []; + let cursor: unknown = undefined; + for (;;) { + const page = await setup.tail(cursor, 1); + if (page.status !== "ok") throw new Error(`unexpected ${page.status}`); + pages.push(...page.updates); + cursor = page.cursor; + if (!page.more) break; + } + expect(pages).toEqual((await setup.tail()).updates); + }); + + it.each<[string, ThreadItem]>([ + ["a reasoning item with no text", {type: "reasoning", id: "a-quiet", summary: [], content: []}], + ["a sleep", {type: "sleep", id: "a-quiet", durationMs: 10}], + ["a hook prompt", {type: "hookPrompt", id: "a-quiet", fragments: [{text: "Check the style", hookRunId: "hook-1"}]}], + ["an interaction with the open grandchild", subagentActivity("a-quiet", "interacted", "grandchild")], + ])("answers ok to an append to a child whose last item is %s and that has an open grandchild", async (_, quiet) => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a")]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: null, items: [ + agentMessage("a-1", "Child A works"), subagentActivity("g-started", "started", "grandchild"), quiet, + ]}], "paginated", "child-a"); + const grandchild = new ThreadStore([{id: "g-turn", completedAt: null, items: [agentMessage("g-1", "Grandchild works")]}], "paginated", "grandchild"); + const setup = await initialized(setUp(store, childA, grandchild), subagentCapabilities); + + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + // The `disconnected` state of the grandchild comes after the last item of child A, which sends no update. + expect(whole.cursor.s["child-a"]).toEqual([expect.any(Number), "a-quiet"]); + + childA.turns[0]!.items.push(agentMessage("a-2", "Child A goes on")); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(grown.updates.filter(({sessionId}) => sessionId === "child-a").map(({update}) => update.sessionUpdate === "subagent_state_update" + ? `${update.subagentSessionId}:${update.state}` : (update as {messageId?: string}).messageId)) + .toEqual(["a-2", "grandchild:disconnected"]); + }); + + it("gives the spawn of the next session of an ended child when the turn of a queued interaction starts", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a"), + subagentActivity("a-completed", "completed", "child-a"), + ]}, + {id: "second", completedAt: 100, items: [ + userMessage("second-input", "Ask A again"), subagentActivity("a-interacted", "interacted", "child-a"), + agentMessage("second-answer", "Asked"), + ]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + const setup = await initialized(setUp(store, childA), subagentCapabilities); + + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(Object.keys(bySession(whole.updates))).toEqual([threadId, "child-a"]); + // The ended child waits for the turn of the queued interaction, so the signature watches it. + expect(whole.cursor.c).toEqual({"child-a": "a-1"}); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + + // The child starts the turn of the interaction: the root thread gets no new item. + childA.turns.push({id: "a-turn-2", completedAt: 60, items: [agentMessage("a-2", "Child A again")]}); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + const spawn = grown.updates.findIndex(({update}) => update.sessionUpdate === "subagent_spawned"); + const message = grown.updates.findIndex(({update}) => (update as {messageId?: string}).messageId === "a-2"); + expect(grown.updates[spawn]).toMatchObject({sessionId: threadId, update: {subagentSessionId: "child-a:generation:2"}}); + expect(grown.updates[message]).toMatchObject({sessionId: "child-a:generation:2"}); + expect(spawn).toBeLessThan(message); + expect(grown.updates.filter(({update}) => update.sessionUpdate === "subagent_spawned")).toHaveLength(1); + // The new session has not ended. + expect(grown.cursor.c).toEqual({"child-a": "a-2"}); + }); + + it("gives the updates after the cursor in replay order, as a load, also in pages", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("b-started", "started", "child-b")]}, + ]); + const childB = new ThreadStore([{id: "b-turn", completedAt: null, items: [agentMessage("b-1", "Child B works")]}], "paginated", "child-b"); + const setup = await initialized(setUp(store, childB), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + childB.turns[0]!.items.push(agentMessage("b-2", "Child B done")); + childB.turns[0]!.completedAt = 60; + store.turns[0]!.items.push(subagentActivity("b-completed", "completed", "child-b"), agentMessage("first-answer", "Done")); + store.turns[0]!.completedAt = 100; + const load = await loadReplay(setup); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + + // The last frame of the child comes before its end, as in a load. + expect(labels(grown.updates)).toEqual(["child-b b-2", "child-b completed", `${threadId} first-answer`]); + expect(labels(load.updates).slice(-3)).toEqual(labels(grown.updates)); + expect(await pagedUpdates(setup, whole.cursor, 1)).toEqual(grown.updates); + }); + + it("gives the spawn of the next session of a child before its frames and its end", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a"), + subagentActivity("a-completed", "completed", "child-a"), + userMessage("second-input", "Ask A again"), subagentActivity("a-interacted", "interacted", "child-a"), + ]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + const setup = await initialized(setUp(store, childA), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + childA.turns.push({id: "a-turn-2", completedAt: 60, items: [agentMessage("a-2", "Child A again")]}); + store.turns.push({id: "second", completedAt: 100, items: [subagentActivity("a-completed-2", "completed", "child-a")]}); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual([ + "spawn child-a:generation:2", "child-a:generation:2 a-2", "child-a:generation:2 completed", + ]); + expect(await pagedUpdates(setup, whole.cursor, 1)).toEqual(grown.updates); + }); + + it("gives the spawn of the next session of a child that starts with an item that sends no update", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a"), + subagentActivity("a-completed", "completed", "child-a"), + userMessage("second-input", "Ask A again"), subagentActivity("a-interacted", "interacted", "child-a"), + ]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + const setup = await initialized(setUp(store, childA), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + childA.turns.push({id: "a-turn-2", completedAt: null, items: [{type: "reasoning", id: "a-quiet", summary: [], content: []}]}); + const started = await setup.tail(whole.cursor); + if (started.status !== "ok") throw new Error(`unexpected ${started.status}`); + expect(labels(started.updates)).toEqual(["spawn child-a:generation:2", "child-a:generation:2 disconnected"]); + + childA.turns[1]!.items.push(agentMessage("a-2", "Child A again")); + const grown = await setup.tail(started.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual(["child-a:generation:2 a-2", "child-a:generation:2 disconnected"]); + }); + + it("gives the spawn of a child with no update once, after a read and after a load", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("m-started", "started", "child-missing")]}, + ]); + const setup = await initialized(setUp(store), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(whole.cursor.s["child-missing"]).toEqual([0, ""]); + const load = await loadReplay(setup); + expect(load.cursor.s["child-missing"]).toEqual([0, ""]); + + store.turns[0]!.items.push(agentMessage("first-answer", "Waiting")); + for (const cursor of [whole.cursor, load.cursor]) { + const grown = await setup.tail(cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual([`${threadId} first-answer`, "child-missing disconnected"]); + } + }); + + it("fails with a retryable error and no cursor when a child read fails, and the next tail gives what a load gives", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a"), + subagentActivity("a-completed", "completed", "child-a"), + userMessage("second-input", "Ask A again"), subagentActivity("a-interacted", "interacted", "child-a"), + ]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + let broken = false; + for (const method of ["read", "itemsList", "turnsList"] as const) { + const real = childA[method] as (params: never) => Promise; + (childA as any)[method] = async (params: never) => { + if (broken) throw new Error("database is locked"); + return await real(params); + }; + } + const setup = await initialized(setUp(store, childA), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + childA.turns.push({id: "a-turn-2", completedAt: 60, items: [agentMessage("a-2", "Child A again")]}); + store.turns.push({id: "second", completedAt: 100, items: [ + subagentActivity("a-completed-2", "completed", "child-a"), agentMessage("second-answer", "Both done"), + ]}); + broken = true; + const retryable = {code: -32603, data: {reason: "history_read_failed", retryable: true, sessionId: threadId, threadIds: ["child-a"]}}; + await expect(setup.tail(whole.cursor)).rejects.toMatchObject(retryable); + await expect(setup.tail()).rejects.toMatchObject(retryable); + + broken = false; + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual([ + "spawn child-a:generation:2", "child-a:generation:2 a-2", "child-a:generation:2 completed", `${threadId} second-answer`, + ]); + // The updates that a load adds to the first read, in the order of the load. + const load = await loadReplay(setup); + expect(grown.updates).toEqual(load.updates.filter(update => !whole.updates.some(old => isDeepStrictEqual(old, update)))); + }); + + it("fails with the retryable error when the read of the models fails", async () => { + const started = {...subagentActivity("b-started", "started", "child-b"), model: "gpt-5"} as ThreadItem; + const store = new ThreadStore([{id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), started]}]); + const childB = new ThreadStore([{id: "b-turn", completedAt: null, items: []}], "paginated", "child-b"); + const setup = await initialized(setUp(store, childB), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + // The client has only the model of the child: an update before its first item. + expect(whole.cursor.s["child-b"]).toEqual([1, "#0"]); + + const models = vi.spyOn(setup.appServer, "listModels").mockRejectedValue(new Error("model/list failed")); + childB.turns[0]!.items.push(agentMessage("b-1", "Child B works")); + await expect(setup.tail(whole.cursor)).rejects.toMatchObject({code: -32603, data: {reason: "history_read_failed", retryable: true, models: true}}); + + models.mockResolvedValue({data: [createTestModel({id: "gpt-5"})], nextCursor: null}); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual(["child-b b-1", "child-b disconnected"]); + }); + + it("sends the load replay end without a cursor after a failed read of a subagent", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: 100, items: [userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a")]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}], "paginated", "child-a"); + childA.read = async () => { throw new Error("database is locked"); }; + const setup = await initialized(setUp(store, childA), subagentCapabilities); + await setup.agent.loadSession({sessionId: threadId, cwd, mcpServers: []}); + const ends = setup.fixture.getAcpConnectionEvents([]) + .filter(event => event.method === "sessionUpdate") + .map(event => event.args[0].update) + .filter(update => update._meta?.jetbrains?.air?.loadReplayEnd === true); + expect(ends).toEqual([{sessionUpdate: "session_info_update", _meta: {jetbrains: {air: {version: 1, loadReplayEnd: true}}}}]); + }); + + it("answers from a fresh replay when the kept replay is older than the cursor", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a")]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: null, items: [ + agentMessage("a-1", "Child A works"), subagentActivity("g-started", "started", "grandchild"), + ]}], "paginated", "child-a"); + const grandchild = new ThreadStore([{id: "g-turn", completedAt: null, items: [agentMessage("g-1", "Grandchild works")]}], "paginated", "grandchild"); + const setup = await initialized(setUp(store, childA, grandchild), subagentCapabilities); + expect(await setup.tail()).toMatchObject({status: "ok"}); + + // The signature does not watch the grandchild, so the kept replay still holds. A load cursor names the new item. + grandchild.turns[0]!.items.push(agentMessage("g-2", "Grandchild goes on")); + const load = await loadReplay(setup); + expect(load.cursor.s["grandchild"]).toEqual([expect.any(Number), "g-2"]); + + expect(await setup.tail(load.cursor)).toMatchObject({status: "ok"}); + }); + + it("fails when Codex says a thread is not materialized on a later page or for a later run of a child", async () => { + const store = new ThreadStore(Array.from({length: 60}, (_, index) => messageTurn(`turn-${index}`))); + const setup = await initialized(setUp(store)); + const notMaterialized = new Error(`thread ${threadId} is not materialized yet; thread/turns/list is unavailable before first user message`); + const real = setup.items.getMockImplementation()!; + setup.items.mockImplementation(async params => { + if (params.sortDirection === "asc" && params.cursor === "asc:100") throw notMaterialized; + return await real(params); + }); + await expect(setup.tail()).rejects.toMatchObject({code: -32603, data: {reason: "history_read_failed", retryable: true, sessionId: threadId}}); + + const root = new ThreadStore([ + {id: "first", completedAt: 100, items: [ + userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a"), + subagentActivity("a-completed", "completed", "child-a"), + userMessage("second-input", "Ask A again"), subagentActivity("a-interacted", "interacted", "child-a"), + ]}, + ]); + const childA = new ThreadStore([ + {id: "a-turn", completedAt: 50, items: [agentMessage("a-1", "Child A done")]}, + {id: "a-turn-2", completedAt: 60, items: [agentMessage("a-2", "Child A again")]}, + ], "paginated", "child-a"); + let reads = 0; + const realRead = childA.read; + // The read of the second run of the child says that the thread has no rollout: a thread with a turn has one. + childA.read = async params => { + if (reads++ % 2 === 1) throw new Error("thread child-a is not materialized yet; includeTurns is unavailable before first user message"); + return await realRead(params); + }; + const children = await initialized(setUp(root, childA), subagentCapabilities); + await expect(children.tail()).rejects.toMatchObject({code: -32603, data: {retryable: true, threadIds: ["child-a"]}}); + }); + + it("gives the spawn and the state of a new session of a grandchild when its parent has no new item", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a")]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: null, items: [ + agentMessage("a-1", "Child A works"), subagentActivity("g-started", "started", "grandchild"), + subagentActivity("g-completed", "completed", "grandchild"), subagentActivity("g-interacted", "interacted", "grandchild"), + ]}], "paginated", "child-a"); + const grandchild = new ThreadStore([{id: "g-turn", completedAt: 40, items: [agentMessage("g-1", "Grandchild done")]}], "paginated", "grandchild"); + const setup = await initialized(setUp(store, childA, grandchild), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + // The next run of the grandchild starts with no item. The root gets an item, so the signature changes. + grandchild.turns.push({id: "g-turn-2", completedAt: null, items: []}); + store.turns[0]!.items.push(agentMessage("first-answer", "Waiting")); + const started = await setup.tail(whole.cursor); + if (started.status !== "ok") throw new Error(`unexpected ${started.status}`); + expect(labels(started.updates)).toEqual([ + "spawn grandchild:generation:2", "grandchild:generation:2 disconnected", `${threadId} first-answer`, "child-a disconnected", + ]); + // Pages give what one answer gives, also the state of the new session after a cut. + expect(await pagedUpdates(setup, whole.cursor, 1)).toEqual(started.updates); + expect(await pagedUpdates(setup, whole.cursor, 2)).toEqual(started.updates); + + grandchild.turns[1]!.items.push(agentMessage("g-2", "Grandchild again")); + store.turns[0]!.items.push(agentMessage("second-answer", "Still waiting")); + const grown = await setup.tail(started.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual(["grandchild:generation:2 g-2", `${threadId} second-answer`, "child-a disconnected"]); + }); + + it("gives in pages the state of a new session of a grandchild that comes before the cursor of its parent", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("a-started", "started", "child-a")]}, + ]); + const childA = new ThreadStore([{id: "a-turn", completedAt: null, items: [ + agentMessage("a-1", "Child A works"), subagentActivity("g-started", "started", "grandchild"), + subagentActivity("g-completed", "completed", "grandchild"), subagentActivity("g-interacted", "interacted", "grandchild"), + ]}], "paginated", "child-a"); + const grandchild = new ThreadStore([{id: "g-turn", completedAt: 40, items: [agentMessage("g-1", "Grandchild done")]}], "paginated", "grandchild"); + const setup = await initialized(setUp(store, childA, grandchild), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + grandchild.turns.push({id: "g-turn-2", completedAt: null, items: [agentMessage("g-2", "Grandchild again"), agentMessage("g-3", "Grandchild more")]}); + store.turns[0]!.items.push(agentMessage("first-answer", "Waiting")); + const grown = await setup.tail(whole.cursor); + if (grown.status !== "ok") throw new Error(`unexpected ${grown.status}`); + expect(labels(grown.updates)).toEqual([ + "spawn grandchild:generation:2", "grandchild:generation:2 g-2", "grandchild:generation:2 g-3", + "grandchild:generation:2 disconnected", `${threadId} first-answer`, "child-a disconnected", + ]); + expect(await pagedUpdates(setup, whole.cursor, 1)).toEqual(grown.updates); + expect(await pagedUpdates(setup, whole.cursor, 2)).toEqual(grown.updates); + // A page whose replay another read replaced answers rewritten. + const first = await setup.tail(whole.cursor, 1); + if (first.status !== "ok" || !first.more) throw new Error("expected a page with more"); + await setup.tail(); + expect(await setup.tail(first.cursor, 1)).toEqual({status: "rewritten", updates: []}); + }); + + it("fails with the retryable error when a read of the root fails", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second")]); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + const retryable = {code: -32603, data: {reason: "history_read_failed", retryable: true, sessionId: threadId}}; + + // The read of the metadata of the thread. + setup.read.mockRejectedValueOnce(new Error("database is locked")); + await expect(setup.tail(whole.cursor)).rejects.toMatchObject(retryable); + // The read of the newest turn of the root. + setup.turns.mockRejectedValueOnce(new Error("database is locked")); + await expect(setup.tail(whole.cursor)).rejects.toMatchObject(retryable); + // The read of the history in the replay. + const real = setup.items.getMockImplementation()!; + setup.items.mockImplementation(async params => { + if (params.sortDirection === "asc") throw new Error("database is locked"); + return await real(params); + }); + await expect(setup.tail()).rejects.toMatchObject(retryable); + setup.items.mockImplementation(real); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + }); + + it("reads the whole history for a null cursor", async () => { + const setup = await initialized(setUp(new ThreadStore([messageTurn("first")]))); + const whole = await setup.tail(); + expect(await setup.agent.historyTail({sessionId: threadId, cwd, cursor: null})).toEqual(whole); + }); + + it("takes turnOpen from the newest turn of now when the turn ends with no end time and no new item", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second", null)]); + const setup = await initialized(setUp(store)); + const load = await loadReplay(setup); + const whole = await setup.tail(); + expect(whole).toMatchObject({status: "ok", turnOpen: true}); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + store.turns[1]!.status = "failed"; + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged", turnOpen: false, cursor: {turnOpen: false}}); + // A load cursor has no signature, so the answer comes from the kept replay. + expect(await setup.tail(load.cursor)).toMatchObject({status: "ok", turnOpen: false, cursor: {turnOpen: false}}); + }); + + it("tells an open turn by its status and its end time", async () => { + const store = new ThreadStore([messageTurn("first"), {...messageTurn("second", null), status: "failed"}]); + const setup = await initialized(setUp(store)); + expect(await setup.tail()).toMatchObject({status: "ok", turnOpen: false}); + + store.turns.push(messageTurn("third", null)); + expect(await setup.tail()).toMatchObject({status: "ok", turnOpen: true}); + }); + + it("answers rewritten for a legacy thread whose rollback reused the item ids of the cursor", async () => { + const legacyTurn = (id: string, first: number, text: string): StoredTurn => ({ + id, completedAt: 100, items: [userMessage(`item-${first}`, `Question ${text}`), agentMessage(`item-${first + 1}`, `Answer ${text}`)], + }); + const store = new ThreadStore([legacyTurn("rollout-1", 1, "first"), legacyTurn("rollout-5", 3, "second")], "legacy"); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(whole.cursor.s[threadId]![1]).toMatch(/^item-4:[\w-]{12}$/); + + // A rollback of the second turn, then a new turn with as many items: Codex counts the item ids again. + store.revert("rollout-5"); + store.turns.push(legacyTurn("rollout-9", 3, "other")); + + expect(await setup.tail(whole.cursor)).toEqual({status: "rewritten", updates: []}); + }); + + it("answers rewritten for a legacy thread whose rollback ends with the same last item at the same index", async () => { + const turn = (id: string, question: string): StoredTurn => ({ + id, completedAt: 100, items: [userMessage("item-3", question), agentMessage("item-4", "The same answer")], + }); + const store = new ThreadStore([ + {id: "rollout-1", completedAt: 100, items: [userMessage("item-1", "Question first"), agentMessage("item-2", "Answer first")]}, + turn("rollout-5", "Question second"), + ], "legacy"); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + store.revert("rollout-5"); + store.turns.push(turn("rollout-9", "Question other")); + + expect(await setup.tail(whole.cursor)).toEqual({status: "rewritten", updates: []}); + }); + + it("does not answer unchanged after Codex appends to the last reasoning item of a legacy thread in place", async () => { + const reasoning = {type: "reasoning", id: "item-2", summary: ["Thinking"], content: []} as ThreadItem & {summary: string[]}; + const store = new ThreadStore([{id: "rollout-1", completedAt: null, items: [userMessage("item-1", "Question"), reasoning]}], "legacy"); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + + reasoning.summary.push("Thinking more"); + + expect(await setup.tail(whole.cursor)).toEqual({status: "rewritten", updates: []}); + }); + + it("reads the root when Codex cannot read the thread of an open subagent", async () => { + const store = new ThreadStore([ + {id: "first", completedAt: null, items: [userMessage("first-input", "Delegate"), subagentActivity("m-started", "started", "child-missing")]}, + ]); + const setup = await initialized(setUp(store), subagentCapabilities); + + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(whole.cursor.c).toEqual({"child-missing": ""}); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + }); + + it("shares one replay between overlapping reads, and starts none for a cancelled read", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second")]); + const setup = await initialized(setUp(store)); + const replays = () => setup.items.mock.calls.filter(([params]) => params.sortDirection === "asc").length; + + const [first, second] = await Promise.all([setup.tail(), setup.tail()]); + expect(second).toEqual(first); + expect(replays()).toBe(1); + + // The kept replay no longer holds, so the read needs a new one. + store.turns.push(messageTurn("third")); + await expect(setup.agent.historyTail({sessionId: threadId, cwd, cursor: {v: 1, s: {}}}, AbortSignal.abort())) + .rejects.toMatchObject({code: -32800}); + expect(replays()).toBe(1); + }); + + it("runs two replays at one time, and does not start a waiting replay whose read was cancelled", async () => { + const tails = new HistoryTails(); + let release!: () => void; + const slow = new Promise(resolve => { release = resolve; }); + const started: string[] = []; + const source = (name: string): HistorySource => ({ + legacy: async () => false, + head: async () => ({item: "", turn: "", turnOpen: false}), + replay: async () => { started.push(name); await slow; }, + }); + const read = (name: string, signal?: AbortSignal) => tails.read({sessionId: name, cwd}, source(name), signal); + + const first = read("first"); + const second = read("second"); + const controller = new AbortController(); + const third = read("third", controller.signal); + await vi.waitFor(() => expect(started).toEqual(["first", "second"])); + controller.abort(); + await expect(third).rejects.toMatchObject({code: -32800}); + + release(); + await expect(first).resolves.toMatchObject({status: "ok"}); + await expect(second).resolves.toMatchObject({status: "ok"}); + await new Promise(resolve => setTimeout(resolve, 10)); + expect(started).toEqual(["first", "second"]); + tails.dispose(); + }); + + it("keeps a replay that ends after its only read was cancelled", async () => { + const tails = new HistoryTails(); + let release!: () => void; + const slow = new Promise(resolve => { release = resolve; }); + let replays = 0; + const source: HistorySource = { + legacy: async () => false, + head: async () => ({item: "", turn: "", turnOpen: false}), + replay: async () => { replays++; await slow; }, + }; + const controller = new AbortController(); + const cancelled = tails.read({sessionId: threadId, cwd}, source, controller.signal); + await vi.waitFor(() => expect(replays).toBe(1)); + controller.abort(); + await expect(cancelled).rejects.toMatchObject({code: -32800}); + release(); + await new Promise(resolve => setTimeout(resolve, 10)); + + await expect(tails.read({sessionId: threadId, cwd, cursor: {v: 1, s: {}}}, source)).resolves.toMatchObject({status: "ok"}); + expect(replays).toBe(1); + tails.dispose(); + }); + + it("joins no running replay that read its head before the read, with a cursor or with none", async () => { + const tails = new HistoryTails(); + let items = ["a"]; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + let replays = 0; + const source: HistorySource = { + legacy: async () => false, + head: async () => ({item: "", turn: "", turnOpen: false}), + replay: async recorder => { + const snapshot = [...items]; + if (replays++ === 0) await gate; + await replayItems(recorder, snapshot); + }, + }; + const first = tails.read({sessionId: threadId, cwd}, source); + await vi.waitFor(() => expect(replays).toBe(1)); + + items = ["a", "b"]; + const withCursor = await tails.read({sessionId: threadId, cwd, cursor: {v: 1, s: {[threadId]: [2, "b"]}}}, source); + expect(withCursor).toMatchObject({status: "ok", cursor: {s: {[threadId]: [2, "b"]}}}); + expect(replays).toBe(2); + + release(); + expect(await first).toMatchObject({status: "ok", cursor: {s: {[threadId]: [1, "a"]}}}); + // A read with no cursor does not use the kept replay either. + expect(await tails.read({sessionId: threadId, cwd}, source)).toMatchObject({status: "ok", cursor: {s: {[threadId]: [2, "b"]}}}); + expect(replays).toBe(3); + tails.dispose(); + }); + + it("does not answer unchanged when the read of the newest item of a subagent fails", async () => { + const tails = new HistoryTails(); + let replays = 0; + const source: HistorySource = { + legacy: async () => false, + head: async threadId => { + if (threadId === "child-x") throw new Error("database is locked"); + return {item: "", turn: "", turnOpen: false}; + }, + replay: async () => { replays++; }, + }; + const cursor = {v: 1, s: {}, end: "", turn: "", c: {"child-x": ""}}; + expect(await tails.read({sessionId: threadId, cwd, cursor}, source)).toMatchObject({status: "ok"}); + expect(replays).toBe(1); + tails.dispose(); + }); + + it("answers rewritten when thread/revert dropped the item of the cursor", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second")]); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + + store.revert("second"); + + expect(await setup.tail(whole.cursor)).toEqual({status: "rewritten", updates: []}); + expect(await setup.tail({v: 99, s: {}})).toEqual({status: "rewritten", updates: []}); + }); + + it("reads a history of more than 100 items in pages, and answers in pages with limit", async () => { + const store = new ThreadStore(Array.from({length: 130}, (_, index) => messageTurn(`turn-${index}`))); + const setup = await initialized(setUp(store)); + + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + const ascending = setup.items.mock.calls.filter(([params]) => params.sortDirection === "asc"); + expect(ascending.map(([params]) => params.cursor)).toEqual([null, "asc:100", "asc:200"]); + expect(whole.updates.filter(notification => notification.update.sessionUpdate === "agent_message_chunk")).toHaveLength(130); + + const pages: HistoryTailResponse[] = []; + let cursor: unknown = undefined; + for (;;) { + const page = await setup.tail(cursor, 50); + pages.push(page); + if (page.status !== "ok") throw new Error(`unexpected ${page.status}`); + cursor = page.cursor; + if (!page.more) break; + } + expect(pages.length).toBeGreaterThan(2); + expect(pages.flatMap(page => page.updates)).toEqual(whole.updates); + expect(pages.slice(0, -1).every(page => page.status === "ok" && page.cursor.p !== undefined && page.turnOpen === undefined)).toBe(true); + }); + + it("reads a thread that another Codex process holds, whose load refusal carries data.held", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("running", null)]); + const setup = await initialized(setUp(store)); + setup.resume.mockRejectedValue(Object.assign(new Error(`thread ${threadId} already has an active writer`), {code: -32600})); + + const error = await setup.agent.loadSession({sessionId: threadId, cwd, mcpServers: []}).catch(caught => caught); + expect(error).toBeInstanceOf(acp.RequestError); + expect(error.data).toMatchObject({reason: "thread_active_writer", threadId, held: {}}); + + const tail = await setup.tail(); + expect(tail.status).toBe("ok"); + expect(tail).not.toHaveProperty("held"); + // Another process sees its running turn as interrupted with no end time: the turn stays open. + expect(tail).toMatchObject({turnOpen: true, cursor: {turn: "running@", turnOpen: true}}); + expect(setup.resume).toHaveBeenCalledTimes(1); + }); + + it("reads a legacy thread with thread/read and no thread/items/list", async () => { + const store = new ThreadStore([messageTurn("first"), messageTurn("second")], "legacy"); + const setup = await initialized(setUp(store)); + const load = await loadReplay(setup); + setup.items.mockClear(); + + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(whole.updates).toEqual(load.updates); + expect(whole.cursor).toMatchObject({end: expect.stringMatching(/^second-answer:[\w-]{12}$/), turn: "second@100"}); + expect(setup.items).not.toHaveBeenCalled(); + + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + store.turns.push(messageTurn("third")); + const grown = await setup.tail(load.cursor); + expect(grown.status).toBe("ok"); + expect(grown.updates.map(notification => notification.update.sessionUpdate)) + .toEqual(["user_message_chunk", "cursor_update", "agent_message_chunk"]); + }); + + it("answers -32002 for a thread that Codex does not have", async () => { + const setup = await initialized(setUp(new ThreadStore([], "paginated", "other-thread"))); + await expect(setup.tail()).rejects.toMatchObject({code: -32002, data: {sessionId: threadId}}); + }); + + it("sends the load replay end without a cursor to a client without historyTail", async () => { + const setup = setUp(new ThreadStore([messageTurn("first")])); + await setup.agent.initialize({protocolVersion: 1, clientCapabilities: {_meta: {jetbrains: {air: {version: 1, capabilities: ["loadReplayEnd"]}}}}}); + await setup.agent.loadSession({sessionId: threadId, cwd, mcpServers: []}); + const ends = setup.fixture.getAcpConnectionEvents([]) + .filter(event => event.method === "sessionUpdate") + .map(event => event.args[0].update) + .filter(update => update._meta?.jetbrains?.air?.loadReplayEnd === true); + expect(ends).toEqual([{sessionUpdate: "session_info_update", _meta: {jetbrains: {air: {version: 1, loadReplayEnd: true}}}}]); + }); +}); + +describe("_session/history_tail pages", () => { + /** A deterministic random source: mulberry32. */ + function random(seed: number): (bound: number) => number { + let state = seed >>> 0; + return bound => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return Math.floor((((t ^ (t >>> 14)) >>> 0) / 4294967296) * bound); + }; + } + + /** + * A random history of a root with subagents and their own subagents. Some subagents end and get a queued interaction, + * so a later change starts their next session at an old item of their parent. + */ + function randomHistory(seed: number) { + const next = random(seed); + let ids = 0; + const id = (prefix: string) => `${prefix}-${ids++}`; + const stores: ThreadStore[] = []; + // The subagents that wait for the turn of a queued interaction, and the open turns that can grow. + const queued: Array<{store: ThreadStore; parent: StoredTurn}> = []; + const open: StoredTurn[] = []; + const thread = (threadId: string, depth: number): StoredTurn => { + const items: ThreadItem[] = []; + const self: StoredTurn = {id: id(`${threadId}-t`), completedAt: null, items}; + const count = 1 + next(3); + for (let index = 0; index < count; index++) { + items.push(agentMessage(id(`${threadId}-m`), `Message ${ids}`)); + if (depth < 3 && next(2) === 0) { + const child = `${threadId}-c${ids++}`; + const store = new ThreadStore([], "paginated", child); + stores.push(store); + items.push(subagentActivity(id(`${child}-s`), "started", child)); + const turn = thread(child, depth + 1); + store.turns.push(turn); + if (next(2) === 0) { + turn.completedAt = 10; + items.push(subagentActivity(id(`${child}-e`), "completed", child)); + if (next(2) === 0) { + items.push(subagentActivity(id(`${child}-i`), "interacted", child)); + queued.push({store, parent: self}); + } + } else { + open.push(turn); + } + } + } + return self; + }; + const root = thread(threadId, 0); + root.items.unshift(userMessage(id("input"), "Go")); + open.push(root); + const change = () => { + for (const {store, parent} of queued) { + if (next(3) === 0) continue; + const items = Array.from({length: next(4)}, () => agentMessage(id(`${store.id}-n`), `New ${ids}`)); + const ended = next(3) === 0; + store.turns.push({id: id(`${store.id}-t`), completedAt: ended ? 20 : null, items}); + // The end of the new run comes as a new item of its parent. + if (ended) parent.items.push(subagentActivity(id(`${store.id}-e2`), "completed", store.id)); + } + for (const turn of open) { + if (next(2) === 0) turn.items.push(agentMessage(id("grown"), `Grown ${ids}`)); + } + // The root always changes, so the tail replays. + root.items.push(agentMessage(id("root"), `Root ${ids}`)); + }; + return {root: new ThreadStore([root]), stores, change}; + } + + it("gives in pages what one answer gives, goes on with each page, and answers rewritten for a page of a replaced replay", async () => { + let replaced = 0; + for (let seed = 1; seed <= 300; seed++) { + const history = randomHistory(seed); + const setup = await initialized(setUp(history.root, ...history.stores), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`seed ${seed}: unexpected ${whole.status}`); + history.change(); + const one = await setup.tail(whole.cursor); + if (one.status !== "ok") throw new Error(`seed ${seed}: unexpected ${one.status}`); + for (const limit of [1, 2, 3, 5]) { + expect(await pagedUpdates(setup, whole.cursor, limit), `seed ${seed}, limit ${limit}`).toEqual(one.updates); + } + const first = await setup.tail(whole.cursor, 1); + if (first.status === "ok" && first.more) { + await setup.tail(); + expect(await setup.tail(first.cursor, 1), `seed ${seed}`).toEqual({status: "rewritten", updates: []}); + replaced++; + } + } + expect(replaced).toBeGreaterThan(100); + }, 120_000); +}); diff --git a/src/__tests__/CodexACPAgent/initialize.test.ts b/src/__tests__/CodexACPAgent/initialize.test.ts index 320f6c83d..763669286 100644 --- a/src/__tests__/CodexACPAgent/initialize.test.ts +++ b/src/__tests__/CodexACPAgent/initialize.test.ts @@ -102,7 +102,7 @@ describe('CodexACPAgent - initialize', () => { controlMethod: "_session/goal", actions: ["set", "pause", "resume", "clear"], }, - capabilities: ["sessionFailure", "diffPatch", "agentFileChangeReport", "customInstructions", "nativeSubagentSessions", "asyncTasks", "recommendedValue", "rawInputRendering", "planContentDelta", "codexHooks"], + capabilities: ["sessionFailure", "diffPatch", "agentFileChangeReport", "customInstructions", "nativeSubagentSessions", "asyncTasks", "recommendedValue", "rawInputRendering", "planContentDelta", "codexHooks", "historyTail"], }, }, }); diff --git a/src/__tests__/CodexACPAgent/thread-active-writer.test.ts b/src/__tests__/CodexACPAgent/thread-active-writer.test.ts index 5b1fc89f9..ba30c0a63 100644 --- a/src/__tests__/CodexACPAgent/thread-active-writer.test.ts +++ b/src/__tests__/CodexACPAgent/thread-active-writer.test.ts @@ -16,6 +16,7 @@ const expectedError = { data: { reason: "thread_active_writer", threadId, + held: {}, details: `thread ${threadId} already has an active writer`, }, }; diff --git a/src/__tests__/integration/history-tail.test.ts b/src/__tests__/integration/history-tail.test.ts new file mode 100644 index 000000000..164d971a2 --- /dev/null +++ b/src/__tests__/integration/history-tail.test.ts @@ -0,0 +1,92 @@ +// Real codex-acp + two real `codex app-server` processes on one temporary Codex home; the model is a local mock. +// The first agent holds the thread. The second one reads it with `_session/history_tail`. +import * as acp from "@agentclientprotocol/sdk/unstable"; +import {afterEach, expect, it} from "vitest"; +import {createSpawnedAgentFixture, type SpawnedAgentFixture} from "../CodexACPAgent/e2e/spawned-agent-fixture"; +import {describeIntegration, openSession, sendPrompt, stopAll} from "./integration-fixture"; +import {type MockResponsesServer, startMockResponsesServer, textResponse} from "./mock-responses-server"; +import type {HistoryTailResponse} from "../../HistoryTail"; + +const TAIL = "_session/history_tail"; + +async function connectAir(connection: acp.ClientContext, baseUrl: string): Promise { + await connection.request(acp.methods.agent.initialize, { + protocolVersion: acp.PROTOCOL_VERSION, + clientCapabilities: { + fs: {readTextFile: true, writeTextFile: true}, + terminal: true, + auth: {_meta: {gateway: true}}, + _meta: {jetbrains: {air: {version: 1, capabilities: ["loadReplayEnd", "historyTail"]}}}, + }, + clientInfo: {name: "vitest", version: "1.0.0"}, + } as acp.InitializeRequest); + await connection.request(acp.methods.agent.authenticate, {methodId: "gateway", _meta: {gateway: {baseUrl, headers: {}}}}); +} + +/** The text of the message chunks of `updates`, by kind. */ +function texts(answer: HistoryTailResponse, kind: "user_message_chunk" | "agent_message_chunk"): string[] { + return answer.updates.flatMap(({update}) => + update.sessionUpdate === kind && update.content.type === "text" ? [update.content.text] : []); +} + +async function until(read: () => Promise, done: (value: T) => boolean, timeoutMs = 15_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = await read(); + if (done(value) || Date.now() > deadline) return value; + await new Promise(resolve => setTimeout(resolve, 200)); + } +} + +describeIntegration("integration: _session/history_tail", () => { + let mock: MockResponsesServer | undefined; + let holder: SpawnedAgentFixture | undefined; + let reader: SpawnedAgentFixture | undefined; + + afterEach(async () => { + await reader?.dispose(); + await stopAll(holder, mock); + }); + + it("reads a thread that another app-server holds, and follows its turns", async () => { + const server = mock = await startMockResponsesServer(); + let release!: () => void; + const slow = new Promise(resolve => { release = resolve; }); + server.setResponseHandler(async request => { + if (JSON.stringify((request as {input: unknown}).input).includes("SLOW")) await slow; + return textResponse("answer"); + }); + holder = await createSpawnedAgentFixture(connection => connectAir(connection, server.baseUrl)); + const sessionId = await openSession(holder); + await sendPrompt(holder, sessionId, "first question"); + + reader = await createSpawnedAgentFixture(connection => connectAir(connection, server.baseUrl), {CODEX_HOME: holder.codexHome}); + const cwd = holder.workspaceDir; + await expect(reader.connection.request(acp.methods.agent.session.load, {sessionId, cwd, mcpServers: []})) + .rejects.toMatchObject({code: -32600, data: {reason: "thread_active_writer", held: {}}}); + + const tail = (cursor?: unknown) => reader!.connection.request(TAIL, {sessionId, cwd, ...(cursor ? {cursor} : {})}) as Promise; + const whole = await tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(texts(whole, "user_message_chunk")).toEqual(["first question"]); + expect(texts(whole, "agent_message_chunk")).toEqual(["answer"]); + expect(whole.turnOpen).toBe(false); + expect(whole).not.toHaveProperty("held"); + expect(await tail(whole.cursor)).toMatchObject({status: "unchanged", turnOpen: false}); + + // The turn of the holder runs: another app-server sees it as interrupted with no end time. + const running = sendPrompt(holder, sessionId, "SLOW second question"); + const open = await until(() => tail(whole.cursor), answer => answer.status === "ok" && answer.turnOpen === true); + expect(open).toMatchObject({status: "ok", turnOpen: true}); + if (open.status !== "ok") throw new Error(`unexpected ${open.status}`); + expect(texts(open, "user_message_chunk")).toEqual(["SLOW second question"]); + expect(texts(open, "agent_message_chunk")).toEqual([]); + + release(); + await running; + const ended = await until(() => tail(open.cursor), answer => answer.status === "ok" && answer.turnOpen === false); + if (ended.status !== "ok") throw new Error(`unexpected ${ended.status}`); + expect(texts(ended, "user_message_chunk")).toEqual([]); + expect(texts(ended, "agent_message_chunk")).toEqual(["answer"]); + }, 60_000); +}); diff --git a/src/__tests__/scenarios/data/air/agent-message-and-reasoning.jsonl b/src/__tests__/scenarios/data/air/agent-message-and-reasoning.jsonl index 13f8d2edd..c0fed9caf 100644 --- a/src/__tests__/scenarios/data/air/agent-message-and-reasoning.jsonl +++ b/src/__tests__/scenarios/data/air/agent-message-and-reasoning.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/background-terminal.jsonl b/src/__tests__/scenarios/data/air/background-terminal.jsonl index 042e44262..6525c05d5 100644 --- a/src/__tests__/scenarios/data/air/background-terminal.jsonl +++ b/src/__tests__/scenarios/data/air/background-terminal.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/collab-agent.jsonl b/src/__tests__/scenarios/data/air/collab-agent.jsonl index 5427fb1b7..1d48736f1 100644 --- a/src/__tests__/scenarios/data/air/collab-agent.jsonl +++ b/src/__tests__/scenarios/data/air/collab-agent.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/collab-controls.jsonl b/src/__tests__/scenarios/data/air/collab-controls.jsonl index 2f9d6767e..494d49be0 100644 --- a/src/__tests__/scenarios/data/air/collab-controls.jsonl +++ b/src/__tests__/scenarios/data/air/collab-controls.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/command-approval.jsonl b/src/__tests__/scenarios/data/air/command-approval.jsonl index 1baf6ac78..c60e99567 100644 --- a/src/__tests__/scenarios/data/air/command-approval.jsonl +++ b/src/__tests__/scenarios/data/air/command-approval.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/command-failed.jsonl b/src/__tests__/scenarios/data/air/command-failed.jsonl index ff0c2f49f..ff3aa9bca 100644 --- a/src/__tests__/scenarios/data/air/command-failed.jsonl +++ b/src/__tests__/scenarios/data/air/command-failed.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/command-output-stdin.jsonl b/src/__tests__/scenarios/data/air/command-output-stdin.jsonl index 0da009231..ec8db0726 100644 --- a/src/__tests__/scenarios/data/air/command-output-stdin.jsonl +++ b/src/__tests__/scenarios/data/air/command-output-stdin.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/command-without-streamed-output.jsonl b/src/__tests__/scenarios/data/air/command-without-streamed-output.jsonl index 91531506f..15718114e 100644 --- a/src/__tests__/scenarios/data/air/command-without-streamed-output.jsonl +++ b/src/__tests__/scenarios/data/air/command-without-streamed-output.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/context-compaction.jsonl b/src/__tests__/scenarios/data/air/context-compaction.jsonl index 02c0fcec1..ae7bd3e2a 100644 --- a/src/__tests__/scenarios/data/air/context-compaction.jsonl +++ b/src/__tests__/scenarios/data/air/context-compaction.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/dynamic-tool.jsonl b/src/__tests__/scenarios/data/air/dynamic-tool.jsonl index a6cbe7bd1..25bc4a720 100644 --- a/src/__tests__/scenarios/data/air/dynamic-tool.jsonl +++ b/src/__tests__/scenarios/data/air/dynamic-tool.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/file-change-approval.jsonl b/src/__tests__/scenarios/data/air/file-change-approval.jsonl index d99aaf80e..8c70e5810 100644 --- a/src/__tests__/scenarios/data/air/file-change-approval.jsonl +++ b/src/__tests__/scenarios/data/air/file-change-approval.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/file-changes.jsonl b/src/__tests__/scenarios/data/air/file-changes.jsonl index b3a02a398..2a2bbd47a 100644 --- a/src/__tests__/scenarios/data/air/file-changes.jsonl +++ b/src/__tests__/scenarios/data/air/file-changes.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/fuzzy-file-search.jsonl b/src/__tests__/scenarios/data/air/fuzzy-file-search.jsonl index 05c9174ca..f03eecf3c 100644 --- a/src/__tests__/scenarios/data/air/fuzzy-file-search.jsonl +++ b/src/__tests__/scenarios/data/air/fuzzy-file-search.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/goal-update.jsonl b/src/__tests__/scenarios/data/air/goal-update.jsonl index ba6473351..c5ab934b7 100644 --- a/src/__tests__/scenarios/data/air/goal-update.jsonl +++ b/src/__tests__/scenarios/data/air/goal-update.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/guardian-review.jsonl b/src/__tests__/scenarios/data/air/guardian-review.jsonl index 7dff686ae..3155583c3 100644 --- a/src/__tests__/scenarios/data/air/guardian-review.jsonl +++ b/src/__tests__/scenarios/data/air/guardian-review.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/history-replay.jsonl b/src/__tests__/scenarios/data/air/history-replay.jsonl index 1046451c1..3ce5628e8 100644 --- a/src/__tests__/scenarios/data/air/history-replay.jsonl +++ b/src/__tests__/scenarios/data/air/history-replay.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/load","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"}}} diff --git a/src/__tests__/scenarios/data/air/image-generation.jsonl b/src/__tests__/scenarios/data/air/image-generation.jsonl index 836abb6e5..6e805dab4 100644 --- a/src/__tests__/scenarios/data/air/image-generation.jsonl +++ b/src/__tests__/scenarios/data/air/image-generation.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/image-view.jsonl b/src/__tests__/scenarios/data/air/image-view.jsonl index d72a2172d..2ac6a7f7d 100644 --- a/src/__tests__/scenarios/data/air/image-view.jsonl +++ b/src/__tests__/scenarios/data/air/image-view.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/late-subagent-update.jsonl b/src/__tests__/scenarios/data/air/late-subagent-update.jsonl index 379abffed..8083e7da1 100644 --- a/src/__tests__/scenarios/data/air/late-subagent-update.jsonl +++ b/src/__tests__/scenarios/data/air/late-subagent-update.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/mcp-elicitation.jsonl b/src/__tests__/scenarios/data/air/mcp-elicitation.jsonl index 6a2b54832..5372eb6b6 100644 --- a/src/__tests__/scenarios/data/air/mcp-elicitation.jsonl +++ b/src/__tests__/scenarios/data/air/mcp-elicitation.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/mcp-startup-failure.jsonl b/src/__tests__/scenarios/data/air/mcp-startup-failure.jsonl index 1908fb998..08c635526 100644 --- a/src/__tests__/scenarios/data/air/mcp-startup-failure.jsonl +++ b/src/__tests__/scenarios/data/air/mcp-startup-failure.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/mcp-tool-approval.jsonl b/src/__tests__/scenarios/data/air/mcp-tool-approval.jsonl index b9d72c815..c7c2440d7 100644 --- a/src/__tests__/scenarios/data/air/mcp-tool-approval.jsonl +++ b/src/__tests__/scenarios/data/air/mcp-tool-approval.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/mcp-tool.jsonl b/src/__tests__/scenarios/data/air/mcp-tool.jsonl index a49e0c85b..f26b89c46 100644 --- a/src/__tests__/scenarios/data/air/mcp-tool.jsonl +++ b/src/__tests__/scenarios/data/air/mcp-tool.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/mcp-url-elicitation.jsonl b/src/__tests__/scenarios/data/air/mcp-url-elicitation.jsonl index 509f8459b..2f134ea1d 100644 --- a/src/__tests__/scenarios/data/air/mcp-url-elicitation.jsonl +++ b/src/__tests__/scenarios/data/air/mcp-url-elicitation.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/native-subagent-session.jsonl b/src/__tests__/scenarios/data/air/native-subagent-session.jsonl index 21e1b8ac0..bdc5a7bc0 100644 --- a/src/__tests__/scenarios/data/air/native-subagent-session.jsonl +++ b/src/__tests__/scenarios/data/air/native-subagent-session.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/nested-subagent-session.jsonl b/src/__tests__/scenarios/data/air/nested-subagent-session.jsonl index 03e08cc1e..42841115a 100644 --- a/src/__tests__/scenarios/data/air/nested-subagent-session.jsonl +++ b/src/__tests__/scenarios/data/air/nested-subagent-session.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/network-and-sandbox-approval.jsonl b/src/__tests__/scenarios/data/air/network-and-sandbox-approval.jsonl index 288bfe5ea..c05f03666 100644 --- a/src/__tests__/scenarios/data/air/network-and-sandbox-approval.jsonl +++ b/src/__tests__/scenarios/data/air/network-and-sandbox-approval.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/plan-deltas-and-turn-plan.jsonl b/src/__tests__/scenarios/data/air/plan-deltas-and-turn-plan.jsonl index 0a887be71..fc8c0b2c9 100644 --- a/src/__tests__/scenarios/data/air/plan-deltas-and-turn-plan.jsonl +++ b/src/__tests__/scenarios/data/air/plan-deltas-and-turn-plan.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/plan-review-permission.jsonl b/src/__tests__/scenarios/data/air/plan-review-permission.jsonl index 494435ab5..809111928 100644 --- a/src/__tests__/scenarios/data/air/plan-review-permission.jsonl +++ b/src/__tests__/scenarios/data/air/plan-review-permission.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"plan","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/plan-stream.jsonl b/src/__tests__/scenarios/data/air/plan-stream.jsonl index ed473ffe3..07c594b58 100644 --- a/src/__tests__/scenarios/data/air/plan-stream.jsonl +++ b/src/__tests__/scenarios/data/air/plan-stream.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/read-search-list.jsonl b/src/__tests__/scenarios/data/air/read-search-list.jsonl index ca1290ce4..71a0ed5e3 100644 --- a/src/__tests__/scenarios/data/air/read-search-list.jsonl +++ b/src/__tests__/scenarios/data/air/read-search-list.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/subagent-activity.jsonl b/src/__tests__/scenarios/data/air/subagent-activity.jsonl index 97d907598..9e2b39fc7 100644 --- a/src/__tests__/scenarios/data/air/subagent-activity.jsonl +++ b/src/__tests__/scenarios/data/air/subagent-activity.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/data/air/web-search.jsonl b/src/__tests__/scenarios/data/air/web-search.jsonl index 1edd84d6c..f5cd3f64a 100644 --- a/src/__tests__/scenarios/data/air/web-search.jsonl +++ b/src/__tests__/scenarios/data/air/web-search.jsonl @@ -1,4 +1,4 @@ -{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} +{"direction":"response","method":"initialize","params":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","diffPatch","agentFileChangeReport","customInstructions","nativeSubagentSessions","asyncTasks","recommendedValue","rawInputRendering","planContentDelta","codexHooks","historyTail"],"goal":{"actions":["set","pause","resume","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":false,"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"subagents":{},"systemPrompt":{},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/codex-acp","title":"Codex","version":""},"authMethods":[{"_meta":{"api-key":{"provider":"openai"}},"description":"Use an API key to authenticate","id":"api-key","name":"API Key"},{"description":"Use ChatGPT to authenticate","id":"chat-gpt","name":"ChatGPT"},{"description":"Sign in to ChatGPT by opening a verification page and entering a one-time code","id":"chat-gpt-device-code","name":"ChatGPT (device code)"}],"protocolVersion":1}} {"direction":"notify","method":"_auth/status_update","params":{"authStatus":{"kind":"none","label":"Not logged in"}}} {"direction":"notify","method":"auth/status_update","params":{"state":"not_required"}} {"direction":"response","method":"session/new","params":{"configOptions":[{"_meta":{"jetbrains":{"air":{"recommendedValue":"model-id","version":1}}},"category":"model","currentValue":"model-id","description":"Model Codex uses for the session","id":"model","name":"Model","options":[{"_meta":{"jetbrains":{"air":{"reasoningEfforts":{"recommended":"medium","values":["medium"]},"version":1}}},"description":"model-id model","name":"model-id","value":"model-id"}],"type":"select"},{"_meta":{"jetbrains":{"air":{"recommendedValue":"medium","version":1}}},"category":"thought_level","currentValue":"medium","description":"How much reasoning effort the model should use","id":"reasoning_effort","name":"Reasoning effort","options":[{"description":"Balanced","name":"Medium","value":"medium"}],"type":"select"},{"category":"mode","currentValue":"agent","description":"Approval and sandboxing preset for the session","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","name":"Read-only","value":"read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","name":"Workspace access","value":"workspace-write"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","name":"Auto review","value":"agent"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","name":"Full access","value":"agent-full-access"}],"type":"select"},{"category":"collaboration_mode","currentValue":"default","description":"How Codex collaborates for subsequent turns","id":"collaboration_mode","name":"Collaboration mode","options":[{"name":"Default","value":"default"},{"description":"Plan before making changes","name":"Plan","value":"plan"}],"type":"select"}],"models":{"availableModels":[{"description":"model-id model Balanced","modelId":"model-id[medium]","name":"model-id (medium)"}],"currentModelId":"model-id[medium]"},"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Requires approval to edit files and access the internet.","id":"read-only","name":"Read-only"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Edit workspace files; ask before writing outside the workspace or accessing the network.","id":"workspace-write","name":"Workspace access"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Only ask for actions detected as potentially unsafe","id":"agent","name":"Auto review"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Unrestricted access to the internet and any file on your computer","id":"agent-full-access","name":"Full access"}],"currentModeId":"agent"},"sessionId":"session-1"}} diff --git a/src/__tests__/scenarios/scenario-harness.ts b/src/__tests__/scenarios/scenario-harness.ts index 583cf6c41..0e744956f 100644 --- a/src/__tests__/scenarios/scenario-harness.ts +++ b/src/__tests__/scenarios/scenario-harness.ts @@ -30,6 +30,7 @@ export const AIR_CAPABILITY_NAMES = [ "rawInputRendering", "planContentDelta", "codexHooks", + "historyTail", ]; /** The client capabilities of each client profile. */ From b3b2c9af3698748b89e07f3508a94e2616caebcb Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Sun, 29 Nov 2026 08:20:47 +0100 Subject: [PATCH 2/3] fix: keep the history tail signature right for legacy threads and process exits - A legacy thread whose newest turn has no item yet now takes the newest item of an earlier turn for its signature. Before, the signature never matched, and each tail replayed the whole history. - The signature of a legacy subagent now names its last item and a rolling hash of all the items of its newest turn. A rollback and a new run that end with the same item now answer `rewritten`, not `unchanged`. - An exit of the Codex process during a read now fails the tail with the retryable `history_read_failed` error, as other failed reads do. --- docs/air-extensions.md | 6 ++- src/CodexAcpClient.ts | 35 ++++++++++++---- src/CodexAcpServer.ts | 7 ++-- src/HistoryTail.ts | 32 +++++++++++--- .../CodexACPAgent/history-tail.test.ts | 42 +++++++++++++++++-- 5 files changed, 101 insertions(+), 21 deletions(-) diff --git a/docs/air-extensions.md b/docs/air-extensions.md index fa37de282..4d0103521 100644 --- a/docs/air-extensions.md +++ b/docs/air-extensions.md @@ -1612,8 +1612,10 @@ The cursor is opaque to the client: A rollback that leaves an item with the same id and content then gives another name, and the answer is `rewritten`. - `end`, `turn` and `c` are the signature of a read of the whole history. A load replay end has no signature, so the first tail after a load reads the whole history. `c` holds each subagent that had not ended, and each ended subagent with a queued interaction that started no turn yet. - On a legacy thread, `end` and `c` name an item by its id and a hash of its content: Codex appends to the last reasoning item in place. - Such an append makes the next tail `rewritten`. + On a legacy thread, `end` names an item by its id and a hash of its content: Codex appends to the last reasoning item in place. + Such an append makes the next tail `rewritten`. A newest turn with no item yet takes the newest item of an earlier turn. + On a legacy thread, `c` names the last item of the subagent and a rolling hash of all the items of its newest turn. + So a rollback and a new run of the subagent that end with the same item still change `c`. - `p` names the kept replay of a page with `more`. `q` holds where the page ended in that replay and the positions of the first page. So the next page goes on in the same replay, and the pages together give what one answer with no `limit` gives. A page goes on only in the replay that `p` names. When the agent no longer keeps that replay, the page answers `rewritten`, and the client reads the whole history again. diff --git a/src/CodexAcpClient.ts b/src/CodexAcpClient.ts index 65573145d..e79fa9330 100644 --- a/src/CodexAcpClient.ts +++ b/src/CodexAcpClient.ts @@ -17,7 +17,7 @@ import type { ExperimentalTurnStartParams, } from "./CodexAppServerClient"; import {withHistoryTimeout} from "./CodexAppServerClient"; -import {itemIdentity} from "./HistoryTail"; +import {itemIdentity, turnItemsIdentity} from "./HistoryTail"; import type {McpServerStartupWaitOptions, McpStartupResult} from "./mcp/McpStartupTracker"; import open from "open"; import type {Disposable} from "vscode-jsonrpc"; @@ -906,21 +906,23 @@ export class CodexAcpClient { * tells that the newest turn can still run, see {@link isTurnOpen}. * * A legacy thread has no `thread/items/list`, so its newest item comes from the newest - * turn with its items. Each request fails when Codex does not answer in time. + * turn with its items, or from an earlier turn when the newest turn has none. With `child`, + * the item of a legacy subagent is the `turnItemsIdentity` of its newest turn. Each request + * fails when Codex does not answer in time. * * A thread that Codex cannot read, such as a subagent thread with no rollout yet, has no * item and no turn, as {@link readSessionHistory} and the replay of a subagent give none. */ - async readSessionHead(threadId: string, legacy: boolean): Promise<{item: string; turn: string; turnOpen: boolean}> { + async readSessionHead(threadId: string, legacy: boolean, child = false): Promise<{item: string; turn: string; turnOpen: boolean}> { try { - return await this.readSessionHeadOnce(threadId, legacy); + return await this.readSessionHeadOnce(threadId, legacy, child); } catch (error) { if (!isNoRolloutOfThreadError(error, threadId)) throw error; return {item: "", turn: "", turnOpen: false}; } } - private async readSessionHeadOnce(threadId: string, legacy: boolean): Promise<{item: string; turn: string; turnOpen: boolean}> { + private async readSessionHeadOnce(threadId: string, legacy: boolean, child: boolean): Promise<{item: string; turn: string; turnOpen: boolean}> { const turns = await withHistoryTimeout(this.codexClient.threadTurnsList({ threadId, cursor: null, @@ -930,9 +932,11 @@ export class CodexAcpClient { }), "thread/turns/list", threadId); const turn = turns.data[0]; let item = ""; - if (legacy) { - const last = turn?.items.at(-1); - item = last ? itemIdentity(last, true) : ""; + if (legacy && child) { + // The session of a subagent is one turn, so its signature names all the items of the newest turn. + item = turnItemsIdentity(turn?.items ?? [], true); + } else if (legacy) { + item = await this.newestLegacyItem(threadId, turn?.items.at(-1), turns.nextCursor); } else { const items = await withHistoryTimeout( this.codexClient.threadItemsList({threadId, cursor: null, limit: 1, sortDirection: "desc"}), @@ -948,6 +952,21 @@ export class CodexAcpClient { }; } + /** + * The {@link itemIdentity} of the newest item of a legacy thread: `last`, the newest item of the newest turn, or else + * the newest item of an earlier turn. A turn that just started has no item yet. + */ + private async newestLegacyItem(threadId: string, last: ThreadItem | undefined, cursor: string | null): Promise { + while (!last && cursor !== null) { + const page: {data: Turn[]; nextCursor: string | null} = await withHistoryTimeout(this.codexClient.threadTurnsList({ + threadId, cursor, limit: 10, sortDirection: "desc", itemsView: "full", + }), "thread/turns/list", threadId); + last = page.data.find(turn => turn.items.length > 0)?.items.at(-1); + cursor = page.nextCursor; + } + return last ? itemIdentity(last, true) : ""; + } + /** * The items of the turn at `index` of a session, oldest first, in pages. * Returns null when the session has fewer turns, or when Codex has no rollout of it for the first turn. diff --git a/src/CodexAcpServer.ts b/src/CodexAcpServer.ts index c3bd6bacb..62388dfc5 100644 --- a/src/CodexAcpServer.ts +++ b/src/CodexAcpServer.ts @@ -2187,7 +2187,7 @@ export class CodexAcpServer { if (thread.id !== sessionId) throw sessionNotFoundRequestError(sessionId); return thread.historyMode === "legacy"; }, - head: (threadId, legacy) => client.readSessionHead(threadId, legacy), + head: (threadId, legacy, child) => client.readSessionHead(threadId, legacy, child), replay: recorder => this.replayDetachedHistory(sessionId, cwd, recorder), }, signal)); logger.log("History tail read", { @@ -2200,8 +2200,9 @@ export class CodexAcpServer { return answer; } catch (error) { const refused = storedSessionError(sessionId, error, this.sessionIndex.enabled); - // A thread that Codex does not have is -32002. Each other failed read can pass on a later try. - if (refused instanceof RequestError) throw refused; + // A thread that Codex does not have is -32002. Each other failed read can pass on a later try, also one + // that the exit of the Codex process failed. + if (refused instanceof RequestError && refused.code !== CODEX_PROCESS_EXITED_ERROR_CODE) throw refused; logger.error(`Failed to read the history tail of ${sessionId}`, error); throw historyReadFailedError(sessionId, {}); } diff --git a/src/HistoryTail.ts b/src/HistoryTail.ts index f8ee41e67..02c5e342d 100644 --- a/src/HistoryTail.ts +++ b/src/HistoryTail.ts @@ -188,6 +188,25 @@ export function itemIdentity(item: {id: string}, legacy: boolean): string { return legacy ? `${item.id}:${contentHash(JSON.stringify(item))}` : item.id; } +/** + * The name of the items of one turn of a subagent in the signature of a cursor: the id of the + * last item. A legacy thread adds a rolling hash of all the items, because a rollback and a + * new run can end with the same last item after other items. + */ +export function turnItemsIdentity(items: readonly {id: string}[], legacy: boolean): string { + const last = items.at(-1); + if (!last) return ""; + if (!legacy) return last.id; + let chain = ""; + for (const item of items) chain = nextChain(chain, item); + return `${last.id}:${chain}`; +} + +/** The rolling hash of the items of a session after `item`. */ +function nextChain(chain: string, item: {id: string}): string { + return contentHash(`${chain}\n${JSON.stringify(item)}`); +} + /** * A {@link ReplaySink} that counts the updates of each session by item. A load uses it to * make the cursor of its load replay end. With `keep`, it also keeps each update and what @@ -227,7 +246,7 @@ export class HistoryRecorder implements ReplaySink { beginItem(sessionId: string, item: {id: string}): void { let name = item.id; if (this.legacy) { - const chain = contentHash(`${this.chains.get(sessionId) ?? ""}\n${JSON.stringify(item)}`); + const chain = nextChain(this.chains.get(sessionId) ?? "", item); this.chains.set(sessionId, chain); name = `${item.id}:${chain}`; } @@ -336,7 +355,10 @@ export class HistoryRecorder implements ReplaySink { record.itemEnd = ends.get(key)!; } const children: Record = {}; - for (const [threadId, sessionId] of this.watchedChildren) children[threadId] = this.lastItems.get(sessionId) ?? ""; + // The session of a subagent is one turn of its thread, see turnItemsIdentity. + for (const [threadId, sessionId] of this.watchedChildren) { + children[threadId] = (this.legacy ? this.currentItems.get(sessionId) : this.lastItems.get(sessionId)) ?? ""; + } return { body: this.body, sessions: this.sessions, @@ -510,7 +532,7 @@ export type HistorySource = { /** Reads the metadata of the thread: whether it has a legacy history. Fails for an unknown thread. */ legacy(): Promise; /** The newest item and turn of `threadId`. */ - head(threadId: string, legacy: boolean): Promise; + head(threadId: string, legacy: boolean, child: boolean): Promise; /** Runs the replay of a `session/load` of the thread into `recorder`, with no session. */ replay(recorder: HistoryRecorder): Promise; }; @@ -552,7 +574,7 @@ export class HistoryTails { const head = (threadId: string): Promise => { let read = heads.get(threadId); if (!read) { - read = source.head(threadId, legacy); + read = source.head(threadId, legacy, threadId !== params.sessionId); // A failed read of a subagent gives the head of no thread: a changed head replays, and the replay reports the failure. if (threadId !== params.sessionId) { read = read.catch(error => { @@ -581,7 +603,7 @@ export class HistoryTails { return {status: "unchanged", cursor: {...cursor as HistoryCursor, turnOpen}, turnOpen, updates: []}; } const key = JSON.stringify([params.sessionId, params.cwd]); - const fresh = () => this.sharedReplay(key, params.sessionId, () => source.head(params.sessionId, legacy), source, signal, startedAt); + const fresh = () => this.sharedReplay(key, params.sessionId, () => source.head(params.sessionId, legacy, false), source, signal, startedAt); const limit = params.limit ?? DEFAULT_HISTORY_TAIL_LIMIT; const kept = this.kept.get(key); // A page goes on in the replay of its read. A read after a cursor uses the kept replay while its signature holds. diff --git a/src/__tests__/CodexACPAgent/history-tail.test.ts b/src/__tests__/CodexACPAgent/history-tail.test.ts index 651e244b5..948ddb763 100644 --- a/src/__tests__/CodexACPAgent/history-tail.test.ts +++ b/src/__tests__/CodexACPAgent/history-tail.test.ts @@ -111,11 +111,13 @@ class ThreadStore { return {data: entries.slice(start, end), nextCursor: end < entries.length ? `asc:${end}` : null, backwardsCursor: null}; }; - turnsList = async ({limit, sortDirection, itemsView}: ThreadTurnsListParams) => { + turnsList = async ({cursor, limit, sortDirection, itemsView}: ThreadTurnsListParams) => { const full = itemsView === "full"; if (sortDirection === "desc") { - const data = this.turns.slice(-(limit ?? 1)).reverse().map(turn => this.turn(turn, full)); - return {data, nextCursor: null, backwardsCursor: null}; + const start = typeof cursor === "string" ? Number(cursor.slice("desc:".length)) : 0; + const end = start + (limit ?? 1); + const data = [...this.turns].reverse().slice(start, end).map(turn => this.turn(turn, full)); + return {data, nextCursor: end < this.turns.length ? `desc:${end}` : null, backwardsCursor: null}; } return {data: this.turns.map(turn => this.turn(turn, full)), nextCursor: null, backwardsCursor: null}; }; @@ -720,6 +722,40 @@ describe("_session/history_tail", () => { expect(await setup.tail(load.cursor)).toMatchObject({status: "ok", turnOpen: false, cursor: {turnOpen: false}}); }); + it("answers unchanged for a legacy thread whose newest turn has no item yet", async () => { + const store = new ThreadStore([messageTurn("first"), {id: "second", completedAt: null, items: []}], "legacy"); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(whole.cursor.end).toMatch(/^first-answer:/); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged", turnOpen: true}); + }); + + it("answers rewritten when a legacy subagent runs again after a rollback and ends with the same item", async () => { + const store = new ThreadStore([{id: "rollout-1", completedAt: null, items: [ + userMessage("item-1", "Delegate"), subagentActivity("item-2", "started", "child-a"), + ]}], "legacy"); + const childA = new ThreadStore([{id: "rollout-1", completedAt: null, items: [ + userMessage("item-1", "Look at the tests"), agentMessage("item-2", "Done"), + ]}], "legacy", "child-a"); + const setup = await initialized(setUp(store, childA), subagentCapabilities); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + expect(await setup.tail(whole.cursor)).toMatchObject({status: "unchanged"}); + + // The rollback and the new run keep the turn and the last item, but not the items before it. + childA.turns = [{id: "rollout-1", completedAt: null, items: [userMessage("item-1", "Look at the docs"), agentMessage("item-2", "Done")]}]; + expect(await setup.tail(whole.cursor)).toEqual({status: "rewritten", updates: []}); + }); + + it("fails with the retryable error when the Codex process exits during a read", async () => { + const store = new ThreadStore([messageTurn("first")]); + const setup = await initialized(setUp(store)); + (setup.agent as any).getExitCode = () => 1; + setup.read.mockRejectedValueOnce(new Error("connection closed")); + await expect(setup.tail()).rejects.toMatchObject({code: -32603, data: {reason: "history_read_failed", retryable: true, sessionId: threadId}}); + }); + it("tells an open turn by its status and its end time", async () => { const store = new ThreadStore([messageTurn("first"), {...messageTurn("second", null), status: "failed"}]); const setup = await initialized(setUp(store)); From c6c36a650d7a40955b7d7118eca00a3de0b3cf83 Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Sun, 29 Nov 2026 08:32:14 +0100 Subject: [PATCH 3/3] fix: stop the legacy head paging on a repeated cursor and keep the cause of a process exit The paging back to the newest item of a legacy thread had no guard for a repeated cursor, so a bad cursor from Codex made the read loop forever. It now fails the read, which gives the retryable history error. When an exit of the Codex process fails a history tail read, the history_read_failed error now keeps the code, the message and the data of the exit error in data.cause. The client can see restartable and retryAfterMs and stop when a later try does not help. --- docs/air-extensions.md | 2 ++ src/CodexAcpClient.ts | 6 +++- src/CodexAcpServer.ts | 6 +++- src/HistoryTail.ts | 13 +++++++-- .../CodexACPAgent/history-tail.test.ts | 28 ++++++++++++++++++- 5 files changed, 49 insertions(+), 6 deletions(-) diff --git a/docs/air-extensions.md b/docs/air-extensions.md index 4d0103521..3bfb448b6 100644 --- a/docs/air-extensions.md +++ b/docs/air-extensions.md @@ -1589,6 +1589,8 @@ Answer: - A failed read fails the whole tail with `-32603` and `data` `{"reason": "history_read_failed", "retryable": true, "sessionId": "…", "threadIds": ["…"]}`. This covers each read of the root thread, of a subagent thread, and of `model/list`. `threadIds` names the subagent threads whose read failed. A failed `model/list` adds `"models": true`: the model reports of the subagents need the models. + An exit of the Codex process adds `cause`: the code, the message and the data of the exit error, such as `restartable` and `retryAfterMs`. + A `cause` with `restartable` `false` tells the client that a later try does not help. A root thread that Codex does not have is not such a failure: the tail answers `-32002`. The error has no updates and no cursor. The client keeps its cursor and asks again later. The agent keeps no replay of a failed read. A load does not fail: it leaves out the history of such a subagent and logs the failure. diff --git a/src/CodexAcpClient.ts b/src/CodexAcpClient.ts index e79fa9330..ab19c6cb9 100644 --- a/src/CodexAcpClient.ts +++ b/src/CodexAcpClient.ts @@ -954,10 +954,14 @@ export class CodexAcpClient { /** * The {@link itemIdentity} of the newest item of a legacy thread: `last`, the newest item of the newest turn, or else - * the newest item of an earlier turn. A turn that just started has no item yet. + * the newest item of an earlier turn. A turn that just started has no item yet. The read fails when Codex returns a + * cursor a second time. */ private async newestLegacyItem(threadId: string, last: ThreadItem | undefined, cursor: string | null): Promise { + const seenCursors = new Set(); while (!last && cursor !== null) { + if (seenCursors.has(cursor)) throw new Error("Codex returned a repeated thread history cursor"); + seenCursors.add(cursor); const page: {data: Turn[]; nextCursor: string | null} = await withHistoryTimeout(this.codexClient.threadTurnsList({ threadId, cursor, limit: 10, sortDirection: "desc", itemsView: "full", }), "thread/turns/list", threadId); diff --git a/src/CodexAcpServer.ts b/src/CodexAcpServer.ts index 62388dfc5..20ca827c8 100644 --- a/src/CodexAcpServer.ts +++ b/src/CodexAcpServer.ts @@ -2204,7 +2204,11 @@ export class CodexAcpServer { // that the exit of the Codex process failed. if (refused instanceof RequestError && refused.code !== CODEX_PROCESS_EXITED_ERROR_CODE) throw refused; logger.error(`Failed to read the history tail of ${sessionId}`, error); - throw historyReadFailedError(sessionId, {}); + // The cause of an exit of the Codex process tells whether a restart can help. + const cause = refused instanceof RequestError + ? {code: refused.code, message: refused.message, ...(refused.data !== undefined ? {data: refused.data} : {})} + : undefined; + throw historyReadFailedError(sessionId, cause ? {cause} : {}); } } diff --git a/src/HistoryTail.ts b/src/HistoryTail.ts index 02c5e342d..611db8128 100644 --- a/src/HistoryTail.ts +++ b/src/HistoryTail.ts @@ -484,11 +484,18 @@ export function historyTailAnswer( /** * The error of a tail whose replay failed to read a subagent thread or the models: `-32603` - * with `data.retryable` `true`. The client keeps its cursor and asks again later. + * with `data.retryable` `true`. The client keeps its cursor and asks again later. `cause` + * holds the code, the message and the data of an exit of the Codex process. */ -export function historyReadFailedError(sessionId: string, failed: {threadIds?: string[]; models?: true}): acp.RequestError { +export function historyReadFailedError( + sessionId: string, + failed: {threadIds?: string[]; models?: true; cause?: {code: number; message: string; data?: unknown}}, +): acp.RequestError { return acp.RequestError.internalError( - {reason: "history_read_failed", retryable: true, sessionId, threadIds: failed.threadIds ?? [], ...(failed.models ? {models: true} : {})}, + { + reason: "history_read_failed", retryable: true, sessionId, threadIds: failed.threadIds ?? [], + ...(failed.models ? {models: true} : {}), ...(failed.cause ? {cause: failed.cause} : {}), + }, "The history tail failed to read the history. Ask again later.", ); } diff --git a/src/__tests__/CodexACPAgent/history-tail.test.ts b/src/__tests__/CodexACPAgent/history-tail.test.ts index 948ddb763..829231507 100644 --- a/src/__tests__/CodexACPAgent/history-tail.test.ts +++ b/src/__tests__/CodexACPAgent/history-tail.test.ts @@ -753,7 +753,33 @@ describe("_session/history_tail", () => { const setup = await initialized(setUp(store)); (setup.agent as any).getExitCode = () => 1; setup.read.mockRejectedValueOnce(new Error("connection closed")); - await expect(setup.tail()).rejects.toMatchObject({code: -32603, data: {reason: "history_read_failed", retryable: true, sessionId: threadId}}); + await expect(setup.tail()).rejects.toMatchObject({code: -32603, data: { + reason: "history_read_failed", retryable: true, sessionId: threadId, + cause: {code: 1001, message: expect.stringContaining("Codex process has exited")}, + }}); + }); + + it("keeps the data of a process exit in the cause of the retryable error", async () => { + const store = new ThreadStore([messageTurn("first")]); + const setup = await initialized(setUp(store)); + const exit = new acp.RequestError(1001, "Codex process has exited", {restartable: false, retryAfterMs: 5000}); + setup.read.mockRejectedValueOnce(exit); + await expect(setup.tail()).rejects.toMatchObject({code: -32603, data: { + reason: "history_read_failed", retryable: true, + cause: {code: 1001, message: "Codex process has exited", data: {restartable: false, retryAfterMs: 5000}}, + }}); + }); + + it("fails with the retryable error when Codex repeats a cursor of the turns of a legacy thread", async () => { + const store = new ThreadStore([messageTurn("first"), {id: "second", completedAt: null, items: []}], "legacy"); + const setup = await initialized(setUp(store)); + const whole = await setup.tail(); + if (whole.status !== "ok") throw new Error(`unexpected ${whole.status}`); + const empty = {id: "second", items: [], status: "inProgress", error: null, startedAt: null, completedAt: null, durationMs: null}; + setup.turns.mockImplementation(async params => params.sortDirection === "desc" + ? {data: [empty], nextCursor: "desc:1", backwardsCursor: null} as any + : store.turnsList(params)); + await expect(setup.tail(whole.cursor)).rejects.toMatchObject({code: -32603, data: {reason: "history_read_failed", retryable: true}}); }); it("tells an open turn by its status and its end time", async () => {