Compare commits

..

3 Commits

Author SHA1 Message Date
Ben Brandt
affc731e3a docs: clarify stream-id tracking and liveStreamed dedup assumptions
Add comments explaining (1) why the streamed-id tracking runs for every
stream_event rather than only parent_tool_use_id === null, and that the
single currentStreamingMessageId field is safe given serialized events,
and (2) that the liveStreamed drop is all-or-nothing per message id.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 11:03:50 +02:00
cuiyiming.leo95
63b708176e fix: dedup fallback text/thinking per content block, not per message id
The fallback added in dc640e2 keyed its dedup on the assistant message
id: once a message id emitted any text/thinking block, the id was added
to `textStreamedMessageIds` and every later block under that id was
filtered out. That breaks when an OpenAI-compatible gateway (observed
with gpt-5.4) splits a single assistant response into several `assistant`
messages that share one id but each carry a different block — typically
an empty `thinking` block first, then the real `text` block. The empty
thinking block flagged the id, so the actual answer arriving in a later
same-id message was dropped: the client saw the fallback log fire but
received an empty turn.

Track the assembled blocks the fallback already emitted this turn
(`fallbackEmittedBlockKeys`, keyed on id + block type + block content)
instead of flagging the whole message id. Distinct blocks that share an
id are all forwarded, while identical re-deliveries (an incremental block
followed by a consolidated message, or the same message delivered twice)
still dedup. `textStreamedMessageIds` returns to its original meaning —
"was this streamed live via deltas" — and is no longer written by the
fallback. The new set is turn-scoped and cleared alongside it.

Tests cover split-block delivery (empty thinking then text under one id),
multiple distinct text blocks sharing an id, and the
incremental-then-consolidated dedup case.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 23:57:26 -07:00
cuiyiming.leo95
dc640e2dcf fix: fall back to assembled assistant text when no stream deltas arrive
The `assistant` case in the prompt loop unconditionally filtered out
`text` and `thinking` content blocks on the assumption that those had
already been pushed to the client via `stream_event` →
`content_block_delta` notifications. That assumption holds when the
underlying SDK / model proxy emits Anthropic-style streaming deltas, but
it breaks when the model is fronted by a proxy that returns the second
model call (the one that consumes a tool_result) as a single non-
streamed assistant message. In that case `content_block_delta` for the
final text is never produced, the assembled `text` block is filtered
out, and the ACP client receives `stopReason: "end_turn"` with no
`agent_message_chunk` notifications — so the user sees the tool's
progress but an empty final answer.

Track which assistant message ids have actually produced streamed
text/thinking deltas (`textStreamedMessageIds` on `Session`, populated
from `message_start` + `content_block_delta` in the `stream_event`
case). In the `assistant` case, keep the existing filter when the id is
in that set and fall back to forwarding the assembled `text` / `thinking`
blocks as `agent_message_chunk` / `agent_thought_chunk` when it isn't.
The fallback emits exactly once per assistant message id, mirroring the
dedupe pattern already used by `toolUseCache` for tool_use blocks.

Tests cover both branches: a session whose assistant message arrives
with no preceding `content_block_delta` now produces exactly one text
chunk, and a session that did stream the same text via deltas does not
re-emit it.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-27 18:51:35 -07:00
18 changed files with 1512 additions and 4713 deletions

View File

@@ -21,7 +21,7 @@ jobs:
timeout-minutes: 5
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
- name: Use Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e

View File

@@ -44,7 +44,7 @@ jobs:
contents: read
id-token: write
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e
with:

View File

@@ -1,3 +1,3 @@
{
".": "0.47.0"
".": "0.37.0"
}

View File

