feat: send the predicted next prompt as prompt_suggestions_update (#1660)

A client that advertises `session.promptSuggestions` now gets the prompt
that Claude Code predicts the user sends next, as ACP's unstable
`prompt_suggestions_update`, on v1 and v2.

## Why

Claude Code predicts the next prompt after a turn. The adapter sent that
prediction only to JetBrains AIR, as
`session_info_update._meta.promptSuggestions`, because ACP had no update
for it. ACP now has one, behind the client capability
`session.promptSuggestions` in both versions.

## What a client sees

- **With the capability:** `prompt_suggestions_update` with one
suggestion, whose prompt is one text block. An empty list withdraws it.
- **JetBrains AIR:** the `_meta` form, unchanged. An AIR client that
also advertises the capability gets both, the standard update first.
- **Neither:** nothing, and the session asks Claude Code for no
prediction. On v2 that was so before. On v1 it is new: see "v1 cost"
below.

The standard form follows the rules of the draft pages ("Prompt
suggestions (unstable)"):

- The list is withdrawn when a prompt is accepted, and at a
`conversation_reset`.
- A suggestion that is empty or only whitespace is not sent.
- A prediction that arrives while Claude works is dropped, for example
when another prompt was queued before the result. ACP requires a
prediction to match the conversation when it is sent.
- On v2, the list is withdrawn when foreground work starts without a
prompt, such as a cycle that Claude Code starts after a background task.
- Nothing is replayed. Predictions are not in the transcript.

## How

`PromptSuggestions` in `src/prompt-suggestions.ts`, which both cores
share, keeps one state per form and returns the updates to send. The
`_meta` form keeps the rules it had. The v1 core changes only its
existing call sites, and `src/v2/session-update.ts` passes the new
update through.

`promptSuggestionOptions` in the same module gives both cores the SDK
option, by the rule that `PromptSuggestions.forClient` uses: on for a
client that takes a form of the prediction, absent for any other.

## For the reviewer

- **v1 cost:** on `main`, the SDK option `promptSuggestions: true` is on
for every v1 client, not only AIR, so Claude Code spends a request per
turn on a prediction that a client other than AIR never gets. This PR
turns the option on only for AIR and for a client that advertises the
capability, as v2 does. A v1 client that is neither stops paying for the
prediction and sees no other change: it got nothing of it before. A
client's own `_meta.claudeCode.options.promptSuggestions` still wins, in
both directions.
- **v1 autonomous cycles:** the withdrawal when work starts without a
prompt is v2 only. On v1, a prediction that arrives during such a cycle
is dropped, but a list already shown stays until the next prompt.
- **A session that stays live through a load or resume** keeps its
state, while the client's list is empty by rule. The next clear can send
a redundant empty list, and an identical prediction is not sent again.

## Checked against the real CLI

A client that advertises the capability got one
`prompt_suggestions_update` after the second turn of a session, on v1
and on v2. Claude Code predicts nothing after a session's first turn. I
did not check the queued-prompt case live.

## Tests

- `prompt-suggestions.test.ts` (v1) and `v2.test.ts`: each form alone
and both together, the withdrawal at a prompt, the dropped prediction
while Claude works, and on v2 the withdrawal when work starts without a
prompt.
- `create-session-options.test.ts` (v1): the SDK option is on for AIR
and for a client with the capability, absent for any other client, and
off when the caller passes `false`.

`npm run build`, `npm run check` and `npm run test:run` pass (4364
tests, with `main` merged in). The live check above was made before the
v1 option was gated. I did not repeat it.
This commit is contained in:
Ben Brandt
2026-11-19 09:46:26 +01:00
committed by GitHub
parent 8990c2441d
commit f20ed1d96a
12 changed files with 561 additions and 173 deletions

View File

@@ -19,6 +19,7 @@ This tool implements an ACP agent by using the official [Claude Agent SDK](https
- Client MCP servers, including the ones that the client serves over the ACP connection ([MCP-over-ACP](https://agentclientprotocol.com/rfds/mcp-over-acp), `"type": "acp"`)
- An Ultracode session config option, which turns on Claude Code's dynamic workflows for every task. It appears when dynamic workflows are enabled and the model supports ultracode (any model with `xhigh` effort)
- `/mcp` in the chat: the MCP server status as a list. The adapter runs `/mcp reconnect`, `/mcp enable`, and `/mcp disable` through the SDK control API, because Claude Code refuses them in SDK mode. A reconnect of an ACP server that needs authentication starts MCP OAuth through URL elicitation
- Prompt suggestions: the prompt that Claude Code predicts the user sends next, as ACP's unstable `prompt_suggestions_update`, for a client that advertises `session.promptSuggestions`
- Session-scoped long-running goals for AIR through the [goal extension](docs/air-extensions.md#goal) under `_meta.jetbrains.air.goal`
- Structured errors, recovery, and warnings through the opt-in [session failure extension](docs/air-extensions.md#session-failure)
- Concrete model and effort defaults through the opt-in [recommended config value extension](docs/air-extensions.md#recommended-config-values)

View File

@@ -859,8 +859,9 @@ A failed command restores the previous state.
After a turn, the Claude Code CLI can predict the prompt the user is likely to send next.
The adapter asks for it with the SDK option `promptSuggestions: true` and forwards the one prediction of the turn.
It asks only in a session of AIR or of a client that advertises `session.promptSuggestions`, on v1 and v2: a prediction costs a request per turn, and no other client would get it.
ACP has no field for a composer prefill, so the prediction travels outside the AIR namespace:
AIR reads the prediction from a `_meta` key outside the AIR namespace, which the adapter used before ACP had an update for it:
```json
{
@@ -869,9 +870,20 @@ ACP has no field for a composer prefill, so the prediction travels outside the A
}
```
The key names no vendor, so another client can read it.
The key names no vendor.
The adapter sends it only to an AIR client; see the [compatibility rule](#compatibility-rule).
Any client that advertises `session.promptSuggestions` gets the same prediction as ACP's unstable `prompt_suggestions_update`, on v1 and v2:
```json
{
"sessionUpdate": "prompt_suggestions_update",
"suggestions": [{ "prompt": [{ "type": "text", "text": "Run the tests" }] }]
}
```
An AIR client that advertises the capability gets both.
AIR shows the first non-blank `suggestions[].text` as gray text in an empty composer.
Tab fills the composer with it and sends nothing.
@@ -882,6 +894,11 @@ Tab fills the composer with it and sends nothing.
A prediction the next prompt outran — the user sent it before the adapter read the prediction off the SDK stream — is dropped instead of published.
`prompt_suggestions_update` follows two more rules of ACP, which the `_meta` form does not:
- a prediction that arrives while Claude works, such as on a prompt that was queued before the turn's result, is dropped;
- on v2, the list is withdrawn when foreground work starts without a prompt, such as a cycle that Claude Code starts after a background task ends.
The CLI predicts nothing on the first turn of a session, after an API error, in plan mode, and at the account's usage limit, so many turns end with no prediction.
A client must treat a turn without one as normal.
A caller can turn the whole feature off with `_meta.claudeCode.options.promptSuggestions: false` on `session/new`; a user can turn it off in Claude Code settings or with `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false`.

View File

@@ -3,9 +3,17 @@
*
* With `promptSuggestions` on, the CLI emits one `prompt_suggestion` message
* after a turn's `result` holding the prompt it expects the user to send next.
* ACP has no field for it, so it travels as
* `session_info_update._meta.promptSuggestions`: a client that does not read
* the key sees a session info update that says nothing and ignores it.
* The adapter turns it on only for a client that takes the prediction
* ({@link promptSuggestionOptions}).
* It reaches the client in up to two forms:
*
* - `prompt_suggestions_update`, ACP's unstable session update, for a client
* that advertised `session.promptSuggestions`, on v1 and v2. The CLI
* predicts one prompt, so the list holds one suggestion, whose prompt is
* one text block.
* - `session_info_update._meta.promptSuggestions`, for JetBrains AIR, which
* read the prediction there before ACP had an update for it. A client that
* does not read the key sees a session info update that says nothing.
*
* AIR renders the first non-blank `suggestions[].text` as gray text in an empty
* composer, where Tab fills the composer without sending.
@@ -14,6 +22,47 @@
* error, in plan mode, and at the account's usage limit, so most sessions have
* turns that end with no prediction at all.
*/
import type { SessionNotification } from "@agentclientprotocol/sdk/unstable";
import type { Options } from "@anthropic-ai/claude-agent-sdk";
type SuggestionUpdate = SessionNotification["update"];
/** The forms of the prediction that a client takes. */
export type PromptSuggestionForms = {
/** `session_info_update._meta.promptSuggestions`: the client is JetBrains AIR. */
meta: boolean;
/** `prompt_suggestions_update`: the client advertised `session.promptSuggestions`. */
update: boolean;
};
/**
* Whether a client advertised `session.promptSuggestions`. `session` is the
* session capabilities of its `initialize` request: `clientCapabilities.session`
* on v1, `capabilities.session` on v2. ACP forbids the update without it.
*/
export function clientTakesPromptSuggestions(
session: { promptSuggestions?: unknown } | null | undefined,
): boolean {
return session?.promptSuggestions != null;
}
/** Whether a client takes the prediction in any form. */
function takesPrediction(forms: PromptSuggestionForms): boolean {
return forms.meta || forms.update;
}
/**
* The SDK option that makes Claude Code predict the next prompt, for a
* session whose client takes the prediction in a form. Empty for any other
* client: a prediction costs a request per turn, and none of it would reach
* that client. Both cores spread it before the client's own options, so
* `_meta.claudeCode.options.promptSuggestions: false` turns the prediction off.
*/
export function promptSuggestionOptions(
forms: PromptSuggestionForms,
): Pick<Options, "promptSuggestions"> {
return takesPrediction(forms) ? { promptSuggestions: true } : {};
}
/** The `_meta` key the suggestion travels under. It names no vendor. */
export const PROMPT_SUGGESTIONS_META_KEY = "promptSuggestions";
@@ -26,7 +75,8 @@ export type PromptSuggestionsMetaValue = {
/**
* The suggestion as it goes on the wire, or `null` for a suggestion that says
* nothing: the CLI can predict whitespace, and an empty text would otherwise
* reach the composer as a hint with no content.
* reach the composer as a hint with no content. ACP forbids a suggestion whose
* only content is empty or whitespace-only text.
*/
export function promptSuggestionText(raw: string | null | undefined): string | null {
const text = raw?.trim();
@@ -44,12 +94,19 @@ export function promptSuggestionsMeta(text: string | null): Record<string, unkno
}
/**
* The prediction a session holds on the client, and whether an arriving
* `prompt_suggestion` still answers the turn the user waits on. Both cores
* keep one per session and send the `_meta` that its methods return as a
* `session_info_update`, to an AIR client only. Undefined: nothing to send.
* The `prompt_suggestions_update` that makes `text` the session's list of
* suggestions. `null` sends an empty list, which withdraws the list that the
* client is offering.
*/
export class PromptSuggestions {
export function promptSuggestionsUpdate(text: string | null): SuggestionUpdate {
return {
sessionUpdate: "prompt_suggestions_update",
suggestions: text === null ? [] : [{ prompt: [{ type: "text", text }] }],
};
}
/** The prediction that a client holds in one form, and what is still to come of the last result. */
class Lane {
/** The last text sent (`null` after a clear). Undefined until the first send. */
private published: string | null | undefined;
/**
@@ -60,33 +117,118 @@ export class PromptSuggestions {
*/
private expected = false;
/** A result came: the CLI predicts the next prompt right after it. */
constructor(
private readonly form: (text: string | null) => SuggestionUpdate,
/** `prompt_suggestions_update`, whose rules ACP sets. */
readonly standard: boolean,
) {}
resultArrived(): void {
this.expected = true;
}
/** The `_meta` of the CLI's `prompt_suggestion`, if it answers the last result and changes what the client holds. */
suggested(raw: string | null | undefined): Record<string, unknown> | undefined {
suggested(text: string | null, working: boolean): SuggestionUpdate | undefined {
if (!this.expected) return undefined;
this.expected = false;
return this.publish(promptSuggestionText(raw));
// ACP: a prediction is discarded when the conversation changed before it
// was sent. AIR's draft has no such rule.
if (working && this.standard) return undefined;
return this.publish(text);
}
/**
* The `_meta` that clears the prediction: a client prompt spent it, or a
* `conversation_reset` dropped the transcript it came from. It also drops
* a prediction still in flight for the last result. Undefined when the
* client holds none.
*/
clear(): Record<string, unknown> | undefined {
clear(): SuggestionUpdate | undefined {
this.expected = false;
return this.publish(null);
}
private publish(text: string | null): Record<string, unknown> | undefined {
private publish(text: string | null): SuggestionUpdate | undefined {
// An unchanged prediction is not sent again.
if ((this.published ?? null) === text) return undefined;
this.published = text;
return promptSuggestionsMeta(text);
return this.form(text);
}
}
/**
* The predictions that a session holds on the client, and whether an arriving
* `prompt_suggestion` still answers the turn the user waits on. Both cores
* keep one per session and send the updates that its methods return, in
* order. An empty list: nothing to send.
*
* Each form has its own state. The `_meta` form keeps the rules it had before
* ACP had the update. The `prompt_suggestions_update` form follows ACP's, so
* it also drops a prediction that arrives while Claude works
* ({@link suggested}) and withdraws its list when work starts
* ({@link workStarted}).
*/
export class PromptSuggestions {
private readonly lanes: Lane[];
/**
* The predictions of a session whose client takes `forms`. Undefined for a
* client that takes neither: nothing of a prediction goes to it.
*/
static forClient(forms: PromptSuggestionForms): PromptSuggestions | undefined {
return takesPrediction(forms) ? new PromptSuggestions(forms) : undefined;
}
private constructor(forms: PromptSuggestionForms) {
this.lanes = [
...(forms.update ? [new Lane(promptSuggestionsUpdate, true)] : []),
...(forms.meta
? [
new Lane(
(text) => ({
sessionUpdate: "session_info_update",
_meta: promptSuggestionsMeta(text),
}),
false,
),
]
: []),
];
}
/** A result came: the CLI predicts the next prompt right after it. */
resultArrived(): void {
for (const lane of this.lanes) lane.resultArrived();
}
/**
* The updates for the CLI's `prompt_suggestion`, in each form where it
* answers the last result and changes what the client holds.
*
* `working`: Claude works in the session now, such as on a prompt that was
* queued before the result, or in a cycle that Claude Code started on its
* own. The prediction does not account for that work, so the
* `prompt_suggestions_update` form drops it.
*/
suggested(raw: string | null | undefined, working: boolean): SuggestionUpdate[] {
const text = promptSuggestionText(raw);
return this.updates((lane) => lane.suggested(text, working));
}
/**
* The updates that clear the prediction: a client prompt spent it, or a
* `conversation_reset` dropped the transcript it came from. It also drops
* a prediction still in flight for the last result. Empty when the client
* holds none.
*/
clear(): SuggestionUpdate[] {
return this.updates((lane) => lane.clear());
}
/**
* Foreground work started. The `prompt_suggestions_update` form withdraws
* its list, as {@link clear} does: ACP asks for it when work starts without
* a prompt, and a prompt's own work finds the list withdrawn already. The
* `_meta` form keeps its prediction until the next prompt, as before.
*/
workStarted(): SuggestionUpdate[] {
return this.updates((lane) => (lane.standard ? lane.clear() : undefined));
}
private updates(of: (lane: Lane) => SuggestionUpdate | undefined): SuggestionUpdate[] {
return this.lanes.flatMap((lane) => of(lane) ?? []);
}
}

View File

@@ -596,23 +596,33 @@ describe("createSession options merging", () => {
expect(capturedOptions?.env?.HOME).toBe("/custom/home");
});
it("asks the SDK for a predicted follow-up prompt per turn", async () => {
await agent.newSession({
cwd: process.cwd(),
mcpServers: [],
describe("the predicted follow-up prompt", () => {
const AIR = { _meta: { jetbrains: { air: { version: 1, capabilities: [] } } } };
const ADVERTISED = { session: { promptSuggestions: {} } };
// Claude Code spends a request per turn on a prediction: only a client
// that gets the prediction has it on.
it.each<[string, ClientCapabilities, true | undefined]>([
["AIR", AIR as ClientCapabilities, true],
["a client that advertises session.promptSuggestions", ADVERTISED, true],
["no other client", {}, undefined],
])("asks the SDK for it for %s", async (_, clientCapabilities, asked) => {
await agent.initialize({ protocolVersion: 1, clientCapabilities });
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.promptSuggestions).toBe(asked);
});
expect(capturedOptions!.promptSuggestions).toBe(true);
});
it("lets a caller turn it off", async () => {
await agent.initialize({ protocolVersion: 1, clientCapabilities: ADVERTISED });
await agent.newSession({
cwd: process.cwd(),
mcpServers: [],
_meta: { claudeCode: { options: { promptSuggestions: false } } },
});
it("lets a caller turn the predicted follow-up prompt off", async () => {
await agent.newSession({
cwd: process.cwd(),
mcpServers: [],
_meta: { claudeCode: { options: { promptSuggestions: false } } },
expect(capturedOptions!.promptSuggestions).toBe(false);
});
expect(capturedOptions!.promptSuggestions).toBe(false);
});
it.each([

View File

@@ -2,7 +2,11 @@ import { describe, it, expect } from "vitest";
import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
import type { AcpClient } from "../../acp-client.js";
import { promptSuggestionsMeta, promptSuggestionText } from "../../prompt-suggestions.js";
import {
promptSuggestionsMeta,
promptSuggestionsUpdate,
promptSuggestionText,
} from "../../prompt-suggestions.js";
import { Pushable } from "../../utils.js";
import {
mockSessionState,
@@ -11,11 +15,20 @@ import {
wrapQuery,
} from "./session-doubles.js";
/** An AIR client: the only one that renders the follow-up prompt. */
/** An AIR client, which reads the follow-up prompt from `_meta`. */
const AIR_CLIENT: ClientCapabilities = {
_meta: { jetbrains: { air: { version: 1, capabilities: [] } } },
};
/** A client that advertised ACP's `prompt_suggestions_update`. */
const SUGGESTIONS_CLIENT: ClientCapabilities = { session: { promptSuggestions: {} } };
/** The session info update that carries `text` to AIR. */
const metaUpdate = (text: string | null) => ({
sessionUpdate: "session_info_update",
_meta: promptSuggestionsMeta(text),
});
describe("the follow-up prompt on the wire", () => {
it("drops a prediction that says nothing", () => {
expect(promptSuggestionText("Run the tests")).toBe("Run the tests");
@@ -31,92 +44,122 @@ describe("the follow-up prompt on the wire", () => {
});
expect(promptSuggestionsMeta(null)).toEqual({ promptSuggestions: { suggestions: [] } });
});
it("is one suggestion of one text block in ACP's update, and an empty list withdraws it", () => {
expect(promptSuggestionsUpdate("Run the tests")).toEqual({
sessionUpdate: "prompt_suggestions_update",
suggestions: [{ prompt: [{ type: "text", text: "Run the tests" }] }],
});
expect(promptSuggestionsUpdate(null)).toEqual({
sessionUpdate: "prompt_suggestions_update",
suggestions: [],
});
});
});
describe("the follow-up prompt at turn-end", () => {
/** Collects the `_meta.promptSuggestions` of every session info update. */
function recorder() {
const published: unknown[] = [];
const client = {
sessionUpdate: async (notification: any) => {
const update = notification.update;
if (update?.sessionUpdate !== "session_info_update") return;
if (update._meta?.promptSuggestions === undefined) return;
published.push(update._meta.promptSuggestions);
},
} as unknown as AcpClient;
return { client, published };
}
/** Collects every update that carries a predicted prompt, in either form. */
function recorder() {
const published: unknown[] = [];
const client = {
sessionUpdate: async (notification: any) => {
const update = notification.update;
const carries =
update?.sessionUpdate === "prompt_suggestions_update" ||
(update?.sessionUpdate === "session_info_update" &&
update._meta?.promptSuggestions !== undefined);
if (carries) published.push(update);
},
} as unknown as AcpClient;
return { client, published };
}
/** One turn per entry: echo the prompt, succeed, predict `suggestion` (when
* the entry has one), go idle. A turn with `null` predicts nothing, as the
* CLI does in plan mode or after an API error. */
function turns(input: Pushable<any>, suggestions: (string | null)[]) {
return (async function* () {
const iter = input[Symbol.asyncIterator]();
for (const suggestion of suggestions) {
const { value: userMessage } = await iter.next();
yield userEcho(userMessage);
yield successfulResultMessage();
if (suggestion !== null) {
yield { type: "prompt_suggestion", suggestion, uuid: "uuid", session_id: "test-session" };
}
yield { type: "system", subtype: "session_state_changed", state: "idle" };
/** One turn per entry: echo the prompt, succeed, predict `suggestion` (when
* the entry has one), go idle. A turn with `null` predicts nothing, as the
* CLI does in plan mode or after an API error. */
function turns(input: Pushable<any>, suggestions: (string | null)[]) {
return (async function* () {
const iter = input[Symbol.asyncIterator]();
for (const suggestion of suggestions) {
const { value: userMessage } = await iter.next();
yield userEcho(userMessage);
yield successfulResultMessage();
if (suggestion !== null) {
yield { type: "prompt_suggestion", suggestion, uuid: "uuid", session_id: "test-session" };
}
})();
}
async function airAgent(client: AcpClient) {
const agent = new ClaudeAcpAgent(client, { log: () => {}, error: () => {} });
await agent.initialize({ protocolVersion: 1, clientCapabilities: AIR_CLIENT });
return agent;
}
async function run(
agent: ClaudeAcpAgent,
suggestions: (string | null)[],
{ drain = true }: { drain?: boolean } = {},
) {
const input = new Pushable<any>();
agent.sessions["test-session"] = mockSessionState(
{ query: wrapQuery(turns(input, suggestions)), input },
agent,
);
for (let i = 0; i < suggestions.length; i++) {
await agent.prompt({
sessionId: "test-session",
prompt: [{ type: "text", text: `prompt ${i}` }],
});
// The prediction lands after the turn's result, so let the consumer read
// it off the stream before the next prompt: a user types slower than this.
if (drain) await new Promise((resolve) => setTimeout(resolve, 0));
yield { type: "system", subtype: "session_state_changed", state: "idle" };
}
await agent.sessions["test-session"]?.consumer;
}
})();
}
async function agentFor(client: AcpClient, clientCapabilities: ClientCapabilities) {
const agent = new ClaudeAcpAgent(client, { log: () => {}, error: () => {} });
await agent.initialize({ protocolVersion: 1, clientCapabilities });
return agent;
}
/**
* Runs one turn per entry of `suggestions`. `drain` lets the consumer read a
* turn's prediction before the next prompt. `queued` sends every prompt
* before the first turn's result.
*/
async function run(
agent: ClaudeAcpAgent,
suggestions: (string | null)[],
{ drain = true, queued = false }: { drain?: boolean; queued?: boolean } = {},
) {
const input = new Pushable<any>();
agent.sessions["test-session"] = mockSessionState(
{ query: wrapQuery(turns(input, suggestions)), input },
agent,
);
const prompts: Promise<unknown>[] = [];
for (let i = 0; i < suggestions.length; i++) {
const prompt = agent.prompt({
sessionId: "test-session",
prompt: [{ type: "text", text: `prompt ${i}` }],
});
prompts.push(prompt);
if (queued) continue;
await prompt;
// The prediction lands after the turn's result, so let the consumer read
// it off the stream before the next prompt: a user types slower than this.
if (drain) await new Promise((resolve) => setTimeout(resolve, 0));
}
await Promise.all(prompts);
await agent.sessions["test-session"]?.consumer;
}
describe.each([
{ form: "AIR's _meta", capabilities: AIR_CLIENT, sent: metaUpdate },
{
form: "prompt_suggestions_update",
capabilities: SUGGESTIONS_CLIENT,
sent: promptSuggestionsUpdate,
},
])("the follow-up prompt at turn-end, as $form", ({ capabilities, sent }) => {
it("publishes the predicted prompt after the turn's result", async () => {
const { client, published } = recorder();
const agent = await airAgent(client);
const agent = await agentFor(client, capabilities);
await run(agent, ["Run the tests"]);
expect(published).toEqual([{ suggestions: [{ text: "Run the tests" }] }]);
expect(published).toEqual([sent("Run the tests")]);
});
it("clears the previous prediction when the next prompt arrives", async () => {
const { client, published } = recorder();
const agent = await airAgent(client);
const agent = await agentFor(client, capabilities);
// The second turn predicts nothing, so without the clear at the prompt the
// first turn's prediction would still sit in the composer after it.
await run(agent, ["Run the tests", null]);
expect(published).toEqual([{ suggestions: [{ text: "Run the tests" }] }, { suggestions: [] }]);
expect(published).toEqual([sent("Run the tests"), sent(null)]);
});
it("does not publish a prediction that is only whitespace", async () => {
const { client, published } = recorder();
const agent = await airAgent(client);
const agent = await agentFor(client, capabilities);
await run(agent, [" "]);
@@ -125,7 +168,7 @@ describe("the follow-up prompt at turn-end", () => {
it("drops a prediction the next prompt outran", async () => {
const { client, published } = recorder();
const agent = await airAgent(client);
const agent = await agentFor(client, capabilities);
// Both prompts are sent before the consumer reads the first turn's
// prediction: it answers a turn the user has already moved past, so it must
@@ -134,14 +177,60 @@ describe("the follow-up prompt at turn-end", () => {
expect(published).toEqual([]);
});
});
it("sends nothing to a client that is not AIR", async () => {
describe("the follow-up prompt of a client by what it declares", () => {
it("sends nothing to a client that is not AIR and advertises no prompt suggestions", async () => {
const { client, published } = recorder();
const agent = new ClaudeAcpAgent(client, { log: () => {}, error: () => {} });
await agent.initialize({ protocolVersion: 1, clientCapabilities: {} as ClientCapabilities });
const agent = await agentFor(client, {} as ClientCapabilities);
await run(agent, ["Run the tests"]);
expect(published).toEqual([]);
});
it("sends both forms to an AIR client that advertises prompt suggestions", async () => {
const { client, published } = recorder();
const agent = await agentFor(client, { ...AIR_CLIENT, ...SUGGESTIONS_CLIENT });
await run(agent, ["Run the tests"]);
expect(published).toEqual([
promptSuggestionsUpdate("Run the tests"),
metaUpdate("Run the tests"),
]);
});
/**
* Scenario:
* 1. Two prompts arrive before the first turn's result.
* 2. Each turn ends with a prediction.
* Expected:
* - The first prediction comes while the second prompt waits, so it does not
* account for that prompt. ACP's update drops it. AIR's `_meta` keeps its
* rules and carries it.
* - The second prediction goes out in both forms.
*/
it.each([
{
form: "prompt_suggestions_update",
capabilities: SUGGESTIONS_CLIENT,
expected: [promptSuggestionsUpdate("Commit")],
},
{
form: "AIR's _meta",
capabilities: AIR_CLIENT,
expected: [metaUpdate("Run the tests"), metaUpdate("Commit")],
},
])(
"handles a prediction that arrives while another prompt waits by the rules of $form",
async ({ capabilities, expected }) => {
const { client, published } = recorder();
const agent = await agentFor(client, capabilities);
await run(agent, ["Run the tests", "Commit"], { queued: true });
expect(published).toEqual(expected);
},
);
});

View File

@@ -8,7 +8,7 @@
import { vi } from "vitest";
import { randomUUID } from "crypto";
import { SessionBackgroundWork } from "../../v1/background-work.js";
import { PromptSuggestions } from "../../prompt-suggestions.js";
import { clientTakesPromptSuggestions, PromptSuggestions } from "../../prompt-suggestions.js";
import { SessionTitles } from "../../session-titles.js";
import { DEFAULT_CONTEXT_WINDOW } from "../../session-usage.js";
@@ -101,10 +101,12 @@ export function mockSessionState(
owedTrailingIdles: 0,
messageIdToUuid: new Map(),
sessionFailureState: { epoch: randomUUID(), revisions: new Map(), active: new Map() },
// As `createSession` gives it to the session of an AIR client.
...(agent?.toolCallCapabilities?.air?.client
? { promptSuggestions: new PromptSuggestions() }
: {}),
// As `createSession` gives it to the session: for an AIR client, and for
// one that advertised `session.promptSuggestions`.
promptSuggestions: PromptSuggestions.forClient({
meta: agent?.toolCallCapabilities?.air?.client === true,
update: clientTakesPromptSuggestions(agent?.clientCapabilities?.session),
}),
...overrides,
} as any;
}

View File

@@ -4789,19 +4789,43 @@ describe("ACP v2 core", () => {
},
);
it.each([
["an AIR client", air(), true],
["any other client", {}, false],
/** The `prompt_suggestion` that Claude Code sends after a result. */
const suggestion = (text: string) => ({
type: "prompt_suggestion",
suggestion: text,
uuid: randomUUID(),
session_id: "session",
});
/**
* The predicted prompts that the session's updates carried, in order: the
* texts of each list, tagged with the form that carried it. An empty list
* clears the prediction.
*/
const predictions = (updates: v2.SessionUpdate[]) =>
updates.flatMap((update): Array<[string, string[]]> => {
if (v2.SessionUpdate.isPromptSuggestionsUpdate(update)) {
const texts = update.suggestions.map(({ prompt }) =>
prompt.map((block) => (block.type === "text" ? block.text : block.type)).join(""),
);
return [["update", texts]];
}
const meta = update._meta as { promptSuggestions?: { suggestions: { text: string }[] } };
return update.sessionUpdate === "session_info_update" && meta?.promptSuggestions
? [["meta", meta.promptSuggestions.suggestions.map(({ text }) => text)]]
: [];
});
const SUGGESTIONS_CLIENT: v2.ClientCapabilities = { session: { promptSuggestions: {} } };
it.each<[string, v2.ClientCapabilities, string | undefined]>([
["an AIR client", air(), "meta"],
["a client that advertises session.promptSuggestions", SUGGESTIONS_CLIENT, "update"],
["any other client", {}, undefined],
])(
"sends %s the predicted follow-up prompt, cleared at the next prompt and at a reset",
async (_, capabilities, predicted) => {
async (_, capabilities, form) => {
const client = v2Client();
const suggestion = (text: string) => ({
type: "prompt_suggestion",
suggestion: text,
uuid: randomUUID(),
session_id: "session",
});
const { claude, sessionId } = await client.connect(async (agent) => {
const { response, claude } = await openSession(agent, capabilities);
const prompt = async (index: number) => {
@@ -4837,16 +4861,80 @@ describe("ACP v2 core", () => {
return { claude, sessionId: response.sessionId };
});
const sent = updatesOf(client.notifications, sessionId).flatMap((update) => {
const meta = update._meta as { promptSuggestions?: { suggestions: unknown } } | null;
return update.sessionUpdate === "session_info_update" && meta?.promptSuggestions
? [meta.promptSuggestions.suggestions]
: [];
});
expect(sent).toEqual(
predicted ? [[{ text: "Run the tests" }], [], [{ text: "Commit" }], []] : [],
expect(predictions(updatesOf(client.notifications, sessionId))).toEqual(
form
? [
[form, ["Run the tests"]],
[form, []],
[form, ["Commit"]],
[form, []],
]
: [],
);
expect(claude.options.promptSuggestions).toBe(predicted ? true : undefined);
expect(claude.options.promptSuggestions).toBe(form ? true : undefined);
},
);
/**
* Scenario:
* 1. A second prompt arrives while the first turn runs. The first turn's
* result and its prediction come before Claude Code takes the prompt in.
* 2. The second turn ends with a prediction.
* 3. Claude Code starts a cycle on its own.
* Expected:
* - `prompt_suggestions_update` follows ACP: the prediction that does not
* account for the waiting prompt is dropped, and the list is withdrawn
* when the cycle starts.
* - AIR's `_meta` form keeps its rules: both predictions go out, and the
* second stays until the next prompt.
*/
it.each<[string, v2.ClientCapabilities, Array<[string, string[]]>]>([
[
"prompt_suggestions_update",
SUGGESTIONS_CLIENT,
[
["update", ["Commit"]],
["update", []],
],
],
[
"AIR's _meta",
air(),
[
["meta", ["Outrun"]],
["meta", ["Commit"]],
],
],
])(
"handles work that a prediction does not account for by the rules of %s",
async (_, capabilities, expected) => {
const client = v2Client();
const sessionId = await client.connect(async (agent) => {
const { response, claude } = await openSession(agent, capabilities);
const send = () =>
agent.request(v2.methods.agent.session.prompt, {
sessionId: response.sessionId,
prompt: PROMPT,
});
const first = send();
claude.send(echo(await claude.prompt(0)));
await first;
const second = send();
const waiting = await claude.prompt(1);
claude.send(result());
claude.send(suggestion("Outrun"));
claude.send(echo(waiting));
await second;
claude.send(result());
claude.send(suggestion("Commit"));
claude.send(sessionState("idle"));
await vi.waitFor(() => expect(client.states().at(-1)).toBe("idle"));
claude.send(cycleStart());
await vi.waitFor(() => expect(client.states().at(-1)).toBe("running"));
return response.sessionId;
});
expect(predictions(updatesOf(client.notifications, sessionId))).toEqual(expected);
},
);

View File

@@ -98,7 +98,11 @@ import {
toGoalSnapshot,
} from "./goal-extension.js";
import { checklistPlanUpdate, resetPlanUpdates, type SubagentChecklists } from "../plans.js";
import { PromptSuggestions } from "../prompt-suggestions.js";
import {
clientTakesPromptSuggestions,
promptSuggestionOptions,
PromptSuggestions,
} from "../prompt-suggestions.js";
import { savedSessionStatus, SESSION_STATUS_CAPABILITY } from "../session-status.js";
import {
applyInitialConfigOptions,
@@ -891,7 +895,8 @@ export type Session = {
/** Last goal snapshot sent to the ACP client, used to roll back an
* optimistic `/goal` update when the command itself fails. */
lastPublishedGoal?: GoalSnapshot | null;
/** The follow-up prompt the client holds, for an AIR client only. */
/** The follow-up prompt the client holds, for an AIR client and for one that
* advertised `session.promptSuggestions`. Undefined for any other client. */
promptSuggestions?: PromptSuggestions;
/** Count of result messages the consumer should treat as orphans and skip
* (not promote/attribute to the current head). When cancel() settles+removes
@@ -2562,7 +2567,7 @@ export class ClaudeAcpAgent {
// session that holds no prediction needs no clear, and the prompt path
// then keeps the ordering it has without this feature.
const cleared = session.promptSuggestions?.clear();
if (cleared) await this.publishPromptSuggestion(params.sessionId, cleared);
if (cleared?.length) await this.publishPromptSuggestions(params.sessionId, cleared);
}
// A `/remote-control` command still in flight answers into the session's
@@ -2909,19 +2914,16 @@ export class ClaudeAcpAgent {
}
/**
* Sends the `_meta` of a session's {@link PromptSuggestions}: the follow-up
* Sends the updates of a session's {@link PromptSuggestions}: the follow-up
* prompt the CLI predicted for the next turn, or the clear of the one the
* client holds. Only AIR renders it, so only an AIR session has the state;
* see `docs/air-extensions.md`.
* client holds, in each form the client takes. Only a session of AIR or of a
* client that advertised `session.promptSuggestions` has the state.
*/
private async publishPromptSuggestion(
private async publishPromptSuggestions(
sessionId: string,
meta: Record<string, unknown>,
updates: SessionNotification["update"][],
): Promise<void> {
await this.client.sessionUpdate({
sessionId,
update: { sessionUpdate: "session_info_update", _meta: meta },
});
for (const update of updates) await this.client.sessionUpdate({ sessionId, update });
}
private async publishTaskPlan(sessionId: string, taskState: TaskState): Promise<void> {
@@ -7140,7 +7142,7 @@ export class ClaudeAcpAgent {
// The follow-up prompt was predicted from the transcript the reset
// dropped, so it no longer follows from anything.
const cleared = session.promptSuggestions?.clear();
if (cleared) await this.publishPromptSuggestion(params.sessionId, cleared);
if (cleared?.length) await this.publishPromptSuggestions(params.sessionId, cleared);
// The recorded request and TTL describe the dropped conversation.
session.idleCompaction?.reset();
break;
@@ -7150,9 +7152,16 @@ export class ClaudeAcpAgent {
case "prompt_suggestion": {
// The CLI predicts the next prompt after the turn's `result`. AIR
// shows it as gray text in an empty composer; Tab fills the
// composer, and nothing is sent until the user sends it.
const suggested = session.promptSuggestions?.suggested(message.suggestion);
if (suggested) await this.publishPromptSuggestion(params.sessionId, suggested);
// composer, and nothing is sent until the user sends it. While
// Claude works, such as on a prompt queued before that result,
// the `prompt_suggestions_update` form drops the prediction.
const suggested = session.promptSuggestions?.suggested(
message.suggestion,
this.claudeIsWorking(params.sessionId, session),
);
if (suggested?.length) {
await this.publishPromptSuggestions(params.sessionId, suggested);
}
break;
}
case "auth_status":
@@ -10185,6 +10194,10 @@ export class ClaudeAcpAgent {
const subagentConfigHook = subagentForm(this.clientCapabilities)
? this.subagentConfigurationHook(sessionId)
: undefined;
const suggestionForms = {
meta: this.toolCallCapabilities.air.client,
update: clientTakesPromptSuggestions(this.clientCapabilities?.session),
};
const options: Options = {
systemPrompt,
settingSources: ["user", "project", "local"],
@@ -10201,12 +10214,16 @@ export class ClaudeAcpAgent {
// `perTaskStopAffordance` wins.
...(subagentForm(this.clientCapabilities) === "rfd" ? { perTaskStopAffordance: true } : {}),
// One predicted follow-up prompt per turn, published as
// `session_info_update._meta.promptSuggestions`. It rides the turn's own
// `prompt_suggestions_update` or, for AIR, as
// `session_info_update._meta.promptSuggestions` (see
// `prompt-suggestions.ts`). Only AIR and a client that advertised
// `session.promptSuggestions` get it, so no other client's session
// spends a request on it. It rides the turn's own
// prompt cache, and the user can turn it off in settings.json
// (`promptSuggestionEnabled`) or with CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false.
// Before `userProvidedOptions`, so a client that passes
// `promptSuggestions: false` keeps it off.
promptSuggestions: true,
...promptSuggestionOptions(suggestionForms),
// Before `userProvidedOptions`, so a client's own `mcpServersDelivery` wins.
mcpServersDelivery: mcpServersDelivery(),
...userProvidedOptions,
@@ -10704,9 +10721,7 @@ export class ClaudeAcpAgent {
settingsManager.getApiKeyHelper(configuredSettingsObject),
)?.kind,
fileChangeReporter,
...(this.toolCallCapabilities.air.client
? { promptSuggestions: new PromptSuggestions() }
: {}),
promptSuggestions: PromptSuggestions.forClient(suggestionForms),
};
const registered = this.sessions[sessionId];
registered.idleCompaction = new IdleCompaction(

View File

@@ -41,6 +41,11 @@ import { forkSession } from "../fork-session.js";
import { supportsMcpOAuth } from "../mcp-oauth.js";
import { McpOverAcp, sdkMcpServers } from "../mcp-servers.js";
import { ALLOW_BYPASS, autoModeDisabled } from "../permissions/modes.js";
import {
clientTakesPromptSuggestions,
promptSuggestionOptions,
type PromptSuggestionForms,
} from "../prompt-suggestions.js";
import {
readHistoryAcrossCompactions,
readResumedTail,
@@ -195,6 +200,8 @@ class V2Agent implements AgentHandle, SessionConnection {
elicitation: ElicitationSupport = { form: false, url: false };
/** The AIR extensions that the client takes (see `air.ts`). */
air: AirSupport = NO_AIR;
/** The forms of the predicted follow-up prompt that the client takes, read at `initialize`. */
promptSuggestions: PromptSuggestionForms = { meta: false, update: false };
constructor(
private readonly ctx: v2.AgentContext,
@@ -342,6 +349,10 @@ class V2Agent implements AgentHandle, SessionConnection {
url: request.capabilities?.elicitation?.url != null,
};
this.air = airSupport(request.capabilities);
this.promptSuggestions = {
meta: this.air.client,
update: clientTakesPromptSuggestions(request.capabilities?.session),
};
const { authMethods, auth, _meta } = this.auth.initialize(request.capabilities);
const airMeta = airInitializeMeta(this.air);
return {
@@ -1085,10 +1096,11 @@ class V2Agent implements AgentHandle, SessionConnection {
// client stops one at a time: `session/cancel` must leave listed work
// running. Before the client's options.
perTaskStopAffordance: true,
// AIR's predicted follow-up prompt (see `reports.ts`), as on v1. Only
// AIR gets it, so no other client's session spends a request on it.
// The predicted follow-up prompt (see `reports.ts`): only AIR and a
// client that advertised `session.promptSuggestions` get it, so no
// other client's session spends a request on it.
// Before the client's options: `promptSuggestions: false` turns it off.
...(this.air.client ? { promptSuggestions: true } : {}),
...promptSuggestionOptions(this.promptSuggestions),
// Before the client's options: its own `mcpServersDelivery` wins.
mcpServersDelivery: mcpServersDelivery(),
...client,

View File

@@ -2,7 +2,7 @@
* The reports of a v2 session that are not Claude's output: the
* context window and cost (`usage_update`), Claude Code's warnings and MCP startup failures (`notice`), compactions
* (`compaction_update`), the title (`session_info_update`), the predicted
* follow-up prompt of an AIR client (`session_info_update._meta.promptSuggestions`),
* predicted follow-up prompt (`prompt_suggestions_update`, and AIR's `_meta.promptSuggestions`),
* and the adapter's own idle compaction.
*
* They are built as the v1 core builds them, from the shared modules
@@ -37,7 +37,7 @@ import {
} from "../context-window.js";
import { IdleCompaction } from "../idle-compaction.js";
import type { UnservedMcpServer } from "../mcp-servers.js";
import { PromptSuggestions } from "../prompt-suggestions.js";
import { PromptSuggestions, type PromptSuggestionForms } from "../prompt-suggestions.js";
import {
informationalNotice,
mcpServerStartupNotice,
@@ -65,11 +65,14 @@ type UsageUpdate = Extract<AcpSessionNotification["update"], { sessionUpdate: "u
export interface ReportsHost {
readonly sessionId: string;
readonly logger: Logger;
/** The client is JetBrains AIR, the only one that gets the predicted follow-up prompt. */
readonly airClient: boolean;
/** The forms of the predicted follow-up prompt that the client takes (see `prompt-suggestions.ts`). */
readonly promptSuggestions: PromptSuggestionForms;
/** Sends v1-shaped updates of the session, in the order of the calls. */
emit(notifications: AcpSessionNotification[]): void;
/** For the idle compaction: whether the session is busy, and its `/compact`. */
/**
* Whether the session is busy: for the idle compaction, and for a predicted
* prompt that arrives meanwhile. `compact` is the idle compaction's `/compact`.
*/
isBusy(): boolean;
compact(): Promise<void>;
/** The session as titles read it, the same object each time; undefined until it starts and once it ends. */
@@ -142,11 +145,11 @@ export class SessionReports {
private disposed = false;
/** The context used after the last main-thread request. */
private contextUsed: number | undefined;
/** The follow-up prompt the client holds, for an AIR client only. */
/** The follow-up prompt the client holds. Undefined for a client that takes none. */
private suggestions: PromptSuggestions | undefined;
constructor(private readonly host: ReportsHost) {
this.suggestions = host.airClient ? new PromptSuggestions() : undefined;
this.suggestions = PromptSuggestions.forClient(host.promptSuggestions);
this.titles = new SessionTitles(
{
client: { sessionUpdate: async (notification) => host.emit([notification]) },
@@ -219,6 +222,10 @@ export class SessionReports {
this.lastTotal = null;
this.lastModel = null;
this.noticeTexts = [];
// ACP: a list of suggestions is withdrawn when foreground work starts
// without a prompt, such as a cycle that Claude Code started on its own.
// A prompt's own turn finds the list withdrawn already (`promptSent`).
this.sendSuggestions(this.suggestions?.workStarted());
}
/**
@@ -285,7 +292,7 @@ export class SessionReports {
// The prediction is spent: the user sent it or something else. A turn
// that predicts nothing (plan mode, an API error, the usage limit) then
// leaves no stale prediction in the composer.
this.sendSuggestion(this.suggestions?.clear());
this.sendSuggestions(this.suggestions?.clear());
}
/** The client prompt went to Claude Code, which may title the session from it. */
@@ -351,7 +358,7 @@ export class SessionReports {
this.titles.reset();
this.idleCompaction?.reset();
// The prediction came from the transcript that the reset dropped.
this.sendSuggestion(this.suggestions?.clear());
this.sendSuggestions(this.suggestions?.clear());
}
/** Sends the usage of an empty context, as a fresh context for an approved plan starts. */
@@ -477,7 +484,10 @@ export class SessionReports {
switch (message.type) {
case "prompt_suggestion":
// AIR shows it as gray text in an empty composer, which Tab fills.
this.sendSuggestion(this.suggestions?.suggested(message.suggestion));
// While the session is busy, such as with a prompt that waits or a
// cycle that Claude Code started on its own, the
// `prompt_suggestions_update` form drops the prediction.
this.sendSuggestions(this.suggestions?.suggested(message.suggestion, this.host.isBusy()));
return true;
case "rate_limit_event":
this.idleCompaction?.noteRateLimit(message.rate_limit_info);
@@ -607,15 +617,10 @@ export class SessionReports {
}
}
/** Sends the `_meta` of {@link PromptSuggestions}, when it has one. */
private sendSuggestion(meta: Record<string, unknown> | undefined): void {
if (!meta) return;
this.host.emit([
{
sessionId: this.host.sessionId,
update: { sessionUpdate: "session_info_update", _meta: meta },
},
]);
/** Sends the updates of {@link PromptSuggestions}, when it has any. */
private sendSuggestions(updates: AcpSessionNotification["update"][] | undefined): void {
if (!updates?.length) return;
this.host.emit(updates.map((update) => ({ sessionId: this.host.sessionId, update })));
}
/**

View File

@@ -61,6 +61,10 @@ export function v2SessionUpdate(
case "session_message_chunk":
// The subagents RFD gives these the same shape in v1 and v2.
return update;
case "prompt_suggestions_update":
// The prompt suggestions RFD gives it the same shape in v1 and v2, and
// v2 content blocks are a superset of the v1 blocks.
return update;
case "current_mode_update":
// v2 has no modes: the mode is the `mode` config option. Every mode
// change also reaches the client as a `config_option_update` or in the

View File

@@ -68,6 +68,7 @@ import type { UnservedMcpServer } from "../mcp-servers.js";
import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
import { planModeUpdate } from "../exit-plan.js";
import { resetPlanUpdates } from "../plans.js";
import type { PromptSuggestionForms } from "../prompt-suggestions.js";
import { forkCursorUpdate, promptGetsCursor } from "../session-cursors.js";
import type { ClearContextReset } from "../clear-context-coordinator.js";
import { agentFileChangeReportMeta } from "../file-change-audit.js";
@@ -105,6 +106,8 @@ export interface SessionConnection {
): Promise<v2.RequestPermissionResponse>;
/** The elicitation modes that the client advertised. */
readonly elicitation: ElicitationSupport;
/** The forms of the predicted follow-up prompt that the client takes, read at `initialize`. */
readonly promptSuggestions: PromptSuggestionForms;
createElicitation(
request: CreateElicitationRequest,
signal: AbortSignal,
@@ -261,7 +264,7 @@ export class V2Session implements RequestTarget {
this.reports = new SessionReports({
sessionId,
logger: connection.logger,
airClient: connection.air.client,
promptSuggestions: connection.promptSuggestions,
emit: (notifications) => this.output.emitV1(notifications),
isBusy: () => this.foreground || this.pending.size > 0 || this.requests.size > 0,
compact: () => this.compact(),