mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-17 14:51:13 +00:00
fix: update to @agentclientprotocol/sdk 2.7.0 (#1629)
Updates `@agentclientprotocol/sdk` from 2.6.0 to 2.7.0 (schema v1.32.0 and v2.0.0-alpha.16), and follows the two protocol changes that affect what the adapter already serves. The SDK's runtime is unchanged apart from an SSE BOM fix. The rest of the release is schema and doc comments, so I read the protocol docs and RFDs between the two schema tags for behavior changes. ## Changes ### `configOptions` on `session/fork` (v1 and v2) `ForkSessionRequest` now has `configOptions`, and clients may send it to an agent that advertises `options`. The adapter advertises `fork` and `options`, so both cores accept it: - Two entries with the same `configId` fail with `-32602` before the transcript is copied. On v2, so does a value type that `session/set_config_option` does not take. - The entries are set on the started fork, in list order, over what the copy starts with. An entry that the session refuses is skipped, as on `session/new`. - No update goes out for them. The response carries the options. This was the only compile break: `v1ForkSessionRequest` passed the v2 entries on to the v1 request. ### `replay_complete` on v2 v2 now requires a `replay_complete` update after the history replay of a `session/resume` with `replayFrom`, and allows only replayed history between the request and that update. - The adapter sends it on the resumed session after the last replayed update, also for an empty history. It does not send it without `replayFrom`, or when the resume fails. - Each subagent session that the replay announces gets its own `replay_complete`, also one without history. - A replayed child's `state_update` now follows the child's `replay_complete`, and the notice that subagent history is missing follows the root's. Neither is history. - AIR's `loadReplayEnd` update is still sent to a v2 client that declares it, right after `replay_complete`. ### Holding live updates during a replay (new mechanism) From the request to `replay_complete`, a session can only send its replay. An active session keeps working while it is resumed, and a session that starts sends its first updates while the transcript is read. So the adapter needs a place to hold them. No existing mechanism did this. `src/v2/replay-hold.ts` holds every update of the session and of its subagent sessions that is not the replay, and their permission requests and elicitations, and sends them after `replay_complete` in the order they were sent. `V2Agent.send` is the one place where v2 session updates leave the agent, so the hold sits there. The replay runs in one synchronous step, so what a session sends during that step is its replay. Nothing else tells the two apart. The comment in the module says so. A resume of an active session now reads the transcript before its other steps, so the history ends as close to the request as it can. ## Already compliant, checked - Initial config values: no notice or mode update before the setup response, and a value that Claude Code refuses is skipped. - `auth/logout` is idempotent, because `claude auth logout` is. - A `tool_call/cancel` or `terminal/cancel` sent again after the item ended gets `-32602`. - The subagent clarifications: no assumed `senderSessionId`, session references sent again with new tool call content, and `unknown` for a child that can no longer be observed. - `thought_level` values go from lowest to highest. This rests on Claude Code's order, which a comment now says. ## Not covered - An active session that streams while it is resumed with a replay: if Claude Code writes a block to the transcript during the few milliseconds of the read, the held chunks of that block reach the client twice. I found no cheap way to close that window. - The new RFD features are left for separate PRs: the `speed` config category for Fast mode, `prompt_suggestions_update`, v2 skills, and `path` on markdown plans (the `file` plan type is gone, and the adapter never sent it). - I did not run the integration tests against the real CLI. ## Tests - `create-session-options.test.ts` (v1) and `v2.test.ts` (v2): a fork sets its `configOptions`, and rejects duplicates before the copy. - `v2.test.ts`: `replay_complete` for an empty history and none without `replayFrom`. What an active session sends during a replay goes out after `replay_complete`, a permission request too, and goes out without one when the replay fails. The same for a live subagent's session. - The existing replay tests and the `session-load-replay` golden file now include `replay_complete`. `npm run build`, `npm run check` and `npm run test:run` pass (4142 tests).
This commit is contained in:
@@ -64,9 +64,9 @@ for v2 is negotiated down to v1. With `v2`, the adapter rejects the `initialize`
|
||||
`auto`, the default, serves both.
|
||||
|
||||
On v2 the adapter serves the session baseline (`session/new`, `session/list`, `session/resume`
|
||||
with replay, `session/close`, `session/prompt`, `session/cancel`), `session/delete`,
|
||||
`session/fork`, `session/status`, `session/options` (with initial `configOptions` on `session/new` and
|
||||
`session/resume`), `session/set_title`, additional directories, config options (the mode is one), plans, notices,
|
||||
with replay, which `replay_complete` ends, `session/close`, `session/prompt`, `session/cancel`), `session/delete`,
|
||||
`session/fork`, `session/status`, `session/options` (with initial `configOptions` on `session/new`,
|
||||
`session/resume` and `session/fork`), `session/set_title`, additional directories, config options (the mode is one), plans, notices,
|
||||
compaction, display terminals for commands, permission requests, elicitation, providers, auth, and
|
||||
[subagents](docs/subagent-sessions.md). Steering is v1 only for now.
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ The v2 core (`src/v2/`) serves an AIR client only the extensions that ACP v2 doe
|
||||
Its `initialize` response lists `agentFileChangeReport` and `recommendedValue`.
|
||||
It also serves the [permission presentation](#permission-presentation), the [question custom answers](#question-custom-answers), the [predicted follow-up prompt](#predicted-follow-up-prompt), and [load replay end](#load-replay-end).
|
||||
The [agent file-change report](#agent-file-change-report) goes out at the end of the turn that serves the prompt, before the turn's idle `state_update`, because a v2 `session/prompt` is answered when Claude Code takes the prompt in.
|
||||
ACP v2 covers subagents, background work, file plans, patches, compaction, the system prompt, and turn failures itself, so the v2 core serves no `nativeSubagentSessions`, `backgroundSubagents`, `asyncTasks`, `planFile`, `diffPatch`, `contextCompaction`, `customInstructions`, or `sessionFailure`.
|
||||
ACP v2 covers subagents, background work, plans, patches, compaction, the system prompt, and turn failures itself, so the v2 core serves no `nativeSubagentSessions`, `backgroundSubagents`, `asyncTasks`, `planFile`, `diffPatch`, `contextCompaction`, `customInstructions`, or `sessionFailure`.
|
||||
It does not serve the [tool call contract](#tool-call-contract) yet.
|
||||
|
||||
### Capabilities
|
||||
@@ -1732,8 +1732,9 @@ A client that is not AIR gets neither key.
|
||||
|
||||
## Load replay end
|
||||
|
||||
ACP has no signal that the history replay of `session/load` is over, other than the response.
|
||||
ACP v1 has no signal that the history replay of `session/load` is over, other than the response.
|
||||
The adapter replays the transcript while the Claude Code CLI starts, so the history can arrive long before the response.
|
||||
ACP v2 has the `replay_complete` update for this, which the adapter sends to every v2 client.
|
||||
|
||||
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:
|
||||
@@ -1751,7 +1752,7 @@ After the history replay of the loaded session, the agent then sends one more up
|
||||
- The update has no `title` and no `updatedAt`. A `null` there would clear the value.
|
||||
- It comes after every replayed update, the subagent history that the replay sends to the child sessions included, and before the `session/load` response.
|
||||
- It comes also for an empty history.
|
||||
- It comes for `session/load` of a new or an already live session, and for the ACP v2 `session/resume` with `replayFrom: {type: "start"}`.
|
||||
- It comes for `session/load` of a new or an already live session, and for the ACP v2 `session/resume` with `replayFrom: {type: "start"}`. On v2 it comes right after the session's `replay_complete`, which marks the same point.
|
||||
- It does not come when the replay stops or fails. The replay stops when the CLI start fails during the replay.
|
||||
- It does not come for a live update, and it does not come to a client without the capability.
|
||||
- The `session/load` can still fail after it, for example when the CLI start fails after the replay. The event means that the recorded history arrived whole. The client decides what to do with the failed load.
|
||||
|
||||
@@ -82,7 +82,9 @@ Task subagent as its own child session, following the [subagents RFD](https://gi
|
||||
|
||||
An [ACP v2](../README.md#experimental-acp-v2) client gets the same without declaring anything, since subagents
|
||||
are part of v2's baseline. Each child also reports its work state as its own `state_update`, right
|
||||
after the parent's copy.
|
||||
after the parent's copy. A replay ends each child's history with a `replay_complete` on the child's
|
||||
session, before the child's `idle`. The notice that subagent history is missing follows the
|
||||
parent's `replay_complete`.
|
||||
|
||||
JetBrains AIR keeps the earlier draft of the RFD (`subagent_spawned`, `subagent_state_update`),
|
||||
which it enables with `nativeSubagentSessions` in `_meta.jetbrains.air.capabilities`. See
|
||||
|
||||
8
package-lock.json
generated
8
package-lock.json
generated
@@ -9,7 +9,7 @@
|
||||
"version": "0.107.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.6.0",
|
||||
"@agentclientprotocol/sdk": "2.7.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.323",
|
||||
"diff": "9.0.0",
|
||||
"zod": "4.6.7"
|
||||
@@ -38,9 +38,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@agentclientprotocol/sdk": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-2.6.0.tgz",
|
||||
"integrity": "sha512-3FtL6MkAV5F9qxg0FQV8wmBszIm2xuVPoDWOILIFSDQ+Vq3Twdh7Cw6Hk2GOPUbevgrTUpUAqZXQy7Geaj79mw==",
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-2.7.0.tgz",
|
||||
"integrity": "sha512-oXdQq0plWv3iOg01zJghNZRSuyWeMYxOgWIaSdwg1BZe2ZAC9LRhNDi023lNYxXq1zVIpQjIp8P6AfsxpvxF6g==",
|
||||
"license": "Apache-2.0",
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/server": "^2.4.0",
|
||||
|
||||
@@ -68,7 +68,7 @@
|
||||
"node": ">=22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.6.0",
|
||||
"@agentclientprotocol/sdk": "2.7.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.323",
|
||||
"diff": "9.0.0",
|
||||
"zod": "4.6.7"
|
||||
|
||||
@@ -8,7 +8,8 @@ import type { Logger } from "./logger.js";
|
||||
|
||||
/**
|
||||
* What a core advertises as `options` in its session capabilities:
|
||||
* `session/options`, and `configOptions` on its setup requests.
|
||||
* `session/options`, and `configOptions` on its setup requests, `session/fork`
|
||||
* included.
|
||||
*/
|
||||
export const SESSION_OPTIONS_CAPABILITY = {};
|
||||
|
||||
|
||||
@@ -110,6 +110,9 @@ export function buildEffortConfigOption(
|
||||
useRecommendedValue: boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
const currentModelInfo = modelInfos.find((model) => model.value === currentModelId);
|
||||
// In Claude Code's order, which lists the levels from lowest to highest
|
||||
// ("low" to "max"), as ACP v2 asks of a `thought_level` select. Nothing
|
||||
// here sorts them.
|
||||
const supportedLevels = currentModelInfo?.supportsEffort
|
||||
? (currentModelInfo.supportedEffortLevels ?? [])
|
||||
: [];
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"content":{"text":"Report.","type":"text"},"type":"content"}],"rawOutput":"Report.","sessionUpdate":"tool_call_update","status":"completed","toolCallId":"toolu_r_task"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[],"messageId":"msg_r2","sessionUpdate":"agent_message"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":{"text":"Fixed.","type":"text"},"messageId":"msg_r2","sessionUpdate":"agent_message_chunk"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"sessionUpdate":"replay_complete"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"description":"The history of 1 subagent of this session could not be restored.","sessionUpdate":"notice","severity":"info","title":"Some subagent history is not available"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"sessionUpdate":"session_info_update","title":"Fix the app","updatedAt":"2026-01-01T00:00:00.000Z"}}}
|
||||
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"idle"}}}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
SessionNotification,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
|
||||
import { getSessionMessages, type Options } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { forkSession, getSessionMessages, type Options } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { ClaudeAcpAgent as ClaudeAcpAgentType } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import type { AcpSessionNotification } from "../../acp-subagents.js";
|
||||
@@ -16,6 +16,9 @@ import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
/** The session that the mocked SDK `forkSession` makes. */
|
||||
const FORK_ID = "3d0f7a52-9b1e-4c7d-8e2a-6f4b5c1d0e9a";
|
||||
|
||||
let capturedOptions: Options | undefined;
|
||||
let contextUsageResult: (() => Promise<{ rawMaxTokens: number; model?: string }>) | undefined;
|
||||
let contextUsageCalls: Array<{ detail?: "summary" | "full" } | undefined> = [];
|
||||
@@ -61,6 +64,7 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
|
||||
});
|
||||
},
|
||||
getSessionMessages: vi.fn(() => sessionMessagesResult()),
|
||||
forkSession: vi.fn(async () => ({ sessionId: FORK_ID })),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -105,6 +109,7 @@ describe("createSession options merging", () => {
|
||||
sessionMessages = [];
|
||||
sessionMessagesResult = async () => sessionMessages;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
vi.mocked(forkSession).mockClear();
|
||||
initModels = undefined;
|
||||
initGate = undefined;
|
||||
initError = undefined;
|
||||
@@ -1525,7 +1530,7 @@ describe("createSession options merging", () => {
|
||||
errors.mockRestore();
|
||||
});
|
||||
|
||||
it.each(["newSession", "loadSession", "resumeSession"] as const)(
|
||||
it.each(["newSession", "loadSession", "resumeSession", "unstable_forkSession"] as const)(
|
||||
"%s rejects two entries of one configId before it starts a query",
|
||||
async (method) => {
|
||||
await expect(
|
||||
@@ -1543,6 +1548,8 @@ describe("createSession options merging", () => {
|
||||
data: { configId: "mode" },
|
||||
});
|
||||
expect(capturedOptions).toBeUndefined();
|
||||
// A fork copies no transcript either.
|
||||
expect(forkSession).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1571,6 +1578,24 @@ describe("createSession options merging", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("sets the configOptions of a session/fork on the fork, without an update", async () => {
|
||||
const response = await agent.unstable_forkSession({
|
||||
sessionId: "7f1c5b0e-3c53-4c0c-9d0a-0d6c1f0a2b11",
|
||||
cwd,
|
||||
mcpServers: [],
|
||||
configOptions: [
|
||||
{ configId: "model", value: "claude-haiku-4-5" },
|
||||
{ configId: "mode", value: "plan" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response.sessionId).toBe(FORK_ID);
|
||||
expect(capturedOptions).toMatchObject({ resume: FORK_ID });
|
||||
expect(values(response)).toMatchObject({ model: "claude-haiku-4-5", mode: "plan" });
|
||||
expect(response.modes?.currentModeId).toBe("plan");
|
||||
expect(updates.filter((u) => u.sessionId === FORK_ID)).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves the warning of an Auto mode fallback for the first prompt", async () => {
|
||||
const response = await agent.newSession({
|
||||
cwd,
|
||||
|
||||
@@ -2360,8 +2360,9 @@ describe("ACP v2 prompts", () => {
|
||||
sessionId === "abc123" || sessionId === "response" ? [update] : [],
|
||||
);
|
||||
// The child's past `running` does not replay; its last state goes once,
|
||||
// after the replay. That state is history to the client, so the child's
|
||||
// current state follows the response: its process is gone, so it is idle.
|
||||
// after the child's own `replay_complete`. That state is history to the
|
||||
// client, so the child's current state follows the response: its process
|
||||
// is gone, so it is idle.
|
||||
// The child's model, from its transcript, goes right after its
|
||||
// announcement. It does not go again after the response: it is unchanged.
|
||||
const model = expect.objectContaining({
|
||||
@@ -2380,6 +2381,7 @@ describe("ACP v2 prompts", () => {
|
||||
messageId: "msg_child",
|
||||
content: text("Child report.")[0],
|
||||
}),
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
{ sessionUpdate: "state_update", state: "idle", stopReason: "end_turn", background: [] },
|
||||
{ sessionUpdate: "response" },
|
||||
{ sessionUpdate: "state_update", state: "idle", stopReason: "end_turn", background: [] },
|
||||
@@ -2520,7 +2522,7 @@ describe("ACP v2 prompts", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends a resume with replay with one end event for a client with loadReplayEnd", async () => {
|
||||
it("ends a resume with replay with one end event after replay_complete for a client with loadReplayEnd", async () => {
|
||||
const client = v2Client();
|
||||
const isEnd = (notification: v2.UpdateSessionNotification) =>
|
||||
(notification.update._meta as any)?.jetbrains?.air?.loadReplayEnd === true;
|
||||
@@ -2552,13 +2554,15 @@ describe("ACP v2 prompts", () => {
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
// The end event closes the replay. v2 then requires the state snapshot
|
||||
// after the replay and before the response.
|
||||
// `replay_complete` closes the replay, and AIR's end event follows it:
|
||||
// it is not history. v2 then requires the state snapshot after the replay
|
||||
// and before the response.
|
||||
expect(atResponse.map(({ update }) => update.sessionUpdate)).toEqual([
|
||||
"user_message",
|
||||
"user_message_chunk",
|
||||
"agent_message",
|
||||
"agent_message_chunk",
|
||||
"replay_complete",
|
||||
"session_info_update",
|
||||
"state_update",
|
||||
]);
|
||||
@@ -2759,6 +2763,7 @@ describe("ACP v2 prompts", () => {
|
||||
summary: text("1. Primary Request and Intent:\n Count upward."),
|
||||
},
|
||||
{ sessionUpdate: "agent_message", messageId: "msg_after", content: [] },
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
]);
|
||||
await client.authUpdate(1);
|
||||
@@ -2812,6 +2817,7 @@ describe("ACP v2 prompts", () => {
|
||||
messageId: "msg_answer",
|
||||
content: text("Hello!")[0],
|
||||
},
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
// The current foreground state, after the replay and before the response.
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
]);
|
||||
@@ -2876,7 +2882,13 @@ describe("ACP v2 prompts", () => {
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
expect(client.sessionUpdates.slice(before).map(({ update }) => update.sessionUpdate)).toEqual(
|
||||
["agent_message", "agent_message_chunk", "session_info_update", "state_update"],
|
||||
[
|
||||
"agent_message",
|
||||
"agent_message_chunk",
|
||||
"replay_complete",
|
||||
"session_info_update",
|
||||
"state_update",
|
||||
],
|
||||
);
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import * as path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
|
||||
import {
|
||||
forkSession,
|
||||
getSessionInfo,
|
||||
getSessionMessages,
|
||||
type Options,
|
||||
@@ -217,6 +218,7 @@ beforeEach(async () => {
|
||||
sdk.startFailure = undefined;
|
||||
sdk.startGate = undefined;
|
||||
sdk.enableRemoteControl = undefined;
|
||||
vi.mocked(forkSession).mockClear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -2032,6 +2034,11 @@ describe("ACP v2 core", () => {
|
||||
cwd,
|
||||
configOptions,
|
||||
}),
|
||||
agent.request(v2.methods.agent.session.fork, {
|
||||
sessionId: STORED,
|
||||
cwd,
|
||||
configOptions,
|
||||
}),
|
||||
].map((request) => request.catch((error: unknown) => error)),
|
||||
);
|
||||
});
|
||||
@@ -2039,8 +2046,32 @@ describe("ACP v2 core", () => {
|
||||
expect(errors).toEqual([
|
||||
expect.objectContaining({ code: -32602 }),
|
||||
expect.objectContaining({ code: -32602 }),
|
||||
expect.objectContaining({ code: -32602 }),
|
||||
]);
|
||||
expect(sdk.processes).toHaveLength(0);
|
||||
// The fork copied no transcript either.
|
||||
expect(forkSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sets the configOptions of a session/fork on the fork, without an update", async () => {
|
||||
const client = v2Client();
|
||||
const fork = await client.connect(async (agent) => {
|
||||
await initialize(agent);
|
||||
return agent.request(v2.methods.agent.session.fork, {
|
||||
sessionId: STORED,
|
||||
cwd,
|
||||
configOptions: [
|
||||
{ configId: "model", type: "id", value: "haiku" },
|
||||
{ configId: "mode", type: "id", value: "plan" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const [claude] = sdk.processes;
|
||||
expect(claude.options.resume).toBe(fork.sessionId);
|
||||
expect(claude.setModel).toHaveBeenCalledWith("haiku");
|
||||
expect(values(fork.configOptions)).toMatchObject({ model: "haiku", mode: "plan" });
|
||||
expect(client.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("sets the configOptions of a session/resume on the session, an active one too", async () => {
|
||||
@@ -2109,7 +2140,7 @@ describe("ACP v2 core", () => {
|
||||
expect(error).toMatchObject({ code: -32602 });
|
||||
});
|
||||
|
||||
it("replays the stored history, then sends the state, before the resume response", async () => {
|
||||
it("replays the stored history, ends it with replay_complete, then sends the state, before the resume response", async () => {
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce([
|
||||
{
|
||||
type: "user",
|
||||
@@ -2157,12 +2188,13 @@ describe("ACP v2 core", () => {
|
||||
messageId: "msg_a",
|
||||
content: { type: "text", text: "Done" },
|
||||
},
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
// A snapshot, not a completion: no stop reason.
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("gives a replayed tool call that has no result a final status, before the state", async () => {
|
||||
it("gives a replayed tool call that has no result a final status, before replay_complete", async () => {
|
||||
const entry = (type: string, uuid: string, message: unknown) => ({
|
||||
type,
|
||||
uuid,
|
||||
@@ -2194,12 +2226,117 @@ describe("ACP v2 core", () => {
|
||||
});
|
||||
});
|
||||
|
||||
expect(client.sessionUpdates.slice(-2)).toEqual([
|
||||
expect(client.sessionUpdates.slice(-3)).toEqual([
|
||||
{ sessionUpdate: "tool_call_update", toolCallId: "toolu_make", status: "failed" },
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends the replay of an empty history with replay_complete, and sends none without replayFrom", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
await agent.request(v2.methods.agent.initialize, {
|
||||
protocolVersion: v2.PROTOCOL_VERSION,
|
||||
info: { name: "v2-test-client", version: "1.0.0" },
|
||||
capabilities: {},
|
||||
});
|
||||
const sessionId = randomUUID();
|
||||
await agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
|
||||
});
|
||||
|
||||
expect(client.sessionUpdates).toEqual([
|
||||
{ sessionUpdate: "replay_complete" },
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
// The resume without a replay.
|
||||
{ sessionUpdate: "state_update", state: "idle", background: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
describe("what an active session sends while a resume replays it", () => {
|
||||
const kinds = (updates: v2.SessionUpdate[]) => updates.map((update) => update.sessionUpdate);
|
||||
|
||||
/**
|
||||
* Resumes the active session with a replay whose transcript read waits
|
||||
* for `read`. Meanwhile Claude Code streams a message and asks for a
|
||||
* permission. Returns the resume, once the client had time to receive
|
||||
* what the session sent.
|
||||
*/
|
||||
async function resumeWhileWorking(
|
||||
agent: v2.ClientContext,
|
||||
read: Promise<Awaited<ReturnType<typeof getSessionMessages>>>,
|
||||
) {
|
||||
const { response, claude } = await openSession(agent);
|
||||
vi.mocked(getSessionMessages).mockReturnValueOnce(read);
|
||||
const resume = agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId: response.sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
await vi.waitFor(() => expect(getSessionMessages).toHaveBeenCalled());
|
||||
for (const message of textDelta("msg_live", "Live")) claude.send(message);
|
||||
const asked = askPermission(claude, "Bash", { command: "make" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
return { resume, asked };
|
||||
}
|
||||
|
||||
it("goes out after replay_complete, a permission request too", async () => {
|
||||
const read = Promise.withResolvers<Awaited<ReturnType<typeof getSessionMessages>>>();
|
||||
let receivedAtRequest: string[] = [];
|
||||
const client = v2Client({
|
||||
answerPermission: () => {
|
||||
receivedAtRequest = kinds(client.sessionUpdates);
|
||||
return { outcome: { outcome: "cancelled" } };
|
||||
},
|
||||
});
|
||||
await client.connect(async (agent) => {
|
||||
const { resume, asked } = await resumeWhileWorking(agent, read.promise);
|
||||
expect(client.sessionUpdates).toEqual([]);
|
||||
expect(client.permissionRequests).toEqual([]);
|
||||
read.resolve([
|
||||
{
|
||||
type: "user",
|
||||
uuid: "u1",
|
||||
session_id: "s",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { role: "user", content: "Fix the build" },
|
||||
},
|
||||
]);
|
||||
await resume;
|
||||
await asked;
|
||||
});
|
||||
|
||||
const received = kinds(client.sessionUpdates);
|
||||
const complete = received.indexOf("replay_complete");
|
||||
// Only the history comes before it.
|
||||
expect(received.slice(0, complete)).toEqual(["user_message", "user_message_chunk"]);
|
||||
expect(received.slice(complete + 1)).toContain("agent_message_chunk");
|
||||
expect(receivedAtRequest).toContain("replay_complete");
|
||||
});
|
||||
|
||||
it("goes out without a replay_complete when the replay fails", async () => {
|
||||
const read = Promise.withResolvers<Awaited<ReturnType<typeof getSessionMessages>>>();
|
||||
const client = v2Client();
|
||||
const error = await client.connect(async (agent) => {
|
||||
const { resume } = await resumeWhileWorking(agent, read.promise);
|
||||
read.reject(new Error("The transcript cannot be read"));
|
||||
const error = await resume.catch((error: unknown) => error);
|
||||
await vi.waitFor(() => expect(client.permissionRequests).toHaveLength(1));
|
||||
return error;
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({ code: -32603 });
|
||||
expect(kinds(client.sessionUpdates)).toContain("agent_message_chunk");
|
||||
expect(kinds(client.sessionUpdates)).not.toContain("replay_complete");
|
||||
});
|
||||
});
|
||||
|
||||
it("replays a compaction's summary message as the completed compaction, at its place", async () => {
|
||||
const entry = (uuid: string, message: unknown, fields: Record<string, unknown> = {}) => ({
|
||||
type: "user",
|
||||
@@ -3525,6 +3662,68 @@ describe("ACP v2 core", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("holds what a live subagent's session sends during a replay until after the child's replay_complete", async () => {
|
||||
sdk.subagents = new Map([
|
||||
[
|
||||
"toolu_bg_agent",
|
||||
{
|
||||
agentId: "a5966d",
|
||||
background: true,
|
||||
stoppedByUser: false,
|
||||
agentType: "general-purpose",
|
||||
},
|
||||
],
|
||||
]);
|
||||
const client = v2Client();
|
||||
const read = Promise.withResolvers<Awaited<ReturnType<typeof getSessionMessages>>>();
|
||||
let resumedAt = 0;
|
||||
await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const sessionId = response.sessionId;
|
||||
const child = subagent("a5966d", "toolu_bg_agent", { is_backgrounded: true });
|
||||
claude.send(cycleStart());
|
||||
claude.send(child.launch());
|
||||
claude.send({
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [{ task_id: "a5966d", task_type: "local_agent", description: "sleeper" }],
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send(child.started());
|
||||
claude.send(result({ result: "launched" }));
|
||||
await vi.waitFor(() => expect(client.states().at(-1)).toBe("idle"));
|
||||
vi.mocked(getSessionMessages).mockReturnValueOnce(read.promise);
|
||||
resumedAt = client.notifications.length;
|
||||
const resume = agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
await vi.waitFor(() => expect(getSessionMessages).toHaveBeenCalled());
|
||||
// The subagent works on while the transcript is read.
|
||||
claude.send(child.says("Live report"));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(client.notifications.slice(resumedAt)).toEqual([]);
|
||||
read.resolve([
|
||||
{
|
||||
type: "assistant",
|
||||
uuid: "a1",
|
||||
session_id: sessionId,
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: child.launch().message,
|
||||
},
|
||||
] as never);
|
||||
await resume;
|
||||
});
|
||||
|
||||
const received = updatesOf(client.notifications.slice(resumedAt), "a5966d").map((update) =>
|
||||
update.sessionUpdate === "agent_message_chunk" ? "live report" : update.sessionUpdate,
|
||||
);
|
||||
expect(received).toContain("replay_complete");
|
||||
expect(received.indexOf("live report")).toBeGreaterThan(received.indexOf("replay_complete"));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["session/prompt", v2.methods.agent.session.prompt, { prompt: PROMPT }],
|
||||
["session/close", v2.methods.agent.session.close, {}],
|
||||
|
||||
@@ -2032,10 +2032,13 @@ export class ClaudeAcpAgent {
|
||||
* Copies the session's transcript into a new session, then starts that
|
||||
* session, so the client can prompt it as soon as the response arrives, as
|
||||
* the schema requires of a fork. It starts like a resumed session: from the
|
||||
* copied transcript, with the model and the permission mode it records. A
|
||||
* later load or resume with the same settings reuses it.
|
||||
* copied transcript, with the model and the permission mode it records,
|
||||
* and then the request's `configOptions`. A later load or resume with the
|
||||
* same settings reuses it.
|
||||
*/
|
||||
async unstable_forkSession(params: ForkSessionRequest): Promise<ForkSessionResponse> {
|
||||
// Before the copy: two entries with the same `configId` fork nothing.
|
||||
const initial = initialConfigOptions(params.configOptions);
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
// Reject a bad `cwd` or prompt before copying the transcript.
|
||||
await this.validateCwd(params.cwd, params.additionalDirectories);
|
||||
@@ -2048,14 +2051,17 @@ export class ClaudeAcpAgent {
|
||||
// The fork row can lack `forkedFrom`: the scan reads it from the first
|
||||
// 64 KB of the transcript only. So the fork is held back by its id too.
|
||||
this.sessionIndex.onForkCreated(params.sessionId, sessionId);
|
||||
const { modes, configOptions } = await this.getOrCreateSession({
|
||||
sessionId,
|
||||
cwd: params.cwd,
|
||||
mcpServers: params.mcpServers,
|
||||
additionalDirectories: params.additionalDirectories,
|
||||
systemPrompt: params.systemPrompt,
|
||||
_meta: params._meta,
|
||||
});
|
||||
const { modes, configOptions } = await this.withInitialConfigOptions(
|
||||
await this.getOrCreateSession({
|
||||
sessionId,
|
||||
cwd: params.cwd,
|
||||
mcpServers: params.mcpServers,
|
||||
additionalDirectories: params.additionalDirectories,
|
||||
systemPrompt: params.systemPrompt,
|
||||
_meta: params._meta,
|
||||
}),
|
||||
initial,
|
||||
);
|
||||
this.afterSetupResponse(sessionId, params.mcpServers ?? []);
|
||||
return { sessionId, modes, configOptions };
|
||||
}
|
||||
@@ -9222,7 +9228,7 @@ export class ClaudeAcpAgent {
|
||||
*
|
||||
* Call it in the same synchronous step as the handler's `return`: an
|
||||
* `await` between them would let the timer run before the response. The ACP
|
||||
* SDK (2.6.0) gives a request handler no responder and no after-response
|
||||
* SDK (2.7.0) gives a request handler no responder and no after-response
|
||||
* hook, so the order rests on two things that its source shows and its API
|
||||
* does not promise. `registerAppRequest` queues the response in the
|
||||
* microtask that follows the handler's return, with no macrotask in
|
||||
|
||||
199
src/v2/agent.ts
199
src/v2/agent.ts
@@ -72,6 +72,7 @@ import { subagentHooks } from "./child-config.js";
|
||||
import { modelSwitchHook, SessionConfig } from "./config.js";
|
||||
import { fileChangePreviewHook } from "./file-preview.js";
|
||||
import { canUseTool, denyingStoppedWork } from "./permissions.js";
|
||||
import { ReplayHolds } from "./replay-hold.js";
|
||||
import { reportHooks } from "./reports.js";
|
||||
import { savedSessionStatus } from "../session-status.js";
|
||||
import { SessionRestarts, type SetupParams } from "./restarts.js";
|
||||
@@ -79,6 +80,7 @@ import { V2Session, type SessionConnection } from "./session.js";
|
||||
import {
|
||||
afterSetupResponse,
|
||||
clientOptions,
|
||||
REPLAY_COMPLETE,
|
||||
replayEndUpdate,
|
||||
sessionModels,
|
||||
withClientHooks,
|
||||
@@ -165,6 +167,8 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
* response, and nothing of the session after it.
|
||||
*/
|
||||
private readonly resuming = new Map<string, Set<Promise<unknown>>>();
|
||||
/** What the resumes that replay hold back until their `replay_complete` (see `replay-hold.ts`). */
|
||||
private readonly replays = new ReplayHolds();
|
||||
readonly translator = new V2UpdateTranslator();
|
||||
readonly auth: V2Auth;
|
||||
/** The `--hide-claude-auth` subscription guard (see `subscription-guard.ts`). */
|
||||
@@ -210,10 +214,48 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
|
||||
// --- SessionConnection ---------------------------------------------------
|
||||
|
||||
/** Sends the update, after the `replay_complete` of a replay that holds it (see {@link heldBy}). */
|
||||
send(notification: v2.UpdateSessionNotification): void {
|
||||
this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => {
|
||||
this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
|
||||
});
|
||||
const send = () => {
|
||||
this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => {
|
||||
this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
|
||||
});
|
||||
};
|
||||
const held = this.heldBy(notification.sessionId);
|
||||
if (held === undefined) send();
|
||||
else this.replays.defer(held, send);
|
||||
}
|
||||
|
||||
/**
|
||||
* The session whose replay holds what the session `sessionId` sends now
|
||||
* (see `replay-hold.ts`): itself, or the root session of a subagent's
|
||||
* session.
|
||||
*/
|
||||
private heldBy(sessionId: string): string | undefined {
|
||||
if (!this.replays.any) return undefined;
|
||||
if (this.replays.holds(sessionId)) return sessionId;
|
||||
const root = this.ownerOfChild(sessionId)?.sessionId;
|
||||
return root !== undefined && this.replays.holds(root) ? root : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request of the session `sessionId` to the client, after the
|
||||
* `replay_complete` of a replay that holds it (see {@link heldBy}). A
|
||||
* request that `signal` withdrew while it waited is not sent, and rejects.
|
||||
*/
|
||||
private afterReplay<T>(
|
||||
sessionId: string | undefined,
|
||||
signal: AbortSignal,
|
||||
send: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const held = sessionId === undefined ? undefined : this.heldBy(sessionId);
|
||||
if (held === undefined) return send();
|
||||
return new Promise((resolve, reject) =>
|
||||
this.replays.defer(held, () => {
|
||||
if (signal.aborted) reject(new Error("The request was withdrawn"));
|
||||
else send().then(resolve, reject);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
requestPermission(
|
||||
@@ -221,23 +263,29 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
signal: AbortSignal,
|
||||
): Promise<v2.RequestPermissionResponse> {
|
||||
// Aborting `signal` sends `$/cancel_request`, and stops waiting for the answer.
|
||||
return this.ctx.request(v2.methods.client.session.requestPermission, request, {
|
||||
cancellationSignal: signal,
|
||||
stopWaitingOnCancel: true,
|
||||
});
|
||||
return this.afterReplay(request.sessionId, signal, () =>
|
||||
this.ctx.request(v2.methods.client.session.requestPermission, request, {
|
||||
cancellationSignal: signal,
|
||||
stopWaitingOnCancel: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
createElicitation(
|
||||
request: CreateElicitationRequest,
|
||||
signal: AbortSignal,
|
||||
): Promise<CreateElicitationResponse> {
|
||||
// An elicitation of a request, not of a session, names no session.
|
||||
const sessionId = (request as { sessionId?: unknown }).sessionId;
|
||||
// The v1 types accept a property schema with any tag; the v2 types accept
|
||||
// one only in a received value. An MCP server's schema is relayed
|
||||
// unchanged, as on v1, so this cast does not check it.
|
||||
return this.ctx.request(
|
||||
v2.methods.client.elicitation.create,
|
||||
request as v2.CreateElicitationRequest,
|
||||
{ cancellationSignal: signal, stopWaitingOnCancel: true },
|
||||
return this.afterReplay(typeof sessionId === "string" ? sessionId : undefined, signal, () =>
|
||||
this.ctx.request(
|
||||
v2.methods.client.elicitation.create,
|
||||
request as v2.CreateElicitationRequest,
|
||||
{ cancellationSignal: signal, stopWaitingOnCancel: true },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -337,17 +385,22 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
|
||||
/**
|
||||
* Copies the session's transcript into a new session (`forkSession`), and
|
||||
* starts it from the copy, so the client can prompt it at once.
|
||||
* starts it from the copy, so the client can prompt it at once. The
|
||||
* request's `configOptions` are set on the fork, over what the copy starts
|
||||
* with.
|
||||
*/
|
||||
async forkSession(params: v2.ForkSessionRequest): Promise<v2.ForkSessionResponse> {
|
||||
if (this.ownerOfChild(params.sessionId)) throw restrictedChild(params.sessionId, "fork");
|
||||
// Rejects a bad `cwd` or MCP server before the transcript is copied.
|
||||
// Rejects bad `configOptions`, a bad `cwd` or MCP server before the transcript is copied.
|
||||
const initial = initialConfigRequests(params.sessionId, params.configOptions);
|
||||
await validatedSetup(params);
|
||||
const { sessionId } = await forkSession(v1ForkSessionRequest(params), {
|
||||
logger: this.logger,
|
||||
messageIdForGrouping,
|
||||
});
|
||||
const session = await this.startSession(sessionId, params, sessionId);
|
||||
// The entries are the fork's: only the copy gave it its id.
|
||||
await session.setInitialConfigOptions(initial.map((entry) => ({ ...entry, sessionId })));
|
||||
const response = { sessionId, ...(await this.setupFields(session)) };
|
||||
this.afterSetup(session, params);
|
||||
return response;
|
||||
@@ -355,10 +408,17 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
|
||||
/**
|
||||
* Resumes a stored session, or attaches to a live one. With `replayFrom:
|
||||
* { type: "start" }` the stored history replays first. Either way, the
|
||||
* state snapshot goes out after any replay and before the response. The
|
||||
* request's `configOptions` are set before the replay, on an active session
|
||||
* too.
|
||||
* { type: "start" }` the stored history replays first, and
|
||||
* `replay_complete` ends it, also when the history is empty. Either way,
|
||||
* the state snapshot goes out after any replay and before the response.
|
||||
* The request's `configOptions` are set before the replay, on an active
|
||||
* session too.
|
||||
*
|
||||
* From the request to `replay_complete`, the session and its subagent
|
||||
* sessions send only the replay. What they send besides, such as the
|
||||
* output of work that goes on in an active session, goes out after
|
||||
* `replay_complete` (see `replay-hold.ts`). A resume that fails sends no
|
||||
* `replay_complete`, and then what the session held.
|
||||
*/
|
||||
resumeSession(params: v2.ResumeSessionRequest): Promise<v2.ResumeSessionResponse> {
|
||||
const { sessionId } = params;
|
||||
@@ -385,15 +445,53 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
}
|
||||
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "resume");
|
||||
const initial = initialConfigRequests(sessionId, params.configOptions);
|
||||
// No await before it: nothing of the session goes out between the request and the hold.
|
||||
const release = replayFrom != null ? this.replays.begin(sessionId) : undefined;
|
||||
try {
|
||||
return await this.resumeHeld(params, initial, release);
|
||||
} finally {
|
||||
// A resume that failed before its `replay_complete`.
|
||||
release?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link resume}, once the request is valid. `release` ends the hold of a
|
||||
* resume that replays.
|
||||
*/
|
||||
private async resumeHeld(
|
||||
params: v2.ResumeSessionRequest,
|
||||
initial: v2.SetSessionConfigOptionRequest[],
|
||||
release: (() => void) | undefined,
|
||||
): Promise<v2.ResumeSessionResponse> {
|
||||
const { sessionId, replayFrom } = params;
|
||||
// The replay: the messages before each compaction too, unless reading them fails.
|
||||
const acrossCompactions = (chain: Promise<SessionMessage[]>, cwd: string) => {
|
||||
const messages = chain.then((read) =>
|
||||
readHistoryAcrossCompactions(sessionId, read, this.logger, cwd),
|
||||
);
|
||||
// A resume that fails before the replay leaves them unawaited.
|
||||
chain.catch(() => {});
|
||||
messages.catch(() => {});
|
||||
return messages;
|
||||
};
|
||||
await this.restarts.settled(sessionId);
|
||||
// A concurrent resume of this session started its query: this one then
|
||||
// attaches to the session that it started.
|
||||
await this.startSettled(sessionId);
|
||||
let session = this.sessions.get(sessionId);
|
||||
let history: Promise<SessionMessage[]> | undefined;
|
||||
// The replay: the messages before each compaction too, unless reading them fails.
|
||||
let replayed: Promise<SessionMessage[]> | undefined;
|
||||
if (session) {
|
||||
// Read first, so the history ends as close to the request as it can.
|
||||
// The session's work goes on, and what it sends from the request on
|
||||
// follows `replay_complete`: an update that the history had too would
|
||||
// reach the client twice.
|
||||
if (replayFrom != null) {
|
||||
replayed = acrossCompactions(
|
||||
getSessionMessages(sessionId, { dir: session.cwd }),
|
||||
session.cwd,
|
||||
);
|
||||
}
|
||||
// Resuming the active session synchronizes it again. Its work goes on,
|
||||
// and the request's MCP servers and additional directories replace the
|
||||
// session's.
|
||||
@@ -413,42 +511,30 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
}
|
||||
} else {
|
||||
// One read of the transcript serves the replay and the resumed model.
|
||||
history = replayFrom != null ? getSessionMessages(sessionId, { dir: params.cwd }) : undefined;
|
||||
const history =
|
||||
replayFrom != null ? getSessionMessages(sessionId, { dir: params.cwd }) : undefined;
|
||||
// The read across compactions overlaps the start of the query.
|
||||
replayed = history?.then((messages) =>
|
||||
readHistoryAcrossCompactions(sessionId, messages, this.logger, params.cwd),
|
||||
);
|
||||
// A failed start leaves them unawaited.
|
||||
history?.catch(() => {});
|
||||
replayed?.catch(() => {});
|
||||
if (history) replayed = acrossCompactions(history, params.cwd);
|
||||
session = await this.startSession(sessionId, params, sessionId, history);
|
||||
}
|
||||
await session.setInitialConfigOptions(initial);
|
||||
let subagents: SubagentReplay | undefined;
|
||||
if (replayFrom != null) {
|
||||
const cwd = session.cwd;
|
||||
const messages = await (replayed ??
|
||||
getSessionMessages(sessionId, { dir: cwd }).then((chain) =>
|
||||
readHistoryAcrossCompactions(sessionId, chain, this.logger, cwd),
|
||||
));
|
||||
if (replayed) {
|
||||
const messages = await replayed;
|
||||
subagents = await session.tasks.loadReplay(messages);
|
||||
session.output.replay(
|
||||
messages,
|
||||
subagents?.hooks(session.output, messages),
|
||||
session.tasks.backgroundWork(sessionId),
|
||||
session.tasks.replayedBackground(sessionId),
|
||||
);
|
||||
subagents?.finish();
|
||||
const end = replayEndUpdate(this.clientCapabilities);
|
||||
if (end) this.send({ sessionId, update: end });
|
||||
this.replay(session, messages, subagents);
|
||||
release?.();
|
||||
// A notice is not history, so it follows `replay_complete`.
|
||||
subagents?.reportMissingHistory();
|
||||
}
|
||||
// The current title, after the replay and before the state.
|
||||
await session.reports.publishTitle();
|
||||
for (const notification of session.resumeSnapshot()) this.send(notification);
|
||||
const response = await this.setupFields(session);
|
||||
this.afterSetup(session, params);
|
||||
// The response ends the replay, and the replayed children's states before
|
||||
// it are history: their current states follow it. The ACP SDK (2.6.0)
|
||||
// A replayed child's state that comes before the response is history to
|
||||
// the client, also after the child's `replay_complete`: the children's
|
||||
// current states follow the response. The ACP SDK (2.7.0)
|
||||
// gives a request handler no responder and no after-response hook, so the
|
||||
// order rests on two things that its source shows and its API does not
|
||||
// promise. `registerAppRequest` queues the response in the microtask that
|
||||
@@ -462,6 +548,33 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays `messages`, the history of `session`, with the histories of its
|
||||
* subagents (`subagents`), and ends the replay: each replayed child's
|
||||
* `replay_complete` (see `SubagentReplay.finish`), then the session's. An
|
||||
* AIR client that declared `loadReplayEnd` gets AIR's own mark after it.
|
||||
* All in one synchronous step, as `ReplayHolds.replay` requires.
|
||||
*/
|
||||
private replay(
|
||||
session: V2Session,
|
||||
messages: SessionMessage[],
|
||||
subagents: SubagentReplay | undefined,
|
||||
): void {
|
||||
const { sessionId } = session;
|
||||
this.replays.replay(() => {
|
||||
session.output.replay(
|
||||
messages,
|
||||
subagents?.hooks(session.output, messages),
|
||||
session.tasks.backgroundWork(sessionId),
|
||||
session.tasks.replayedBackground(sessionId),
|
||||
);
|
||||
subagents?.finish();
|
||||
this.send({ sessionId, update: REPLAY_COMPLETE });
|
||||
const end = replayEndUpdate(this.clientCapabilities);
|
||||
if (end) this.send({ sessionId, update: end });
|
||||
});
|
||||
}
|
||||
|
||||
async listSessions(params: v2.ListSessionsRequest): Promise<v2.ListSessionsResponse> {
|
||||
if (params.cwd != null && !path.isAbsolute(params.cwd)) {
|
||||
throw RequestError.invalidParams({ cwd: params.cwd }, "`cwd` must be an absolute path");
|
||||
|
||||
64
src/v2/replay-hold.ts
Normal file
64
src/v2/replay-hold.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* What a `session/resume` with `replayFrom` holds back. Between the request
|
||||
* and the session's `replay_complete`, v2 allows only the session's replayed
|
||||
* history. Every other update of the session and of its subagent sessions,
|
||||
* such as a chunk of a message that streams, a notice or a state, waits and
|
||||
* goes out after `replay_complete`, in the order it was sent. So does a
|
||||
* permission request or an elicitation.
|
||||
*
|
||||
* The replay itself runs in one synchronous step ({@link ReplayHolds.replay}),
|
||||
* so what a session sends during that step is its replayed history. Nothing
|
||||
* else tells the two apart.
|
||||
*/
|
||||
export class ReplayHolds {
|
||||
/** What each session with a replay in flight holds, in send order, with the count of its replays. */
|
||||
private readonly sessions = new Map<string, { resumes: number; sends: Array<() => void> }>();
|
||||
/** Whether {@link replay} runs. */
|
||||
private replaying = false;
|
||||
|
||||
/** Whether any session holds its sends. */
|
||||
get any(): boolean {
|
||||
return this.sessions.size > 0;
|
||||
}
|
||||
|
||||
/** Whether the session `sessionId` holds what it sends now: a replay of it is in flight, and is not the sender. */
|
||||
holds(sessionId: string): boolean {
|
||||
return !this.replaying && this.sessions.has(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A resume of `sessionId` that replays came: the session holds its sends
|
||||
* from now on. Returns the release, to call once the session's
|
||||
* `replay_complete` went out, or the resume failed. It sends what the
|
||||
* session held, unless another replay of the session is still in flight.
|
||||
* Calling it again does nothing.
|
||||
*/
|
||||
begin(sessionId: string): () => void {
|
||||
const hold = this.sessions.get(sessionId) ?? { resumes: 0, sends: [] };
|
||||
hold.resumes++;
|
||||
this.sessions.set(sessionId, hold);
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
if (--hold.resumes > 0) return;
|
||||
this.sessions.delete(sessionId);
|
||||
for (const send of hold.sends) send();
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs `send` once the session `sessionId` no longer holds its sends (see {@link holds}). */
|
||||
defer(sessionId: string, send: () => void): void {
|
||||
this.sessions.get(sessionId)!.sends.push(send);
|
||||
}
|
||||
|
||||
/** Runs `replay`, which must send the history and its `replay_complete` before it returns. */
|
||||
replay(replay: () => void): void {
|
||||
this.replaying = true;
|
||||
try {
|
||||
replay();
|
||||
} finally {
|
||||
this.replaying = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,13 @@ export function v1NewSessionRequest(params: v2.NewSessionRequest): NewSessionReq
|
||||
};
|
||||
}
|
||||
|
||||
/** The v1 request of a v2 `session/fork`. */
|
||||
/**
|
||||
* The v1 request of a v2 `session/fork`. Without `configOptions`: the fork
|
||||
* applies them once it started (see {@link initialConfigRequests}).
|
||||
*/
|
||||
export function v1ForkSessionRequest(params: v2.ForkSessionRequest): ForkSessionRequest {
|
||||
const { mcpServers, systemPrompt, ...request } = params;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { mcpServers, systemPrompt, configOptions, ...request } = params;
|
||||
return {
|
||||
...request,
|
||||
...(mcpServers ? { mcpServers: v1McpServers(mcpServers) } : {}),
|
||||
|
||||
@@ -103,8 +103,16 @@ export async function sessionModels(
|
||||
}
|
||||
|
||||
/**
|
||||
* The update that ends a replay, for a client that declares AIR's
|
||||
* `loadReplayEnd` capability, as v1 sends it.
|
||||
* The update that ends the history replay of a `session/resume` with
|
||||
* `replayFrom`, on the resumed session and on each subagent session that the
|
||||
* replay announced.
|
||||
*/
|
||||
export const REPLAY_COMPLETE: v2.SessionUpdate = { sessionUpdate: "replay_complete" };
|
||||
|
||||
/**
|
||||
* AIR's own mark of the end of a replay, for a client that declares AIR's
|
||||
* `loadReplayEnd` capability, as v1 sends it. It is not history, so on v2 it
|
||||
* follows {@link REPLAY_COMPLETE}.
|
||||
*/
|
||||
export function replayEndUpdate(
|
||||
capabilities: v2.ClientCapabilities | null | undefined,
|
||||
|
||||
@@ -20,10 +20,12 @@
|
||||
* history follows its launch, so a call to a child from its parent is always
|
||||
* delivered first. Any other SendMessage call stays a tool call.
|
||||
*
|
||||
* Every child's end goes out on its parent at the end of the replay, and once
|
||||
* on the child's own stream: v2 forbids replaying a child's past `running` as
|
||||
* current activity. These states are history to the client, so each child's
|
||||
* current state goes out again after the response ({@link afterResponse}).
|
||||
* Every child's end goes out on its parent at the end of the replay. Each
|
||||
* announced child then gets its own `replay_complete`, as v2 requires, and
|
||||
* its end once on its own stream: v2 forbids replaying a child's past
|
||||
* `running` as current activity. These states are history to the client, so
|
||||
* each child's current state goes out again after the response
|
||||
* ({@link afterResponse}).
|
||||
* A child that the live session still tracks, on a resume of the active
|
||||
* session, gets its current state from the resume snapshot instead
|
||||
* (`SessionTasks.currentState`). After the response, a child whose
|
||||
@@ -32,8 +34,8 @@
|
||||
*
|
||||
* A launch without metadata has no known id, so it is not announced: the RFD
|
||||
* forbids inventing one. Its Agent call stays an ordinary tool call of the
|
||||
* parent, and a notice at the end says that subagent history is missing, as
|
||||
* it does for a child whose transcript cannot be read.
|
||||
* parent, and a notice after the root's `replay_complete` says that subagent
|
||||
* history is missing, as it does for a child whose transcript cannot be read.
|
||||
*/
|
||||
import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
|
||||
import type { SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
|
||||
@@ -68,6 +70,7 @@ import {
|
||||
} from "../subagent-replay.js";
|
||||
import { taskNotificationsOf } from "../task-notifications.js";
|
||||
import type { V2UpdateTranslator } from "./update-translator.js";
|
||||
import { REPLAY_COMPLETE } from "./setup.js";
|
||||
import { SessionOutput, type ReplayHooks } from "./stream.js";
|
||||
import { sameDirectory } from "./tasks.js";
|
||||
|
||||
@@ -144,8 +147,11 @@ export class SubagentReplay {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the replay: every child's end, on its parent, then once on its own
|
||||
* stream, and the notice when subagent history is missing.
|
||||
* Ends the replay of the children. Every child's end goes out on its
|
||||
* parent, whose history it is. Then each announced child gets its
|
||||
* `replay_complete`, also one without history, and its end once on its own
|
||||
* stream. A `state_update` is not history, so it follows the child's
|
||||
* `replay_complete`.
|
||||
*/
|
||||
finish(): void {
|
||||
const announced = [...this.transcript.children.values()].filter((child) => child.announced);
|
||||
@@ -160,11 +166,19 @@ export class SubagentReplay {
|
||||
});
|
||||
}
|
||||
for (const child of announced) {
|
||||
this.host.send({ sessionId: child.sessionId, update: REPLAY_COMPLETE });
|
||||
this.host.send({
|
||||
sessionId: child.sessionId,
|
||||
update: { sessionUpdate: "state_update", ...replayEndState(child) } as v2.SessionUpdate,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The notice when subagent history is missing, on the root session. It is
|
||||
* no history, so the caller sends the root's `replay_complete` first.
|
||||
*/
|
||||
reportMissingHistory(): void {
|
||||
const missing = this.transcript.omitted.size + this.withoutHistory;
|
||||
if (missing > 0) {
|
||||
this.rootOutput?.emitV1([
|
||||
|
||||
Reference in New Issue
Block a user