@@ -1,136 +1,5 @@
# Changelog
## [0.47.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.46.0...v0.47.0) (2026-06-17)
### Features
* Update to claude-agent-sdk 0.3.179 ([#783](https://github.com/agentclientprotocol/claude-agent-acp/issues/783)) ([59a098c](https://github.com/agentclientprotocol/claude-agent-acp/commit/59a098c2b530bbae034e9a2dfbd31f8b4ef2a4d0))
### Bug Fixes
* Duplicate assistant messages in feed ([#785](https://github.com/agentclientprotocol/claude-agent-acp/issues/785)) ([12d34e6](https://github.com/agentclientprotocol/claude-agent-acp/commit/12d34e64e53564602ac1c38a30127e234c5c25ff))
## [0.46.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.45.1...v0.46.0) (2026-06-16)
### Features
* Update to claude-agent-sdk 0.3.178 ([#777](https://github.com/agentclientprotocol/claude-agent-acp/issues/777)) ([58549ff](https://github.com/agentclientprotocol/claude-agent-acp/commit/58549ffe6a8b02ce59894e567407bd4299c11428))
### Bug Fixes
* Better handle out of turn events ([#780](https://github.com/agentclientprotocol/claude-agent-acp/issues/780)) ([4f273a2](https://github.com/agentclientprotocol/claude-agent-acp/commit/4f273a20d870c9c69f71556b8e0519f1de30f285))
* Forward option details in elicitation meta ([#779](https://github.com/agentclientprotocol/claude-agent-acp/issues/779)) ([b364059](https://github.com/agentclientprotocol/claude-agent-acp/commit/b3640599ae685beecacd93e012d5bbc9dac716f7)), closes [#764](https://github.com/agentclientprotocol/claude-agent-acp/issues/764)
## [0.45.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.45.0...v0.45.1) (2026-06-16)
### Bug Fixes
* Fix terminal error printing as text instead of terminal output ([#776](https://github.com/agentclientprotocol/claude-agent-acp/issues/776)) ([db6eaaf](https://github.com/agentclientprotocol/claude-agent-acp/commit/db6eaaf71484a321e47093ad65bcf8994943cb31))
* Scope custom answers per question ([#774](https://github.com/agentclientprotocol/claude-agent-acp/issues/774)) ([d58004a](https://github.com/agentclientprotocol/claude-agent-acp/commit/d58004a34880e0a76833697319eb2a9efa6a43c7))
## [0.45.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.44.0...v0.45.0) (2026-06-15)
### Features
* **deps-dev:** bump the minor group with 3 updates ([#763](https://github.com/agentclientprotocol/claude-agent-acp/issues/763)) ([7de5e4b](https://github.com/agentclientprotocol/claude-agent-acp/commit/7de5e4bcca9bfea70593092060f82bc8abe33e0e))
* **deps:** bump @anthropic-ai/claude-agent-sdk to 0.3.177 ([#771](https://github.com/agentclientprotocol/claude-agent-acp/issues/771)) ([1be5ca5](https://github.com/agentclientprotocol/claude-agent-acp/commit/1be5ca57ee772fe90e41126365dc4186a18ad257))
### Bug Fixes
* preserve ANTHROPIC_CUSTOM_MODEL_OPTION when availableModels is set ([#768](https://github.com/agentclientprotocol/claude-agent-acp/issues/768)) ([cc2885f](https://github.com/agentclientprotocol/claude-agent-acp/commit/cc2885f6a9993cf61e759c3c770015f94c218627))
## [0.44.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.43.0...v0.44.0) (2026-06-09)
### Features
* **deps:** bump the minor group with 14 updates ([#758](https://github.com/agentclientprotocol/claude-agent-acp/issues/758)) ([7a70162](https://github.com/agentclientprotocol/claude-agent-acp/commit/7a701623df2e05aec8e552bdfd1cf573413c3471))
* **deps:** update to @anthropic-ai/claude-agent-sdk 0.3.170 ([#761](https://github.com/agentclientprotocol/claude-agent-acp/issues/761)) ([d8af943](https://github.com/agentclientprotocol/claude-agent-acp/commit/d8af943a1efef9be27d771cec089d2f1cb56c523))
## [0.43.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.42.0...v0.43.0) (2026-06-09)
### Features
* Add experimental elicitation support ([#756](https://github.com/agentclientprotocol/claude-agent-acp/issues/756)) ([12bd276](https://github.com/agentclientprotocol/claude-agent-acp/commit/12bd2762d9ba0ccb7497a3848a5928b8bb2ce820))
* **deps:** update to @anthropic-ai/claude-agent-sdk 0.3.169 ([#754](https://github.com/agentclientprotocol/claude-agent-acp/issues/754)) ([bd0ae4d](https://github.com/agentclientprotocol/claude-agent-acp/commit/bd0ae4dde160f59559ab4ac1bf703fcf151eff17))
* Update ACP SDK to 0.25.0 ([#753](https://github.com/agentclientprotocol/claude-agent-acp/issues/753)) ([0dbccf5](https://github.com/agentclientprotocol/claude-agent-acp/commit/0dbccf588ff702015494dd29969d47f0b7402feb))
### Bug Fixes
* Forward unstreamed assistant text blocks ([#757](https://github.com/agentclientprotocol/claude-agent-acp/issues/757)) ([7ff6b7f](https://github.com/agentclientprotocol/claude-agent-acp/commit/7ff6b7fd6b157aedbce0c636087f51ae7d1df3a7))
* Validate cwd before creating sessions ([#751](https://github.com/agentclientprotocol/claude-agent-acp/issues/751)) ([9854b0c](https://github.com/agentclientprotocol/claude-agent-acp/commit/9854b0c6790ebafff514e3c4c8e03a131f065a4a)), closes [#749](https://github.com/agentclientprotocol/claude-agent-acp/issues/749)
## [0.42.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.41.0...v0.42.0) (2026-06-05)
### Features
* **deps-dev:** bump obug from 2.1.1 to 2.1.2 in the minor group ([#743](https://github.com/agentclientprotocol/claude-agent-acp/issues/743)) ([7ffb78c](https://github.com/agentclientprotocol/claude-agent-acp/commit/7ffb78c57280fc32af77862896c0035ce0e690b7))
* Send message ids for assistant and user messages ([#750](https://github.com/agentclientprotocol/claude-agent-acp/issues/750)) ([18516a3](https://github.com/agentclientprotocol/claude-agent-acp/commit/18516a3088f847a38f5eee0fe81ad5ca3e2a751c))
* Update Claude Agent SDK to 0.3.165 ([#746](https://github.com/agentclientprotocol/claude-agent-acp/issues/746)) ([23cbe6f](https://github.com/agentclientprotocol/claude-agent-acp/commit/23cbe6f58fa9e10ad736f664c4cf94dbd1c6ad65))
### Bug Fixes
* Prevent cross-family model matching in resolveModelPreference ([#731](https://github.com/agentclientprotocol/claude-agent-acp/issues/731)) ([f4704c1](https://github.com/agentclientprotocol/claude-agent-acp/commit/f4704c168f917e6710f2b3cd49e1fef49613a469))
* Prune tool cache per session after results ([#748](https://github.com/agentclientprotocol/claude-agent-acp/issues/748)) ([ec14211](https://github.com/agentclientprotocol/claude-agent-acp/commit/ec142110561f680330c6976783805685c5c069ec))
* Update to better utilize existing SDK data ([#747](https://github.com/agentclientprotocol/claude-agent-acp/issues/747)) ([398f763](https://github.com/agentclientprotocol/claude-agent-acp/commit/398f763f71bd2fe2ca9e8269de120d26a744b7a8))
## [0.41.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.40.0...v0.41.0) (2026-06-04)
### Features
* **deps:** upgrade to @anthropic-ai/claude-agent-sdk@0.3.162 ([#740](https://github.com/agentclientprotocol/claude-agent-acp/issues/740)) ([add7e31](https://github.com/agentclientprotocol/claude-agent-acp/commit/add7e31704581aa70febb6341ca0e8cee5d93b43))
### Bug Fixes
* Force cancellation when SDK query hangs ([#742](https://github.com/agentclientprotocol/claude-agent-acp/issues/742)) ([cffea4b](https://github.com/agentclientprotocol/claude-agent-acp/commit/cffea4be28e6def91027110433a99e80b1be8a0c)), closes [#680](https://github.com/agentclientprotocol/claude-agent-acp/issues/680)
## [0.40.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.39.0...v0.40.0) (2026-06-02)
### Features
* **deps-dev:** bump the minor group with 2 updates ([#726](https://github.com/agentclientprotocol/claude-agent-acp/issues/726)) ([51a370e](https://github.com/agentclientprotocol/claude-agent-acp/commit/51a370e4feb8a74279698b156e35b96631a74d74))
* **deps:** bump actions/checkout from 6.0.2 to 6.0.3 ([#736](https://github.com/agentclientprotocol/claude-agent-acp/issues/736)) ([9cda07b](https://github.com/agentclientprotocol/claude-agent-acp/commit/9cda07ba9df27b48bd94332e365eed982e3f5613))
* **deps:** bump the minor group with 50 updates ([#737](https://github.com/agentclientprotocol/claude-agent-acp/issues/737)) ([32175b8](https://github.com/agentclientprotocol/claude-agent-acp/commit/32175b83a0227d0baa1f7d7eedabe743b4b870e8))
### Bug Fixes
* Optimize local command marker stripping ([#738](https://github.com/agentclientprotocol/claude-agent-acp/issues/738)) ([895422c](https://github.com/agentclientprotocol/claude-agent-acp/commit/895422c72d5f955903f227dc6887df823d2730e6)), closes [#727](https://github.com/agentclientprotocol/claude-agent-acp/issues/727)
## [0.39.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.38.0...v0.39.0) (2026-05-29)
### Features
* **deps:** update Claude Agent SDK to 0.3.156 ([#722](https://github.com/agentclientprotocol/claude-agent-acp/issues/722)) ([3fb6db4](https://github.com/agentclientprotocol/claude-agent-acp/commit/3fb6db4e5ee5bd1f431cf5d2ce5331ce983f9597))
## [0.38.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.37.0...v0.38.0) (2026-05-28)
### Features
* **deps:** bump to @anthropic-ai/claude-agent-sdk 0.3.154 (Opus 4.8) ([#716](https://github.com/agentclientprotocol/claude-agent-acp/issues/716)) ([a172885](https://github.com/agentclientprotocol/claude-agent-acp/commit/a172885c80fc32c108a8501268a543641088f543))
* Support Opus 4.8 ([#718](https://github.com/agentclientprotocol/claude-agent-acp/issues/718)) ([98b54a0](https://github.com/agentclientprotocol/claude-agent-acp/commit/98b54a02c267cdef619becceccf6ef519fbf8f6f))
### Bug Fixes
* Remove hide Claude auth flag handling ([#707](https://github.com/agentclientprotocol/claude-agent-acp/issues/707)) ([7ed1daf](https://github.com/agentclientprotocol/claude-agent-acp/commit/7ed1daf7b42088ad149e9bf742f764752b82d093))
## [0.37.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.36.1...v0.37.0) (2026-05-21)

630
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
"publishConfig": {
"access": "public"
},
"version": "0.47.0",
"version": "0.37.0",
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
"main": "dist/lib.js",
"types": "dist/lib.d.ts",
@@ -60,22 +60,22 @@
"author": "Zed Industries",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "0.26.0",
"@anthropic-ai/claude-agent-sdk": "0.3.179",
"@agentclientprotocol/sdk": "0.22.1",
"@anthropic-ai/claude-agent-sdk": "0.3.146",
"zod": "^3.25.0 || ^4.0.0"
},
"devDependencies": {
"@anthropic-ai/sdk": "0.104.2",
"@anthropic-ai/sdk": "0.97.1",
"@eslint/js": "10.0.1",
"@types/node": "25.9.3",
"@typescript-eslint/eslint-plugin": "8.61.1",
"@typescript-eslint/parser": "8.61.1",
"eslint": "10.5.0",
"@types/node": "25.9.1",
"@typescript-eslint/eslint-plugin": "8.59.4",
"@typescript-eslint/parser": "8.59.4",
"eslint": "10.4.0",
"eslint-config-prettier": "10.1.8",
"globals": "17.6.0",
"prettier": "3.8.4",
"prettier": "3.8.3",
"ts-node": "10.9.2",
"typescript": "6.0.3",
"vitest": "4.1.9"
"vitest": "4.1.7"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,301 +0,0 @@
import { randomUUID } from "node:crypto";
import type {
CreateElicitationRequest,
CreateElicitationResponse,
ElicitationPropertySchema,
ElicitationSchema,
EnumOption,
} from "@agentclientprotocol/sdk";
import type { ElicitationRequest, ElicitationResult } from "@anthropic-ai/claude-agent-sdk";
import type {
AskUserQuestionInput,
AskUserQuestionOutput,
} from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
/**
* Bridges between the Claude Agent SDK's elicitation/dialog callbacks and ACP's
* (unstable) elicitation protocol.
*
* Two distinct SDK surfaces flow through here:
*
* 1. `onElicitation` — fired when an MCP server requests user input. These map
* directly onto ACP `session/create_elicitation` (form or url mode).
* 2. The built-in AskUserQuestion tool — when a `canUseTool` callback is
* registered the SDK routes its permission check through `canUseTool`
* (not the interactive `permission_ask_user_question` dialog). We render
* its questions as an ACP form elicitation and feed the user's selections
* back as the tool's `updatedInput`, which the tool's own `call()` reads.
*/
/** Modes the connected client advertised support for. */
export type ElicitationSupport = {
form: boolean;
url: boolean;
};
/**
* Convert an MCP elicitation request (from the SDK's `onElicitation` callback)
* into an ACP `CreateElicitationRequest`. Returns `null` when the request can't
* be represented (e.g. a url-mode request with no url).
*/
export function mcpElicitationToCreateRequest(
request: ElicitationRequest,
sessionId: string,
): CreateElicitationRequest | null {
if (request.mode === "url") {
if (!request.url) {
return null;
}
return {
mode: "url",
sessionId,
message: request.message,
url: request.url,
// URL elicitations need a stable id so the client can correlate the
// later `session/complete_elicitation` notification. MCP servers usually
// provide one; fall back to a generated id if not.
elicitationId: request.elicitationId ?? randomUUID(),
};
}
// Form mode (the default). The MCP `requestedSchema` is already a JSON Schema
// with primitive-typed properties, which is structurally what ACP expects.
return {
mode: "form",
sessionId,
message: request.message,
requestedSchema: normalizeElicitationSchema(request.requestedSchema),
};
}
/**
* Map an ACP elicitation response back to the MCP `ElicitResult` the SDK expects
* to hand back to the requesting server.
*/
export function createElicitationResponseToElicitResult(
response: CreateElicitationResponse,
): ElicitationResult {
switch (response.action) {
case "accept":
return { action: "accept", content: response.content ?? {} };
case "decline":
return { action: "decline" };
case "cancel":
default:
return { action: "cancel" };
}
}
/**
* A single question as supplied by the AskUserQuestion tool. Derived from the
* SDK's input type so the shape stays in sync; the SDK validates the model's
* tool call against this schema before it reaches us.
*/
export type AskUserQuestion = AskUserQuestionInput["questions"][number];
/**
* Pull the well-formed questions out of an AskUserQuestion tool input. Returns
* `null` when there are no usable questions — including the case where every
* entry is malformed and filtering leaves an empty list — so callers can treat
* "nothing to ask" uniformly.
*/
export function extractAskUserQuestions(input: Record<string, unknown>): AskUserQuestion[] | null {
const questions = (input as { questions?: unknown }).questions;
if (!Array.isArray(questions)) {
return null;
}
const valid = questions.filter(
(q): q is AskUserQuestion =>
!!q && typeof q.question === "string" && Array.isArray(q.options) && q.options.length > 0,
);
return valid.length > 0 ? valid : null;
}
/** Stable form-field key for the question at the given index. */
function questionFieldKey(index: number): string {
return `question_${index}`;
}
/**
* Form-field key for the per-question free-text "custom answer" field that sits
* alongside `question_<n>`. Mirrors the first-party clients, where every
* question carries its own "Other" box rather than one form-level field.
*/
function questionCustomFieldKey(index: number): string {
return `question_${index}_custom`;
}
/**
* `_meta` key under which a bridged enum option carries its structured
* `description`/`preview`, since ACP's `EnumOption` has no field for either.
* Namespaced like the agent's other `_meta` extensions (`_claude/...`).
*/
const OPTION_META_KEY = "_claude/askUserQuestionOption";
/** A single option as supplied by the AskUserQuestion tool. */
type AskUserQuestionOption = AskUserQuestion["options"][number];
/**
* Build the `_meta` payload that carries an option's structured `description`
* and optional `preview` for clients that can render them as distinct fields.
* Returns `undefined` when neither is present, so we don't emit an empty `_meta`.
*/
function askUserQuestionOptionMeta(
option: AskUserQuestionOption,
): NonNullable<EnumOption["_meta"]> | undefined {
const detail: { description?: string; preview?: string } = {};
if (option.description) {
detail.description = option.description;
}
if (option.preview) {
detail.preview = option.preview;
}
return Object.keys(detail).length > 0 ? { [OPTION_META_KEY]: detail } : undefined;
}
/**
* Render the AskUserQuestion tool's questions as an ACP form elicitation.
*
* Fields are keyed by a short stable id (`question_<n>`) rather than the full
* question text, so the question text appears in exactly one place per field.
* Single-select questions use a titled `oneOf` enum; multi-select questions use
* an array with a titled `anyOf` item enum. The enum `const` is always the
* option label, since that is what the tool records as the answer.
*
* Each question is followed by its own optional free-text "custom answer" field
* (`question_<n>_custom`), mirroring the CLI's per-question "Other" box: the
* user can type their own answer instead of picking an option, scoped to that
* specific question. Nothing is marked required, so the user can also just skip
* — matching the built-in tool, which always offers Skip + a free-text box.
*/
export function askUserQuestionsToCreateRequest(
questions: AskUserQuestion[],
sessionId: string,
toolCallId: string | undefined,
): CreateElicitationRequest {
const single = questions.length === 1;
const properties: Record<string, ElicitationPropertySchema> = {};
questions.forEach((question, index) => {
const options: EnumOption[] = question.options.map((option) => {
const enumOption: EnumOption = {
const: option.label,
// `title` stays a flattened "label — description" string so clients that
// only read `const`/`title` still surface the description. Clients that
// understand the `_meta` below should prefer its structured fields (and
// treat `const` as the clean label) rather than parsing this title.
title: option.description ? `${option.label} — ${option.description}` : option.label,
};
// The SDK option carries a `description` (secondary text) and an optional
// `preview` (mockups, code snippets, comparisons shown on focus). Neither
// has a structural slot in `EnumOption`, so forward them under ACP's
// reserved `_meta` extension point for clients that can render them.
const meta = askUserQuestionOptionMeta(option);
if (meta) {
enumOption._meta = meta;
}
return enumOption;
});
// For a single question the prompt is carried by `message`, so we don't
// repeat it in the field description. With multiple questions each field
// needs its own question text.
const description = single ? undefined : question.question;
const title = question.header || undefined;
properties[questionFieldKey(index)] = question.multiSelect
? { type: "array", title, description, items: { anyOf: options } }
: { type: "string", title, description, oneOf: options };
properties[questionCustomFieldKey(index)] = {
type: "string",
title: "Other",
description: "Type your own answer instead of choosing an option above (optional).",
};
});
const requestedSchema: ElicitationSchema = {
type: "object",
properties,
};
const message = single ? questions[0].question : "Please answer the following questions.";
return {
mode: "form",
sessionId,
...(toolCallId ? { toolCallId } : {}),
message,
requestedSchema,
};
}
/** Outcome of an AskUserQuestion elicitation, decoupled from any transport. */
export type AskUserQuestionOutcome =
| { action: "answered"; updatedInput: Record<string, unknown> }
| { action: "cancel" };
/**
* Fold an ACP elicitation response into the AskUserQuestion tool's input.
*
* Selected labels are read back from the indexed form fields and written into
* `answers` as a `{ [questionText]: label }` map (comma-joining multi-selects)
* — the key shape the tool's own `call()` reads. A non-empty per-question
* custom-answer field (`question_<n>_custom`) takes precedence over that
* question's selection, since the user typed their own answer instead of
* picking one. Decline yields empty answers (the model is told the user skipped
* rather than the turn aborting); cancel aborts the tool call.
*/
export function applyAskElicitationResponse(
response: CreateElicitationResponse,
toolInput: Record<string, unknown>,
questions: AskUserQuestion[],
): AskUserQuestionOutcome {
if (response.action === "cancel") {
return { action: "cancel" };
}
if (response.action === "decline") {
return { action: "answered", updatedInput: { ...toolInput, answers: {} } };
}
const content = response.content ?? {};
// Typed against the tool's own output schema so the answer/response shapes
// stay in sync with what the built-in tool's call() expects to read back.
const answers: AskUserQuestionOutput["answers"] = {};
questions.forEach((question, index) => {
// A typed custom answer wins over the selection: the user chose to write
// their own answer for this question instead of picking an option.
const custom = content[questionCustomFieldKey(index)];
if (typeof custom === "string" && custom.trim() !== "") {
answers[question.question] = custom.trim();
return;
}
const value = content[questionFieldKey(index)];
if (value === undefined || value === null) {
return;
}
const text = Array.isArray(value) ? value.join(", ") : String(value);
if (text === "") {
return;
}
answers[question.question] = text;
});
return { action: "answered", updatedInput: { ...toolInput, answers } };
}
/**
* Coerce an arbitrary MCP `requestedSchema` into an ACP `ElicitationSchema`.
* The two are structurally compatible JSON Schemas; we just guarantee the
* `type: "object"` discriminator is present.
*/
function normalizeElicitationSchema(
schema: Record<string, unknown> | undefined,
): ElicitationSchema {
if (!schema || typeof schema !== "object") {
return { type: "object", properties: {} };
}
return { ...(schema as ElicitationSchema), type: "object" };
}

View File

@@ -3,4 +3,4 @@ description: Say hello
argument-hint: name
---
Respond with "Hello $ARGUMENTS" and nothing else.
Respond with "Hello $1" and nothing else.

View File

@@ -225,9 +225,7 @@ describe("ClaudeAcpAgent settings", () => {
// No setModel call is needed because no override was applied — the SDK is
// already on its own default.
expect(setModelSpy).not.toHaveBeenCalled();
expect(response.configOptions?.find((o: any) => o.id === "model")?.currentValue).toBe(
"claude-sonnet-4-6",
);
expect(response.models.currentModelId).toBe("claude-sonnet-4-6");
});
describe("auto mode availability per model", () => {
@@ -580,12 +578,10 @@ describe("ClaudeAcpAgent settings", () => {
});
expect(setModelSpy).toHaveBeenCalledWith("claude-haiku-4-5");
expect(response.configOptions?.find((o: any) => o.id === "model")?.currentValue).toBe(
"claude-haiku-4-5",
);
expect(response.models.currentModelId).toBe("claude-haiku-4-5");
});
it("does not inherit display info across mismatched model versions", async () => {
it("does not inherit display info across mismatched model family versions", async () => {
// https://github.com/agentclientprotocol/claude-agent-acp/issues/639:
// when the SDK's `opus` alias resolves to Opus 4.7, an allowlist entry
// of `claude-opus-4-6` (or `claude-opus-4-6[1m]`) used to substring-match
@@ -646,172 +642,6 @@ describe("ClaudeAcpAgent settings", () => {
expect(byValue["claude-opus-4-7"].name).toBe("Opus 4.7");
expect(byValue["claude-opus-4-7[1m]"].name).toMatch(/Opus 4\.7/);
});
it("does not inherit display info across mismatched model families", async () => {
// https://github.com/agentclientprotocol/claude-agent-acp/issues/639:
// when the SDK's `opus` alias resolves to Opus 4.8, `claude-opus-4-6[1m]`
// fails the version check against `opus` but the tokenized matcher
// falls through to `sonnet[1m]` because the `1m` context hint alone
// is enough to score a match.
await fs.promises.writeFile(
path.join(tempDir, "settings.json"),
JSON.stringify({
availableModels: ["claude-opus-4-6", "claude-opus-4-6[1m]"],
}),
);
const projectDir = path.join(tempDir, "project");
await fs.promises.mkdir(projectDir, { recursive: true });
mockQueryWithModels([
{ value: "default", displayName: "Default", description: "Default model" },
{
value: "sonnet",
displayName: "Sonnet",
description: "Sonnet 4.6 · Best for everyday tasks",
},
{
value: "sonnet[1m]",
displayName: "Sonnet (1M context)",
description: "Sonnet 4.6 for long sessions",
},
{
value: "opus",
displayName: "Opus 4.8",
description: "Claude Opus 4.8",
},
]);
const { ClaudeAcpAgent } = await import("../acp-agent.js");
const agent: ClaudeAcpAgentType = new ClaudeAcpAgent(createMockClient());
const response = await (agent as any).createSession({
cwd: projectDir,
mcpServers: [],
_meta: { disableBuiltInTools: true },
});
const modelOption = response.configOptions.find((o: any) => o.id === "model");
const byValue: Record<string, { name: string; description?: string }> = {};
for (const opt of modelOption.options) {
byValue[opt.value] = { name: opt.name, description: opt.description };
}
expect(byValue["claude-opus-4-6[1m]"].name).toBe("claude-opus-4-6[1m]");
expect(byValue["claude-opus-4-6"].name).toBe("claude-opus-4-6");
});
it("preserves ANTHROPIC_CUSTOM_MODEL_OPTION even when absent from the allowlist", async () => {
// Per the model-config docs, ANTHROPIC_CUSTOM_MODEL_OPTION adds an entry
// "without replacing the built-in aliases" and "appears at the bottom of
// the /model picker", so it is exempt from the availableModels allowlist
// (the same way the Default option is "not affected by availableModels").
// ACP must match: a slim alias allowlist must not hide the custom model
// row, and it appears last, after the allowlisted entries.
// https://code.claude.com/docs/en/model-config#add-a-custom-model-option
const originalEnv = process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
process.env.ANTHROPIC_CUSTOM_MODEL_OPTION = "claude-opus-4-8[1m]";
try {
await fs.promises.writeFile(
path.join(tempDir, "settings.json"),
JSON.stringify({
availableModels: ["sonnet", "opus", "haiku"],
}),
);
const projectDir = path.join(tempDir, "project");
await fs.promises.mkdir(projectDir, { recursive: true });
mockQueryWithModels([
{ value: "default", displayName: "Default", description: "Default model" },
{ value: "sonnet", displayName: "Sonnet", description: "Claude Sonnet 4.6" },
{ value: "opus", displayName: "Opus", description: "Claude Opus 4.6" },
{ value: "haiku", displayName: "Haiku", description: "Claude Haiku 4.5" },
{
value: "claude-opus-4-8[1m]",
displayName: "Opus 4.8",
description: "Claude Opus 4.8",
},
]);
const { ClaudeAcpAgent } = await import("../acp-agent.js");
const agent: ClaudeAcpAgentType = new ClaudeAcpAgent(createMockClient());
const response = await (agent as any).createSession({
cwd: projectDir,
mcpServers: [],
_meta: { disableBuiltInTools: true },
});
const modelOption = response.configOptions.find((o: any) => o.id === "model");
expect(modelOption.options.map((o: any) => o.value)).toEqual([
"default",
"sonnet",
"opus",
"haiku",
"claude-opus-4-8[1m]",
]);
const custom = modelOption.options.find((o: any) => o.value === "claude-opus-4-8[1m]");
expect(custom.name).toBe("Opus 4.8");
expect(custom.description).toBe("Claude Opus 4.8");
} finally {
if (originalEnv === undefined) {
delete process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
} else {
process.env.ANTHROPIC_CUSTOM_MODEL_OPTION = originalEnv;
}
}
});
it("does not duplicate the custom model option when also in the allowlist", async () => {
// If the user lists the custom model's exact ID in availableModels AND it
// is set as ANTHROPIC_CUSTOM_MODEL_OPTION, it must appear exactly once.
const originalEnv = process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
process.env.ANTHROPIC_CUSTOM_MODEL_OPTION = "claude-opus-4-8[1m]";
try {
await fs.promises.writeFile(
path.join(tempDir, "settings.json"),
JSON.stringify({
availableModels: ["sonnet", "claude-opus-4-8[1m]"],
}),
);
const projectDir = path.join(tempDir, "project");
await fs.promises.mkdir(projectDir, { recursive: true });
mockQueryWithModels([
{ value: "default", displayName: "Default", description: "Default model" },
{ value: "sonnet", displayName: "Sonnet", description: "Claude Sonnet 4.6" },
{
value: "claude-opus-4-8[1m]",
displayName: "Opus 4.8",
description: "Claude Opus 4.8",
},
]);
const { ClaudeAcpAgent } = await import("../acp-agent.js");
const agent: ClaudeAcpAgentType = new ClaudeAcpAgent(createMockClient());
const response = await (agent as any).createSession({
cwd: projectDir,
mcpServers: [],
_meta: { disableBuiltInTools: true },
});
const modelOption = response.configOptions.find((o: any) => o.id === "model");
expect(modelOption.options.map((o: any) => o.value)).toEqual([
"default",
"sonnet",
"claude-opus-4-8[1m]",
]);
} finally {
if (originalEnv === undefined) {
delete process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
} else {
process.env.ANTHROPIC_CUSTOM_MODEL_OPTION = originalEnv;
}
}
});
});
it("resolves model aliases like opus[1m] to the correct model", async () => {
@@ -857,9 +687,7 @@ describe("ClaudeAcpAgent settings", () => {
});
expect(setModelSpy).toHaveBeenCalledWith("claude-opus-4-6-1m");
expect(response.configOptions?.find((o: any) => o.id === "model")?.currentValue).toBe(
"claude-opus-4-6-1m",
);
expect(response.models.currentModelId).toBe("claude-opus-4-6-1m");
});
it("skips the initial setModel when the resolved value matches the SDK's model list verbatim", async () => {
@@ -899,9 +727,7 @@ describe("ClaudeAcpAgent settings", () => {
});
expect(setModelSpy).not.toHaveBeenCalled();
expect(response.configOptions?.find((o: any) => o.id === "model")?.currentValue).toBe(
"claude-opus-4-6",
);
expect(response.models.currentModelId).toBe("claude-opus-4-6");
} finally {
if (originalEnv === undefined) {
delete process.env.ANTHROPIC_MODEL;
@@ -951,8 +777,6 @@ describe("ClaudeAcpAgent settings", () => {
});
expect(setModelSpy).toHaveBeenCalledWith("claude-haiku-4-5");
expect(response.configOptions?.find((o: any) => o.id === "model")?.currentValue).toBe(
"claude-haiku-4-5",
);
expect(response.models.currentModelId).toBe("claude-haiku-4-5");
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -39,7 +39,7 @@ vi.mock("../tools.js", async () => ({
describe("additionalRoots", () => {
let agent: ClaudeAcpAgentType;
const tempDirs: string[] = [];
const newSession = (meta: Record<string, unknown>, cwd = process.cwd()) =>
const newSession = (meta: Record<string, unknown>, cwd = "/test") =>
agent.newSession({ cwd, mcpServers: [], _meta: meta });
beforeEach(async () => {
@@ -79,7 +79,7 @@ describe("additionalRoots", () => {
it("prefers the official ACP additionalDirectories field over _meta.additionalRoots", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
additionalDirectories: ["/from/official"],
_meta: { additionalRoots: ["/from/meta"] },
@@ -89,7 +89,7 @@ describe("additionalRoots", () => {
it("merges official ACP additionalDirectories with claudeCode SDK additionalDirectories", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
additionalDirectories: ["/from/official"],
_meta: { claudeCode: { options: { additionalDirectories: ["/from/sdk"] } } },
@@ -99,7 +99,7 @@ describe("additionalRoots", () => {
it("falls back to _meta.additionalRoots when the official field is omitted", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: { additionalRoots: ["/from/meta"] },
});

View File

@@ -15,10 +15,7 @@ const mockQuery = vi.hoisted(() =>
})),
);
vi.mock("@anthropic-ai/claude-agent-sdk", async () => ({
...(await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(
"@anthropic-ai/claude-agent-sdk",
)),
vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
query: mockQuery,
}));
@@ -103,7 +100,7 @@ describe("authorization", () => {
});
await agent.newSession({
cwd: process.cwd(),
cwd: "testRoot",
mcpServers: [],
_meta: {
claudeCode: {
@@ -148,7 +145,7 @@ describe("authorization", () => {
});
await agent.newSession({
cwd: process.cwd(),
cwd: "testRoot",
mcpServers: [],
});

View File

@@ -1,10 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { AgentSideConnection, RequestError, SessionNotification } from "@agentclientprotocol/sdk";
import { AgentSideConnection, SessionNotification } from "@agentclientprotocol/sdk";
import type { Options } from "@anthropic-ai/claude-agent-sdk";
import type { ClaudeAcpAgent as ClaudeAcpAgentType } from "../acp-agent.js";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
let capturedOptions: Options | undefined;
vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
@@ -68,7 +65,7 @@ describe("createSession options merging", () => {
it("merges user-provided disallowedTools with ACP internal list", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -88,7 +85,7 @@ describe("createSession options merging", () => {
it("works when user provides no disallowedTools", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
});
@@ -97,7 +94,7 @@ describe("createSession options merging", () => {
it("works when user provides empty disallowedTools", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -113,7 +110,7 @@ describe("createSession options merging", () => {
it("sets tools to empty array when disableBuiltInTools is true", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
disableBuiltInTools: true,
@@ -136,7 +133,7 @@ describe("createSession options merging", () => {
const userPreToolUseHook = { hooks: [{ command: "echo pre" }] };
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -158,7 +155,7 @@ describe("createSession options merging", () => {
it("inherits HOME and PATH from process.env when no env is provided", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
});
@@ -168,7 +165,7 @@ describe("createSession options merging", () => {
it("merges user-provided env vars on top of process.env", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -188,7 +185,7 @@ describe("createSession options merging", () => {
it("allows user-provided env vars to override process.env entries", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -206,7 +203,7 @@ describe("createSession options merging", () => {
it("defaults tools to claude_code preset when not provided", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
});
@@ -215,7 +212,7 @@ describe("createSession options merging", () => {
it("passes through user-provided tools string array", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -231,7 +228,7 @@ describe("createSession options merging", () => {
it("explicit tools array takes precedence over disableBuiltInTools", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
disableBuiltInTools: true,
@@ -248,7 +245,7 @@ describe("createSession options merging", () => {
it("passes through empty tools array to disable all built-in tools", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -264,7 +261,7 @@ describe("createSession options merging", () => {
describe("systemPrompt via _meta", () => {
it("defaults to the claude_code preset when not provided", async () => {
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(capturedOptions!.systemPrompt).toEqual({
type: "preset",
@@ -274,7 +271,7 @@ describe("createSession options merging", () => {
it("replaces the preset when a string is provided", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: { systemPrompt: "custom prompt" },
});
@@ -284,7 +281,7 @@ describe("createSession options merging", () => {
it("forwards append", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: { systemPrompt: { append: "extra instructions" } },
});
@@ -298,7 +295,7 @@ describe("createSession options merging", () => {
it("forwards excludeDynamicSections", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: { systemPrompt: { excludeDynamicSections: true } },
});
@@ -312,7 +309,7 @@ describe("createSession options merging", () => {
it("forwards append and excludeDynamicSections together", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
systemPrompt: {
@@ -332,7 +329,7 @@ describe("createSession options merging", () => {
it("ignores caller-provided type/preset overrides", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
systemPrompt: {
@@ -372,7 +369,7 @@ describe("createSession options merging", () => {
modelOverrides: { "claude-opus-4-6": "us.anthropic.claude-opus-4-6-v1" },
});
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(capturedOptions!.settings).toEqual({
modelOverrides: { "claude-opus-4-6": "us.anthropic.claude-opus-4-6-v1" },
@@ -384,7 +381,7 @@ describe("createSession options merging", () => {
availableModels: ["opus", "sonnet"],
});
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(capturedOptions!.settings).toEqual({
availableModels: ["opus", "sonnet"],
@@ -397,7 +394,7 @@ describe("createSession options merging", () => {
availableModels: ["opus"],
});
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(capturedOptions!.settings).toEqual({
modelOverrides: { "claude-opus-4-6": "us.anthropic.claude-opus-4-6-v1" },
@@ -406,7 +403,7 @@ describe("createSession options merging", () => {
});
it("does not add settings when env var is not set", async () => {
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(capturedOptions!.settings).toBeUndefined();
});
@@ -417,7 +414,7 @@ describe("createSession options merging", () => {
});
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [],
_meta: {
claudeCode: {
@@ -441,13 +438,13 @@ describe("createSession options merging", () => {
it("throws on invalid JSON", async () => {
process.env.CLAUDE_MODEL_CONFIG = "not-json";
await expect(agent.newSession({ cwd: process.cwd(), mcpServers: [] })).rejects.toThrow();
await expect(agent.newSession({ cwd: "/test", mcpServers: [] })).rejects.toThrow();
});
});
it("merges user-provided mcpServers with ACP mcpServers", async () => {
await agent.newSession({
cwd: process.cwd(),
cwd: "/test",
mcpServers: [
{
name: "acp-server",
@@ -476,140 +473,4 @@ describe("createSession options merging", () => {
// ACP-provided MCP server should also be present
expect(capturedOptions!.mcpServers).toHaveProperty("acp-server");
});
describe("thinking config from MAX_THINKING_TOKENS", () => {
let originalMaxThinking: string | undefined;
beforeEach(() => {
originalMaxThinking = process.env.MAX_THINKING_TOKENS;
delete process.env.MAX_THINKING_TOKENS;
});
afterEach(() => {
if (originalMaxThinking !== undefined) {
process.env.MAX_THINKING_TOKENS = originalMaxThinking;
} else {
delete process.env.MAX_THINKING_TOKENS;
}
});
it("leaves thinking unset (SDK default) when env var is absent", async () => {
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.thinking).toBeUndefined();
// The deprecated option must not be set either.
expect(capturedOptions!.maxThinkingTokens).toBeUndefined();
});
it("maps 0 to disabled thinking", async () => {
process.env.MAX_THINKING_TOKENS = "0";
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.thinking).toEqual({ type: "disabled" });
});
it("maps a positive value to a fixed thinking budget", async () => {
process.env.MAX_THINKING_TOKENS = "12000";
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.thinking).toEqual({ type: "enabled", budgetTokens: 12000 });
});
it("ignores a non-numeric value", async () => {
process.env.MAX_THINKING_TOKENS = "lots";
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.thinking).toBeUndefined();
});
it("lets a user-provided thinking option override the env default", async () => {
process.env.MAX_THINKING_TOKENS = "12000";
await agent.newSession({
cwd: process.cwd(),
mcpServers: [],
_meta: {
claudeCode: {
options: {
thinking: { type: "adaptive" },
},
},
},
});
expect(capturedOptions!.thinking).toEqual({ type: "adaptive" });
});
});
describe("cwd validation", () => {
it("rejects a relative cwd with invalidParams", async () => {
await expect(
agent.newSession({ cwd: "relative/path", mcpServers: [] }),
).rejects.toMatchObject({ code: RequestError.invalidParams().code });
});
it("rejects a non-existent cwd with invalidParams", async () => {
const missing = path.join(os.tmpdir(), "claude-acp-does-not-exist-xyz");
await expect(agent.newSession({ cwd: missing, mcpServers: [] })).rejects.toMatchObject({
code: RequestError.invalidParams().code,
});
});
it("rejects a cwd that points at a file with invalidParams", async () => {
const file = path.join(os.tmpdir(), "claude-acp-cwd-is-a-file.txt");
fs.writeFileSync(file, "not a directory");
try {
await expect(agent.newSession({ cwd: file, mcpServers: [] })).rejects.toMatchObject({
code: RequestError.invalidParams().code,
});
} finally {
fs.rmSync(file, { force: true });
}
});
it("accepts an existing absolute directory", async () => {
await expect(agent.newSession({ cwd: process.cwd(), mcpServers: [] })).resolves.toBeDefined();
});
});
describe("elicitation", () => {
it("keeps AskUserQuestion disabled and omits callbacks without elicitation capability", async () => {
await agent.initialize({ protocolVersion: 1, clientCapabilities: {} });
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.disallowedTools).toContain("AskUserQuestion");
expect(capturedOptions!.onElicitation).toBeUndefined();
});
it("enables AskUserQuestion and wires the elicitation callback when form is supported", async () => {
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { elicitation: { form: {} } },
});
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.disallowedTools).not.toContain("AskUserQuestion");
expect(typeof capturedOptions!.onElicitation).toBe("function");
});
it("wires callbacks for url-only elicitation but keeps AskUserQuestion disabled", async () => {
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { elicitation: { url: {} } },
});
await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
expect(capturedOptions!.disallowedTools).toContain("AskUserQuestion");
expect(typeof capturedOptions!.onElicitation).toBe("function");
});
it("still merges user-provided disallowedTools when AskUserQuestion is enabled", async () => {
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { elicitation: { form: {} } },
});
await agent.newSession({
cwd: process.cwd(),
mcpServers: [],
_meta: { claudeCode: { options: { disallowedTools: ["WebSearch"] } } },
});
expect(capturedOptions!.disallowedTools).toContain("WebSearch");
expect(capturedOptions!.disallowedTools).not.toContain("AskUserQuestion");
});
});
});

View File

@@ -1,391 +0,0 @@
import { describe, it, expect } from "vitest";
import type {
CreateElicitationRequest,
CreateElicitationResponse,
EnumOption,
} from "@agentclientprotocol/sdk";
import type { ElicitationRequest } from "@anthropic-ai/claude-agent-sdk";
import {
applyAskElicitationResponse,
askUserQuestionsToCreateRequest,
AskUserQuestion,
createElicitationResponseToElicitResult,
extractAskUserQuestions,
mcpElicitationToCreateRequest,
} from "../elicitation.js";
const SESSION_ID = "session-1";
/**
* Build a question matching the SDK's (strict) AskUserQuestion schema while
* keeping test sites terse. Option descriptions default to "" (the tool always
* provides one); pass a description to exercise the "label — description" title.
*/
function mkQuestion(
question: string,
options: Array<{ label: string; description?: string; preview?: string }>,
opts: { header?: string; multiSelect?: boolean } = {},
): AskUserQuestion {
return {
question,
header: opts.header ?? "",
multiSelect: opts.multiSelect ?? false,
options: options.map((o) => ({
label: o.label,
description: o.description ?? "",
...(o.preview ? { preview: o.preview } : {}),
})),
} as AskUserQuestion;
}
describe("mcpElicitationToCreateRequest", () => {
it("maps a form-mode request, defaulting the schema type to object", () => {
const request: ElicitationRequest = {
serverName: "server",
message: "Need your name",
mode: "form",
requestedSchema: { properties: { name: { type: "string" } } },
};
const result = mcpElicitationToCreateRequest(request, SESSION_ID);
expect(result).toEqual({
mode: "form",
sessionId: SESSION_ID,
message: "Need your name",
requestedSchema: { type: "object", properties: { name: { type: "string" } } },
});
});
it("maps a url-mode request and preserves the elicitation id", () => {
const request: ElicitationRequest = {
serverName: "server",
message: "Authorize",
mode: "url",
url: "https://example.com/auth",
elicitationId: "el-123",
};
expect(mcpElicitationToCreateRequest(request, SESSION_ID)).toEqual({
mode: "url",
sessionId: SESSION_ID,
message: "Authorize",
url: "https://example.com/auth",
elicitationId: "el-123",
});
});
it("generates an elicitation id when a url request omits one", () => {
const request: ElicitationRequest = {
serverName: "server",
message: "Authorize",
mode: "url",
url: "https://example.com/auth",
};
const result = mcpElicitationToCreateRequest(request, SESSION_ID);
expect(result?.mode).toBe("url");
expect((result as { elicitationId: string }).elicitationId).toMatch(/.+/);
});
it("returns null for a url request with no url", () => {
const request: ElicitationRequest = {
serverName: "server",
message: "Authorize",
mode: "url",
};
expect(mcpElicitationToCreateRequest(request, SESSION_ID)).toBeNull();
});
});
describe("createElicitationResponseToElicitResult", () => {
it("maps accept with content", () => {
const response = { action: "accept", content: { name: "Ada" } } as CreateElicitationResponse;
expect(createElicitationResponseToElicitResult(response)).toEqual({
action: "accept",
content: { name: "Ada" },
});
});
it("defaults accept content to an empty object", () => {
const response = { action: "accept" } as CreateElicitationResponse;
expect(createElicitationResponseToElicitResult(response)).toEqual({
action: "accept",
content: {},
});
});
it("maps decline and cancel", () => {
expect(
createElicitationResponseToElicitResult({ action: "decline" } as CreateElicitationResponse),
).toEqual({ action: "decline" });
expect(
createElicitationResponseToElicitResult({ action: "cancel" } as CreateElicitationResponse),
).toEqual({ action: "cancel" });
});
});
describe("extractAskUserQuestions", () => {
const question = mkQuestion("Which?", [{ label: "A" }, { label: "B" }]);
it("reads questions off the tool input", () => {
expect(extractAskUserQuestions({ questions: [question] })).toEqual([question]);
});
it("returns null when there are no questions", () => {
expect(extractAskUserQuestions({})).toBeNull();
expect(extractAskUserQuestions({ questions: [] })).toBeNull();
});
it("filters out malformed questions (missing options, empty options, bad question)", () => {
const input = {
questions: [
question,
{ question: "missing options" },
{ options: [] },
{ options: [], question: "empty" },
],
} as unknown as Record<string, unknown>;
expect(extractAskUserQuestions(input)).toEqual([question]);
});
it("returns null when every question is filtered out", () => {
const input = {
questions: [{ question: "no options" }, { options: [{ label: "A" }] }],
} as unknown as Record<string, unknown>;
expect(extractAskUserQuestions(input)).toBeNull();
});
});
describe("askUserQuestionsToCreateRequest", () => {
it("keys a single-select question by a stable id and carries the prompt in message only", () => {
const questions = [
mkQuestion(
"Which library?",
[{ label: "date-fns", description: "Lightweight" }, { label: "luxon" }],
{
header: "Library",
},
),
];
const result = askUserQuestionsToCreateRequest(questions, SESSION_ID, "tool-1");
expect(result).toMatchObject({
mode: "form",
sessionId: SESSION_ID,
toolCallId: "tool-1",
message: "Which library?",
});
const schema = (result as Extract<CreateElicitationRequest, { mode: "form" }>).requestedSchema;
// Nothing is required; the user can pick, type a custom answer, or skip.
expect(schema.required).toBeUndefined();
// Single question → no duplicated description (prompt is in `message`).
expect(schema.properties?.["question_0"]).toEqual({
type: "string",
title: "Library",
description: undefined,
oneOf: [
{
const: "date-fns",
title: "date-fns — Lightweight",
// Structured description forwarded under `_meta` so clients can render
// it as secondary text instead of parsing it out of the title.
_meta: { "_claude/askUserQuestionOption": { description: "Lightweight" } },
},
// No description → no `_meta` emitted.
{ const: "luxon", title: "luxon" },
],
});
// The full question text is not used as a property key.
expect(schema.properties?.["Which library?"]).toBeUndefined();
});
it("forwards option description and preview under _meta for rich clients", () => {
const questions = [
mkQuestion("Which layout?", [
{
label: "Grid",
description: "Cards in a responsive grid",
preview: "```\n[ ] [ ] [ ]\n[ ] [ ] [ ]\n```",
},
{ label: "List", description: "Stacked rows" },
{ label: "Plain" },
]),
];
const schema = (
askUserQuestionsToCreateRequest(questions, SESSION_ID, undefined) as Extract<
CreateElicitationRequest,
{ mode: "form" }
>
).requestedSchema;
const oneOf = (schema.properties?.["question_0"] as { oneOf: EnumOption[] }).oneOf;
// Both description and preview travel structurally; the title still flattens
// the description for clients that only read const/title.
expect(oneOf[0]).toEqual({
const: "Grid",
title: "Grid — Cards in a responsive grid",
_meta: {
"_claude/askUserQuestionOption": {
description: "Cards in a responsive grid",
preview: "```\n[ ] [ ] [ ]\n[ ] [ ] [ ]\n```",
},
},
});
// Description only → preview omitted from _meta.
expect(oneOf[1]._meta).toEqual({
"_claude/askUserQuestionOption": { description: "Stacked rows" },
});
// Neither → no _meta at all.
expect(oneOf[2]._meta).toBeUndefined();
});
it("includes a per-question optional free-text custom-answer field", () => {
const questions = [
mkQuestion("Which?", [{ label: "A" }, { label: "B" }]),
mkQuestion("What else?", [{ label: "C" }, { label: "D" }]),
];
const schema = (
askUserQuestionsToCreateRequest(questions, SESSION_ID, undefined) as Extract<
CreateElicitationRequest,
{ mode: "form" }
>
).requestedSchema;
// Each question gets its own "Other" box, not one shared form-level field.
expect(schema.properties?.["question_0_custom"]).toMatchObject({
type: "string",
title: "Other",
});
expect(schema.properties?.["question_1_custom"]).toMatchObject({
type: "string",
title: "Other",
});
});
it("builds an array property for multi-select questions and includes per-field question text", () => {
const questions = [
mkQuestion("Pick one?", [{ label: "A" }, { label: "B" }]),
mkQuestion("Which features?", [{ label: "auth" }, { label: "logging" }], {
multiSelect: true,
}),
];
const result = askUserQuestionsToCreateRequest(questions, SESSION_ID, undefined);
const schema = (result as Extract<CreateElicitationRequest, { mode: "form" }>).requestedSchema;
expect(result).not.toHaveProperty("toolCallId");
// Multiple questions → generic message, each field carries its own question.
expect(result.message).toBe("Please answer the following questions.");
expect(schema.properties?.["question_1"]).toEqual({
type: "array",
title: undefined,
description: "Which features?",
items: {
anyOf: [
{ const: "auth", title: "auth" },
{ const: "logging", title: "logging" },
],
},
});
});
});
describe("applyAskElicitationResponse", () => {
const questions = [
mkQuestion("Single?", [{ label: "A" }, { label: "B" }]),
mkQuestion("Multi?", [{ label: "X" }, { label: "Y" }], { multiSelect: true }),
];
const toolInput = { questions, metadata: { source: "test" } };
it("writes selected labels (keyed by indexed fields) into updatedInput on accept", () => {
const response = {
action: "accept",
content: { question_0: "A", question_1: ["X", "Y"] },
} as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "answered",
updatedInput: {
questions,
metadata: { source: "test" },
answers: { "Single?": "A", "Multi?": "X, Y" },
},
});
});
it("folds a per-question custom answer into that question's answer", () => {
const response = {
action: "accept",
content: { question_0: "A", question_1_custom: "something else entirely" },
} as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "answered",
updatedInput: {
questions,
metadata: { source: "test" },
answers: { "Single?": "A", "Multi?": "something else entirely" },
},
});
});
it("prefers a question's custom answer over its selection", () => {
const response = {
action: "accept",
content: { question_0: "A", question_0_custom: " my own take " },
} as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "answered",
updatedInput: {
questions,
metadata: { source: "test" },
answers: { "Single?": "my own take" },
},
});
});
it("ignores empty selections and blank custom answers", () => {
const response = {
action: "accept",
content: { question_1: [], question_0_custom: " " },
} as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "answered",
updatedInput: { questions, metadata: { source: "test" }, answers: {} },
});
});
it("treats decline as answered with no answers", () => {
const response = { action: "decline" } as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "answered",
updatedInput: { questions, metadata: { source: "test" }, answers: {} },
});
});
it("returns cancel on cancel", () => {
const response = { action: "cancel" } as CreateElicitationResponse;
expect(applyAskElicitationResponse(response, toolInput, questions)).toEqual({
action: "cancel",
});
});
it("omits answers for questions the user left unanswered", () => {
const response = {
action: "accept",
content: { question_0: "B" },
} as CreateElicitationResponse;
const result = applyAskElicitationResponse(response, toolInput, questions);
expect(result.action).toBe("answered");
expect((result as Extract<typeof result, { action: "answered" }>).updatedInput.answers).toEqual(
{ "Single?": "B" },
);
});
});

View File

@@ -148,13 +148,13 @@ describe("session config options", () => {
describe("newSession returns configOptions", () => {
it("includes configOptions in the response", async () => {
const response = await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
const response = await agent.newSession({ cwd: "/test", mcpServers: [] });
expect(response.configOptions).toBeDefined();
expect(response.configOptions).toEqual(MOCK_CONFIG_OPTIONS);
});
it("includes mode and model config options", async () => {
const response = await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
const response = await agent.newSession({ cwd: "/test", mcpServers: [] });
const modeOption = response.configOptions?.find((o) => o.id === "mode");
const modelOption = response.configOptions?.find((o) => o.id === "model");
expect(modeOption).toBeDefined();
@@ -173,7 +173,7 @@ describe("session config options", () => {
(agent as unknown as { loadSession: typeof loadSessionSpy }).loadSession = loadSessionSpy;
const response = await agent.loadSession({
cwd: process.cwd(),
cwd: "/test",
sessionId: SESSION_ID,
mcpServers: [],
});
@@ -216,31 +216,6 @@ describe("session config options", () => {
).rejects.toThrow("Invalid value for config option mode: invalid-mode");
});
it("rejects mode and config changes once the query stream has closed (husk session)", async () => {
// After an unexpected stream death the session lingers as a husk
// (queryClosed=true) so prompt() can answer with a clear error. The
// config/mode handlers must do the same rather than calling setModel/
// setPermissionMode on the closed query.
const session = (agent as unknown as { sessions: Record<string, { queryClosed?: boolean }> })
.sessions[SESSION_ID];
session.queryClosed = true;
await expect(
agent.setSessionConfigOption({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
}),
).rejects.toThrow(/start a new session/);
await expect(agent.setSessionMode({ sessionId: SESSION_ID, modeId: "plan" })).rejects.toThrow(
/start a new session/,
);
// Short-circuited before touching the (closed) query.
expect(setModelSpy).not.toHaveBeenCalled();
expect(setPermissionModeSpy).not.toHaveBeenCalled();
});
it("changes mode, sends current_mode_update but not config_option_update", async () => {
await agent.setSessionConfigOption({
sessionId: SESSION_ID,
@@ -402,30 +377,33 @@ describe("session config options", () => {
});
});
describe("setSessionConfigOption(model) returns updated configOptions", () => {
describe("unstable_setSessionModel sends config_option_update", () => {
beforeEach(() => {
populateSession();
});
it("returns configOptions with the new model when changed", async () => {
const response = await agent.setSessionConfigOption({
it("sends config_option_update when model is changed via setSessionModel", async () => {
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
expect(response.configOptions).toEqual(
expect.arrayContaining([
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
expect(configUpdate).toBeDefined();
expect(configUpdate?.update).toMatchObject({
sessionUpdate: "config_option_update",
configOptions: expect.arrayContaining([
expect.objectContaining({ id: "model", currentValue: "claude-sonnet-4-6" }),
]),
);
});
});
it("updates stored configOptions currentValue when model changes", async () => {
await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
const session = (
@@ -437,7 +415,7 @@ describe("session config options", () => {
expect(modelOption?.currentValue).toBe("claude-sonnet-4-6");
});
it("drops effort from returned configOptions when model drops effort support", async () => {
it("includes updated effort in config_option_update when model drops effort support", async () => {
const session = (agent as unknown as { sessions: Record<string, any> }).sessions[SESSION_ID];
session.modelInfos = [
{
@@ -455,18 +433,23 @@ describe("session config options", () => {
},
];
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
const effortOption = response.configOptions.find((o) => o.id === "effort");
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
expect(configUpdate).toBeDefined();
const effortOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "effort",
);
expect(effortOption).toBeUndefined();
expect(applyFlagSettingsSpy).toHaveBeenCalledWith({ effortLevel: null });
});
it("clamps effort in returned configOptions when new model has different supported levels", async () => {
it("clamps effort in config_option_update when new model has different supported levels", async () => {
// Set current effort to "max" which the new model won't support
const session = (agent as unknown as { sessions: Record<string, any> }).sessions[SESSION_ID];
const effortOpt = session.configOptions.find((o: any) => o.id === "effort");
@@ -489,31 +472,39 @@ describe("session config options", () => {
},
];
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
const effortOption = response.configOptions.find((o) => o.id === "effort");
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
const effortOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "effort",
);
expect(effortOption).toBeDefined();
expect(effortOption?.currentValue).toBe("default");
expect(effortOption.currentValue).toBe("default");
expect(applyFlagSettingsSpy).toHaveBeenCalledWith({ effortLevel: null });
});
it("preserves effort in returned configOptions when new model supports same level", async () => {
it("preserves effort in config_option_update when new model supports same level", async () => {
// Set effort to "low" first
const session = (agent as unknown as { sessions: Record<string, any> }).sessions[SESSION_ID];
const effortOpt = session.configOptions.find((o: any) => o.id === "effort");
if (effortOpt) effortOpt.currentValue = "low";
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
const effortOption = response.configOptions.find((o) => o.id === "effort");
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
const effortOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "effort",
);
expect(effortOption?.currentValue).toBe("low");
// Effort didn't change, so applyFlagSettings should NOT be called
expect(applyFlagSettingsSpy).not.toHaveBeenCalled();
@@ -830,11 +821,10 @@ describe("session config options", () => {
expect(session.configOptions.find((o) => o.id === "mode")?.currentValue).toBe("plan");
});
it("setSessionConfigOption(model) also syncs configOptions", async () => {
await agent.setSessionConfigOption({
it("setSessionModel also syncs configOptions", async () => {
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-sonnet-4-6",
modelId: "claude-sonnet-4-6",
});
const session = (
@@ -957,21 +947,58 @@ describe("session config options", () => {
it("drops `auto` from available modes when switching to Haiku", async () => {
setupHaikuOpusSession("default");
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-haiku-4-5",
modelId: "claude-haiku-4-5",
});
const modeOption = response.configOptions.find((o) => o.id === "mode");
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
expect(configUpdate).toBeDefined();
const modeOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "mode",
);
expect(modeOption).toBeDefined();
const modeValues = (modeOption as any).options.map((o: any) => o.value);
const modeValues = modeOption.options.map((o: any) => o.value);
expect(modeValues).not.toContain("auto");
expect(modeValues).toEqual(
expect.arrayContaining(["default", "acceptEdits", "plan", "dontAsk"]),
);
});
it("clamps to `default` and emits current_mode_update when Opus(auto) → Haiku", async () => {
setupHaikuOpusSession("auto");
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
modelId: "claude-haiku-4-5",
});
// SDK was synced to "default".
expect(setPermissionModeSpy).toHaveBeenCalledWith("default");
// current_mode_update was emitted before config_option_update so a
// client applying notifications in order observes the mode change
// before re-rendering the config-option list.
const modeUpdateIdx = sessionUpdates.findIndex(
(n) => n.update.sessionUpdate === "current_mode_update",
);
const configUpdateIdx = sessionUpdates.findIndex(
(n) => n.update.sessionUpdate === "config_option_update",
);
expect(modeUpdateIdx).toBeGreaterThanOrEqual(0);
expect(configUpdateIdx).toBeGreaterThanOrEqual(0);
expect(modeUpdateIdx).toBeLessThan(configUpdateIdx);
expect((sessionUpdates[modeUpdateIdx].update as any).currentModeId).toBe("default");
// configOptions reflect the clamped mode.
const modeOption = (sessionUpdates[configUpdateIdx].update as any).configOptions.find(
(o: any) => o.id === "mode",
);
expect(modeOption.currentValue).toBe("default");
});
it("re-adds `auto` when switching from Haiku back to Opus", async () => {
const session = setupHaikuOpusSession("default");
// Pretend Haiku is the current model with no `auto`.
@@ -986,15 +1013,19 @@ describe("session config options", () => {
description: m.description,
}));
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-opus-4-5",
modelId: "claude-opus-4-5",
});
const modeOption = response.configOptions.find((o) => o.id === "mode");
expect(modeOption).toBeDefined();
const modeValues = (modeOption as any).options.map((o: any) => o.value);
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
expect(configUpdate).toBeDefined();
const modeOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "mode",
);
const modeValues = modeOption.options.map((o: any) => o.value);
expect(modeValues).toContain("auto");
// The current mode ("default") is still valid on Opus, so no
@@ -1008,10 +1039,9 @@ describe("session config options", () => {
it("preserves the current mode when it remains valid after a model switch", async () => {
setupHaikuOpusSession("plan");
const response = await agent.setSessionConfigOption({
await agent.unstable_setSessionModel({
sessionId: SESSION_ID,
configId: "model",
value: "claude-haiku-4-5",
modelId: "claude-haiku-4-5",
});
// `plan` is in availableModes for both Opus and Haiku, so no clamp.
@@ -1022,15 +1052,20 @@ describe("session config options", () => {
);
expect(modeUpdates).toHaveLength(0);
const modeOption = response.configOptions.find((o) => o.id === "mode");
expect((modeOption as any).currentValue).toBe("plan");
const configUpdate = sessionUpdates.find(
(n) => n.update.sessionUpdate === "config_option_update",
);
const modeOption = (configUpdate?.update as any).configOptions.find(
(o: any) => o.id === "mode",
);
expect(modeOption.currentValue).toBe("plan");
});
it("clamps mode and emits current_mode_update via setSessionConfigOption(model)", async () => {
// Switching Opus(auto) → Haiku clamps the mode to "default". The
// `current_mode_update` side effect must fire so clients learn about the
// clamp even though the request/response API returns the new
// configOptions rather than emitting a config_option_update.
// Mirrors the unstable_setSessionModel(auto → Haiku) test, but goes
// through the request/response API. The `current_mode_update` side
// effect must still fire so clients learn about the clamp regardless of
// which entry point triggered the model switch.
setupHaikuOpusSession("auto");
const response = await agent.setSessionConfigOption({

View File

@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach } from "vitest";
import { describe, it, expect } from "vitest";
import { AgentSideConnection, ClientCapabilities } from "@agentclientprotocol/sdk";
import { ImageBlockParam, ToolResultBlockParam } from "@anthropic-ai/sdk/resources";
import {
@@ -502,23 +502,6 @@ describe("Bash terminal output", () => {
});
});
it("should route failed commands through the terminal when supportsTerminalOutput is true", () => {
const toolResult: ToolResultBlockParam = {
type: "tool_result",
tool_use_id: "toolu_bash",
content: "some error output",
is_error: true,
};
const update = toolUpdateFromToolResult(toolResult, bashToolUse, true);
expect(update.content).toEqual([{ type: "terminal", terminalId: "toolu_bash" }]);
expect(update._meta).toEqual({
terminal_info: { terminal_id: "toolu_bash" },
terminal_output: { terminal_id: "toolu_bash", data: "some error output" },
terminal_exit: { terminal_id: "toolu_bash", exit_code: 1, signal: null },
});
});
it("should fall back to stderr when stdout is empty", () => {
const toolResult = makeBashResult("", "some error output", 1);
const update = toolUpdateFromToolResult(toolResult, bashToolUse, false);
@@ -627,25 +610,10 @@ describe("Bash terminal output", () => {
});
});
it("should route is_error through the terminal when supportsTerminalOutput is true", () => {
it("should use error handler when is_error is true (early return before Bash case)", () => {
const toolResult = makeStringBashResult("command not found: bad_cmd", true);
const update = toolUpdateFromToolResult(toolResult, bashToolUse, true);
// Failed Bash commands skip the early error return and reach the Bash
// case so the client receives terminal output with a non-zero exit code
// instead of plain markdown details.
expect(update.content).toEqual([{ type: "terminal", terminalId: "toolu_bash" }]);
expect(update._meta).toEqual({
terminal_info: { terminal_id: "toolu_bash" },
terminal_output: { terminal_id: "toolu_bash", data: "command not found: bad_cmd" },
terminal_exit: { terminal_id: "toolu_bash", exit_code: 1, signal: null },
});
});
it("should use error handler when is_error is true and terminal output is unsupported", () => {
const toolResult = makeStringBashResult("command not found: bad_cmd", true);
const update = toolUpdateFromToolResult(toolResult, bashToolUse, false);
// is_error with content hits the early error return at the top of
// toolUpdateFromToolResult, before reaching the Bash switch case.
// So there's no terminal _meta, just error-formatted content.
@@ -705,19 +673,14 @@ describe("Bash terminal output", () => {
});
describe("toAcpNotifications with clientCapabilities", () => {
// Reset before each test: toAcpNotifications prunes the cache entry once it
// maps the tool_result, so a shared object would be empty by the 2nd test.
let toolUseCache: ToolUseCache;
beforeEach(() => {
toolUseCache = {
toolu_bash: {
type: "tool_use",
id: "toolu_bash",
name: "Bash",
input: { command: "ls -la" },
},
};
});
const toolUseCache: ToolUseCache = {
toolu_bash: {
type: "tool_use",
id: "toolu_bash",
name: "Bash",
input: { command: "ls -la" },
},
};
const bashResult: BetaBashCodeExecutionResultBlock = {
type: "bash_code_execution_result",
@@ -829,21 +792,11 @@ describe("Bash terminal output", () => {
{ clientCapabilities: { _meta: { terminal_output: true } } },
);
// Fresh cache: the withSupport call above already consumed the entry,
// since toAcpNotifications prunes the tool_use once it maps the result.
const toolUseCacheWithoutSupport: ToolUseCache = {
toolu_bash: {
type: "tool_use",
id: "toolu_bash",
name: "Bash",
input: { command: "ls -la" },
},
};
const withoutSupport = toAcpNotifications(
[toolResult],
"assistant",
"test-session",
toolUseCacheWithoutSupport,
toolUseCache,
mockClient,
mockLogger,
);
@@ -895,31 +848,6 @@ describe("Bash terminal output", () => {
});
});
describe("toolUseCache pruning", () => {
it("retains the tool_use entry until its result, then prunes it", () => {
const toolUseCache: ToolUseCache = {};
const toolUse = {
type: "tool_use" as const,
id: "toolu_read",
name: "Read",
input: { file_path: "/tmp/x.txt" },
};
// tool_use is cached and kept (the matching result hasn't arrived yet).
toAcpNotifications([toolUse], "assistant", "s", toolUseCache, mockClient, mockLogger);
expect(toolUseCache.toolu_read).toBeDefined();
// tool_result resolves it, so the entry is pruned to bound memory.
const toolResult: ToolResultBlockParam = {
type: "tool_result",
tool_use_id: "toolu_read",
content: [{ type: "text", text: "hello" }],
};
toAcpNotifications([toolResult], "assistant", "s", toolUseCache, mockClient, mockLogger);
expect(toolUseCache.toolu_read).toBeUndefined();
});
});
describe("post-tool-use hook sends diff content for Edit tool", () => {
it("should include content and locations from structuredPatch in hook update", async () => {
const toolUseCache: ToolUseCache = {};

View File

@@ -8,7 +8,6 @@ import {
import { HookCallback } from "@anthropic-ai/claude-agent-sdk";
import {
AgentInput,
AskUserQuestionInput,
BashInput,
FileEditInput,
FileReadInput,
@@ -416,24 +415,6 @@ export function toolInfoFromToolUse(
};
}
case "AskUserQuestion": {
const input = toolUse.input as Partial<AskUserQuestionInput> | undefined;
const questions = Array.isArray(input?.questions) ? input.questions : [];
return {
title:
questions.length === 1 && questions[0]?.question
? questions[0].question
: "Asking for your input",
kind: "other",
content: questions
.filter((q) => typeof q?.question === "string")
.map((q) => ({
type: "content" as const,
content: { type: "text" as const, text: q.question },
})),
};
}
case "Other": {
const input = toolUse.input;
let output;
@@ -485,8 +466,7 @@ export function toolUpdateFromToolResult(
"is_error" in toolResult &&
toolResult.is_error &&
toolResult.content &&
toolResult.content.length > 0 &&
!(toolUse?.name === "Bash" && supportsTerminalOutput)
toolResult.content.length > 0
) {
// Only return errors
return toAcpContentUpdate(toolResult.content, true);