Compare commits

...

88 Commits

Author SHA1 Message Date
acp-release-bot[bot]
764fb84f9f chore(main): release 0.113.0 (#1713)
🤖 I have created a release *beep* *boop*
---


##
[0.113.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.112.0...v0.113.0)
(2026-11-26)


### Features

* serve /plugin in ACP sessions
([#1716](https://github.com/agentclientprotocol/claude-agent-acp/issues/1716))
([0f095f6](0f095f678d))
* start Remote Control with the session when Claude Code asks for it
([#1523](https://github.com/agentclientprotocol/claude-agent-acp/issues/1523))
([893f768](893f7680c7))


### Bug Fixes

* **background:** keep a tool call whose task joins the live set after
its result
([#1639](https://github.com/agentclientprotocol/claude-agent-acp/issues/1639))
([677a6d9](677a6d9afa))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-26 14:34:17 +01:00
Mark Tkachenko
0f095f678d feat: serve /plugin in ACP sessions (#1716)
Closes #580.

In an ACP session, `/plugin …` (and its aliases `/plugins`,
`/marketplace`) answers "/plugin isn't available in this environment."
Claude Code defines `/plugin` as an Ink-only `local-jsx` command and
refuses it outside the interactive terminal by design, so the adapter
can't just forward it. The adapter now serves it itself, as it already
does for `/remote-control`.
2026-11-26 14:01:08 +01:00
PerryLink
677a6d9afa fix(background): keep a tool call whose task joins the live set after its result (#1639)
## What

A `Monitor` or `Workflow` call whose task joins Claude Code's live
background set after the call's result now stays that task's entity: the
call is kept `in_progress`, and a later level names it instead of
`adoptTasks()` starting a separate `task_<taskId>` card.

I have not seen this order with the real CLI; #1537 described it from
the adapter's own tests. The SDK promises no order between a tool result
and `background_tasks_changed`, so it can happen.

## Why

`toolResults()` kept a task call only when the live set (the list of
running tasks that Claude Code sends in `background_tasks_changed`)
already named the task; when the level named it later, the call had
ended and `adoptTasks()` could start a separate card. This ports the fix
from the closed branch #1537 to current main, where
`src/background-work.ts` no longer exists:

- `toolResults()` keeps the call in `toolCalls` with an `unleveled` flag
when the level does not name the task yet, and keeps that call running
in the result's own updates. A task that already ended before the result
is remembered (`endedTasks`), so its call is not kept for a level that
can no longer name it;
- `levelChanged()` clears the flag and reports the call `in_progress`
when the level names the task; if the task is not the call's (for
example a `local_bash` task of a PowerShell call), the call ends
`completed` as its result reported it, before the level publishes;
- one `keepsTaskCall()` helper applies the existing rule in both places
— always skip `local_agent`, and skip `local_bash` only when the tool is
not in `TASK_TOOLS` (Claude Code reports a Monitor's task as
`local_bash`) — so the two copies cannot drift apart again;
- because the call lives in `toolCalls`, `closeTurn()`, `queryEnded()`
and `backgroundCalls()` end it as they end any background call.

Comments in the file header, `levelChanged()`, `adoptTasks()` and the
`task_<taskId>` example match the behaviour.

## Tests

In `src/tests/v2/acp-v2.test.ts`:

- `it.each` over a Monitor (`local_bash` task, as the CLI sends it) and
a Workflow whose level arrives after the result: the whole trace asserts
the call goes `pending` → `in_progress` (result) → `in_progress`
(level), never `completed` before the notification, and no
`task_<taskId>` card is listed;
- a Monitor call whose task ends before the result arrives (level,
`task_started`, `task_notification`, a level without the task, then the
result): the call stays `completed` and is unlisted — this order failed
on the previous revision;
- a PowerShell call whose level names a `local_bash` task that is not
the call's: the call ends `completed` rather than staying `in_progress`;
- `monitorStarts()` gained a result-first order; the Workflow helper
reuses the `workflow` task constant.

```console
$ npx tsc --noEmit       # clean
$ npx eslint src/v2/tasks.ts src/tests/v2/acp-v2.test.ts
$ npx prettier --check src/v2/tasks.ts src/tests/v2/acp-v2.test.ts
$ npx vitest run src/tests/v2/   # 555 passed, 4 skipped
```

I also applied the patch to current `main` (`9d71d12`) locally: it
applies cleanly and `src/tests/v2/` is 567 passed / 5 skipped there. The
PR branch itself is not rebased.

## Related

Supersedes #1537, which was based on the removed
`src/background-work.ts`. The Monitor-as-`local_bash` task type comes
from #1606.

---------

Co-authored-by: Andrey Bragin <andrey.bragin@jetbrains.com>
2026-11-25 16:28:25 +01:00
Jeremy Espinoza
893f7680c7 feat: start Remote Control with the session when Claude Code asks for it (#1523)
Closes #1396.

Terminal sessions connect to Remote Control on their own when
`remoteControlAtStartup` is on. Sessions started over ACP don't, so you
have to type `/remote-control` in each one.

Claude Code already reports this at startup: `initializationResult()`
includes `remote_control_auto_enable`. When it's true, the adapter now
turns Remote Control on right after the session is set up, with the same
`enableRemoteControl` call that `/remote-control` uses.

- It works for new, loaded, resumed and forked sessions, on ACP v1 and
v2. It runs once per query, so a session whose query restarts (after a
provider change or a sign-out, for example) connects again, since Remote
Control ended with the old query. A `/remote-control off` holds across
those restarts: the new query doesn't turn it back on. On v1, a plan
approved with a fresh context also restarts the query, but in the middle
of the turn, so it doesn't connect then.
- The result goes out as a notice instead of an agent message, since
nothing is mid-turn at that point. Clients without notice support get a
transcript line.
- A notice can't be withdrawn, so it says "Remote Control connected" (an
event) rather than "is active", which `/remote-control off` would make
untrue.
- Like `/remote-control`, it holds prompts back while it connects, and
it does nothing while Claude is already working. On v1, a
`/remote-control` sent while it connects is refused ("Try again in a
moment"), as during another `/remote-control`.
- `remote_control_auto_enable` isn't in the SDK's published types, so
it's typed locally like `enableRemoteControl`. A missing field means
off.
- Both cores share the startup steps through `RemoteControlAtStartup` in
`src/remote-control.ts`, beside the existing Remote Control helpers.
Each core holds prompts back and sends the notice its own way: v2 in
`src/v2/remote-control.ts`, v1 in the new `src/v1/remote-control.ts`,
which `/remote-control` now uses too.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Andrey Bragin <andrey.bragin@jetbrains.com>
2026-11-25 16:08:07 +01:00
acp-release-bot[bot]
aa93ed06c1 chore(main): release 0.112.0 (#1712)
🤖 I have created a release *beep* *boop*
---


##
[0.112.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.111.0...v0.112.0)
(2026-11-24)


### Features

* rewind the same provider session on an edited message
([#1704](https://github.com/agentclientprotocol/claude-agent-acp/issues/1704))
([f2897d6](f2897d6687))


### Bug Fixes

* stop holding an MCP request that Claude Code gave up
([#1711](https://github.com/agentclientprotocol/claude-agent-acp/issues/1711))
([d5be0e5](d5be0e5827))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-24 19:12:34 +01:00
Mark Tkachenko
f2897d6687 feat: rewind the same provider session on an edited message (#1704)
Based on #1378 by @nikita-ashihmin: a clean reimplementation on current
`main`, addressed by ACP session cursors instead of message ids.
Supersedes #1378, which can be closed after this merges.
2026-11-24 18:56:10 +01:00
Ben Brandt
d5be0e5827 fix: stop holding an MCP request that Claude Code gave up (#1711)
## Summary

A subagent's MCP request waits up to 500 ms for the announcement of the
subagent's child session. When Claude Code closed the request's HTTP
connection during that wait, the adapter kept the request waiting until
the tool use ended or the time passed. It now stops at once.

`@agentclientprotocol/sdk` 2.12.0 gives the HTTP bridge's attribution
resolver the request's `signal`. The signal aborts when the HTTP
connection or the ACP connection closes. `McpOverAcp` ends the wait on
it.

What a request names does not change. The bridge already sent nothing
for an abandoned request.

## Changes

- `@agentclientprotocol/sdk` 2.11.0 to 2.12.0.
- `src/mcp-servers.ts`: the wait for a child session's announcement also
ends when the request's signal aborts.
- `src/tests/mcp-servers.test.ts`: a request that Claude Code gives up
stops waiting and sends nothing.

## Verification

- `npm run check` passes.
- `npm run test:run`: 4,552 tests passed and 53 were skipped.
- The new test fails without the change: the request stays held.
2026-11-24 18:49:34 +01:00
acp-release-bot[bot]
743ae8dcd4 chore(main): release 0.111.0 (#1706)
🤖 I have created a release *beep* *boop*
---


##
[0.111.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.110.1...v0.111.0)
(2026-11-24)


### Features

* name the session and tool call of MCP requests sent over ACP
([#1705](https://github.com/agentclientprotocol/claude-agent-acp/issues/1705))
([fa02bc2](fa02bc239f))


### Bug Fixes

* start a session without the MCP servers that Claude Code refuses
([#1708](https://github.com/agentclientprotocol/claude-agent-acp/issues/1708))
([f6525de](f6525de507))
* update to @anthropic-ai/claude-agent-sdk 0.3.331
([#1707](https://github.com/agentclientprotocol/claude-agent-acp/issues/1707))
([9062779](9062779cda))
* write error messages as plain text
([#1709](https://github.com/agentclientprotocol/claude-agent-acp/issues/1709))
([2c37f97](2c37f979b6))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-24 16:23:24 +01:00
Ben Brandt
f6525de507 fix: start a session without the MCP servers that Claude Code refuses (#1708)
## Summary

A session now starts without its MCP servers when Claude Code refuses to
start with them, and tells the user which servers are missing and why.

With a managed `disableSideloadFlags`, Claude Code takes MCP servers and
plugins only from sources that the administrator approved, and refuses a
start that brings others. A client that passes its MCP servers with
every session, as Zed does, got no session at all on such a machine:
`session/new` failed with `-32603`.

This builds on #1707, which updates the Claude Agent SDK to 0.3.331.
That version names the reason of the refusal
(`sideload_flags_disabled`).

## What changes

- **Claude Code decides.** The adapter reads no policy of its own. It
starts the session as before. When Claude Code refuses the start with
`sideload_flags_disabled` and the session has MCP servers, the adapter
starts it once more without them: `startAroundRefusedMcpServers()` in
`src/mcp-servers.ts`, used by both cores. So a session gets its servers
back at its next start once the setting is gone.
- **The servers are reported as not started**, through the lane that
already reports a server whose endpoint cannot open (`unserved`). They
are the session's ACP servers and the ones of
`_meta.claudeCode.options.mcpServers`.
- **One notice for servers that failed for the same reason.** Each
unserved server got a notice of its own. `mcpServerStartupNotices()` in
`src/session-notices.ts` now gives the servers with the same error one
notice: "3 MCP servers failed to start", with their names and the
reason. A client with eight MCP servers would otherwise get eight equal
warnings in every session. This also covers the `acp` servers of a
connection whose local endpoint cannot open. A notice about one server
is as before.
- **On v2, a resume of the active session keeps those servers out too.**
Such a resume replaces the session's MCP servers on the running query. A
session whose start was refused with MCP servers stays without them
until its query starts again.
- **The MCP-over-ACP bridge hears of no server that the query starts
without** (`sessionStarted`, `toolUseHooks` and `sessionServersChanged`
of #1705).
- **A second refusal is an error, as before.** A client's `plugins` are
refused by the same setting. The session then fails with Claude Code's
text and `data.startupFailureReason`.

## What a client can notice

On a machine with that managed setting:

- `session/new`, `session/load`, `session/resume` and `session/fork`
with MCP servers succeed. The start takes one refused launch of Claude
Code longer.
- With the first turn the client gets the notice (a `notice` on v2 and
for a v1 client with `session.notices`, quoted text for other v1
clients):

> **3 MCP servers failed to start:** The tools of "files", "search" and
"docs" are unavailable in this session. Your organization's managed
settings (disableSideloadFlags) let Claude Code use MCP servers only
from sources that your administrator approved.

- On v1 without `session.notices`, the `_meta.claudeCode` of a notice
about several servers has `servers` (a list) where a notice about one
server has `server`.

Elsewhere nothing changes, but that several servers with the same error
share a notice.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,551 tests
pass)
- Unit tests of the two helpers, and on each core a test that a refused
start is repeated without the MCP servers. On v1 the servers are
unserved, and a start that is still refused fails with its error. On v2
the notice goes out once over two turns, and a resume of the active
session in between sets no servers on the query. They fail without the
change.
- Real CLI: a new test in `v2/v2-integration.test.ts`. A session with
two stdio MCP servers under `managedSettings: { disableSideloadFlags:
true }` starts, answers a Haiku prompt and sends the one notice.
- Real CLI: all of `v2/v2-integration.test.ts` and
`mcp-servers-integration.test.ts` (22 tests pass)
- Real CLI: the whole suite, as `npm run test:integration` runs it (with
`CLAUDE_CODE_ENTRYPOINT` unset): 4,593 tests pass. Two timing tests that
this PR does not touch failed in that run on a loaded machine and pass
by themselves: "holds the requests of two subagents of a v1 session with
child sessions until it knows their announcements went out" in
`mcp-servers-integration.test.ts` (its file passed in 5 of 5 runs
alone), and "absorbs the interrupt's lagged trailer after cancelling a
held turn mid-followup" in `v1/acp-agent.test.ts`.
- Real CLI through the built adapter: `session/new` on v1 and v2 with
MCP servers under that setting, and a Haiku prompt on v1 with and
without `session.notices`. With a client plugin too, the session fails
with "--plugin-dir is disabled by your organization's managed settings
(disableSideloadFlags) …".
2026-11-24 15:06:59 +00:00
Ben Brandt
9062779cda fix: update to @anthropic-ai/claude-agent-sdk 0.3.331 (#1707)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.330 to 0.3.331, which
bundles Claude Code 2.1.331. The adapter's code does not change: the
build passes, and no changelog entry needs a change.

Also bumps these dev dependencies: `@anthropic-ai/sdk` 1.12.0 → 1.13.0,
and `@typescript-eslint/eslint-plugin` and `@typescript-eslint/parser`
8.73.0 → 8.74.0.

`npm update` brings the in-range lockfile bumps: `brace-expansion`
5.0.13 → 5.1.0, `hono` 4.13.19 → 4.13.21, `pkce-challenge` 5.0.1 → 5.0.2
and `tinybench` 6.2.4 → 6.2.5.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.74.0 still requires `typescript <6.1.0`.

## Claude Agent SDK 0.3.331 and Claude Code 2.1.331

Read the SDK changelog for 0.3.331 and the Claude Code changelog for
2.1.331, and compared `sdk.d.ts` and `sdk-tools.d.ts` of 0.3.330 and
0.3.331.

### What a client can notice

- **A clearer error for a start that managed `disableSideloadFlags`
refuses.** On a machine with that managed setting, Claude Code starts no
session that brings MCP servers or plugins of its own, as before. The
failure now has the reason `sideload_flags_disabled`. Through the built
adapter, `session/new` with a client MCP server fails with `-32603`,
Claude Code's own text ("--mcp-config is disabled by your organization's
managed settings (disableSideloadFlags). … Ask your administrator …")
and `data.startupFailureReason`. With 0.3.330 the SDK reported only that
the process exited with code 1. A session without MCP servers and
plugins starts. #1708 starts such a session without its MCP servers.
- **`session/list` on a project with very many sessions.**
`listSessions()` no longer opens every transcript at once, which could
leave sessions out at the open-file limit.

### No change for the adapter

- **Types.** Doc text, the new startup failure reason, and members the
adapter does not use (`soft_error_result`, `registryPolicyFingerprint`,
`downloadsMirrorUrl`).
- **Edit and Write results now say when `canUseTool` changed the text
through `updatedInput`.** The adapter answers with the input it was
asked about. Checked through the built adapter: an approved Edit still
ends with "has been updated successfully".
- **`task_notification.output_file` for a foreground subagent.** The
async task lane of v1 leaves subagent tasks out, and v2 does not read
the field.
- **`rewindFiles()` refuses under a managed `fileCheckpointingEnabled:
false`.** The file change report of such a turn ends `unavailable`, as
for any preview that Claude Code refuses. Read from the code, not
reproduced.
- **Start-up no longer waits for the model list when a session starts
soon after another.** The initialize response lists the same models:
compared for three sessions started together and one right after,
0.3.330 against 0.3.331.
- **SubagentStop hooks wait for the transcript's last reply.** Both
cores use the hook to report a child's configuration only.
- **`getSessionInfo`, `listSessions` and `getSessionMessages`** read a
transcript as before: a differential run of 0.3.330 against 0.3.331 over
4,500 generated transcripts gave no mismatch. The run is not part of
this PR.
- **Compaction summaries that quote XML tags, MCP tool calls that hung
on a malformed reply, a request that went silent while Claude was
thinking.** Fixes of Claude Code, picked up as they are.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,541 tests
pass)
- Real CLI: the whole suite, as `npm run test:integration` runs it (with
`CLAUDE_CODE_ENTRYPOINT` unset): 4,584 tests pass and 9 are skipped (the
live capability audits, the baseline recording, and one test that skips
itself)
- Real CLI through the built adapter, without a prompt: `session/new`
under a managed `disableSideloadFlags` (plain, with an MCP server, with
an agent definition, with a plugin)
- Real CLI through the built adapter: one Haiku prompt that edits a file
behind a permission request
- Real SDK and CLI without a prompt, 0.3.330 against 0.3.331: the
startup refusal and its reason, and the model lists
2026-11-24 15:06:58 +00:00
Ben Brandt
2c37f979b6 fix: write error messages as plain text (#1709)
## Summary

Removes the Markdown code spans from thirteen error messages. Schema
v2.0.0-beta.4 says that the `message` of an error is plain text, and
these messages put a field or capability name in backticks.

## Why only these

I checked every v2 field that the schema marks as plain text against
what the adapter sends for it: tool call and permission titles,
permission option names, elicitation messages and labels, auth method
names, config option names, command names and hints, session and
subagent titles, notices, compaction errors and error messages. Text
that the adapter composes is plain everywhere else. The Glob title
already drops its code spans on v2.

Not changed: text that the adapter passes on from the model, Claude
Code, an MCP server or the user, such as an AskUserQuestion question, a
Bash command in a title, a session title or Claude Code's error text.
The adapter does not rewrite it.

## The messages

All are `-32602` messages:

- `src/v2/agent.ts`: "cwd must be an absolute path" (two forms), "cwd is
not a directory: …", "… with that cwd"
- `src/v2/prompt.ts`: "prompt must hold at least one content block"
- `src/initial-config-options.ts`: "configOptions sets … more than once.
…"
- `src/fork-session.ts`: "… announced with the fork capability, or send
the request without cursorId …"
- `src/providers.ts`: the two `_meta.gateway` messages and the vertex
message
- `src/session-index/service.ts`: the three `_meta.jetbrains.air.list`
messages

The last four files are shared, so a v1 client gets the same text
without the backticks. v1's schema has no rule for it either way, and
one text for both versions needs no switch in each helper.

## Testing

- `npm run build` and `npm run check` pass. `npm run test:run` passed
before the rebase onto #1705 (4,485 tests; one file watcher test of
`v1/session-index.test.ts` failed once on a loaded machine and passed
three times by itself). No test pinned the old text.
2026-11-24 16:05:18 +01:00
Ben Brandt
fa02bc239f feat: name the session and tool call of MCP requests sent over ACP (#1705)
## Summary

Sends the ACP session and tool call with the MCP requests that Claude
Code makes to a server the client provides over the ACP connection, in
ACP v1 and v2. Updates `@agentclientprotocol/sdk` from 2.9.1 to 2.11.0,
which adds the fields and the bridge option this uses.

An `mcp/message` request can carry `sessionId` and `toolCallId` since
ACP schema 1.35.0 / 2.0.0-beta.4. A client uses the session to run the
request for the right session, and can reject a request without one. It
uses the tool call to show the tool's own output on the tool call the
agent reports. See the [MCP-over-ACP
RFD](https://agentclientprotocol.com/rfds/mcp-over-acp#session-and-tool-call-attribution).

## How a request is matched

Claude Code makes the MCP request itself, over HTTP, to the SDK's
bridge. The adapter never makes the call, so it cannot pass the values
at call time. That is a Claude Code limitation, and the reason for the
hook:

- A PreToolUse hook records which agent each tool use belongs to before
the tool runs.
- Claude Code sends the same tool-use ID in
`params._meta["claudecode/toolUseId"]` of `tools/call`.
- The bridge's `attribution` resolver looks the record up and names the
session and the tool call. The tool call ID is the tool-use ID, which is
what both cores already report in `session/update`.

The record lives in `McpOverAcp` in `src/mcp-servers.ts`, which owns the
bridge. `src/v1/acp-agent.ts` and `src/v2/agent.ts` only wire it in.

## What is sent

| Who runs the tool | v1, no child sessions | v1, child sessions | v2 |
|---|---|---|---|
| Main conversation | root + tool call | root + tool call | root + tool
call |
| Announced subagent | root + tool call | child + tool call | child +
tool call |
| Subagent not announced yet | root, no tool call | waits up to 500 ms,
then child + tool call | waits up to 500 ms, then child + tool call |
| Workflow agent | root, no tool call | root, no tool call | root, no
tool call |

- **The root is never sent in place of a child.** A v1 client without
child sessions gets the root because the root reports the subagent's
tool calls there.
- **A workflow agent is never exposed as a child,** and the root shows
its work on the Workflow tool call. Its own tool uses are not reported,
so no tool call ID is sent for them.
- **Once a tool call has been reported,** the request names the session
of that report.
- **Nothing is sent** for `server/discover` and `tools/list`, for a tool
use no hook reported, for a server the session's last setup request did
not declare, after the root session closed, and for AIR's draft child
sessions, which are never announced with `subagent_update`.

## Holding a request for an unannounced subagent

A subagent can run a tool a few milliseconds before the adapter has sent
the `subagent_update` that announces its child session. A client that
needs the session could then reject a subagent's first tool call for
that reason alone. So the resolver waits for the announcement, up to
`ANNOUNCEMENT_WAIT_MS` (500 ms), then names the child. In 15 measured
runs the announcement was 1.5 to 12 ms ahead of the request.

- Only a request that can gain from it is held. The main conversation,
workflow agents, announced children, forgotten children, requests
without a tool-use ID, and v1 without child sessions are not delayed.
- The wait also ends when the tool use ends or the session closes. When
the limit passes, the request goes out without attribution.
- It cannot deadlock: the hook answers at once, a pending MCP request
does not stop Claude Code's message stream, and the messages the
announcement depends on are written before the subagent's tool runs.

## Hooks

The PreToolUse, PostToolUse and PostToolUseFailure hooks are only
registered for a session that declares an `acp` server, and only match
those servers' tools (`mcp__(?:<names>)__.*`, with names normalised the
way Claude Code does).

## SDK 2.11.0

Nothing in the update broke the build. One visible change: the bridge
now words a client's rejection for the model. A rejected tool call shows
"The MCP server refused this request before running it. Reason: ...
Changing the tool arguments will not help." The resolver's new
`connection` argument is not used, because each agent app has its own
bridge for its one connection.

## Known limits

- **A server added by a v2 resume to a running query** gets no hook
record, so its requests name no session until the session's next query.
Hooks cannot change on a running query. The adapter logs it and never
names a wrong session.
- **A request Claude Code abandons stays held** until the tool use ends
or the limit passes. The resolver gets no cancellation signal in SDK
2.11.0.
- **Workflow agents are recognised by Claude Code's `agent_type:
"workflow-subagent"`.** If a session defines its own agent with that
name, the child-session modes name nothing for an agent of that type
without an announced child.
- **Agent teams were not examined.** They are treated as an agent the
adapter does not know.

## Tests

- `src/tests/mcp-servers.test.ts`: the record, every attributed and
unattributed case, the hold and its limit, and cleanup.
- `src/tests/v2/acp-v2.test.ts`: router tests for v1 and v2.
- `src/tests/mcp-servers-integration.test.ts`: the bundled CLI with a
scripted local model, gated by `RUN_INTEGRATION_TESTS` like the other
real-CLI tests. A parent and two concurrent subagents call the same tool
with the same arguments, in all three modes. It also covers a workflow
agent, the hold (with an injected delay, since the natural race cannot
be made repeatable), and a client `-32602` producing a failed tool call.
It needs no account.

## Verification

`npm run check`, `npm run build` and `npm run test:run` pass (77 files,
4,541 tests). `RUN_INTEGRATION_TESTS=true npx vitest run
src/tests/mcp-servers-integration.test.ts` passes (10 tests). The rest
of `npm run test:integration` was not run, since it needs an account.
2026-11-24 13:30:40 +00:00
acp-release-bot[bot]
37241a9e28 chore(main): release 0.110.1 (#1698)
🤖 I have created a release *beep* *boop*
---


##
[0.110.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.110.0...v0.110.1)
(2026-11-23)


### Bug Fixes

* Closing the gaps for the ACP v2 support
([#1542](https://github.com/agentclientprotocol/claude-agent-acp/issues/1542))
([105e1c3](105e1c38da))
* preserve existing line endings in ACP v2 terminal output
([#1697](https://github.com/agentclientprotocol/claude-agent-acp/issues/1697))
([9ca8984](9ca8984d55))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-24 00:30:23 +01:00
Kirill Alekhnovich
105e1c38da fix: Closing the gaps for the ACP v2 support (#1542)
1. **[Prompts during active
work](https://youtrack.jetbrains.com/issue/IJAI-6021).** Deliver
priority prompts while Claude is running and keep the foreground turn
open until those prompts are answered. Withdraw cancelled queued prompts
without interrupting unrelated work, and handle prompt rejection or
completion without ending another prompt's turn.

2. **Work state and session restoration.** Report `running` while a
parallel foreground tool can still progress, even when another tool
awaits input. Preserve active work during resume. Restart the Claude
query for changed workspace roots only at a work boundary, and wait for
that restart before reporting success.

3. **Subagent results.** Publish a child's handback report even when
Claude provides it only in the launch result and sends no separate child
stream. Deduplicate reports and preserve their child-session
association. Restore successful handback reports in the existing Air v1
history view as well.

4. **Question form compatibility.** Keep custom answers attached to
their choices in Air on both protocol versions. Add request-level
`customAnswerFields` because the Kotlin SDK drops property metadata,
while retaining the existing property markers for older clients. Limit
v2 schema conversion to removing unsupported string patterns.

5. **Plan review outcomes.** Report a rejected plan as a cancelled turn.
Keep an accepted plan continuation inside the same foreground lifecycle
when it clears the context, so the interruption does not appear as a
completed answer.
2026-11-23 23:51:50 +01:00
Artur Bańkowski
ffb3225413 test: stabilize the ACP v2 live cancellation test (#1694)
The live cancellation test uses loopback ping to keep a foreground
command active. On systems that deny ICMP socket creation, ping exits
immediately. A terminal announcement can still arrive, and Claude Code
can insert the second prompt before the test cancels it.

Use a shell command that prints a start marker and sleeps. Wait for the
marker in streamed stdout before submitting the second prompt. The test
still requires the queued prompt to fail with `-32800`, the session to
go idle with `cancelled`, and a subsequent prompt to complete normally.

The original test failed and the corrected test passed against Claude
Code on base `184b7df`. On current upstream `4af4581`, `npm run check`
passed and `npm run test:integration -- --maxWorkers=2
src/tests/v2/v2-integration.test.ts` compiled the adapter and passed all
11 tests.

## Related CI failure

The failing Build job hit a flaky ACP v1 subagent announcement test. The
fix is in
[#1700](https://github.com/agentclientprotocol/claude-agent-acp/pull/1700).

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-23 21:39:07 +00:00
Artur Bańkowski
74abe32983 test: stabilize ACP v1 subagent cwd announcements (#1700)
The ACP v1 worktree-child test sometimes receives two announcements for
the isolated child. The `session/new` setup timer can publish the
current subagent snapshot after the test has already simulated a child
starting. The failing CI run in #1694 received that snapshot in addition
to the two expected announcements.

Wait for the real setup snapshot publication to finish before simulating
either child's start. Keep the existing assertions for both
announcements and their working directories.

On Node 26.13.1 the original test failed 12 times in 80 attempts. The
updated test passed all 80 attempts.

`npm run check`, `npm run build`, and `npm run test:run --
--maxWorkers=2` passed. The full suite reported 4,450 passed and 44
skipped.
2026-11-23 19:01:13 +00:00
dependabot[bot]
7c86d4b5a4 chore(deps): bump actions/create-github-app-token from 3.3.0 to 3.4.0 (#1699)
Bumps
[actions/create-github-app-token](https://github.com/actions/create-github-app-token)
from 3.3.0 to 3.4.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/create-github-app-token/releases">actions/create-github-app-token's
releases</a>.</em></p>
<blockquote>
<h2>v3.4.0</h2>
<h2><a
href="https://github.com/actions/create-github-app-token/compare/v3.3.0...v3.4.0">3.4.0</a>
(2026-11-18)</h2>
<h3>Features</h3>
<ul>
<li>bump actions/setup-node from 6 to 7 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/410">#410</a>)
(<a
href="09c1ab7079">09c1ab7</a>)</li>
<li>bump actions/stale from 10 to 11 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/409">#409</a>)
(<a
href="679345a20e">679345a</a>)</li>
<li>bump stefanzweifel/git-auto-commit-action from 7.2.0 to 7.2.1 in the
github-actions group (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/408">#408</a>)
(<a
href="660c44c8ce">660c44c</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> bump undici (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/406">#406</a>)
(<a
href="18e9994c8d">18e9994</a>)</li>
</ul>
<h2>v3.4.0-beta</h2>
<h2><a
href="https://github.com/actions/create-github-app-token/compare/v3.3.0...v3.4.0-beta">3.4.0-beta</a>
(2026-11-17)</h2>
<h3>Features</h3>
<ul>
<li>support GitHub Actions OIDC authentication (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/411">#411</a>)
(<a
href="8240f10d3a">8240f10</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/actions/create-github-app-token/blob/main/CHANGELOG.md">actions/create-github-app-token's
changelog</a>.</em></p>
<blockquote>
<h1>Changelog</h1>
<h2><a
href="https://github.com/actions/create-github-app-token/compare/v3.3.0...v3.4.0">3.4.0</a>
(2026-11-18)</h2>
<h3>Features</h3>
<ul>
<li>bump actions/setup-node from 6 to 7 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/410">#410</a>)
(<a
href="09c1ab7079">09c1ab7</a>)</li>
<li>bump actions/stale from 10 to 11 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/409">#409</a>)
(<a
href="679345a20e">679345a</a>)</li>
<li>bump stefanzweifel/git-auto-commit-action from 7.2.0 to 7.2.1 in the
github-actions group (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/408">#408</a>)
(<a
href="660c44c8ce">660c44c</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> bump undici (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/406">#406</a>)
(<a
href="18e9994c8d">18e9994</a>)</li>
</ul>
<h2><a
href="https://github.com/actions/create-github-app-token/compare/v3.2.0...v3.3.0">3.3.0</a>
(2026-10-12)</h2>
<h3>Features</h3>
<ul>
<li>update permission inputs (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/399">#399</a>)
(<a
href="a47236f79f">a47236f</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> bump nested undici from 6.24.0 to 6.29.0 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/403">#403</a>)
(<a
href="12461a3a79">12461a3</a>)</li>
<li><strong>deps:</strong> bump the production-dependencies group across
1 directory with 3 updates (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/395">#395</a>)
(<a
href="a69c19ddfd">a69c19d</a>)</li>
</ul>
<h2><a
href="https://github.com/actions/create-github-app-token/compare/v3.1.1...v3.2.0">3.2.0</a>
(2026-05-12)</h2>
<h3>Features</h3>
<ul>
<li>add support for enterprise-level GitHub Apps (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/263">#263</a>)
(<a
href="952a2a7073">952a2a7</a>)</li>
<li>support full repository names in <code>repositories</code> input (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/372">#372</a>)
(<a
href="85eb8dd414">85eb8dd</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> bump <code>@​actions/core</code> from 3.0.0
to 3.0.1 in the production-dependencies group (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/364">#364</a>)
(<a
href="43e5c345bf">43e5c34</a>)</li>
<li>validate private-key input (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/376">#376</a>)
(<a
href="f24bbd8964">f24bbd8</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="f418cff399"><code>f418cff</code></a>
chore(main): release 3.4.0 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/415">#415</a>)</li>
<li><a
href="09c1ab7079"><code>09c1ab7</code></a>
feat: bump actions/setup-node from 6 to 7 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/410">#410</a>)</li>
<li><a
href="01b8009bd6"><code>01b8009</code></a>
test: strip ANSI escape codes from snapshot output (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/412">#412</a>)</li>
<li><a
href="e056864841"><code>e056864</code></a>
build(deps-dev): bump undici from 8.12.3 to 8.12.4 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/416">#416</a>)</li>
<li><a
href="679345a20e"><code>679345a</code></a>
feat: bump actions/stale from 10 to 11 (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/409">#409</a>)</li>
<li><a
href="660c44c8ce"><code>660c44c</code></a>
feat: bump stefanzweifel/git-auto-commit-action from 7.2.0 to 7.2.1 in
the gi...</li>
<li><a
href="18e9994c8d"><code>18e9994</code></a>
fix(deps): bump undici (<a
href="https://redirect.github.com/actions/create-github-app-token/issues/406">#406</a>)</li>
<li>See full diff in <a
href="64ab729a62...f418cff399">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/create-github-app-token&package-manager=github_actions&previous-version=3.3.0&new-version=3.4.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-23 15:57:45 +01:00
Ben Brandt
9ca8984d55 fix: preserve existing line endings in ACP v2 terminal output (#1697)
Claude Code pipes command output, so a v2 display terminal needs a
carriage return before a bare line feed to start the next line at column
zero. Bash output can also contain CRLF and standalone carriage returns
used for progress updates. The encoder added an extra CR to existing
CRLF.

Convert only bare LF in v2 terminal chunks and snapshots. Track the
preceding CR on each running terminal so CRLF can span two chunks. A
replacement snapshot starts fresh and supplies the trailing character
for the next chunk. This also covers background output, where the
output-file reader can send a snapshot ending in CR and then append a
chunk starting with LF.

The regression test checks mixed line endings, progress updates, empty
chunks, and snapshot replacement. The corresponding Codex fix is
[codex-acp#795](https://github.com/agentclientprotocol/codex-acp/pull/795).
2026-11-23 14:06:40 +00:00
acp-release-bot[bot]
f9c25404ec chore(main): release 0.110.0 (#1695)
🤖 I have created a release *beep* *boop*
---


##
[0.110.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.109.1...v0.110.0)
(2026-11-23)


### Features

* name each model's effort levels in its model option entry for AIR
([#1692](https://github.com/agentclientprotocol/claude-agent-acp/issues/1692))
([130fbbc](130fbbc02a))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-23 13:46:55 +04:00
nikita-ashihmin
130fbbc02a feat: name each model's effort levels in its model option entry for AIR (#1692)
## Summary

The `effort` option lists the levels of the current model only. AIR
cannot show the effort steps and the recommended effort of a model
before that model becomes current. AIR Cloud sessions and Manage Presets
have no correct steps at all.

This PR adds the effort levels of each model to its entry of the `model`
config option:

```json
{ "value": "claude-opus-5-5", "name": "Opus 5.5",
  "_meta": { "jetbrains": { "air": { "version": 1,
    "reasoningEfforts": { "values": ["low", "medium", "high", "xhigh", "max"], "recommended": "medium" } } } } }
```

## Changes

- `values` are the `supportedEffortLevels` of the SDK `ModelInfo` of the
entry, in the SDK order. They never contain the `default` row of the
effort option.
- `recommended` uses the adapter rule: "medium" when the model offers
it, else the first level. The SDK names no recommended effort per model.
The rule moves into `recommendedEffortLevel()`, and the effort option
uses it too. For the current model, `recommended` is equal to
`recommendedValue` of the effort option.
- A model without effort levels gets no `_meta`. The `default` entry
gets the levels of the listed model that its `resolvedModel` names.
Without such a model, it gets no `_meta`.
- The adapter sends the key to every AIR client. The key only adds data,
so it needs no capability. A client that is not AIR gets no AIR key, as
the Compatibility rule says.
- All config option answers carry the key: new, load, resume, fork,
`session/set_config_option` and `config_option_update`, for ACP v1 and
v2. They all use `buildConfigOptions`.
- Out of scope: subagent `model` options. They have no effort slider.
- `docs/air-extensions.md` documents the key and the capability.

## Tests

- `recommended-config-values.test.ts`: values and order, the
`recommended` rule, a model without efforts, both cases of the `default`
row, and a model that the picker does not list.
- v1: new, set, load, resume, fork, and `config_option_update` after an
external model switch.
- v2: new, set, resume, fork, and the update.
- No golden file changes.

`npm run build`, `npm run check`, `npx vitest run`: pass in a clean
environment.

Tracking: IJAI-6873. AIR consumer: IJAI-5161.
2026-11-23 11:03:26 +04:00
acp-release-bot[bot]
4af4581ad5 chore(main): release 0.109.1 (#1675)
🤖 I have created a release *beep* *boop*
---


##
[0.109.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.109.0...v0.109.1)
(2026-11-21)


### Bug Fixes

* announce a live subagent again when its session is loaded or resumed
([#1688](https://github.com/agentclientprotocol/claude-agent-acp/issues/1688))
([b977017](b977017ed8))
* apply a provider's route to the running session
([#1691](https://github.com/agentclientprotocol/claude-agent-acp/issues/1691))
([988a58b](988a58b908))
* give a forked skill's child session its tool calls and text
([#1677](https://github.com/agentclientprotocol/claude-agent-acp/issues/1677))
([1c90fb9](1c90fb959a))
* keep built-in web-fetch and claude-code-guide agents out of the Agent
picker
([#1672](https://github.com/agentclientprotocol/claude-agent-acp/issues/1672))
([eb4c16f](eb4c16f10a))
* match v1 session/options to resume when workspace roots change
([#1679](https://github.com/agentclientprotocol/claude-agent-acp/issues/1679))
([184b7df](184b7df993))
* reject requests that name a replayed subagent session with -32602
([#1686](https://github.com/agentclientprotocol/claude-agent-acp/issues/1686))
([3304ca7](3304ca724c))
* report unusable Claude subscriptions as unauthenticated
([#1678](https://github.com/agentclientprotocol/claude-agent-acp/issues/1678))
([a4f0f78](a4f0f78bb3))
* send a replayed subagent's configuration after the replay, not inside
it
([#1685](https://github.com/agentclientprotocol/claude-agent-acp/issues/1685))
([6a760cb](6a760cbca6))
* show readable titles for MCP tool calls
([#1674](https://github.com/agentclientprotocol/claude-agent-acp/issues/1674))
([80440d8](80440d8b82))
* update to @agentclientprotocol/sdk 2.9.0
([#1687](https://github.com/agentclientprotocol/claude-agent-acp/issues/1687))
([022ff53](022ff53244))
* update to @agentclientprotocol/sdk 2.9.1
([#1690](https://github.com/agentclientprotocol/claude-agent-acp/issues/1690))
([85a0d6c](85a0d6c6f1))
* update to @anthropic-ai/claude-agent-sdk 0.3.330
([#1689](https://github.com/agentclientprotocol/claude-agent-acp/issues/1689))
([6d9e276](6d9e2766c7))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-21 16:33:53 +01:00
Ben Brandt
988a58b908 fix: apply a provider's route to the running session (#1691)
## Summary

Both cores now send the route of a provider, or of a gateway login, to
Claude Code a second time: right after a session starts, with
`applyFlagSettings()`.

The route is already part of the query's `settings` option, in one
object with the client's settings and the model configuration of the
environment. Claude Code loads that object as a whole or not at all: one
value that fails validation leaves all of it out. Since 2.1.330 it says
so in a warning (see #1689). The second delivery does not depend on that
object.

## What changes

- **One place for the route as settings.** `providerRouteSettings()` in
`src/providers.ts` builds it: `apiKeyHelper: ""` and the env of
`createEnvForProvider()`. Both cores built that object on their own
before.
- **`applyProviderRoute()`** in the same module sends it to a running
query. v1 and v2 call it right after the query's initialize response,
before a request of the session reaches the provider. The context read
is such a request: `getContextUsage()` sends `count_tokens`.
- **A session without a provider or gateway login** gets no such call.
- **When Claude Code refuses the call, the session is not started.** The
request fails with `-32603`, "The session was not started, because
Claude Code did not take its provider or gateway route. Try again, or
set the provider or the gateway login again.", and Claude Code's text in
`data.details`. The adapter builds the route itself, and I know no input
that makes Claude Code refuse it.

## What a client can notice

Nothing when its `settings` load. The call then changes nothing: Claude
Code merges `env` key by key, and the values are the ones of the
`settings` option. Recorded with the real CLI: after the call, the flag
settings still hold the client's own `env` keys and its `permissions`.

When a value of its `settings` fails validation, the client's settings
are not in effect, as before. The route of the provider is.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,437 tests
pass)
- Each core has a test that the route is applied (on v1: before the
first context read), and a test that a refused route starts no session
and releases the query. They fail without the change.
- Real CLI: a new test in `v2/v2-integration.test.ts` with two local
servers, so it costs no API usage. One is the provider. The project's
`.claude/settings.json` names the other as `ANTHROPIC_BASE_URL`, and the
client's `settings` hold `permissions.allow: "Bash"`. The session's
model requests reach the provider's server. The test fails without the
change. It passes with Claude Code 2.1.330 and 2.1.328, and with a CLI
named in `CLAUDE_CODE_EXECUTABLE`, which gets its settings in a flag.
- Real CLI through the built adapter, with the same two servers: on v1
and on v2, with valid and with invalid client `settings`, every model
request reaches the provider's server.
- Real CLI: the whole suite, as `npm run test:integration` runs it (with
`CLAUDE_CODE_ENTRYPOINT` unset): 4,470 tests pass and 9 are skipped (the
live capability audits, the baseline recording, and one test that skips
itself)
2026-11-21 15:28:56 +00:00
Ben Brandt
6d9e2766c7 fix: update to @anthropic-ai/claude-agent-sdk 0.3.330 (#1689)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.328 to 0.3.330, which
bundles Claude Code 2.1.330. The adapter's code does not change: the
build passes, and no changelog entry needs a change.

Also bumps the dev dependency `@anthropic-ai/sdk` 1.10.0 → 1.12.0.

`npm update` brings the in-range lockfile bumps: `@babel/runtime`
7.29.14 → 7.29.15, `@hono/node-server` 2.1.9 → 2.1.11 and
`source-map-js` 1.2.3 → 1.2.4.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.73.0 still requires `typescript <6.1.0`.

## Changelog review

Read the SDK changelog for 0.3.329 and 0.3.330 and the Claude Code
changelog for 2.1.329 and 2.1.330, and compared `sdk.d.ts` and
`sdk-tools.d.ts` of 0.3.328 and 0.3.330.

### What a client can notice

- **A warning when settings do not load** (0.3.330). When a value in a
session's `settings` or in a settings file fails validation, Claude Code
leaves the whole object or file out, as before. It now says so in the
session's first turn, in an `informational` message at level `warning`
(tag `settings_not_in_effect`). Both cores pass such a message on: as a
`notice` with `severity: "warning"` on v2 and for a v1 client with
`session.notices`, as quoted `**Warning:**` text for other v1 clients.
Checked through the built adapter, see Testing.
- **A warning when the hooks of managed settings do not load** (0.3.329,
tag `managed_hooks_not_loaded`). The same kind of message, passed on the
same way. Not reproduced: it needs managed settings.
- **The Fast mode state of a new session is that of its model.** The
initialize response's `fast_mode_state` described the default model, and
both cores set the Fast mode option of a new session from it. Recorded
with `settings: { model: "haiku", fastMode: true }`: `on` with 0.3.328,
`off` with 0.3.330.
- **A login that the macOS Keychain cannot save** ends a request with
`invalid_request` and no status, not with `authentication_failed` and
401. The adapter then fails the prompt with Claude Code's text ("… can't
save to the Keychain …") and no longer asks the client to sign in again.
Read from the changelogs and the CLI's text, not reproduced.
- **Prompt suggestions.** Claude Code now drops a placeholder such as
`_(no suggestion)_` where it generates the suggestion, so the adapter's
suggestion updates do not carry one.
- **claude.ai connectors are in the server list of `system/init` at
once.** Before, the list was empty at start and they came later. The
startup notices of both cores cover the client's own MCP servers only,
so a client gets no new notice.

### No change for the adapter

- **Types.** Doc text, plus:
- two `Settings` keys, `permissions.workingDirectoriesExclude` and
`desktopMcpServersListScope`
- the subkind `external-event` of a `task-notification` origin, which
only a session server stamps
  - `maxAgeMs` and `otherOneShots` on the output of `CronCreate`
- **`query()` refuses a `settings` JSON string that does not parse**,
when the `sandbox` option is set. The adapter passes no string: it reads
a client's settings file itself and passes an object.
- **Request ids of SDK MCP servers.** The adapter starts none.
- **`rewind_conversation` and `SpareProcess.claim()`.** Not used.
- **Background agents.** A stopped agent stays stopped, and Claude no
longer waits for an agent that `stopTask()` stopped as it finished.
Picked up as they are.
- **The system prompt after a model change that follows a context read,
and the memory use of idle sessions.** Picked up as they are.
- **The shorter sign-in link.** The adapter runs `claude auth login` in
the client's terminal and reads no link.
- **`getSessionInfo`, `listSessions` and `getSessionMessages`** read a
transcript as before: a differential run of 0.3.328 against 0.3.330 over
4,500 generated transcripts gave no mismatch. The run is not part of
this PR.
- **`@anthropic-ai/sdk` 1.11.0 and 1.12.0.** The adapter uses its types
only. The releases add Admin API methods and an error code, and fix the
client's default headers.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,434 tests
pass), on `main` with #1690
- Real CLI: the whole suite, as `npm run test:integration` runs it (with
`CLAUDE_CODE_ENTRYPOINT` unset). Before #1690 landed, the run passed in
full: 4,465 tests pass and 9 are skipped (the live capability audits,
the baseline recording, and one test that skips itself). On `main` with
#1690, on a machine under heavy load, 4,460 pass; one timing test of
`v1/acp-agent.test.ts` failed, and the 10-second build hook of the v1
subprocess tests timed out, which skipped those five. All six pass when
run again by themselves.
- Real CLI through the built adapter: one Haiku prompt in a session
whose client `settings` hold `permissions.allow: "nope"`. On v1 without
`session.notices` the warning is quoted text, on v1 with it and on v2 it
is a `notice`. Each time it comes inside the turn, before the answer.
- Real SDK and CLI without a prompt, 0.3.328 against 0.3.330: the Fast
mode state per model, the settings read for valid and invalid settings,
and the MCP server list at start
2026-11-21 16:18:08 +01:00
Ben Brandt
85a0d6c6f1 fix: update to @agentclientprotocol/sdk 2.9.1 (#1690)
Updates `@agentclientprotocol/sdk` from 2.9.0 to 2.9.1 (schema
v2.0.0-beta.3). The release has two changes, and both come from the
review for #1687.

## A relative stdio MCP `command` is rejected on v2

ACP v2 requires the `command` of a stdio MCP server to be an absolute
path, and an Agent rejects a relative one with `-32602`. SDK 2.9.1 does
that in `assertSupportedMcpServers`
(agentclientprotocol/typescript-sdk#361), which the adapter already
calls for `session/new`, `session/resume` and `session/fork` on v2. So
this needs no adapter code.

A v2 client that sends a bare command name, such as `npx`, now gets
`-32602` with `{ name, command }` before anything is created, resumed or
copied. It has to send the full path. v1 does not require an absolute
path and is unchanged.

The SDK accepts a path that is absolute in POSIX or in Windows syntax,
because it does not know which machine the Agent runs on. A path in the
other system's syntax passes the check and fails when Claude Code starts
the server, like any missing executable.

- The existing test of rejected MCP server lists is now an `it.each`
with the relative `command` as a second case, over new, resume with and
without replay, and fork.
- The doc comment of `v1McpServers` and the README's v2 section say it.

## Markdown in descriptions

The schema change is description text only: the `description` of an
authentication method, a command, a config option and each of its
values, a permission request and a subagent may contain Markdown on v2
(agentclientprotocol/agent-client-protocol#2974). The adapter already
sends Markdown in some of them, such as the remote login method's ``Run
`claude /login` in the terminal``, so nothing changes.

## Tests

`npm run build`, `npm run check` and `npm run test:run` pass (4,434
tests).

Against the real Claude Code CLI, the whole suite ran with 4,461 passed
and one suite not run: the `tsc` step in the `beforeAll` of "ACP
subprocess integration" hit its 10 second limit twice, on a machine with
a load average above 50. That suite's five tests pass when it runs
alone.
2026-11-21 14:55:13 +00:00
Ben Brandt
b977017ed8 fix: announce a live subagent again when its session is loaded or resumed (#1688)
A session that is loaded or resumed while it runs keeps its subagents'
runs. A child that works then, and that the request's replay does not
announce, was not reported as the protocol asks, on v1 or v2. A forked
skill's child is one such child: its metadata names no launch call, so
no replay has it. A subagent launched after the stored history was
written is another.

Found while reviewing the protocol changes since ACP SDK 2.8.0. One
commit per protocol version.

## v2: `session/resume` with replay of the active session

The rules, from the session setup and subagents pages:

- "The Agent **MUST** send `replay_complete` exactly once on each child
session that it announces with `subagent_update` between the request and
the response… An announced child with no replayed history gets one too."
- "The Agent **MUST** send the announcing `subagent_update` before any
request or notification that carries the child's `sessionId`", and "The
announcement rule applies again on every resume".
- "The Agent sends current updates for a child after that child's
marker."

Before, with a forked skill's child running and one of its messages sent
while the history was read:

```
root   replay_complete
child  agent_message_chunk    <- held update, before any announcement in this resume
root   subagent_update        <- from the state snapshot
child  state_update
root   state_update
```

The child never got a `replay_complete`, and its held update came before
its announcement.

After:

```
root   replay_complete
root   subagent_update        <- labels and the cancel capability
child  replay_complete
child  agent_message_chunk
root   subagent_update running
child  state_update running
root   state_update
```

Right after the root's `replay_complete`, in the same synchronous replay
step, each current child that the replay did not announce is announced
again on its parent and gets its own `replay_complete`. What the replay
held follows, then the snapshot. A child counts as current when it
works, when its parent lists it, or when the replay holds something its
session sent, such as the end of a run that ended while the history was
read.

`SessionTasks.unreplayedChildren` builds these updates, and
`ReplayHolds` now records which sessions sent what it holds. A child
whose launch is in the history was already handled and is unchanged.

## v1: `session/load` or `session/resume` of the active session

The rules, from the v1 subagents page:

- "When the Client sends `session/load` or `session/resume` for a
session, it **MUST** discard the state and capabilities it holds for
that session's children."
- "The Client **MUST NOT** send `session/cancel` for a child until the
request succeeds and a current `subagent_update` advertises `cancel`."
- "The Agent **SHOULD** report each child's current state when it can
determine it."

Before, the adapter reported only the children that a load's replay had
announced. A working child of a resumed session, which replays nothing,
got no `subagent_update` after the response. Nor did a working child
whose launch a loaded history does not have. A conforming client could
no longer cancel either one.

After, each working child that no replay announced is announced again on
its parent after the response, with its labels, `cwd`, `capabilities: {
cancel: {} }` and its state, and then gets the configuration that the
client last had for it. A child that no longer works but has a working
child of its own is named first, with its labels only, so parents come
before children.

`NativeSubagentRuntime.currentChildren` builds these, and
`publishCurrentSubagentStates` sends them after the replayed children's
current states. AIR's draft form is unchanged.

## Tests

- v2 (`src/tests/v2/v2.test.ts`): one `it.each` with three cases, a
forked skill's child that reports during the resume, a quiet subagent,
and a subagent whose run ends during the resume.
- v1: a runtime test in `src/tests/native-subagents.test.ts` (a nested
working child under an ended parent, a `requires_action` child with its
own `cwd`, an ended child, a child the replay covers, and the
configuration), an `it.each` over resume and load of the active session
in `src/tests/v1/create-session-options.test.ts`, and a working child
that the replay lacks in the existing load test.

Each new case fails without its source change. `npm run build`, `npm run
check` and `npm run test:run` pass, and so does the whole suite against
the real Claude Code CLI (4,465 passed, 9 skipped).

## Not covered

- v2: a child that is first announced between the root's
`replay_complete` and the response still gets no marker. The window is a
few awaits long.
- v2: an unreplayed live child's configuration is not sent again after
its marker.
- v1 has no hold, so a working child's own updates can still reach the
client between the request and this announcement. The change restores
the child's capabilities, state and configuration after the response,
not that order.
- v1 covers working children only, as the v2 snapshot does.

## Not verified

The tests drive the frames that Claude Code is known to send for a
forked skill, but no live session was resumed while one ran. Two things
only a live run shows: the real timing of a forked skill's frames during
a resume, and whether the stored history of an active session already
has a launch that was just made.
2026-11-21 14:25:25 +00:00
Ben Brandt
3304ca724c fix: reject requests that name a replayed subagent session with -32602 (#1686)
A child session that a `session/load` or `session/resume` replay
announced was known only to the replay. A request that named it was
answered as one of an unknown session: `session/close` and
`session/delete` reported success, and the rest failed with `-32002`. A
live child was forgotten the same way after `/clear` and after a restart
of its root's query.

Found while reviewing the protocol changes since ACP SDK 2.8.0
(agentclientprotocol/agent-client-protocol#2952).

## The rules

- Errors page, v1 and v2: "A child session that the Agent announced with
`subagent_update` is not an unknown session… Agents **SHOULD** reject
any other request that names a child with `-32602`."
- v2 session setup: "Agents **SHOULD** reject a `session/close` that
names one with `-32602`." The delete page says the same for
`session/delete`.
- Subagents, restricted methods: the Client can name a child from the
child's announcement until the child's root session stops being active.

## Before

- v2: `V2Agent.ownerOfChild` asked `SessionTasks.hasChild`, which reads
only the children of the current conversation.
- v1: `assertNoChildSession` asked `NativeSubagentRuntime.hasChild`,
which reads only live children.

## After

Each connection keeps one record of the child sessions it announced,
`AnnouncedChildren` in `src/acp-subagents.ts`. It takes the child of
every `subagent_update` at the point where updates go out
(`V2Agent.send` on v2, `ChangedMetaClient` on v1), and forgets a root's
children when the client ends that root.

A request that names such a child now fails with `-32602` through the
existing `restrictedChild`, on v1 and v2. `session/cancel` of a child
that does not run still does nothing. On v2, `tool_call/cancel` and
`terminal/cancel` answer `-32602` for it, also after its root's query
ended (it was `-32002`).

The record is per connection and not per session because per-session
state does not last long enough. On v1 a load's replay runs before the
session record and its runtime exist. On both versions a query restart
creates a new session object, and `/clear` drops the live children,
while the client still holds every child it was told about.

Other changes that follow from it:

- v1: a new `endSession` (teardown plus forgetting the children) serves
`session/close`, `session/delete` and archive. A load or resume that
replaces the query still only tears down, and keeps the children.
- v2: a replayed child's own updates are now held while a second replay
of its root is in flight, like the parent's `subagent_update` for it.
Before, the child's state could overtake its announcement.
- `NativeSubagentRuntime.hasChild` had no caller left and is removed.
`SessionTasks.hasChild` is private and documented as live-only.
- AIR's draft announces with `subagent_spawned` and keeps its own rules,
so its children are never in the record, as before.

`docs/subagent-sessions.md` says which children are covered and for how
long.

## Tests

- `src/tests/acp-subagents.test.ts` covers the record.
- v1: the existing `it.each` over the methods now announces through the
agent's client. New cases: a child from a live run, a child from a load
replay with no session record (forgotten after close), and a child kept
when a resume recreates the session.
- v2: the `it.each` gains a row after a conversation reset. New cases: a
replay-only child (close, cancel as a no-op, item cancel while the root
runs and after its query ended, `-32002` after the root closes), and a
child across a provider restart.

`npm run build`, `npm run check` and `npm run test:run` pass. The whole
suite also passes against the real Claude Code CLI on this branch merged
with the SDK 2.9.0 bump and the other replay fix (4,459 passed, 9
skipped).

## Not verified

- v1 delete and archive forgetting is covered only through
`closeSession`. They share `endSession`.
- Three paths leave an entry until the connection ends: a root whose
process died without a close, a v2 resume that fails after its replay
announced children, and a `subagent_update` sent after a close. The only
effect is `-32602` instead of not-found for an id that is invalid either
way.
2026-11-21 14:58:30 +01:00
Ben Brandt
6a760cbca6 fix: send a replayed subagent's configuration after the replay, not inside it (#1685)
A child session's `config_option_update` inside a replay describes a
past value. Both replays sent each child's `model` option inside the
replay, and then dropped the update after the replay when it was the
same. A client that follows the ACP rules never got a configuration it
may show.

Found while reviewing the protocol changes since ACP SDK 2.8.0
(agentclientprotocol/agent-client-protocol#2881 and
agentclientprotocol/agent-client-protocol#2896).

## The rules

- v2, Replay contents: "Historical `usage_update`,
`session_info_update`, `config_option_update`, and
`available_commands_update` notifications. They describe past values and
**SHOULD NOT** be replayed."
- v2, Subagents: "Agents **SHOULD** send a current
`config_option_update` for a restored child when it is available."
- v1, Subagents: "A child's `config_option_update` that arrives before
the `session/load` response is historical. The Client **MUST NOT**
present it, or configuration it held before the load or resume, as the
child's confirmed current configuration. Agents **SHOULD** send a
current `config_option_update` for a restored child when it is
available. After `session/load`, they send it after the response."

## Before

- v2 (`src/v2/subagent-replay.ts`): the child's `model` went out as a
`config_option_update` at its announcement, and again for each response
with another model. After the root's `replay_complete`, the current
configuration was skipped when it equalled what the replay sent.
- v1 (`src/subagent-replay.ts`): the same during the `session/load`
replay, and `currentStates` dropped the update after the response when
it equalled the replayed one.

## After

Both versions behave the same way:

- The replay sends no `config_option_update` of a child. It only tracks
the model of the child's latest response.
- After the boundary, each announced child gets one
`config_option_update` when a configuration is known: the configuration
of a child that still runs, else its `model` option with the model of
the latest response in its transcript, as the session's model list names
it. It goes out also when nothing changed.
- The boundary is the root's `replay_complete` on v2 and the load
response on v1.

On a child's own stream on v2 the order is now: history,
`replay_complete`, `state_update`, `config_option_update`. On v1, after
the load response: the parent's `subagent_update`, then the child's
`config_option_update`.

`currentChildConfiguration` and `trackResponseModel` in
`src/subagent-replay.ts` serve both cores. The replayed-model state that
only the dedupe needed is gone (`ReplayChild.model`, `mapsDuringReplay`,
`sendModel`, `firstResponseModel`). AIR's draft form
(`publishReplayedChildModels`) is unchanged.

One thing goes slightly beyond the spec: a child that no longer runs
still gets its model after the boundary. The SHOULD names a "restored
child". `currentStates` already did this when the model list mapped the
model to another entry, and a client has no other way to learn which
model a past child ran on.

## Tests

- v1 (`src/tests/v1/acp-agent.test.ts`): one replay with four children
covers no model before the response, the latest response's model mapped
by the model list, an unlisted model sent as its id, a `<synthetic>`
response ignored, none for a child without responses, and a live child
getting its live configuration.
- v2 (`src/tests/v2/acp-v2.test.ts`): the history test pins the
configuration after the child's `replay_complete` and state. The
live-child test expects the live configuration once. An `it.each` covers
the latest of two response models and no update without a response.

`npm run build`, `npm run check` and `npm run test:run` pass. The whole
suite also passes against the real Claude Code CLI on this branch merged
with the SDK 2.9.0 bump and the other replay fix (4,459 passed, 9
skipped).

## Not verified

No real client's rendering of a child's model that arrives after the
boundary was checked.
2026-11-21 14:58:05 +01:00
Ben Brandt
022ff53244 fix: update to @agentclientprotocol/sdk 2.9.0 (#1687)
Updates `@agentclientprotocol/sdk` from 2.8.0 to 2.9.0 (schema v1.34.1
and v2.0.0-beta.2), and follows the protocol rules that changed for what
the adapter already serves.

The adapter compiles against 2.9.0 unchanged. The behavior rules are in
the protocol docs, so I read the protocol repo from the last reviewed
commit to `schema-v2.0.0-beta.2`, which is 90 commits.

Each change below is its own commit.

## Changes

### The bump

- SDK 2.9.0 dispatches one incoming message per event-loop task, in the
order received. Two v2 tests asserted a `running` state right after a
permission answer, before the in-process test client had read it. They
now wait for it. The adapter sends that update before it returns the
decision, as before.
- ACP made plan operations and subagent sessions stable in v1 and moved
v2 to Preview. The adapter already serves them as specified, so only
words change: the README section is "ACP v2 (Preview)", the subagent
docs link the protocol page instead of the RFD, and comments no longer
say "draft".
- The README says how long the `idempotencyKey` of a prompt that Claude
Code does not store is known: until `session/close` or the end of the
connection.

### The text items of a v2 tool call stay apart

v2 now says that adjacent text blocks form one continuous text, which a
Client joins without a separator
(agentclientprotocol/agent-client-protocol#2885). The adapter's text
items in a tool call's content are separate paragraphs: one per
AskUserQuestion question, per reported finding, or per block of a tool
result. Joined, two fenced error blocks would run into each other.

`v2ToolCallPatch` in `src/v2/tool-call.ts` now ends each text item that
another text item follows with a blank line. v1 is unchanged.

### A v2 Glob title is plain text

v2 now says that a tool call `title` is plain text, which a Client
should not render as Markdown
(agentclientprotocol/agent-client-protocol#2887). A Glob title wrapped
its path and pattern in backticks, which such a Client shows literally.
A v2 client gets them as they are. v1 states no format, so a v1 client
keeps the code spans.

### An empty `systemPrompt.content` is rejected on v1 too

A Client must not send an empty `content` list, and an Agent may reject
one with `-32602` (agentclientprotocol/agent-client-protocol#2912). SDK
2.9.0 rejects it on v2 in the schema. On v1 it reached the session. With
`override`, Claude Code then got an empty custom prompt, which is also
what the Claude Agent SDK sends when its `systemPrompt` option is
omitted.

`clientSystemPrompt` now rejects it, so both versions answer the same.
This is a behavior change for a v1 client that sent `content: []`.

### A stale usage origin is removed (v2)

The top-level `_meta` of a v2 `usage_update` is now a metadata patch: a
Client keeps each key until an update replaces it or sets it to `null`
(agentclientprotocol/agent-client-protocol#2933). `_claude/origin` went
only with a result that had an origin, so a Client kept `{ kind:
"task-notification" }` for every later result.

The next result without an origin now sends `"_claude/origin": null`.
`_claude/model` and `_claude/rateLimit` are the last ones reported,
which is what a Client keeping them means.

## Already compliant, checked

- Cancellation: a prompt that came before a `session/cancel` and is not
inserted gets `-32800`, a prompt after it is held and not rejected, the
cancelled work's final updates come before its `idle` with `cancelled`,
and listed background work keeps running.
- Permissions: the `optionId` is matched against the options offered,
and an unknown option or outcome, an error response and a withdrawn
request all leave the tool unapproved.
- `replay_complete`: the hold starts with the request, each replayed
child gets its own marker, and the children's current states follow the
root's marker.
- `idempotencyKey`: a stored message keeps its key across restarts, and
an error leaves the key unused.
- An MCP server that fails to start does not fail the session. The user
gets a notice.
- A prompt with a content type the adapter did not advertise gets
`-32602` before it is inserted.
- Plan operations and subagent updates go to a v1 client only when it
advertises `plan` or `subagents`, and to every v2 client.
- `status` is a patch field on a v2 `compaction_update` now. The adapter
still sends it on every update.
- Elicitations are session-scoped and carry no `requestId`, which the
new scope validators require.
- The SDK no longer answers `tool_call/cancel` and `terminal/cancel` by
default. The adapter has its own handlers.
- The v1 `auth/status` response passes the response validation that SDK
clients now run.

## Not covered

- **Relative stdio MCP `command` on v2.** v2 asks an Agent to reject one
with `-32602`. The check belongs in the SDK's
`assertSupportedMcpServers`: agentclientprotocol/typescript-sdk#361. The
adapter gets it with the SDK release that has it, and a test case for it
is ready.
- **Markdown in descriptions.**
agentclientprotocol/agent-client-protocol#2974 lets several
`description` fields contain Markdown. The remote login method's
description keeps its code span.
- **Replayed subagents.** #1685 sends a replayed child's configuration
after the replay, and #1686 answers requests that name a replayed child
with `-32602`.
- **Relayed MCP forms.** A form with an empty `enum`, `oneOf` or `anyOf`
goes to a v2 client as the MCP server sent it. Only a non-conforming
server sends one, and the Client's `-32602` already ends in `cancel` for
the server.
- **A cancel during an open turn** reports `cancelled` also when Claude
Code's result was not aborted. v2 now says that the stop reason of work
that had already ended stands.
- Still open from earlier bumps: a Markdown plan's `path`, and v2
skills.

## Tests

`npm run build`, `npm run check` and `npm run test:run` pass (4,417
tests). The whole suite also passes against the real Claude Code CLI on
this branch merged with #1685 and #1686 (4,459 passed, 9 skipped).
2026-11-21 14:57:46 +01:00
Ben Brandt
184b7df993 fix: match v1 session/options to resume when workspace roots change (#1679)
The [Session options
RFD](https://agentclientprotocol.com/rfds/session-options) says that
querying an existing session should report what restoring it in the
requested workspace would return, without changing that session. On v1
the query always returned the held session’s options. Changing
`additionalDirectories` could therefore show Haiku in the picker even
though `session/resume` with the same directories returned Sonnet.

`session/options` now makes the same reuse decision as `session/load`
and `session/resume`. When the workspace matches, it answers from the
live session without launching Claude Code. When it differs, it reads
the options through a non-persisting query and leaves the live query
running. The probe keeps the live permission mode, starts no configured
MCP servers, and does not attach the adapter’s session-update hooks.
Claude Code has no transcript until the first prompt, so for a held but
unprompted session the probe can fall back to a fresh query without
claiming the held session’s ID. An unknown ID still returns `-32002`.

## Verification

- Added regression coverage for held sessions with and without a stored
conversation. The changed-workspace cases failed before the fix. Also
covered the no-query path when the held session has MCP servers and a
system prompt, neither of which `session/options` accepts.
- `npm run build` and `npm run check` passed. Adapter test suite: 4,414
passed, 41 skipped; the focused v1 options suite passed with the final
assertions.
- Exercised v1 over stdio with the bundled Claude Code binary and a
local Messages API stub. For both a saved conversation and an unprompted
one, the live session stayed on `opus`; the preview for the changed
roots and subsequent resume both returned `default`. The preview left
`session/list` and the transcript files unchanged.
2026-11-20 15:48:20 +00:00
Ben Brandt
a4f0f78bb3 fix: report unusable Claude subscriptions as unauthenticated (#1678)
With `--hide-claude-auth`, clients could see `authenticated` for a
subscription the adapter would refuse at `session/new`. On ACP v1 and
v2, `auth/status` and `auth/status_update` now report `unauthenticated`
with no accounts when the stored subscription cannot be used. Enterprise
subscriptions, API keys and setup tokens remain usable.

Keep the legacy `_auth/status_update` payload separate: it still
describes the stored identity, including a refused subscription. Each
notification is sent only when its own payload changes. No login or
billing policy changes.

**Validation:** `npm run check`, `npm run build`, and `npm run test:run`
passed (4,412 tests). A stdio check with a simulated Max login verified
the query and notification on v1 and v2.
2026-11-20 11:59:57 +00:00
Ben Brandt
1c90fb959a fix: give a forked skill's child session its tool calls and text (#1677)
## Problem

A forked skill (`context: fork`, such as `/code-review`) runs as a
subagent that no Agent or Task call launched. The adapter ties a
subagent's messages to its child session through that call, so a client
with subagent sessions got an empty child:

- **The user types `/code-review`:** the child was announced with its
prompt, then went `idle`. On v2 the fork's tool calls landed on the root
session; on v1 they were never sent.
- **Claude calls the Skill tool:** no child was announced, and the
fork's tool calls were never sent.

What Claude Code 2.1.328 sends, captured from its output stream:

| | Skill tool | Typed |
| --- | --- | --- |
| `task_started` names a tool call | yes, the Skill call | no |
| `parent_tool_use_id` of the fork's messages | the Skill call's id |
`forked-command-<skill>`, the same for every run |
| `agent_id` of the fork's messages | the task id | the task id |
| When the messages come | live | together, after the
`task_notification` and before the turn's result |

## Change

1. **Route by `agent_id`.** A message whose `parent_tool_use_id` names
no launch call goes to the child that its `agent_id` names.
2. **Announce a Skill-launched child** on the session that made the
Skill call. The call stays a tool call, and the skill's prompt is a
`session_message` in the child only.
3. **Hold the child's end until its messages came,** so its `idle`
follows its tool calls and text. The end is reported at the first
message of the main conversation after one of the child's, at the turn's
result, at Claude Code's `idle`, or when the turn or the query ends.

Both cores apply the same two rules, `endWaitsForMessages` and
`endsMessageWait` in `src/native-subagents.ts`. AIR gets the change
through the v1 runtime; I could not check it against an AIR client.

## Workarounds for Claude Code's behavior

- **The hold is a heuristic.** No task event marks a typed fork. The
adapter holds the end of every foreground subagent that no tool call
launched, and reports it when the turn ends at the latest.
- **`messageCame` returns a promise only when it reports an end.** The
v1 loop calls it for every message, and an `await` on each one let a
cancel run between a message and its handling.

## What a client gets

- **Typed:** the child stays `running` until the command ends, then gets
its tool calls and text together, then `idle`. Claude Code writes the
fork's messages only then, so the transcript is not live.
- **Skill tool:** the child's work is live. The Skill call carries the
RFD's `session` reference on an update with content, such as a failed
result.
- **A subagent that a typed skill launches** gets no session: Claude
Code reports the end of its task before the Agent call that launched it.
That call is a tool call of the skill's child.
- **`session/cancel` of the root:** a typed skill's messages are the
output of stopped work, which the adapter drops. The child reports
`idle` with `cancelled`.
- **`session/cancel` of the child:** its messages still go to it, before
its `idle` with `cancelled`.
- **Replay:** no child for a forked skill. The Skill call stays a tool
call.

`docs/subagent-sessions.md` and the AIR section of
`docs/air-extensions.md` describe this.

## Testing

- Against the real CLI (2.1.328, Haiku), on v2 and on v1 with
`clientCapabilities.subagents`: a typed skill, a typed skill that
launches a subagent, a Skill call, a cancel of the root, and a cancel of
the child.
- New unit tests for the v2 core, the v1 agent and the shared runtime,
built from the captured frames. They fail without the change.
- A new integration case (`v2-integration.test.ts`) runs a typed forked
skill against the real CLI. It fails without the `agent_id` routing.
- `npm run build`, `npm run check`, and the whole suite against the real
CLI (`RUN_INTEGRATION_TESTS=true`): 4440 passed, 9 skipped. An earlier
run had one failure, a temp-directory cleanup race (`ENOTEMPTY`) in
`acp-agent-settings.test.ts`, which passed on three reruns.
2026-11-20 11:49:33 +01:00
Ben Brandt
80440d8b82 fix: show readable titles for MCP tool calls (#1674)
ACP clients use the tool-call `title` for display. The adapter used to
copy the raw Claude tool name into that field, so users saw
`mcp__github__create_issue` on tool calls and permission requests.

Send `github: create_issue` as the `title` and keep
`mcp__github__create_issue` as the programmatic `name`. Both ACP v1 and
v2 use the same parser that supplies AIR's structured MCP metadata. It
preserves any `__` inside the tool portion and leaves incomplete MCP
names as they were.

**Verification:** `npm run build` and `npm run check` passed. The
targeted tool-call, permission, and ACP v1/v2 scenario suites passed
(1,586 tests passed, 11 skipped).
2026-11-19 21:13:57 +00:00
Ben Brandt
eb4c16f10a fix: keep built-in web-fetch and claude-code-guide agents out of the Agent picker (#1672)
Fixes #1670.

## Problem

The Agent picker is meant to show only when the user has custom agents.
It showed with none, listing `web-fetch` as if it were one.

`supportedAgents()` returns Claude Code's built-in subagents together
with the custom ones, and `AgentInfo` does not say which is which, so
the adapter filters the built-ins by name (`BUILTIN_AGENT_NAMES`).
Claude Code lists two built-ins that the set did not name:

- `web-fetch`: listed where Claude Code's staged rollout turns it on, or
with `CLAUDE_CODE_WEB_FETCH_AGENT=1`.
- `claude-code-guide`: listed where the adapter's environment already
sets `CLAUDE_CODE_ENTRYPOINT`. The SDK sets `sdk-ts` only when the
variable is unset, and Claude Code leaves the agent out for that value.

The roster integration test (`src/tests/agent-discovery.test.ts`) exists
to catch this drift. It did not, because neither agent is in the roster
of an account outside the rollout that runs the test from a plain shell.

## Change

- Add `web-fetch` and `claude-code-guide` to `BUILTIN_AGENT_NAMES`. This
covers v1 and v2: both build the picker from the same set.
- The roster test sets `CLAUDE_CODE_WEB_FETCH_AGENT=1` and its own
`CLAUDE_CODE_ENTRYPOINT`, so the roster it compares against no longer
depends on the account or on the shell.

## Why the list is still hard-coded

The issue asks to derive the built-ins from the SDK. The only SDK
surface that separates them is `getContextUsage().agents`, which lists
the agents that are not built in. Session setup deliberately does not
wait for `getContextUsage` (see `readContextWindow` and the "does not
wait for getContextUsage during session creation" tests), so the picker
cannot be built from it without putting that request back on the
`session/new` and `session/load` path. A built-in behind a future
rollout can therefore still leak until it is added to the set and to the
test.

## Testing

- With CLI 2.1.328 and `CLAUDE_CODE_WEB_FETCH_AGENT=1`,
`supportedAgents()` reports `web-fetch` with no custom agents
configured, as in the issue. With a preset `CLAUDE_CODE_ENTRYPOINT` it
reports `claude-code-guide`.
- Both the roster test and the `discoverCustomAgents` unit test fail on
the old set and pass with the new one.
- `npm run build`, `npm run check`, and the whole suite against the real
CLI (`RUN_INTEGRATION_TESTS=true`): 4406 passed, 9 skipped.
2026-11-19 16:22:29 +01:00
acp-release-bot[bot]
9f1ca6eb9c chore(main): release 0.109.0 (#1665)
🤖 I have created a release *beep* *boop*
---


##
[0.109.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.1...v0.109.0)
(2026-11-19)


### Features

* announce session cursors on v2 and fork at a cursor
([#1658](https://github.com/agentclientprotocol/claude-agent-acp/issues/1658))
([5075d2e](5075d2e0df))
* insert one message per idempotencyKey on v2 session/prompt
([#1657](https://github.com/agentclientprotocol/claude-agent-acp/issues/1657))
([1c0792e](1c0792ea8c))
* order config options as model, effort, fast, ultracode, mode, agent
([#1666](https://github.com/agentclientprotocol/claude-agent-acp/issues/1666))
([f31da7f](f31da7f9f5))
* report Fast mode in the speed config option category
([#1659](https://github.com/agentclientprotocol/claude-agent-acp/issues/1659))
([8990c24](8990c2441d))
* send the predicted next prompt as prompt_suggestions_update
([#1660](https://github.com/agentclientprotocol/claude-agent-acp/issues/1660))
([f20ed1d](f20ed1d96a))


### Bug Fixes

* send a session's settings to Claude Code over stdin
([#1669](https://github.com/agentclientprotocol/claude-agent-acp/issues/1669))
([a768a9f](a768a9f50c))
* update to @anthropic-ai/claude-agent-sdk 0.3.328
([#1668](https://github.com/agentclientprotocol/claude-agent-acp/issues/1668))
([6e30711](6e307116d4))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-19 14:31:59 +01:00
Ben Brandt
a768a9f50c fix: send a session's settings to Claude Code over stdin (#1669)
## Summary

The adapter now sends a session's `settings` to Claude Code over stdin,
in the SDK's initialize request, as it has done for MCP servers since
#1647. They went in the `--settings` flag before.

Builds on #1668, which updated the SDK to 0.3.328.

## What changes

`cliDelivery()` in `src/claude-cli.ts` replaces `mcpServersDelivery()`.
It returns the SDK options `mcpServersDelivery` and `settingsDelivery`
together, because one rule decides both:

- **The CLI that the adapter ships** gets MCP servers and settings over
stdin: `'initialize'`. Claude Code is then started with
`--await-initialize --initialize-fields=settings` and without
`--settings`.
- **A CLI that `CLAUDE_CODE_EXECUTABLE` names** gets both in flags as
before: `'argv'`. Its version is not known, and an older one fails the
session at startup. Checked with 2.1.323: "unknown option
'--initialize-fields=settings'".
- **Settings stay in the flag when the client's `extraArgs` hold
`settings` or `sdk-url`.** With `settings` there, Claude Code refuses to
start with both ("--initialize-fields=settings cannot be used with
--settings"), and in the flag the `settings` option replaces that
argument, as before. A session with `sdk-url` cannot read the initialize
request at launch, which is why the SDK sends its MCP servers in the
flag too.

Both cores set the two options before the client's options, so a
client's own `mcpServersDelivery` or `settingsDelivery` wins.

The settings in question are the ones the adapter passes as the SDK's
`settings` option: a client's `_meta.claudeCode.options.settings`, the
model configuration of the environment, and the route of a provider or
gateway. A `settings` value that is a file path stays in the flag: the
SDK only sends an object over stdin.

## `settingsDelivery` is not in the SDK's types

SDK 0.3.328 reads `settingsDelivery`, but `sdk.d.ts` does not declare it
and the changelog does not name it. The SDK version is pinned, and no
cast is needed: the options are spread into the query's options.

Nothing fails to compile if a later SDK drops the option. For that case
the v2 integration tests have a new test against the real CLI: it starts
a session with settings, and checks that Claude Code was started with
`--initialize-fields=settings` and that no command line holds the
settings' value.

## Delivery tests in `npm run test:integration`

Each core has a test that expects `'argv'` for the MCP servers and one
for the settings ("sends MCP servers as the CLI takes them", "sends
settings as the CLI takes them"). They now set `CLAUDE_CODE_EXECUTABLE`
themselves.

Before, they relied on the value that `vitest.config.ts` sets for unit
runs only. In `npm run test:integration` the variable is unset, the
adapter's own CLI gets `'initialize'`, and the tests failed. On `main`,
the MCP servers test fails in that run on both cores since #1647. This
PR fixes it.

## Checked against the real CLI

Through the built adapter, on v1 and on v2, without API usage:

| Session | Started with | Result |
| --- | --- | --- |
| A client's `settings` | `--await-initialize
--initialize-fields=settings` | the session starts |
| The same, with the client's `settingsDelivery: 'argv'` | `--settings`
| the session starts |
| A provider with a header (`providers/set`, a local stand-in gateway) |
`--await-initialize --initialize-fields=settings` | the session's model
request reaches the gateway, with the provider's header |

With the SDK alone:

- The settings land in the same layer as before (`flagSettings` in
`getSettings()`), and they survive `applyFlagSettings()` calls for
effort and Fast mode.
- Without a `settings` option, nothing changes in the launch flags.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,375 tests
pass)
- Real CLI: the whole suite, as `npm run test:integration` runs it (with
`CLAUDE_CODE_ENTRYPOINT` unset): 4,406 tests pass and 9 are skipped (the
live capability audits, the baseline recording, and one test that skips
itself). With `CLAUDE_CODE_EXECUTABLE` set, the new integration test is
skipped.
- Real CLI: the probes above
2026-11-19 14:28:44 +01:00
Ben Brandt
6e307116d4 fix: update to @anthropic-ai/claude-agent-sdk 0.3.328 (#1668)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.326 to 0.3.328, which
bundles Claude Code 2.1.328. The new version needs one adapter fix,
included here: a session's settings are released when the SDK refuses
the session's options.

Also bumps these dev dependencies: `@anthropic-ai/sdk` 1.9.0 → 1.10.0
and `vitest` 5.1.0 → 5.1.1.

`npm update` brings the in-range lockfile bumps: `express-rate-limit`
8.7.4 → 8.7.5, `jose` 6.2.17 → 6.2.18, `object-inspect` 1.13.4 → 1.14.0,
`standardwebhooks` 1.1.1 → 1.3.0, `source-map-js` 1.2.2 → 1.2.3 and
`tinybench` 6.2.3 → 6.2.4.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.73.0 still requires `typescript <6.1.0`.

## Options that the SDK refuses

SDK 0.3.327 has a breaking change: `query()` refuses options that it
cannot send to Claude Code, and it does so by throwing at once. Recorded
with the real SDK for `hooks: { PreToolUse: [{ matcher: "Bash" }] }`, a
matcher without `hooks`:

- 0.3.326: `query()` returns, and `initializationResult()` rejects with
"a.hooks is not iterable".
- 0.3.328: `query()` throws "The session was not started, because the
hooks option can't be sent to Claude Code: hooks.PreToolUse[0].hooks
must be an array of callbacks. Fix that value and try again."

Both cores disposed the settings of a session that fails to start (the
`SettingsManager` and its file watchers) only when
`initializationResult()` rejected. A `query()` that throws skipped that,
and v1 also left the session's input open. Both cores now release them
there too. On v1, `discardUnregisteredQuery` does it, and takes no query
for this case.

What changes for a client:

- The error for such options is still `-32603`, now with the SDK's
message in `data.details`. Checked through the built adapter on v1 and
v2. The adapter serves the next request as before.
- **The SDK is stricter.** `hooks` with an event that is no list of
matchers, such as `{ "SessionStart": { … } }`, started a session on
0.3.326. It is refused now ("hooks.SessionStart must be an array of
matchers"), for the events that the adapter adds no hooks of its own to.

## Changelog review

Read the SDK changelog for 0.3.327 and 0.3.328 and the Claude Code
changelog for 2.1.327 and 2.1.328. No other entry needs a code change:

- **Types.** Doc text and new optional members, plus one new
`SDKStartupFailureReason` (`initialize_fields_not_delivered`).
`startupFailureError` treats a reason it does not list as an internal
error with the CLI's message.
- **`task_started` has no `prompt` when Claude Code wakes a background
subagent with text of its own**, such as a task notification. Both cores
start a run without a prompt then (`promptText` in
`src/native-subagents.ts`, `startRun` in `src/v2/tasks.ts`), so the
child's session no longer gets that text as a prompt.
- **The error for usage credits that run out mid-response** no longer
names a rate limit. The adapter takes the failure kind from the SDK's
`error` field, not from the text.
- **More calls ask for permission:** `ExitWorktree` for a worktree that
may hold unsaved work, some paths and symbolic links, and a subagent
that a sibling's message resumed. They reach `canUseTool` as any other
request.
- **`agent` and `agents` fixes** (an inline definition wins over one of
the same name, `--agents` survive a plugin reload). Picked up as they
are: the adapter passes a client's `agents` on.
- **"Background agents still running" after an interrupt, and after a
permission request that waited 30 seconds.** Picked up as they are.
- **`CLAUDE_CODE_DISABLE_DEFERRED_TOOL_RESUME`** and
**`CLAUDE_CODE_DISABLE_SHELL_HEAD_START`.** The adapter sets neither, so
it keeps Claude Code's defaults.
- **`getSessionInfo` and `listSessions`** read a transcript as before: a
differential run of 0.3.326 against 0.3.328 over 4,500 generated
transcripts gave no mismatch. The run is not part of this PR.
- **`@anthropic-ai/sdk` 1.10.0.** The adapter uses its types only. The
release adds API error codes and fixes tool runners that the adapter
does not use.
- **`vitest` 5.1.1.** Bug fixes.

## Not in this PR

- A throw of the adapter's own between the settings read and `query()`
still skips the dispose. Example: a client's `hooks.PostToolUse` that is
an object, which the adapter's own merge of the hooks cannot spread.
- `-32602` for options that the SDK refuses. The code is `-32603`, as it
was for these requests before.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,369 tests
pass)
- Each core has a test with a `query()` that throws the SDK's refusal.
Both fail without the fix.
- Real CLI: the integration tests (`RUN_INTEGRATION_TESTS=true`, with
`CLAUDE_CODE_ENTRYPOINT` unset), 941 tests pass, and one that the test
file itself skips
- Real SDK and CLI, without a prompt: the two `hooks` cases above with
0.3.326 and 0.3.328, and through the built adapter on v1 and v2
2026-11-19 13:53:15 +01:00
Ben Brandt
f31da7f9f5 feat: order config options as model, effort, fast, ultracode, mode, agent (#1666)
## What

A session's config options now reach the client in a new order:

|        | Order                                       |
| ------ | ------------------------------------------- |
| Before | mode, model, effort, fast, ultracode, agent |
| After  | model, effort, fast, ultracode, mode, agent |

Options that do not apply to a session are still left out, and the rest
keep this relative order. The order is the same on ACP v1 and v2, and
for a subagent's (child) session, which was mode-first too and now sends
model, effort, mode, agent.

Clients that render config options in list order will show the model
picker first and the mode after ultracode.

## How

- The order is defined once, by option id, as `CONFIG_OPTION_ORDER` in
`src/session-config-options.ts`. `buildConfigOptions` (root sessions,
both cores) and the two senders of a child's options
(`NativeSubagentRuntime.publishConfiguration` on v1,
`ChildConfigurations.unsent` on v2) sort through the new
`orderedConfigOptions`.
- An option with an id the order does not name follows the named ones,
in the order it came.
- `orderedSubagentConfiguration` is removed. It ranked by `category`,
which the agent option does not have, and it did not rank `speed` (Fast
mode). It was not exported from `src/lib.ts`.
- `src/v1/acp-agent.ts` is unchanged: every other write to a session's
list replaces an option in place, by id.

## Tests

- New: the root order with all six options present, and the sorter with
ids the order does not name.
- Updated: `session/new` on v1; `session/new`, `session/resume` and
`session/set_config_option` on v2, including the list a model switch
rebuilds; the child session tests on the shared runtime, v1 and v2.
- 43 scenario golden files are regenerated. Five lines of the
`origin-main` baselines (plain and zed) are reordered in place, as #1533
did, instead of adding an allowed difference to `compare.ts`. Every
changed fixture line differs only in the order of `configOptions`.
2026-11-19 11:46:12 +01:00
Ben Brandt
f20ed1d96a 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.
2026-11-19 09:46:26 +01:00
Ben Brandt
8990c2441d feat: report Fast mode in the speed config option category (#1659)
The Fast mode config option now has the `speed` category, on v1 and v2.
It was `model_config`.

## Why

ACP has an unstable `speed` category for "an option that changes how
fast the model responds, such as a fast mode toggle" (the [speed config
category
RFD](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/docs/rfds/speed-config-category.mdx),
and the draft session config options pages of both versions).
`model_config` tells a client where to put an option, not what it does.
With `speed`, a client can treat this option like any other agent's fast
mode toggle.

A category needs no capability. A client that does not know `speed`
handles it as an unknown category.

## Changes

- `createFastModeConfigOption` in `src/session-fast-mode.ts` builds the
option for both versions, so one change covers both: `category:
"speed"`.
- The two-value select that a v1 client without boolean options gets now
lists Off before On. ACP asks for the values of a `speed` select from
slowest to fastest.

## For the reviewer

- A client that shows `model_config` options next to the model selector
and does not know `speed` will place Fast mode with its other options.
- A client that picks the select's value by position now gets Off first.
- Nothing in the adapter or in `docs/air-extensions.md` reads the
option's category. I did not check how AIR, Zed or Delta place it.

## Tests

- `fast-mode-config.test.ts` (v1): the category, and the order of the
select's values.
- `acp-v2.test.ts`: the category on v2.

`npm run build`, `npm run check` and `npm run test:run` pass (4338
tests).
2026-11-19 09:34:30 +01:00
Ben Brandt
5075d2e0df feat: announce session cursors on v2 and fork at a cursor (#1658)
Stacked on #1657: both change the same lines of `V2Session.start` and
the same README paragraph. Merge #1657 first. GitHub then points this PR
at `main`.

On v2, the adapter now announces a session cursor before each user
message, and `session/fork` forks at one. This is the validation step of
the [session cursors
RFD](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/docs/rfds/session-cursors.mdx)
for this adapter, with the position that its "Adapter validation" table
calls the one both runtimes share: before a user message.

## What a client sees

- **Live:** a prompt that follows another entry of the conversation gets
a `cursor_update` right after its `user_message`:

  ```json
  {
    "sessionUpdate": "cursor_update",
    "cursorId": "before:<messageId>",
    "capabilities": { "fork": {} },
"anchor": { "type": "user_message", "messageId": "<messageId>",
"position": "before" }
  }
  ```

- **Replay:** `session/resume` with `replayFrom` sends the same update
after each replayed user message, with the same `cursorId`.
- **Fork:** `session/fork` with a `cursorId` copies the history before
that message. A client can edit the message, or send it again, in the
new session.
- Any other `cursorId` fails with `-32602` before anything is copied.
#1655 refused every `cursorId`.

No cursor:

- The first entry of a history. Nothing is before it, and Claude Code
forks at an entry.
- A slash command, live. Claude Code stores a command as command
metadata or not at all, so a replay shows no user message for it.
- A subagent's session. A client cannot fork a child.
- A v1 client. See "Not covered".

## How

`src/session-cursors.ts` owns the rules, for both cores:

- `hasForkCursor` decides which stored user messages have a cursor. The
replay uses it to announce, and the fork uses it to accept, so a fork
accepts exactly the cursors that a replay announces.
- The `cursorId` is derived from the uuid of the user message, which
Claude Code stores. It is the same live, in every replay and after a
restart. The adapter keeps no cursors of its own.
- `forkSession` (`src/fork-session.ts`) reads the stored history as a
replay reads it, with the messages before each compaction, and passes
the uuid of the entry before the cursor's message to the SDK's
`forkSession` as `upToMessageId`.

Live, `V2Session.inserted` announces the cursor with the prompt's
`user_message`. A fork finds it once Claude Code has stored the message.

## Not covered

- **v1.** The RFD's v1 form needs message IDs on every anchored message
and anchors a live prompt `after` the entity before it. That is the
RFD's open question, and it needs its own change in the v1 core. A fork
takes a `cursorId` on v1 too, but a v1 client is told of none.
- **Other positions.** The RFD's table also lists after a tool call's
result and after an agent message that ends a turn. The position before
the next user message covers every turn boundary but the last, and
forking the whole session covers that one.
- **A prompt folded into a running turn.** Its cursor's fork ends at a
tool result. I checked a fork at a turn boundary against the real CLI,
not this case.
- A cursor is never withdrawn: it works for as long as the transcript
holds its message.
- AIR's `_meta.jetbrains.air.fork` point is unchanged. A `cursorId` wins
when a request has both.

## Tests

- `fork-session.test.ts` (real SDK, temporary transcripts): a fork at a
cursor copies the history before its message. An unknown id, the first
entry's and a non-user entry's are rejected, and nothing is copied.
- `v2.test.ts`: the live cursor follows the second prompt's
`user_message`, with none for the first prompt or a slash command. A
replay sends the cursor after its message's chunks. `session/fork`
passes `upToMessageId`, and rejects a cursor that the history does not
have.
- `acp-v2.test.ts`: a replayed subagent session gets no cursor.
- The `task-create-update` golden file gains the cursor of its second
prompt.
- `v2-integration.test.ts` (real CLI, run locally): two prompts, a fork
at the second one's cursor, and the fork's replay shows only the first.

`npm run build`, `npm run check` and `npm run test:run` pass (4351
tests).
2026-11-19 09:32:43 +01:00
Ben Brandt
1c0792ea8c feat: insert one message per idempotencyKey on v2 session/prompt (#1657)
On v2, a `session/prompt` with an `idempotencyKey` now inserts at most
one user message for that key. This is the follow-up that #1655 left
open.

## Why

ACP v2 (schema v2.0.0-alpha.17) added an optional `idempotencyKey` to
`session/prompt`. Every Agent that advertises `capabilities.session`
must support it: a Client that lost a prompt's response sends the prompt
again with the same key, and the Agent answers with the first
`messageId` without inserting a second message.

The adapter accepted the field and ignored it, so a retry was inserted
again and started its work again.

## What a client sees

| The key in this session | Response |
| --- | --- |
| Not seen | The prompt is handled as before. Its `messageId` is
recorded with the key. |
| A prompt with the key is not answered yet | The same outcome as that
prompt, when it is answered. Nothing more goes to Claude Code. |
| A message was inserted with the key | That message's `messageId`. No
update, no new work. |
| A prompt with the key failed, for example with `-32800` after
`session/cancel` | The key is unused. The prompt is handled as a new
one. |

- A key is known for as long as Claude Code stores its message, also
after `session/close`, on a new connection, and after the adapter
restarts.
- A message that Claude Code does not store, such as a local command's,
keeps its key while the session is active on the connection: from its
start to `session/close`, across restarts of the session's query.
- The same key in another session, a fork too, names another prompt.
- Prompts of one key are not compared. A different prompt with a
recorded key is answered as a retry, which the protocol allows.
- The ACP SDK rejects a key that is not a string of 1 to 255 characters
with `-32602` before the adapter sees it.

## How

The protocol suggests storing the key as part of the message's id, and
Claude Code makes that possible: a prompt that the adapter pushes with a
uuid is stored under that uuid.

`src/v2/prompt-keys.ts` owns the keys of one session:

- A keyed prompt gets a version 8 (custom) UUID. Its first 32 characters
are a SHA-256 hash of the session id and the key. Its last 4 hex digits
count the attempts.
- The `messageId` is that uuid, so no update, `session/list` result or
replay shows the key.
- After a resume, the first keyed prompt reads the stored history once
(`getSessionMessages`, with the messages before each compaction, as a
replay reads it) and looks for a user message with the key's prefix. A
session that this connection created needs no read.
- When that read fails, the key counts as unused and the next lookup
reads again. The session stays usable.

`V2Session.prompt` calls `PromptKeys.once`, which returns the pending
attempt's promise, the stored `messageId`, or runs the prompt. The
promise is returned as it is, so the response keeps its order relative
to the turn's `running`.

`V2Agent` keeps one record per session, so a restart of the session's
query (a provider change, new additional directories) keeps the keys.

### Why each attempt has its own uuid

Claude Code ignores a prompt whose uuid it has seen: it echoes it and
starts no turn. A prompt that `session/cancel` answered with `-32800`
may already have reached Claude Code. If the next attempt reused the
uuid, Claude Code could drop it, and the adapter's own record of prompts
that a cancel stopped would take the new attempt for the old one. So an
attempt after a failure gets the next number, and the lookup matches on
the prefix.

## Checked against the real CLI

Bundled Claude Code of `@anthropic-ai/claude-agent-sdk` 0.3.326:

- A pushed version 8 uuid is accepted, echoed, and returned by
`getSessionMessages` as the user message's uuid.
- The same holds for a prompt that waited in Claude Code's queue, and
for one that it folded into a running turn. The raw transcript stores a
folded prompt as a `queued_command` attachment, and `getSessionMessages`
still returns it under the pushed uuid.
- A second push of a uuid gets an echo and an `idle`, with no
`command_lifecycle` frame and no result.

## Not covered

- `$/cancel_request` for a held prompt is still not honored, with or
without a key. The protocol makes it optional.
- A `session/cancel` that arrives while a retry's history lookup runs
answers the retry with `-32800`, also when the message is stored. The
client's next retry gets the `messageId`.
- If Claude Code took in a prompt that a cancel had already answered
with `-32800`, a retry is inserted as a new message. That is today's
behavior for any cancelled prompt.
- v1 has no `idempotencyKey`.

## Tests

- `v2.test.ts`: a retry of an inserted prompt, of a pending one, and
after a failure (with a new uuid). The same key in another session. The
record across a restart of the query. After a close and a resume, a key
that the stored history holds and one that it does not.
- `v2-integration.test.ts` (real CLI, run locally): one message for a
key, and the key is known after `session/close` and `session/resume`.

`npm run build`, `npm run check` and `npm run test:run` pass (4344
tests).
2026-11-19 09:32:43 +01:00
acp-release-bot[bot]
e62d084e9d chore(main): release 0.108.1 (#1650)
🤖 I have created a release *beep* *boop*
---


##
[0.108.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.0...v0.108.1)
(2026-11-18)


### Bug Fixes

* answer -32602 on v1 for a request that names a subagent's session
([#1656](https://github.com/agentclientprotocol/claude-agent-acp/issues/1656))
([253cd84](253cd84ed8))
* close a server tool call whose reply Claude Code gave up on, once its
next reply starts
([#1604](https://github.com/agentclientprotocol/claude-agent-acp/issues/1604))
([3205f0b](3205f0bf02))
* end a v1 turn at its result for a client in the subagents RFD form
([#1603](https://github.com/agentclientprotocol/claude-agent-acp/issues/1603))
([c4b64f6](c4b64f628d))
* reject session setup for an incompatible model provider
([#1506](https://github.com/agentclientprotocol/claude-agent-acp/issues/1506))
([90070d6](90070d6cbf))
* start a session without an MCP-over-ACP server whose local endpoint
cannot open
([#1653](https://github.com/agentclientprotocol/claude-agent-acp/issues/1653))
([96dd2bb](96dd2bb10d)),
closes
[#1651](https://github.com/agentclientprotocol/claude-agent-acp/issues/1651)
* update to @agentclientprotocol/sdk 2.8.0
([#1655](https://github.com/agentclientprotocol/claude-agent-acp/issues/1655))
([b6167a8](b6167a82db))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-18 18:14:55 +01:00
Ben Brandt
253cd84ed8 fix: answer -32602 on v1 for a request that names a subagent's session (#1656)
On v1, a client's request that names a subagent's child session now
fails with `-32602` (Invalid params), as it already does on v2.

## Why

The subagents RFD changed on 2026-11-17: an Agent SHOULD reject a
client's request that is not permitted for a child session with
`-32602`, in both protocol versions. `session/close` and
`session/delete` are included, and do not report success for a child. A
child that the Agent announced is not an unknown session.
`session/cancel` is the one message that can name a child.

The v1 core treated a child's id as an unknown session:

| Request | Before | Now |
| --- | --- | --- |
| `session/prompt`, `session/load`, `session/resume`, `session/fork`,
`session/set_mode`, `session/set_config_option` | `-32002` | `-32602` |
| `session/close`, `session/delete` | success | `-32602` |
| `session/set_title`, `session/status`, `session/options` | handled as
a session without a transcript | `-32602` |

`session/cancel` of a child still stops the child.

## How

- `NativeSubagentRuntime.hasChild` tells whether a session id is a child
that the runtime announced in the RFD form. `cancelChild` now uses the
same lookup. AIR's earlier draft of the RFD keeps its own rules, so the
check is false there.
- `ClaudeAcpAgent.assertNoChildSession` asks the runtime of each session
of the connection.
- `v1AgentApp` wraps each request that names a session in
`ofRootSession`, so all of them get the same check before their handler
runs. The wrapper is not `async`. It returns the handler's promise as it
is, so a setup response keeps its place before the timer of
`afterSetupResponse`.
- `restrictedChild`, the error that the v2 core already threw, moves
from `src/v2/tasks.ts` to `src/acp-subagents.ts`, which both cores
share.

## Not covered

- A child that only a `session/load` replay announced, and whose agent
did not run again on this connection, is still an unknown session
(`-32002`). The check covers the children of a running session. The v2
core has the same limit.
- The adapter's own extension requests (steer, async task stop, goal)
are unchanged.

## Tests

- `acp-agent.test.ts`: each of the eleven requests, sent through the
protocol router with a child's id, fails with `-32602` and names the
child in `data.sessionId`.
- `native-subagents.test.ts`: `hasChild` is true for an announced child,
and false for the root, for an unknown id and in AIR's draft.

`npm run build`, `npm run check` and `npm run test:run` pass (4335
tests). This branch and #1655 merge without conflicts.
2026-11-18 16:47:24 +01:00
Ben Brandt
b6167a82db fix: update to @agentclientprotocol/sdk 2.8.0 (#1655)
Updates `@agentclientprotocol/sdk` from 2.7.0 to 2.8.0 (schema v1.33.0
and v2.0.0-alpha.17), and follows the protocol rules that changed for
what the adapter already serves.

The adapter compiles and passes against 2.8.0 unchanged. The behavior
rules are in the protocol docs, so I read the protocol repo from
`schema-v2.0.0-alpha.16` to its current `main`, which is four docs
commits past the alpha.17 tag.

## Changes

### `session/fork` refuses a `cursorId` (v1 and v2)

`ForkSessionRequest` gained `cursorId` with the session cursors RFD. An
Agent must reject a cursor it did not issue with `-32602`, and must not
fork the whole session in its place.

The adapter sends no `cursor_update`, so it issued no cursor. Before
this change it ignored the field and copied the whole session.
`forkSession` in `src/fork-session.ts` now fails with `-32602` before it
copies anything. Both cores call it.

### No `pattern` in a v2 elicitation form

v2 removed `pattern` from string properties. v1 still has it. The
adapter builds its own forms without it, but it relays an MCP server's
schema as the server sent it.

`v2ElicitationRequest` in `src/v2/elicitation.ts` drops `pattern` from
the string properties of a form before it goes to a v2 client. Nothing
else in the schema changes. The MCP server still gets the answer as the
client sent it and checks it against its own schema.

### A replayed child's current state comes before the response (v2)

On a `session/resume` with replay, the adapter replays each subagent's
end on its parent, then sends the child's current state once more as
current.

- Until alpha.16, the response separated a replayed child state from a
current one. The adapter sent the current states from a timer after the
response, because the ACP SDK has no after-response hook.
- In alpha.17, a `subagent_update` is an update of the child's parent,
so the parent's `replay_complete` is the boundary. A `state_update` on
the child's own stream is never replayed.

The current states now go out after the root's `replay_complete` and
before the state snapshot and the response:

- `SubagentReplay.finish` sends each child's replayed end on its parent,
then the child's `replay_complete`. It no longer sends a `state_update`
on the child's stream.
- `SubagentReplay.currentStates` (was `afterResponse`) then sends each
child's current state on its parent and on its own stream, with `cwd:
null` for a directory that is gone, and the child's configuration when
it differs from what the replay sent.
- The timer is gone from the v2 core. The v1 core keeps
`afterSetupResponse`: on v1 the response is still the boundary.

One case changes besides the order. A child that the live session still
tracks and whose work has ended used to get no current state on its
parent after a replay. It now gets its replayed end there, as a child
whose process is gone does. A child that works now still gets its state
from the resume snapshot.

A v2 client that still reads a child state before the response as
history shows such a child without a confirmed state until it follows
alpha.17.

### Docs

- The README says that `session/prompt` does not use `idempotencyKey`
yet, and that `session/fork` refuses a `cursorId`.
- `docs/subagent-sessions.md` describes the v2 order.

## Already compliant, checked

- `$/cancel_request` for every permission request and elicitation that a
cancel withdraws, now a MUST, and for a closed session's descendants.
- Tool call status: no update moves a live tool call back to `pending`,
and a final status does not change. The `status: null` of
`v2RestartedToolCall` only resets a tool call that a replay or a
repeated `tool_call` starts again.
- A v2 diff always carries one change.
- A `systemPrompt` the adapter cannot apply fails with `-32602` and
creates no session.
- Replay sends terminal output, session messages and compaction
summaries whole, so the wider "clear before replaying chunks" rule adds
nothing. Message chunks were already cleared.
- `tool_call/cancel` and `terminal/cancel`: `-32002` for an unknown
session, `-32602` for an item that cannot be cancelled, and a child
session's id is accepted.
- A request that names a child session fails with `-32602` on v2.
- Only the root session reports a cost, and Claude Code's total includes
its subagents.
- A child's `model` option offers only its current value.
- SDK 2.8.0 dispatches a notification that arrived before the peer
closed its stream. A late `session/cancel` finds the session closed and
does nothing.

## Not covered

- `idempotencyKey` on v2 `session/prompt`. It is part of the v2 baseline
since alpha.17. The adapter accepts the field and does not use it, so a
retry with the same key inserts the message again. The SDK rejects a
malformed key with `-32602`. A follow-up PR adds the lookup.
- Session cursors (`cursor_update`, forking at a cursor) are a new draft
RFD.
- The plan operations RFD now says an Agent can send an empty `items`
plan before `plan_removed`, for a v2 client without plan operations. I
left it out: a client that shows plan updates in its transcript would
show an empty plan.
- I did not run the integration tests against the real CLI.

## Tests

- `fork-session.test.ts`: a `cursorId` fails with `-32602` and no
transcript is copied.
- `v2.test.ts`: `v2ElicitationRequest` drops `pattern` from string
properties only, and passes a URL request as it is.
- `acp-v2.test.ts`: the three replay tests now expect the child's
current state, its parent's copy and a live child's configuration before
the response, and the parent's copy after the root's `replay_complete`.

`npm run build`, `npm run check` and `npm run test:run` pass (4327
tests).
2026-11-18 16:46:44 +01:00
Hussain Hammad
c4b64f628d fix: end a v1 turn at its result for a client in the subagents RFD form (#1603)
Fixes #1527.

A v1 client that declares `clientCapabilities.subagents` and is not AIR
gets the RFD form of subagent sessions, but still got the prompt hold of
#864/#866: `session/prompt` stayed open until the turn's background
subagents ended. The RFD has the client keep receiving child events
after the parent's prompt response, so the reason for the hold doesn't
apply to it.

`endsTurnsWithLiveSubagents` now also returns true for
`subagentForm(...) === "rfd"`. The rest is the existing no-hold path
that AIR's `backgroundSubagents` uses: the turn ends at its result, and
the subagent's updates and requests go out after the response, with the
same routing. A client that declares neither keeps the hold.

What else changes for an RFD client: the parent's summary when a child
ends used to arrive inside the held turn. It now comes from a followup
cycle out of a turn. Its result ends no turn, and a plan approval that
cycle asks for has no clear-context option, as for AIR.

Tests: the no-hold blocks of "deferred settlement for live background
subagents" run for both clients, except the streamed-tool-input test,
whose fixture has no Agent call that the RFD form could expose the child
from. The RFD test of a background child's tool call closing after a
cancel expects `end_turn` at the result and the cancel while no prompt
runs. `docs/subagent-sessions.md` and `docs/air-extensions.md` say which
clients get the hold.

---------

Co-authored-by: Andrey Bragin <andrey.bragin@jetbrains.com>
2026-11-18 15:01:48 +00:00
Ben Brandt
96dd2bb10d fix: start a session without an MCP-over-ACP server whose local endpoint cannot open (#1653)
## Summary

An MCP server that the client declares with `"type": "acp"` can no
longer fail session setup. The session starts without the server and the
user gets the usual "failed to start" warning.

This comes out of #1651. It does not make the server of that issue
connect (see "Not fixed here").

## What was failing

The adapter serves an `acp` server to Claude Code through a listener on
`127.0.0.1` (`McpOverAcp`, #1645). When that listener could not open,
for example `listen EPERM` where the process may not open a socket,
`session/new` failed with `-32603`:

> Could not open the local endpoint that serves MCP server tools to
Claude Code: listen EPERM: operation not permitted 127.0.0.1. Start the
session without the server, or try again.

A session starts without any other MCP server that does not connect (a
stdio command that is missing, an HTTP server that is down). The `acp`
case was the only one that ended setup.

## What changes

- **`sdkMcpServers`** (`src/mcp-servers.ts`) returns `{ configs,
unserved }`. An `acp` server that gets no endpoint is in `unserved` with
the error, and the other servers keep their configs.
- **Both cores report it** through the existing notice of a client
server that did not start (`mcpServerStartupNotice`), once per server,
on the first turn. On v1 that is `reportMcpServerStartupFailures`, on v2
`SessionReports.mcpStartupFailures`. A resume of the active session on
v2 (`setMcpServers`) reports it the same way.
- **The notice has the error.** Claude Code was never given the server,
so `/mcp` does not list it and "Run /mcp for the error" would lead
nowhere:

> **MCP server "tools" failed to start:** Its tools are unavailable in
this session. The adapter could not open the local endpoint that serves
it to Claude Code (listen EPERM: operation not permitted 127.0.0.1). A
new session tries again.

- The adapter also logs the server and the error at setup.

A later session, or a restart of the session's query, tries to open the
listener again.

## Not fixed here

In #1651 the server is listed as failed because Claude Code sends
`initialize` first and the endpoint accepts MCP 2026-07-28 requests
only. That is unchanged.

Setup did not fail in that case before this PR either. Checked through
the built adapter with Claude Code 2.1.326, without a model turn:

| Case | `session/new` | The server |
| --- | --- | --- |
| Claude Code as it starts by default | succeeds | connects
(`server/discover`, then `tools/list`) |
| `MCP_PROTOCOL_NEGOTIATION=legacy` (Claude Code sends `initialize`) |
succeeds | failed, with the warning |
| The client rejects `server/discover` | succeeds | failed, with the
warning |
| The client never answers `mcp/message` | succeeds | not connected |
| The listener cannot open, before this PR | fails with `-32603` | |
| The listener cannot open, with this PR | succeeds | left out, with the
warning above |

For the last two rows the adapter ran with a preload that makes
`http.Server.prototype.listen` fail.

## Testing

- `npm run check`, `npm run build`, `npm run test:run` (4,314 tests
pass)
- New tests: `sdkMcpServers` with an endpoint that rejects,
`session/new` on v1, the notice on v1, and on v2 both `session/new` and
a resume of the active session
- The live cases in the table above

Refs #1651
2026-11-18 14:08:22 +01:00
Erdős Péter
3205f0bf02 fix: close a server tool call whose reply Claude Code gave up on, once its next reply starts (#1604)
## Problem

Claude Code gives up on a reply that stays silent past its stream idle
timeout (5 minutes off Anthropic's API, for example on Bedrock or behind
a gateway), then asks again. If that reply had made a server tool call,
such as the advisor's, the call never gets a result:

- **v1:** the tool call stayed open until the turn ended. Because the
complete assistant message had dispatched it, the turn then failed with
`incomplete_tool_call`, even though Claude Code went on and finished the
work.
- **v2:** the tool call stayed open after the next reply started, and
ended `cancelled` only at the idle.

## Change

- `UnansweredServerToolCalls` (`src/tool-calls/server-tool-calls.ts`)
finds the server tool calls that will never get a result. It tracks each
conversation on its own: the main one, and each subagent's.
- The API puts a server tool's result in Claude's reply: right after the
call or, if the reply ended first (after a client `tool_use`, or at
`pause_turn`), at the start of the next reply. So once a later reply
starts with any other block, the calls still waiting will get no result,
and they close as `retracted`, as the calls of a message Claude Code
took back do: Claude Code replaced the response that made them, and they
may have run. They end `failed` on v1 and `cancelled` on v2.
- Both cores call it from the same two places:
- **Streamed block:** the calls close after that block's own updates, so
a client sees the next step start first.
- **Consolidated message:** matched by its message id, which covers a
retry that did not stream (Claude Code's non-streaming fallback). The
calls close before the message renders.
- On v1 the close carries `_meta.claudeCode.parentToolUseId` for a
subagent's call, as the call's other updates do.
- A server tool call that the turn's last reply leaves without a result
still fails a v1 turn, as before.

## Tests

- `server-tool-calls.test.ts`: unit tests for
`UnansweredServerToolCalls`.
- `v1/incomplete-tools.test.ts`:
- A cut-off advisor call closes once the next reply starts, and the turn
ends with `end_turn`. The close comes after the next reply's tool call
reaches the client and before its text.
- A cut-off advisor call closes when the retry does not stream, by the
consolidated message's id.
  - A subagent's cut-off advisor call closes with its `parentToolUseId`.
- A call left pending is answered at the start of the next reply and is
not closed.
- `v2/acp-v2.test.ts`: a cut-off advisor call ends `cancelled` before
the next reply's text, for a retry that streams and one that does not.
- I disabled each change in turn (the consolidated path, the parent
stamp, the close after the block's updates, and each v2 call site), and
its test failed every time.
- `npm run test:run`: 4206 passed. `npm run build` and `npm run check`
are clean.
2026-11-17 22:12:53 +01:00
Slapoguzov Alexander
90070d6cbf fix: reject session setup for an incompatible model provider (#1506)
When a `providers/set` gateway lists none of the allowed models Claude
Code reports, session setup fails with an actionable standard ACP error
before any prompt reaches the provider. The shared
`narrowToGatewayModels` function now owns this check for both ACP
versions. Empty catalogs, model rows without a resolved identity, and
providers without model discovery retain their existing behavior.

Open sessions also fail if they cannot restart under the new provider:
v1 drops the session and reports a session failure to clients with the
AIR capability; v2 preserves the error code and data and tells the
client to fix the cause and then resume the session. Setting a
compatible provider alone does not revive a stopped v2 session. Other
standard restart errors, including authentication failures, also keep
their details and the resume instruction; unknown restart failures
retain the generic recovery message.

Validation: 671 focused tests passed (3 skipped), TypeScript build and
lint/format checks passed. Independent review accepted the exact commit
and separately passed all 206 directly affected tests. The restart
regression fails on the unchanged production code and passes with the
fix. Tests cover a prompt after restoring a compatible provider but
before resuming, preservation of authentication-error code/data,
incompatible listings and cleanup in both protocols, and empty,
alias-only, and mixed model catalogs. These checks use a fake SDK and
gateway with an isolated Claude config directory; the full suite,
installed Air, and a live provider were not exercised in this revision.

---------

Co-authored-by: Codex <codex@openai.com>
2026-11-17 21:54:08 +01:00
acp-release-bot[bot]
a6ba98ff3c chore(main): release 0.108.0 (#1642)
🤖 I have created a release *beep* *boop*
---


##
[0.108.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.3...v0.108.0)
(2026-11-17)


### Features

* stream the output of foreground Bash commands
([#1587](https://github.com/agentclientprotocol/claude-agent-acp/issues/1587))
([378e85d](378e85d060))
* support MCP servers that the client serves over the ACP connection
(MCP-over-ACP)
([#1645](https://github.com/agentclientprotocol/claude-agent-acp/issues/1645))
([20aeb46](20aeb46ece))


### Bug Fixes

* an autonomous result naming the original prompt must not end a steered
turn early
([#1451](https://github.com/agentclientprotocol/claude-agent-acp/issues/1451))
([edab713](edab713502))
* do not count a confirmWithUser question as an unfinished tool call
([#1644](https://github.com/agentclientprotocol/claude-agent-acp/issues/1644))
([bcd3cda](bcd3cdad35))
* handle invalid file paths in tool reports
([#1419](https://github.com/agentclientprotocol/claude-agent-acp/issues/1419))
([0073280](0073280b97))
* keep a workflow agent's tool call out of the turn's unfinished tools
([#1638](https://github.com/agentclientprotocol/claude-agent-acp/issues/1638))
([451bc04](451bc04ae0))
* offer clearing the context on plan approval only when Claude Code's
setting is on
([#1627](https://github.com/agentclientprotocol/claude-agent-acp/issues/1627))
([9d71d12](9d71d12336))
* send MCP servers to Claude Code over stdin, not on its command line
([#1647](https://github.com/agentclientprotocol/claude-agent-acp/issues/1647))
([c4dd80d](c4dd80d739))
* update to @anthropic-ai/claude-agent-sdk 0.3.326
([#1646](https://github.com/agentclientprotocol/claude-agent-acp/issues/1646))
([4a07639](4a076397c6))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-17 13:37:02 +00:00
Ben Brandt
c4dd80d739 fix: send MCP servers to Claude Code over stdin, not on its command line (#1647)
## Summary

The adapter now sends a session's MCP servers to Claude Code over stdin,
not on its command line. A server's `env` and `headers` were readable
there by other users of the machine (`ps`). That includes the bearer
token of the local endpoint that serves an MCP-over-ACP server (#1645).

This uses the `mcpServersDelivery` option of SDK 0.3.326. It is stacked
on #1646, which updates the SDK and sets the option to `'argv'`. Merge
#1646 first.

## What changes

`mcpServersDelivery()` in `src/claude-cli.ts` picks the delivery, next
to `claudeCliPath()`, because it depends on which CLI is started:

- **The CLI that the adapter ships** (next to the executable, or the
SDK's platform package) gets the servers in the SDK's initialize
request: `'initialize'`. The SDK starts it with `--await-initialize` and
without `--mcp-config`.
- **A CLI that `CLAUDE_CODE_EXECUTABLE` names** gets them in the
`--mcp-config` flag as before: `'argv'`. Its version is not known, and
the SDK ends the session at startup when the CLI cannot read the servers
from the initialize request. For such a CLI nothing changes, and the
README says so.

Both cores set the value before the client's options, so a client's
`_meta.claudeCode.options.mcpServersDelivery` still wins. A session
without MCP servers starts as before: the SDK adds `--await-initialize`
only when it has servers to send.

## Why `CLAUDE_CODE_EXECUTABLE` keeps `'argv'` for now

Reading the servers from the initialize request needs Claude Code
2.1.326, which came out on 2026-11-16. The `stable` channel of Claude
Code is at 2.1.311. With `'initialize'` for every CLI, a session with an
MCP server would fail for each user whose `CLAUDE_CODE_EXECUTABLE` CLI
is older. Checked with 2.1.323 through the adapter: `session/new` fails
with `-32603` and "This Claude Code (version 2.1.323) is too old to read
MCP servers from the initialize request".

The plan is to drop the `'argv'` case once the `stable` channel is at
2.1.326 or newer, with an error that names `CLAUDE_CODE_EXECUTABLE`.

## Checked against the real CLI

Through the built adapter, with a stdio server that has a secret in its
`env` and an HTTP server with a secret `Authorization` header, and
without a prompt:

| | The adapter's CLI | `CLAUDE_CODE_EXECUTABLE` |
| --- | --- | --- |
| Launch flag | `--await-initialize` | `--mcp-config` |
| Secret on a command line (`ps`) | no | yes, as before |
| stdio server connects and gets its `env` | yes | yes |

This holds on v1 (a probe that is not part of this PR) and on v2. On v2
the MCP-over-ACP integration test now also checks that no command line
of the adapter's processes holds the endpoint's bearer token. With
`CLAUDE_CODE_EXECUTABLE` set, that check finds the token, so the test
skips it there.

With the SDK alone, under `'initialize'`:

- A resumed session (`--resume`) gets its servers: `mcp_servers_applied`
is true and the server connects.
- A startup failure still rejects with its reason: an invalid
`HTTPS_PROXY` gives `startupFailureReason: "proxy_invalid"` and the same
message as under `'argv'`.

## Notes for review

- **One difference that the SDK documents:** a Claude Code process that
the session's own process starts is not handed servers that came in the
initialize request. Subagents run in the session's process and are not
affected.
- **Unit runs take the `'argv'` case.** `vitest.config.ts` sets
`CLAUDE_CODE_EXECUTABLE` for them. So the session tests of v1 and v2
show that the value is passed and that the client's option wins.
`src/tests/claude-cli.test.ts` covers the rule, and the integration test
covers `'initialize'` end to end.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,285 tests
pass)
- Real CLI: the integration tests (`RUN_INTEGRATION_TESTS=true`, with
`CLAUDE_CODE_ENTRYPOINT` unset), 916 tests pass
- Real CLI: the probes above. One of them sends a prompt (one short
Haiku turn, to make a session to resume).

Of 6 full unit runs, 4 passed and 2 had one failure each. The one I
captured is "reads only the changed transcript for a subscription" in
`src/tests/v1/session-index.test.ts`, which passed in 12 runs alone. It
counts the transcripts that the session index reads after a file watcher
event (3 where it expects at most 1). This PR does not touch that code.
Not changed here. The other failure was not captured.
2026-11-17 13:33:52 +00:00
Ben Brandt
4a076397c6 fix: update to @anthropic-ai/claude-agent-sdk 0.3.326 (#1646)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.325 to 0.3.326, which
bundles Claude Code 2.1.326. The new version needs one adapter change,
included here: the adapter now sets the SDK's new `mcpServersDelivery`
option. Its value keeps today's behavior. A follow-up PR changes the
value, so that MCP servers no longer reach Claude Code on its command
line.

Also bumps these dev dependencies: `@anthropic-ai/sdk` 1.8.0 → 1.9.0,
and `@typescript-eslint/eslint-plugin` and `@typescript-eslint/parser`
8.72.2 → 8.73.0.

`npm update` brings the in-range lockfile bumps: `hono` 4.13.18 →
4.13.19, `@hono/node-server` 2.1.8 → 2.1.9, `router` 2.2.0 → 2.3.0,
`ignore` 7.0.14 → 7.0.16 and `@tybys/wasm-util` 0.10.4 → 0.10.5.
typescript-eslint 8.73.0 depends on `minimatch` 11, so the lockfile now
holds one `minimatch`, 11.0.9, in place of 10.2.6 and two nested copies
of 11.0.8. That clears the advisory GHSA-g3hv-75wg-m249: `npm audit`
finds nothing.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.73.0 still requires `typescript <6.1.0`.

## `mcpServersDelivery`

SDK 0.3.326 adds the option `mcpServersDelivery`, which says how a
session's MCP servers reach Claude Code:

- `'argv'`, the default: in one `--mcp-config` flag. A server's `env`
and `headers` are then on Claude Code's command line.
- `'initialize'`: over stdin, in the initialize request.

Without a change, the new SDK breaks the adapter in two ways:

- The build fails. `OPTION_REBUILDS_SESSION` in
`src/v1/session-fingerprint.ts` must classify every SDK option. The new
one is read when the process starts, so a changed value rebuilds the
query.
- The SDK prints a `DeprecationWarning`
(`CLAUDE_SDK_MCP_SERVERS_ARGV_DEPRECATED`) on stderr, once per process,
when an app names the Claude Code to start, a session has MCP servers
and the option is unset. The adapter always passes
`pathToClaudeCodeExecutable`, so every adapter process with an MCP
server would print it.

The adapter now sets `'argv'`, so MCP servers reach Claude Code as they
did before. The value is one constant, `MCP_SERVERS_DELIVERY` in
`src/claude-cli.ts`, which both cores set before the client's options: a
client's `_meta.claudeCode.options.mcpServersDelivery` wins.

## Changelog review

Read the SDK changelog for 0.3.326 and the Claude Code changelog for
2.1.326. No other entry needs a code change:

- **Types.** Besides `mcpServersDelivery`: doc text, new optional
members, and `BUILTIN_TOOL_NAMES` lists `SetGoal` in place of
`ProposeGoal`. The adapter names neither tool.
- **A warning for a tool list entry that does not look like a complete
rule**, on stderr and as a `system/informational` message. The adapter
adds only `AskUserQuestion` to `disallowedTools` and passes the
`claude_code` preset or `[]` as `tools`, so only a client's own list can
cause it. Both cores send an `informational` warning to the client as a
notice.
- **The `managed_mcp_arrived` warning** is an `informational` warning
too, and is sent the same way.
- **Some tool calls now ask in bypass permissions mode.** Such a call
reaches `canUseTool`. Neither core allows a call there because of the
session's mode, so the user is asked.
- **Bash permission checks ask before more commands.** These reach
`canUseTool` as any other request.
- **`modelUsage` and `total_cost_usd` count billed permission classifier
calls and calls that were stopped or cut.** Both cores take the row of
the turn's model and the increment over the last reading, so a new row
or a larger total needs no change.
- **`message_uuid` on `cancel_async_message` responses.**
`Query.cancelAsyncMessage()` still returns only `cancelled`, and the
adapter does not read the response.
- **`rewindFiles()` skips some files when the sandbox is on.** The
adapter only calls it with `dryRun: true`, for the file-change report.
- **`setMcpServers()`, `resumeSessionAt` and startup hook fixes.**
Picked up as they are: the adapter has no workaround for the old
behavior.
- **`getSessionInfo` and `listSessions`** read a transcript as before: a
differential run of 0.3.325 against 0.3.326 over 4,500 generated
transcripts gave no mismatch. The run is not part of this PR.
- **`@anthropic-ai/sdk` 1.9.0.** The adapter uses its types only. The
release changes API resources and tool helpers that the adapter does not
use.
- **typescript-eslint 8.73.0.** One new rule, which the config does not
turn on, and a narrower report location for `consistent-type-imports`.
`npm run lint` reports nothing.

## Not in this PR

- `mcpServersDelivery: 'initialize'`, which keeps a server's `env` and
`headers` off Claude Code's command line. It changes how a session with
MCP servers starts, and a Claude Code older than 2.1.326 cannot take it,
so it is its own PR, on top of this one.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,283 tests
pass)
- Real CLI: the integration tests (`RUN_INTEGRATION_TESTS=true`, with
`CLAUDE_CODE_ENTRYPOINT` unset), 914 tests pass. They include an MCP
server served over ACP, the output of a foreground Bash command and the
model list.
- Real CLI, without a prompt: with `'argv'`, Claude Code 2.1.326 and
2.1.323 both start a session with a stdio and an HTTP MCP server, and
the SDK prints no deprecation warning.
2026-11-17 13:33:51 +00:00
Mikhail Rodionov
451bc04ae0 fix: keep a workflow agent's tool call out of the turn's unfinished tools (#1638)
## Problem

With workflows on (`CLAUDE_CODE_WORKFLOWS=1`), the prompt fails when a
workflow agent asks for permission while the main agent's turn is open:

```text
RequestError: Internal error: Claude ended the turn without returning results for tool calls: toolu_…
data: { errorKind: "incomplete_tool_call" }
```

Seen in a client running workflows in default mode: the main agent
starts a background workflow and keeps working, a workflow agent runs a
quick Bash command after the user allows it, and the main agent's turn
then ends with this error. The workflow itself finishes fine.

## Cause

Claude Code calls `canUseTool` for a workflow agent with an `agentID`
that no `task_started` announces. The workflow's own `task_started`
names the Workflow call, and the agent's tool_use and tool_result never
stream on the root query. `toolUseOwner` finds no parent (the adapter
logs "No parent tool_use recorded for subagent a…; sending the Bash
permission request unattributed"), so `ensureToolCallEmitted` sees no
`parentToolUseId` and the root session id, and records the call as the
turn's foreground work:

```ts
if (!parentToolUseId && notificationSessionId === sessionId && toolName !== "SandboxNetworkAccess") {
  recordForegroundToolCall(session, toolCallId);
}
```

The call is still open when the turn's result arrives. The permission
path also recorded it as dispatched, so `settleActive` counts it as
stuck and fails the prompt. A command that runs a few seconds gets a
`task_started`, and `registerLiveTask` forgets the call, so only quick
commands hit this.

## Fix

`ensureToolCallEmitted` takes `canUseTool`'s `agentID`, and a call with
an `agentID` is not recorded as foreground work:

```ts
if (!agentID && toolName !== "SandboxNetworkAccess") {
  recordForegroundToolCall(session, toolCallId);
}
```

`toolUseOwner` finds a parent or a child session only for a set
`agentID`, so the two dropped conditions are implied by `!agentID`, and
the result changes only for a subagent with neither. That is a workflow
agent, or a Task subagent whose request beats its `task_started`; the
latter's call was already unlisted by its streamed frame.
`foregroundToolCallIds` feeds only the end-of-turn check. Both callers,
the permission request and the AskUserQuestion elicitation, pass
`agentID`.

v2 is not affected: it never fails a turn for an open tool call, and it
emits a permission's tool call early only for SandboxNetworkAccess.

## Tests

- `v1/incomplete-tools.test.ts`: "does not claim a workflow agent's
permission tool as a foreground tool". The stream is what the CLI sends:
a Workflow tool_use, its `local_workflow` `task_started` and launch
result, then the agent's `canUseTool` with an `agentID` no
`task_started` announced, then the result. It fails without the fix with
"Claude ended the turn without returning results for tool calls:
unfinished-bash".
- `npm run check`, `npm run build` and `tsc --noEmit` pass. `npm run
test:run`: 4179 passed, 36 skipped, 1 failed. The failure is
`acp-scenarios.test.ts` "replaces only the version of this adapter and
the path of this Node binary", which fails the same way on `main` on my
machine.
- Real repro: an ACP client spawning the adapter with Claude Code
2.1.325, default mode, permissions allowed after 1.5s. The main agent
starts a workflow whose one agent runs `date > stamp.txt; cat
stamp.txt`, then goes on with its own work:

  | Build | Main turn ends | Result |
  | --- | --- | --- |
  | `main` (7d9e1f6) | ~27s after the workflow's command | failed 2/2 |
  | this branch | ~27s after the workflow's command | clean 4/4 |
  | `main` (7d9e1f6) | ~1s after the command is allowed | failed 3/3 |
  | this branch | ~1s after the command is allowed | clean 3/3 |

0.101.1 fails the same way (2/2), and this change alone makes it clean
(2/2).

## Not covered

- The workflow agent's tool call still never closes in the client:
nothing streams its result on the root query. That was already the case
when the main turn ended before the request. A probe shows the adapter's
PostToolUse hook does fire for it, with the call's `tool_use_id`, its
`agent_id` and `agent_type: "workflow-subagent"`, so a follow-up could
close it from there.
- The "No parent tool_use recorded" log now fires on every workflow
agent's request, not only on a lost race with `task_started`. Its
comment says so; it is still only `logger.log`.
- `npm run test:integration` was not run.

Related: #1501 hits the same check through the same eager permission
call, for a root `confirm_<uuid>` question with no `agentID`. This PR
does not change it.

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-17 12:52:59 +00:00
Ben Brandt
20aeb46ece feat: support MCP servers that the client serves over the ACP connection (MCP-over-ACP) (#1645)
Implements the [MCP-over-ACP
RFD](https://agentclientprotocol.com/rfds/mcp-over-acp) for ACP v1 and
v2. A client can declare an MCP server with `"type": "acp"` in a session
setup request, and the agent sends that server's MCP requests to the
client as `mcp/message` over the ACP connection it already has.

## What changes for a client

- `initialize` advertises the transport:
`agentCapabilities.mcpCapabilities.acp: true` on v1, and
`capabilities.session.mcp.acp: {}` on v2.
- `session/new`, `session/load`, `session/resume` and `session/fork`
take `acp` servers in `mcpServers`. v2 used to reject them with
`-32602`.
- Claude Code discovers the server, lists its tools and calls them. Each
request reaches the client as an `mcp/message` request, and the client's
request-scoped `mcp/message` notifications (such as progress) reach
Claude Code.

## How it works

Claude Code's MCP client connects to a command or a URL, so it cannot
send `mcp/message` itself. The adapter uses the ACP SDK's helpers for
this case: `McpOverAcpCaller` and `McpOverAcpHttpBridge`. Each `acp`
server gets an MCP 2026-07-28 HTTP endpoint on `127.0.0.1` that forwards
every MCP request over the ACP connection. The `acp` servers of a
connection share one listener, which closes with the connection, and a
request needs the bearer token of its server.

- The new `McpOverAcp` class in `src/mcp-servers.ts` owns the caller and
the bridge. `sdkMcpServers` is now async and maps an `acp` server to the
SDK's `http` config through it. Both cores use it: v1 through
`AcpClient.mcpServerOverAcp`, v2 through `V2Agent.sdkMcpServers`.
- Both agent apps register `McpOverAcp.handleNotification` for
`mcp/message` notifications.
- A server gets the same config for as long as the connection lives. A
session that restarts, or a v2 resume of an active session with the same
servers, does not reconnect it.

## Notes for review

- **Depends on Claude Code's MCP negotiation.** The endpoint speaks MCP
2026-07-28 only and takes no `initialize`. Claude Code 2.1.325 sends
`server/discover` to an HTTP server first by default. With
`MCP_PROTOCOL_NEGOTIATION=legacy`, or with its
`tengu_mcp_protocol_negotiation_http` flag off, it sends `initialize`
instead. Then the server is listed as failed in `/mcp`, and the client
gets the existing "failed to start" notice. The adapter does not force
`MCP_PROTOCOL_NEGOTIATION=auto`: that would also change the handshake of
the user's other servers.
- **A listener that cannot open fails the setup request** with `-32603`
and a message that names the server, instead of starting the session
without it.
- **Golden files.** The 42 scenario snapshots change only in the
`initialize` line. `compare.ts` documents the new capability as an
allowed difference from the origin/main baseline.

## Testing

- `src/tests/mcp-servers.test.ts`: the transport mapping, a request and
its progress through a real in-memory ACP connection, one config and one
listener per connection, and the requests the endpoint refuses (another
server's token, `initialize`).
- `src/tests/v2/acp-v2.test.ts`: a tool call of a v1 session and of a v2
session through the protocol router, also after a v2 resume of the
active session. Both fail when the `mcp/message` notification handler is
not registered.
- `src/tests/v2/v2-integration.test.ts`: the bundled Claude Code CLI
lists the tools of an `acp` server. It sends no prompt, so it costs no
API usage.
- Run by hand against the built adapter with a real ACP client that
serves a tool: on v1 and on v2, Claude Code 2.1.325 sent
`server/discover`, `subscriptions/listen`, `tools/list` and `tools/call`
as `mcp/message`, and answered with the tool's result.
2026-11-17 13:47:34 +01:00
Ben Brandt
bcd3cdad35 fix: do not count a confirmWithUser question as an unfinished tool call (#1644)
## Summary

Fixes #1501. Supersedes #1643 by dreaifekks: this PR carries that commit
unchanged and adds one on top. The push to the author's branch was
refused, so the second commit could not go there.

Claude Code's `confirmWithUser` asks the user a question on its own, for
example whether to download a connector's file, or which model to
continue on after a refusal. It asks through `canUseTool` as
`AskUserQuestion` under a synthetic id `confirm_<uuid>`, and reads the
answer from the callback's result. No `tool_use` and no `tool_result`
stream for that id.

On v1, for a client with form elicitation, the adapter emitted a tool
call for the question and recorded it as the turn's foreground work.
Nothing ended that call, so the turn failed at its result, whatever the
user answered:

```text
RequestError: Internal error: Claude ended the turn without returning results for tool calls: confirm_…
data: { errorKind: "incomplete_tool_call" }
```

Two changes:

1. A `confirm_` id is not recorded as foreground work, next to the
SandboxNetworkAccess exemption in `ensureToolCallEmitted` (the commit
from #1643).
2. The answer ends the question's tool call. With the first change alone
the turn ended, but the call stayed `pending` in the client.

| What happens to the question | Tool call |
| --- | --- |
| The client answers | `completed` |
| The client declines the form | `completed`: the question is answered
with nothing selected |
| The client cancels it, or cannot show it | `failed` |
| `session/cancel` while the client shows it | `failed`, once, with the
cancel's report |

## Design

- No new mechanism. `settleSandboxNetworkCall` already ended the one
other tool call that no tool result ends. It is now
`settlePermissionOnlyCall` and ends both.
- That helper now forgets the call it ends, as `closeToolCall` does.
Before, a `session/cancel` later in the turn ended the same call a
second time, as `failed`. An answered SandboxNetworkAccess call had the
same defect.
- `isConfirmQuestion()` in `src/elicitation.ts` names the `confirm_`
rule for its two uses. Claude Code tests the same prefix itself.
- A request whose signal aborted is not settled. At a `session/cancel`
the turn ends its open tool calls itself (`closeOpenToolCalls`).
SandboxNetworkAccess follows the same rule on v1 and v2.
- v2 needs no change: it emits no tool call for the question, and it
never fails a turn for an open tool call.
- A v1 client without form elicitation is not affected either: the
callback rejects before a tool call is emitted, and Claude Code reads
the question as unanswered.

Not addressed: when the SDK aborts the callback's signal while the turn
goes on, the tool call stays `pending`. SandboxNetworkAccess has the
same limit on v1 and v2.

## Tests

`src/tests/v1/incomplete-tools.test.ts`:

- The client answers, declines, cancels, or cannot show the question:
the turn ends with `end_turn`, and the tool call gets the status of the
table above.
- Claude Code withdraws the question and the turn goes on: the turn ends
with `end_turn`. With the answer ending the call, this is the case that
still needs the foreground exemption.
- `session/cancel` while the client shows the question, and after the
client answered it: the tool call ends once.

Each rule fails one of these tests when it is removed.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,272 tests pass
on this branch merged with `main`)
- Not run against the real CLI: I found no cheap way to make Claude Code
ask such a question. The test doubles follow the code of CLI 2.1.325:
the id prefix, the shape of the question, and how it reads the answer.

---------

Co-authored-by: dreaife <dreaifehe@gmail.com>
2026-11-17 13:26:26 +01:00
Hussain Hammad
9d71d12336 fix: offer clearing the context on plan approval only when Claude Code's setting is on (#1627)
Refs #1077

Claude Code's plan-approval dialog offers "clear context" only when
`showClearContextOnPlanAccept` is on (the SDK's `Settings` docs: "When
true, the plan-approval dialog offers a "clear context" option. Defaults
to false."). The adapter offered it on every ExitPlanMode request, and
#1077 shows what a cleared context then loses on `session/load`.

- `SettingsManager.getShowClearContextOnPlanAccept` resolves the setting
as the CLI does: managed settings, then the `--settings` override, then
the user/project/local files; false otherwise.
- `buildClaudePermissionOptions` offers the clear-context option only
when it is on, for v1 and v2.

Tests cover the default, the v1 wiring and the settings precedence; the
existing clear-context tests and the exit-plan scenarios turn the
setting on. Checked with a real session: without the setting, Approve
Plan offers `exit-plan-default`, `exit-plan-auto` and `reject`; with
`showClearContextOnPlanAccept: true` in the project's
`.claude/settings.json`, `exit-plan-clear-auto` is back and the plan
runs.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-17 11:22:59 +00:00
Viz
378e85d060 feat: stream the output of foreground Bash commands (#1587)
Hi! I work on an ACP client that renders the agent's commands as
terminals. With Codex, a long command's terminal fills while it runs.
With this adapter, a foreground Bash command's terminal stays empty
until the command ends, and then gets all of its output at once. For
example, `for i in 1 2 3 4 5 6; do echo line$i; sleep 1; done` shows
nothing for about six seconds. Commands in the background already stream
(`BackgroundOutputTail` on v2); foreground ones don't, on v1 or v2.

As far as I can tell, Claude Code sends no output for a foreground
command before its tool result: `tool_progress` carries only
`elapsed_time_seconds`. But it does make the output available while the
command runs. After about 3 seconds it starts a `local_bash` task for
the command (`task_started` with `is_backgrounded: false` and the Bash
call's `tool_use_id`), and `get_task_output` returns that task's output
so far. I checked with a small script on the SDK pinned here (0.3.322),
polling every 0.3 s:

```
  3.0 assistant tool_use toolu_015v...
  6.2 system/task_started {"task_id":"bd1jlb3sb","task_type":"local_bash","is_backgrounded":false,"tool_use_id":"toolu_015v..."}
  6.5   getTaskOutput {"output":"line1\nline2\nline3\nline4\n","total_bytes":24,"truncated":false}
  7.4   getTaskOutput {"output":"line1\nline2\nline3\nline4\nline5\n","total_bytes":30,"truncated":false}
  8.3   getTaskOutput {"output":"line1\nline2\nline3\nline4\nline5\nline6\n","total_bytes":36,"truncated":false}
  9.2 system/task_notification {"status":"completed"}
  9.3 tool_result
```

The same run logged every `tool_progress` and
`background_tasks_changed`: none came for the command before
`task_started`, so there's no earlier task id to read from.

This PR uses that to stream the output into the command's terminal, on
both agents.

**What changes**
- `TaskOutputPoll` (`src/background-output.ts`, shared): calls
`get_task_output` every `BACKGROUND_OUTPUT_POLL_MS` and publishes the
text past the bytes already sent, using `total_bytes`.
- When it can't cut the new text out exactly, it sends the whole
`output` as a snapshot instead. That happens when more was added than
the 8 KiB tail holds, when the output shrank (a new run), or when the
decoded text doesn't match `total_bytes` (output that isn't UTF-8).
- A read that ends in U+FFFD may have cut a character the command is
still writing, so it waits for the next read.
- `finish()` waits for a read in progress; `end()` stops at once, for
the v2 tool result path, which is synchronous. A read in progress
publishes nothing after either.
- `supportsTaskOutput()` (same file): the type guard for `getTaskOutput`
(see below).
- v2 (`src/v2/tasks.ts`): `SessionTasks` owns the polls, keyed by the
Bash tool call id, next to the background terminals it already tails.
`followForeground()` starts one on a foreground `local_bash`
`task_started` whose Bash call the session's stream holds. A subagent's
command goes to the subagent's session, and gets none before that
session is announced. `toolResults()` ends the poll; if anything was
streamed, `withStreamedTerminal()` (`src/tool-calls/background.ts`)
turns the result's `terminal_output_delta` into `terminal_output`, so
the result's full output replaces what the terminal showed
(`terminal_update` with `output`) instead of being appended again. A
command that went to the background keeps its streamed output, since its
result only has the "Command running in background" text and its output
file's tail takes over. `queryEnded()` and `withdrawAll()` stop the
polls. `src/v2/session.ts` gives the tasks `taskOutput()`.
- v1 (`src/v1/background-work.ts`, `src/v1/acp-agent.ts`):
`SessionBackgroundWork.followForeground()` / `finishForeground()` own
the polls, and `queryClosed()` stops them when the session's query
closes. `foregroundBashTerminal()` decides which `task_started` gets
one, as on v2; a subagent's command goes under its Agent call (via
`parent_task_id` and `liveBackgroundTasks`), and gets none if that call
isn't known. `acp-agent.ts` only wires it in: start on `task_started`,
finish on the tool result, `withStreamedTerminal()` on the result
update.
- Who gets it: every v2 client (chunks are `terminal_output_chunk`, the
final output a `terminal_update`), and v1 clients that declared
`terminal_output_delta` and aren't AIR. v1 clients that declared only
`terminal_output`, and AIR on v1, which shows commands through its async
tasks, get the output with the result, as before.

**Two things you may want to weigh in on**
- `getTaskOutput` is on the SDK's query object but not in the public
`Query` type yet, so it's reached through a type guard,
`supportsTaskOutput()`, the same way `mcpAuthenticate` is. Its doc in
the SDK also mentions only background tasks; the run above shows it
works on a foreground one. If you'd rather wait for the SDK to type and
document it, I understand.
- Output from the first ~3 seconds, before `task_started`, still arrives
in one piece, at the first read. Commands that finish sooner never get a
task, so nothing changes for them.

Tests in `src/tests/background-output.test.ts`,
`src/tests/v1/tool-call-contract.test.ts`,
`src/tests/v1/acp-agent.test.ts` and `src/tests/v2/acp-v2.test.ts`
(which also checks that a command Claude Code runs in the background is
never polled); the scenario recordings don't change. `npm run check`
passes, and the full suite passes (4042 passed, 33 skipped). I also ran
the built adapter against real Claude Code over both protocols with the
command above: on v2 the terminal got `line1`–`line4` at the first read
and then `line5` and `line6` a second apart, before the result's
`terminal_update` replaced it; v1 with `terminal_output_delta` got the
same as `terminal_output_delta` chunks, then `terminal_output` and
`terminal_exit`.

The changes are two commits: the first adds the shared pieces and v2,
the second v1 on top of it, so the v1 half can be dropped if you only
want v2. I'm happy to change the approach, the poll interval or which
clients get it if you'd prefer something else.

---------

Co-authored-by: Jonathan <visionik@administrators-Mac-mini.local>
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-17 10:57:15 +00:00
Langning Zhang
0073280b97 fix: handle invalid file paths in tool reports (#1419)
Keep malformed Read/Edit paths out of display metadata so a tool
validation error reaches the client without aborting the ACP prompt.
Regression tests cover partial and consolidated input, adjacent Write
calls, and a subsequent prompt.

Fixes #1308.

Validation: the 42 file-path regression cases and all 380 tests in the
affected suites passed. `npm run check` and `npm run build` also passed.

The full suite failed locally: 40 failures, 3,288 passed, and 32
skipped. All 40 failure assertions were reproduced on unmodified
`f7d6030`: 39 in the full suite and the Skill file-rewrite fixture in a
focused run.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 15:00:24 +00:00
KlausUllrich
edab713502 fix: an autonomous result naming the original prompt must not end a steered turn early (#1451)
Thanks for merging #1392, and for #1233, which fixed the original hang
we reported in #1145.

**Problem.** Call the original prompt P and the steered instruction S.
While S is still running, a result from a cycle Claude Code started
itself (`origin: task-notification`), stamped with P's uuid, clears
`steeredAwaitingResult`. Its trailing idle then meets
`isSteeredSettleReady` and `session/prompt` returns while the steered
work is still streaming. The `steeredAwaitingResult` doc already states
the rule: *"while this is set the recorded outcome predates the steered
work and an idle must not settle on it"*. The code doesn't keep it for
this one shape.

The sequence (v0.97.0):
1. the interrupted cycle's result names P: `settleOrDefer`'s steering
branch records it;
2. S's echo: `steeredAwaitingResult = true`;
3. an autonomous result stamped `[P]`: `answersPendingPrompt` is true (P
is still in `turnQueue`), so it takes the user lane, reaches
`settleOrDefer`, and **clears `steeredAwaitingResult`**;
4. that cycle's idle: `isSteeredSettleReady` is true, so P settles
before S's own result.

#1185 doesn't cover this: it matches results that name the *steer*, and
this one names the original prompt.

**Change.**
- `settleOrDefer` takes one optional `{ steeredWork }` (default `true`,
so every existing caller is unchanged). In the steering branch it still
records `steeredSettle` (the last result and its usage still win), but
clears `steeredAwaitingResult` only for steered work.
- `answersSteer` moves up to the head of the result handling, so the two
settle calls can read it. Both the refusal settle and the end-of-result
settle pass `steeredWork: !startedByClaudeCode || answersSteer`.
- No new state. No change to `answersPendingPrompt`,
`isSteeredSettleReady`, the idle lane, owed-idle accounting or usage.
- The steered cycle's own result is not autonomous (in the existing
steer tests it carries no origin), so it still clears the flag. A result
that names the steer still leaves the steer lane at the result, as
before. If a CLI ever answered the steer with an autonomous result
naming only P, the turn would wait for the next result, `session/cancel`
or the next prompt, instead of ending early.

**Test.** Two cases (`end_turn` and `refusal` trailers) beside "does not
settle a steered turn on a lagged owed idle before the steered result",
which covers the unstamped variant of the same guard. They are the same
shape, with the autonomous result stamped with P and placed after the
steer's echo. Both fail on main and pass with the fix. The turn keeps
one stop reason across its cycles, so the refusal case expects
`refusal`. What it asserts is that the prompt ends last.

**Repro.** We have a ~180-line fake-CLI replay (no model, no network)
that drives the real adapter over stdio and times `session/prompt`
against the steered result: on 0.97.0 the prompt returns ~2.5 s early,
and with this change 1 ms after. It's the repro offered on #1145, and we
can attach it.

**Not covered:**
- An `is_error` autonomous result naming a pending prompt mid-steer
still fails that prompt (`failActiveWithSessionFailure`). That is a
different behaviour, an early failure rather than an early completion,
and is not addressed here.
- The steer-error arm (`is_error && isSteering && steeredEchoes.size >
0`) is unchanged. It runs only before the steer's echo, when there is no
wait to end yet.

Related: #1144, #1145, #1185, #1292 (the same family of protection for
autonomous cycles with an empty queue; if it lands first, this can be
re-expressed on top of it).

**Validation.** Both new cases fail on main and pass with the fix. `npm
run check` and `tsc --noEmit` are clean. Default suite with the fix:
3358 passed, 32 skipped, 2 failed: the `acp-scenarios` path
normalization, which also fails on main at `/usr/bin/node`, and one run
of a timing-sensitive hold test under heavy machine load (re-run quiet:
0/50 both ways, with and without the fix). Re-run on current `main`
(c7c80f7): 3378 passed, 32 skipped, 1 failed (the same `acp-scenarios`
case). No live-provider tests were run.

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 14:39:11 +00:00
acp-release-bot[bot]
7ad73cceb9 chore(main): release 0.107.3 (#1640)
🤖 I have created a release *beep* *boop*
---


##
[0.107.3](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.2...v0.107.3)
(2026-11-16)


### Bug Fixes

* allow Claude Enterprise accounts under --hide-claude-auth
([#1641](https://github.com/agentclientprotocol/claude-agent-acp/issues/1641))
([be2219c](be2219cef1))
* pass a model id the picker does not list to Claude Code
([#1630](https://github.com/agentclientprotocol/claude-agent-acp/issues/1630))
([dc769c1](dc769c132c))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-16 15:34:42 +01:00
Andrey Bragin
be2219cef1 fix: allow Claude Enterprise accounts under --hide-claude-auth (#1641)
## Problem

Under `--hide-claude-auth` the subscription guard refuses every
claude.ai account, Claude Enterprise included, so Enterprise users in
Air get `authRequired` (`claude_subscription_not_supported`) on every
session and prompt. Enterprise plans are allowed in this integration
(IJAI-2528).

## Change

- `isClaudeEnterprisePlan()` matches "Claude Enterprise" (the SDK's
`AccountInfo.subscriptionType`) and "enterprise" (older CLIs). Any other
name, including a custom `plan_display_name`, is still refused.
- `claudeAuthRefusal()` is now the guard's single decision, used by v1
and v2 session creation and the per-prompt guard instead of three copies
of the same check.

Free, Pro, Max and Team stay refused, and the claude.ai login method
stays hidden under the flag.

## Testing

v1 and v2 tests: Enterprise is allowed, Team is refused. `npm run build`
and `npm run check` pass. 24 tests in `create-session-options`,
`providers`, `session-index` and the v2 provider tests fail locally on
`main` too. Not checked against a real Enterprise account.
2026-11-16 15:30:58 +01:00
Sampanna Dahal
dc769c132c fix: pass a model id the picker does not list to Claude Code (#1630)
Fixes #1033. Same goal as #1034, which was closed because its rebase
reverted #1458. This version is written against current `main` and keeps
#1458's error codes.

## Problem

`session/set_config_option` refuses a model id that resolves to no entry
of the model option, even when Claude Code runs it. With telemetry off,
Claude Code 2.1.318 lists `default, opus, claude-fable-5-1[1m], sonnet,
haiku`. Against 0.107.0:

```
claude-opus-5-5   -> ok, now opus
claude-fable-5-1  -> ok, now claude-fable-5-1[1m]
claude-fable-5-2  -> -32602 Invalid value for config option model: claude-fable-5-2
claude-opus-4-6   -> -32602 Invalid value for config option model: claude-opus-4-6
```

`ANTHROPIC_MODEL` and a typed `/model` already reach these models, and
the option lists such a model once the session runs it
(`buildModelConfigOption`). Only this path refuses.

## Change

A model id that resolves to no entry goes to `query.setModel` as it is
(`configOptionValue` marks it `unlisted`, and `setSelectedModel` sends
it, shared by v1 and v2). Claude Code is the one that decides. Checked
against CLI 2.1.318 through the SDK's `setModel`:

| Request | Claude Code |
|---|---|
| `claude-fable-5-2`, `claude-opus-4-6`, `claude-opus-4-6[1m]` |
accepted |
| `gpt-4`, `not-a-model`, `son`, `foo-sonnet` | `Model '…' not found` |
| `claude-fable-5-2` with `availableModels: ["sonnet"]` | `Model
"claude-fable-5-2" is restricted by your organization's settings` |

A refusal from Claude Code becomes `-32602` with its reason (`Invalid
value for config option model: gpt-4. Model 'gpt-4' not found`), and the
option stays as it was. For a listed value, a `setModel` failure stays
the internal error it was.

Two cases still refuse without asking Claude Code:

- **A session whose models a `providers/set` gateway listed.** Only
those models can run there, but Claude Code would accept the id. v1
records this as `Session.modelsNarrowedByGateway`; v2 as
`ConfigSetup.narrowsModels`, from `routing.narrowsModels`.
- **Restoring the replaced query's choices after a restart**
(`restoreSessionChoices`, `SessionConfig.restoreFrom`). A model the new
provider dropped falls back as before ("reports the actual fallback when
a model disappears or its switch is refused").

Initial `configOptions` at setup behave like
`session/set_config_option`, as documented: an unlisted id goes to
Claude Code, and an entry it refuses is skipped.

## Tests

- **Updated.** The junk-id cases (`gpt-4`, `not-a-model`, `son`,
`foo-sonnet` in v1; `not-a-model` in v2 and in the setup entries) now
have the mock refuse unknown ids, as Claude Code does. They expect
`-32602` with Claude Code's reason and an unchanged option. "lists an
off-list current model until the session switches away" no longer
expects re-selecting that id to fail.
- **New (v1 and v2):** an unlisted id that Claude Code accepts becomes
the current value and is listed. A gateway-listed session refuses an
unlisted id without calling `setModel`.
- `npm run check`, `npm run build`, and `npm run test:run` all pass
(4146 passed, 34 skipped).
- **End to end:** I built this branch and drove it over ACP stdio
against Claude Code 2.1.318. `claude-fable-5-2` and `claude-opus-4-6`
switch, `gpt-4` gets `-32602 … Model 'gpt-4' not found`, and
`claude-opus-5-5` still resolves to `opus`.

---------

Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 14:30:58 +01:00
acp-release-bot[bot]
b437e4ee16 chore(main): release 0.107.2 (#1635)
🤖 I have created a release *beep* *boop*
---


##
[0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2)
(2026-11-16)


### Bug Fixes

* end the turn task of a cycle that has no turn to claim its result
([#1622](https://github.com/agentclientprotocol/claude-agent-acp/issues/1622))
([8de4981](8de49818f1))
* keep Fast mode on when it is turned on after a model switch or
mid-turn
([#1637](https://github.com/agentclientprotocol/claude-agent-acp/issues/1637))
([81650db](81650db3d3))
* list a live Monitor whose task Claude Code reports as local_bash
([#1607](https://github.com/agentclientprotocol/claude-agent-acp/issues/1607))
([41417f6](41417f6eee))
* read the Claude Code stream after a query restart, not at the next
prompt
([#1636](https://github.com/agentclientprotocol/claude-agent-acp/issues/1636))
([c03b66c](c03b66cc9f))
* read the Claude Code stream after every session setup, not at the
first prompt
([#1623](https://github.com/agentclientprotocol/claude-agent-acp/issues/1623))
([7d9e1f6](7d9e1f6135))
* reject the SDK no-token sentinel in auth guards
([#1609](https://github.com/agentclientprotocol/claude-agent-acp/issues/1609))
([c203b91](c203b919ec))
* update to @anthropic-ai/claude-agent-sdk 0.3.325
([#1634](https://github.com/agentclientprotocol/claude-agent-acp/issues/1634))
([db54135](db5413513c))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-16 11:36:50 +00:00
Ben Brandt
81650db3d3 fix: keep Fast mode on when it is turned on after a model switch or mid-turn (#1637)
A user reported that turning Fast mode on "does nothing or keeps getting
reset". This fixes two causes, in both cores.

## Turning Fast mode back on did nothing

Claude Code acts on `applyFlagSettings({ fastMode: true })` only when
its flag does not already hold `true`, and ignores a repeat. Its flag
stays `true` when it stops serving Fast mode at a model switch: Fable
5.2 and Mythos 5.2 take only a Fast mode that was turned on while they
were selected.

So with Fast mode on under Opus:

1. The user switches to Fable 5.2. The toggle still shows on.
2. The next `system`/init reports `fast_mode_state: "off"` with no
reason, and the adapter turns the toggle off.
3. The user turns it on again. The adapter sends `fastMode: true`, which
Claude Code ignores.
4. The next prompt turns the toggle off again.

The adapter now sends `fastMode: false` before `fastMode: true`. This is
a workaround for that Claude Code behaviour (CLI 2.1.325), and
`applyFastModeFlag` in `session-fast-mode.ts` says so.

## A toggle changed during a turn flipped back when the turn ended

Claude Code reads the `fastMode` flag once when a turn starts and builds
that turn's init and its result from the one reading. The result
therefore reported the value from before the request, and the adapter
mirrored it until the next turn's init.

A result that repeats its turn's init is now ignored
(`fastModeResultIsNews`). A result that says more, such as an
`extra_usage_disabled` refusal, is mirrored as before, with its notice.

## Not changed

- Fast mode is still dropped at a switch to Fable 5.2, as in Claude
Code. The toggle shows on until the next prompt's init turns it off,
without a notice. It can now be turned on again.
- A request that Claude Code applies after it read the flag and before
it sent the init is not covered: that init reports the earlier value
too, and the next turn's init corrects the toggle.

## Verification

Drove the built adapter over ACP against Claude Code 2.1.325, with and
without the change. The org check was skipped
(`CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`) and the prompts were
`/context` only, so this shows the toggle state and makes no model
request.

| step | `fast` on main | `fast` with this change |
| --- | --- | --- |
| turn Fast mode on (Opus 5.5), prompt | on | on |
| switch to Fable 5.2, prompt | off | off |
| turn Fast mode on, prompt | off | on |

The mid-turn case was not run against the real CLI, because it needs a
model turn. It is covered by the tests below.

## Tests

- v1 and v2: a client turns Fast mode on during a turn whose result
repeats the init, and the option stays on. On v1 the same flow with an
`extra_usage_disabled` result turns it off.
- v1 and v2: the requests sent for the toggle are `fastMode: false`,
then `fastMode: true`.
- Unit cases for `fastModeResultIsNews`.

The flow and request tests fail without the change.
2026-11-16 11:33:03 +00:00
Ben Brandt
c03b66cc9f fix: read the Claude Code stream after a query restart, not at the next prompt (#1636)
## Summary

Follow-up to #1623, which left this case open.

On v1, `replaceSessionQuery` resumes a session on a new query in two
cases: a provider change (`providers/set`, `providers/disable`) and a
sign-out respawn under `--hide-claude-auth`. The reader of the old query
ends with that query, and nothing started one for the new query until
the next prompt.

Claude Code can run a cycle of its own on the new query before that
prompt, for example a cron prompt or the follow-up to a finished
background task. Its output waited in the stream. At the next prompt the
consumer read the backlog with the prompt's turn queued, and the first
result in it, which has no `origin`, went to that turn. The prompt
resolved with another cycle's usage and stop reason. #1623 fixed the
same for `session/load`, `session/resume` and `session/fork`.

`replaceSessionQuery` now starts the reader once the session's choices
are restored and published.

## Design

- No new mechanism. `ensureConsumer` already owns starting the reader,
and `replaceSessionQuery` is the one function both restarts go through,
so one call covers the provider restart and the sign-out respawn.
- The reader starts after `restoreSessionChoices` and the
`config_option_update`, so what it reports is read against the restored
state. A setup has the same order: choices first, then the reader.
- The `queryClosed` check is at the call site, as in
`afterSetupResponse`, and not inside `ensureConsumer`. `prompt()` relies
on a consumer that starts on a closed stream to reject its queued turn.
- v2 needs no change: it reads every query from `Session.start()`, a
restart's included. A test now pins that.

Not addressed, as in #1623: a prompt sent while such a cycle is still
running can claim that cycle's result.

## Tests

- v1 (`provider-session-configuration.test.ts`): the new query of a
provider restart sends a cron cycle before the next prompt. The cycle is
read without a prompt, and the prompt gets its own usage. Fails without
the fix.
- v2 (`acp-v2.test.ts`): the same cycle after `providers/set` is
reported as it comes. v2 passed this before the change.
- `providers.test.ts`: the query mock's stream now stays open until
`close()`, like Claude Code's. It ended at once, so the reader that now
starts at a restart closed the query, and "switches every loaded session
through proxy replacements and back to native routing" saw a `close()`
it did not expect.
- Two comments said the reader starts only at a prompt
(`ensureConsumer`, and the Remote Control command). Both now name the
setup and the restart.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,183 tests
pass)
- Not run against the real CLI: no provider restart or sign-out respawn
was driven live.
2026-11-16 11:30:10 +00:00
Jonathan Ellis
7d9e1f6135 fix: read the Claude Code stream after every session setup, not at the first prompt (#1623)
On v1, `ensureConsumer` started only from `prompt()`, Remote Control and
the clear-context coordinator. `session/load`, `session/resume` and
`session/fork` did not start it. A resumed session can run cycles before
the first prompt: a cron prompt that came due while the bridge was down,
or the follow-up of a background task that finished. That output waited
in the stream. When the first prompt arrived, the consumer read the
backlog first, with the prompt's turn queued at the head and not yet
echoed. The first result in the backlog was a cron cycle's, which has no
`origin`, so it took the user lane and `ensureActiveTurn` gave it to the
queued head. The prompt resolved with another cycle's usage and stop
reason, and its own cycle then ran with no turn to claim it.

This change starts the consumer in `afterSetupResponse`, the existing
step that already runs after a setup response and sends the commands and
starts MCP authentication. It runs after a load's replay, so live output
cannot interleave with the replayed history. `ensureConsumer` is
idempotent, so a prompt that arrives later finds the consumer running,
and one that arrives first starts it as before.

## Design

- No new component: `ensureConsumer` already owns starting the reader,
and `afterSetupResponse` already owns "what follows a setup response".
The change is one call and the comments that said otherwise.
- Every setup starts the reader, new sessions included, not only resumed
ones. This is the rule v2 already has (`Session.start()` calls
`consume()` when the session opens), it needs no flag that tells a
resumed setup from a new one, and a new session has no history from
which Claude Code could start a cycle, so for it the early read only
means nothing waits unread.
- It does not start in `createSession`: a load replays history after
`createSession`, and live output from the reader would interleave with
it. `afterSetupResponse` runs after the replay.
- One behavior change: a stream that ends before the first prompt now
closes the session at that moment (the consumer's existing stream-end
handling and `queryClosed`) and not at the first prompt.
- The query mocks in `create-session-options.test.ts` returned an empty
stream, which Claude Code does not. With a reader running from setup,
the empty stream closed the session at once, so the mock now keeps the
stream open until `close()`, like Claude Code's.

## v2

Not affected. `Session.start()` calls `consume(query)` when the session
opens, for new, resumed and forked sessions alike, so output before the
first prompt is reported as it comes. A test in
`src/tests/v2/acp-v2.test.ts` resumes a session that runs a cron cycle
before the first prompt and checks that the cycle is reported apart from
the prompt's turn, with its own usage. It passes with and without this
change.

## Tests

`it.each(["resumeSession", "loadSession"])` in the `session/fork`
describe of `src/tests/v1/acp-agent.test.ts`: that describe holds
`forkingAgent`, the only helper that drives the real setup methods with
a scripted query. It gained a `backlog` parameter for what Claude Code
sends before the first prompt. The test sends a cron cycle (no origin)
and a task-notification cycle as the backlog, waits until the consumer
has read them, then prompts, and checks that the prompt's response
carries its own usage (7 input tokens, not the cron cycle's 111).
Without the fix the consumer never starts before the prompt, so the wait
times out, and with the wait replaced by a fixed delay the response
carries the cron cycle's usage.

This is independent of #1620: each fix passes its own tests alone. #1620
is the case where an unclaimed result leaves the turn task open; this
change removes the way a loaded session got there at its first prompt.

Fixes #1621.

## Validation

Rebased on `main` at 7e857d5.

- `npm run check` and `npm run build` pass.
- `npm run test:run`: 4,135 passed, 36 skipped, 1 failed. The failure is
`tools.test.ts` "picks up a rewrite that restored the modification time
of the file", which also fails on `main` at 7e857d5 without this change.
- The new v1 test fails on `main`, and passes with the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:16:46 +00:00
Slapoguzov Alexander
c203b919ec fix: reject the SDK no-token sentinel in auth guards (#1609)
The SDK reports `tokenSource: "none"` for a signed-out first-party
account. That non-empty string currently passes the `--hide-claude-auth`
credential guard and suppresses the subscription check. Treat the
sentinel as absent in both shared predicates, so signed-out sessions and
prompts are refused and a known subscription without another credential
retains its specific auth-required reason. Accepted keys, bearer/setup
tokens, external providers and unavailable-account fail-open behavior
are preserved.

Validation: 413 tests pass across the v1 authorization and v2 protocol
suites; 13 regression cases fail on unchanged main. TypeScript build and
lint/format checks pass. Native ACP v1/v2 signed-out session creation
returns auth-required with isolated configuration, no prompts and zero
loopback endpoint requests. Independently reviewed. The full repository
suite and live provider/client acceptance were not run.

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
2026-11-16 11:14:18 +00:00
Dave Meehan
41417f6eee fix: list a live Monitor whose task Claude Code reports as local_bash (#1607)
Fixes #1606

## Summary

Under ACP v2 a running `Monitor` never reached
`state_update.background`. Claude Code reports its task as `local_bash`
(no `ambient` flag), and the tool-result handling dropped every
`local_bash` task:

```diff
 // src/v2/tasks.ts, tool-result handling
 const task = taskId === undefined ? undefined : this.level.get(taskId);
-if (!task || task.taskType === "local_bash" || task.taskType === "local_agent") continue;
+if (!task || task.taskType === "local_agent") continue;
+// a command is its display terminal; the call of a task-starting tool is that task's entity
+if (task.taskType === "local_bash" && !TASK_TOOLS.has(toolUse.name)) continue;
 this.toolCalls.set(taskId!, { toolCallId, ... });
```

Why nothing else caught the Monitor:

```text
Monitor result, taskType local_bash
  toolResults        skipped by the line above      -> not in toolCalls
  adoptTasks         same local_bash skip           -> no task_<id> call
  terminals          needs a Bash result with backgroundTaskId
  lists()            lists only toolCalls/terminals -> background: []
```

Plain commands still go through `terminals`; `local_agent` is still
skipped. `adoptTasks()` is unchanged, since it already skips a task
whose call is registered.

## Evidence

- **Before:** the new test fails, and a real agent lists nothing (3
runs, 30 `state_update` frames, every one `background: []`).

  ```text
keeps the call in_progress and listed when Claude Code reports the
Monitor's task as local_bash, not ambient
AssertionError: expected [ 'running []', 'idle end_turn []' ] to include
'idle end_turn [toolu_mon]'
  ```

**After:** the same test passes, and the full suite is green (`npx
vitest run`: 4104 passed, 33 skipped; `tsc --noEmit`, `eslint` and
`prettier --check` clean). A real agent built from this branch (SDK
0.3.322) lists the Monitor in 10 of 11 `state_update` frames (the one
before it starts is `[]`), and its call goes `pending` → `in_progress`
with `capabilities: { cancel: {} }`.

The test, in pseudocode:

```text
task = { id: mon1, type: "local_bash" }          // no ambient, as the CLI sends it
script: Monitor tool_use, level [task], task_started, tool_result { taskId: mon1 },
        result, idle, task_notification completed, level []
expect trace == running [] | pending | in_progress | cancel | running [toolu_mon]
              | idle end_turn [toolu_mon] | completed | no cancel | idle []
```

The existing Monitor fixture models the task as `local_monitor` +
`ambient: true` (the shape #1538 fixed), which is why it never saw this.
`monitorStarts` now takes an optional task, defaulting to that fixture,
so the existing tests are unchanged.

## Merge Danger

**Door:** two-way

Revert the commit; nothing is persisted or migrated.

**Blast Radius:** Narrow

ACP v2 only (`src/v2`); v1 is untouched. A `Monitor`, or any tool in
`TASK_TOOLS` whose task Claude Code reports as `local_bash`, is now
registered and listed. A client that decides whether a session is quiet
(to restart or release it, say) will now see a live Monitor as
background work. That is the intended behavior, but it differs from what
those clients saw before.

Not covered:

- The late-level race in #1537 (a level that joins after the tool
result) is a separate bug, and a `local_bash` Monitor hit by it would
still go unlisted.
- `npm run test:integration` was not run against the real CLI. The
real-agent result above is a manual probe, not a test.
- `tool_call/cancel` and the task's end were not exercised against the
real agent, only through fixtures.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 11:13:21 +00:00
Jonathan Ellis
8de49818f1 fix: end the turn task of a cycle that has no turn to claim its result (#1622)
When Claude Code's scheduler fires a `ScheduleWakeup` or a cron prompt
with no prompt open, the bridge opens an AIR async task for the cycle,
but nothing ends it. The cycle's result has no `origin`, so it is not in
`AUTONOMOUS_RESULT_ORIGINS` and takes the user lane. With no active or
queued turn it settles nothing, and it records an owed trailing idle.
The `idle` handler ends an open autonomous task only at
`owedTrailingIdles === 0`, and it absorbs the owed idle first. The task
stays open until the stream ends or a later cycle sweeps the debt.

This change ends the open autonomous task at any result that no turn can
own: the session is not cancelled and has no active turn and no
unsettled queued turn. That is the condition that already opens the
task, so both ends now call one helper (`noTurnOwnsCycle`, next to
`firstUnsettledQueuedTurn`). The new end uses the same placeholder rule
as the autonomous lane (`num_turns > 0 || is_error`).

It adds a scripted SDK-stream regression: a prompt's turn, a
`command_lifecycle` `started` with `wakeup_source: "loop_wakeup"` before
the prompt's idle, a cycle with a result that has no origin, then one
idle for both. It checks that the task completes. It fails before the
fix (the task is only closed as `failed` when the stream ends) and
passes after.

## Why this rule

I considered two designs:

1. End the task for any result with no turn to claim it (this PR).
2. Treat a scheduler-fired cycle as autonomous, so its result takes the
autonomous lane.

I chose 1:

- The result carries no origin, so 2 needs state that remembers "this
cycle started with a `wakeup_source`" from the `command_lifecycle`
frame, and a way to match that state to a later result. It would miss
cycles with no fire frame (Claude Code before 2.1.307 sends no
`wakeup_source`), and any other origin-less cycle that Claude Code
starts on its own, including origins it adds later.
- The comment on `AUTONOMOUS_RESULT_ORIGINS` explains why the lane
default is fail-open: moving a user result into the autonomous lane
hangs the prompt where the #825 detector cannot see it. This change
moves no result between lanes. It only ends a task when no turn exists
that a user-lane result could settle, so there is nothing to hang.
- Starting and ending the task now share one predicate, so they cannot
disagree about which cycles belong to no turn.

The state of the task lives in `AsyncTaskRuntime`
(`autonomousTurnEnded`, unchanged). The predicate reads the session's
turn queue, which `async-tasks.ts` does not own, so the check stays in
the v1 consumer next to `firstUnsettledQueuedTurn` and only calls the
runtime.

## What stays as it was

- #825 (the abandoned-turn detector) fails an unsettled active turn at
an idle that no result owes. The new end needs no active and no queued
turn, so the detector never has a turn to fail here. A result with an
active or queued turn is claimed as before (`ensureActiveTurn` still
ends the task when it promotes the head).
- The result keeps its owed trailing idle (`owedTrailingIdles++`), its
usage and its other user-lane handling. Its idle is absorbed as owed, so
it cannot be read as a later prompt being abandoned. The `running`
transition still sweeps unpaid debt.
- A cancelled session is excluded, so the orphan results of cancelled
prompts keep their existing handling.

## v2

Not affected. v2 reports a cycle as a turn and ends it at the cycle's
result, whatever its origin: `Session.result` opens a turn if none is
open, then ends it. v2 has no async task that a result must close
separately. A test in `src/tests/v2/acp-v2.test.ts` runs the same stream
(a prompt, a scheduler fire, one idle for both results) and checks that
the cycle reports `running` and `idle end_turn`. It passes with and
without this change.

Fixes #1620.

## Validation

Rebased on `main` at 7e857d5.

- `npm run check` and `npm run build` pass.
- `npm run test:run`: 4,134 passed, 36 skipped, 1 failed. The failure is
`tools.test.ts` "picks up a rewrite that restored the modification time
of the file", which also fails on `main` at 7e857d5 without this change.
- The new v1 test fails on `main` (`['async_task_spawned', 'failed']`
instead of `['async_task_spawned', 'completed']`) and passes with the
fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:11:03 +00:00
Ben Brandt
db5413513c fix: update to @anthropic-ai/claude-agent-sdk 0.3.325 (#1634)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.323 to 0.3.325, which
bundles Claude Code 2.1.325. The adapter needs no code change for it.

Also bumps the dev dependency `eslint` 10.14.0 → 10.15.0.

`npm update` brings the in-range lockfile bumps: `@eslint/config-array`
0.23.5 → 0.23.6 and `postcss` 8.5.32 → 8.5.33. `eslint` 10.15.0 and
`@eslint/config-array` 0.23.6 require `minimatch` ^11, so the lockfile
gains `minimatch` 11.0.8 under each of them, and its dependency
`@isaacs/nonrecursive-glob-match` 1.1.0. All are dev-only.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.72.2 still requires `typescript <6.1.0`.

`npm audit` lists one moderate advisory, GHSA-g3hv-75wg-m249, for the
`minimatch` 10.2.6 that `@typescript-eslint/typescript-estree` depends
on. This PR does not change that package, and no typescript-eslint
release fixes it yet. It is dev-only: `npm audit --omit=dev` finds
nothing.

## Changelog review

Read the SDK changelog for 0.3.324 and 0.3.325 and the Claude Code
changelog for 2.1.325, which has no 2.1.324 section. Every type change
is in 0.3.324; the type files of 0.3.325 are the same. No entry needs a
code change:

- **Types.** Doc text and new optional members only, plus the new
functions `archiveSession()` and `unarchiveSession()`.
- **`applyFlagSettings()` rejects a call with an invalid value**, where
it used to drop the settings of earlier calls without an error. Checked
against the real CLI: it accepts every value the adapter sends (the five
effort levels, each with and without `ultracode: true`, `effortLevel:
null`, `fastMode` and `ultracode` as booleans, `agent: null` and a
listed agent). A value of the wrong type is rejected with "nothing in
this request was applied and earlier settings stay in force". Every call
site applies the setting before it changes its own state, so a rejection
leaves the config option as it was.
- **A new warning when a `PreToolUse` hook gives no verdict.** Recorded
from the real CLI, for a hook that timed out:

  ```json
  {
    "type": "system",
    "subtype": "informational",
"content": "A hook didn't answer in time, so it didn't check this
action.",
    "level": "warning",
    "tag": "hook_no_verdict",
    "hook_no_verdict": {
      "hook_event": "PreToolUse",
      "tool_use_id": "toolu_01E5…",
      "timed_out": true
    }
  }
  ```

A hook whose command cannot run sends "A hook gave no usable answer, so
it didn't check this action." The frame comes after the tool call and
before its result, once per hook in a session. Both cores already send
an `informational` warning to the client: as a warning notice, or as a
`**Warning:**` line for a client without notices. The frame has no
top-level `tool_use_id`, so the rule that keeps one notice per tool use
does not drop it. The adapter's own `PreToolUse` hooks catch their
errors, so they do not cause this warning.
- **Sandboxed Bash commands and read-only git commands in a repository
outside the session's folders** now go through the permission flow, so
they reach `canUseTool`. The adapter passes ACP `additionalDirectories`
as the SDK option, which is `--add-dir`, so git commands in those
folders still run without a prompt.
- **`canUseTool` suggestions for Bash and Monitor** hold a list of rules
alone only when saving it would allow the command. Without suggestions
the adapter offers no "always allow" option.
- **`getSessionInfo` and `listSessions`** return `archived` and
otherwise read a transcript as before. A differential run of 0.3.323
against 0.3.325 over 4,500 generated transcripts gave no mismatch, so
`sdkTitles` in `src/session-index/transcript-scan.ts` stays as it is.
The run is not part of this PR.
- **`supportedEffortLevels`** no longer lists levels above the
organization's effort cap or `maxEffortLevel`. The effort option is
built from that list, so it follows.
- **`managed_lock` on `init.plugin_errors`.** The adapter only logs
these errors.
- **`refuseIfBusy` on `reloadPlugins()`.** The adapter does not call
`reloadPlugins()`.
- **`ProposeSkillsInput`** (`edits`, optional `skillMd`). The adapter
has no reporter for this tool and reads neither field.

## Not in this PR

Left for follow-ups, because each is its own change:

- The SDK's archive mark. `archiveSession()` writes `<session
id>/archived.json` beside the transcript, and `listSessions()` reports
it as `archived`. The adapter's `_session/archive` stores the
`[archived] ` title prefix instead
(`src/session-index/archive-title.ts`). The two are not synced: a
session archived through the SDK is listed as unarchived by the adapter,
and the reverse.
- `invalid_config_file` of the `config_file_invalid` startup failure.
The paths are on the result frame only; the error that
`initializationResult()` rejects with carries just the reason. Its
message already names the file.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,146 tests
pass)
- Real CLI: the integration tests (`RUN_INTEGRATION_TESTS=true`), 877 of
878 pass. The one failure is a unit test that uses no real CLI: "absorbs
the interrupt's lagged trailer after cancelling a held turn
mid-followup" in `src/tests/v1/acp-agent.test.ts`. It failed once in
that run, and passed in six runs alone and in every `npm run test:run`.
The test calls `cancel()` once the turn is held, which can be before the
adapter has read the follow-up's `running` frame; `cancel()` then counts
no trailing idle for the interrupt. Not changed here.
- Real CLI: `applyFlagSettings()` with each value above, without a
prompt
- Real CLI: one short turn with a `PreToolUse` hook that times out and
one whose command does not exist, to record the warning frames and their
order

Note for running the integration tests: `agent-discovery.test.ts` fails
in a shell that sets `CLAUDE_CODE_ENTRYPOINT` to a value other than
`sdk-ts`, `sdk-py` or `sdk-cli`, for example a terminal inside Claude
Code. The CLI inherits the variable and then lists a sixth built-in
agent, `claude-code-guide`, which `BUILTIN_AGENT_NAMES` does not hold.
Claude Code 2.1.323 does the same. Run the tests with the variable
unset.
2026-11-16 12:08:00 +01:00
acp-release-bot[bot]
3067a5db36 chore(main): release 0.107.1 (#1619)
🤖 I have created a release *beep* *boop*
---


##
[0.107.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.0...v0.107.1)
(2026-11-16)


### Bug Fixes

* end a v2 turn once when Claude Code folds a prompt into it
([#1618](https://github.com/agentclientprotocol/claude-agent-acp/issues/1618))
([7e857d5](7e857d59ec))
* resolve a model preference without a version to the newest listed row
([#1633](https://github.com/agentclientprotocol/claude-agent-acp/issues/1633))
([e73d790](e73d7909ce))
* send v2 terminal output with CR LF, as a PTY would
([#1632](https://github.com/agentclientprotocol/claude-agent-acp/issues/1632))
([29dde36](29dde3633a))
* update to @agentclientprotocol/sdk 2.7.0
([#1629](https://github.com/agentclientprotocol/claude-agent-acp/issues/1629))
([b1c1987](b1c198754d))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-16 10:46:25 +01:00
nikita-ashihmin
e73d7909ce fix: resolve a model preference without a version to the newest listed row (#1633)
## Problem

A `settings.model` of `opus[1m]`, with an `availableModels` allowlist of
versioned ids from oldest to newest, starts a new session on Opus 4.5:

```json
"model": "opus[1m]",
"availableModels": ["claude-sonnet-4-5-20250929", "claude-haiku-4-5-20251001", "claude-opus-4-5-20251101", "...", "claude-opus-5-5", "..."]
```

No row matches `opus[1m]` directly. The fuzzy tiers of
`resolveModelPreference` then return the first `opus` row,
`claude-opus-4-5-20251101`, and `getAvailableModels` calls `setModel`
with it. The CLI resolves the same settings to the newest Opus: the
`default` row of `supportedModels()` gives `claude-opus-5-5`.

## Fix

For a preference without a version (`opus`, `opus[1m]`, `sonnet`), the
fuzzy tiers take the row of the newest version. The new `newestModel`
reads the version with `familyVersionOf`. A row of an unknown version,
such as `my-opus`, ranks below each row of a known version. A preference
with a version keeps the first compatible row, as before.

## Tests

- `model-resolution.test.ts`: a new `it.each` resolves `opus[1m]`,
`opus` and `sonnet` against an allowlist from oldest to newest. Without
the fix the test fails and gives the oldest row.
- I checked the fix against the real `supportedModels()` with the
settings above. Before the fix, `opus[1m]` resolved to
`claude-opus-4-5-20251101`. After the fix, it resolves to
`claude-opus-5-5`.
- `npm run check` and `npm run build` pass.
- On my machine, `npm run test:run` has 26 failures in
`v1/create-session-options`, `v1/providers` and `v2/acp-v2`. They fail
the same way on `main` without this change. They come from the local
`ANTHROPIC_*` environment.
2026-11-16 12:30:08 +04:00
John Tur
29dde3633a fix: send v2 terminal output with CR LF, as a PTY would (#1632)
ACP v2 display terminals carry the bytes a terminal emulator receives.
Claude Code runs a command with its output piped, so no line discipline
turns each LF into CR LF (ONLCR), and the adapter sent the bare LFs
through. An emulator then moves down a row without returning to column
0, so each line starts where the previous one ended. Zed feeds v2 bytes
to its emulator unchanged and showed this staircase; on v1, Zed adds the
CRs itself.

V2Terminals now adds a CR before every LF of terminal_update snapshots
and terminal_output_chunks, which covers foreground commands and the
output files of background commands.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 06:43:00 +00:00
Ben Brandt
b1c198754d fix: update to @agentclientprotocol/sdk 2.7.0 (#1629)
Updates `@agentclientprotocol/sdk` from 2.6.0 to 2.7.0 (schema v1.32.0
and v2.0.0-alpha.16), and follows the two protocol changes that affect
what the adapter already serves.

The SDK's runtime is unchanged apart from an SSE BOM fix. The rest of
the release is schema and doc comments, so I read the protocol docs and
RFDs between the two schema tags for behavior changes.

## Changes

### `configOptions` on `session/fork` (v1 and v2)

`ForkSessionRequest` now has `configOptions`, and clients may send it to
an agent that advertises `options`. The adapter advertises `fork` and
`options`, so both cores accept it:

- Two entries with the same `configId` fail with `-32602` before the
transcript is copied. On v2, so does a value type that
`session/set_config_option` does not take.
- The entries are set on the started fork, in list order, over what the
copy starts with. An entry that the session refuses is skipped, as on
`session/new`.
- No update goes out for them. The response carries the options.

This was the only compile break: `v1ForkSessionRequest` passed the v2
entries on to the v1 request.

### `replay_complete` on v2

v2 now requires a `replay_complete` update after the history replay of a
`session/resume` with `replayFrom`, and allows only replayed history
between the request and that update.

- The adapter sends it on the resumed session after the last replayed
update, also for an empty history. It does not send it without
`replayFrom`, or when the resume fails.
- Each subagent session that the replay announces gets its own
`replay_complete`, also one without history.
- A replayed child's `state_update` now follows the child's
`replay_complete`, and the notice that subagent history is missing
follows the root's. Neither is history.
- AIR's `loadReplayEnd` update is still sent to a v2 client that
declares it, right after `replay_complete`.

### Holding live updates during a replay (new mechanism)

From the request to `replay_complete`, a session can only send its
replay. An active session keeps working while it is resumed, and a
session that starts sends its first updates while the transcript is
read. So the adapter needs a place to hold them. No existing mechanism
did this.

`src/v2/replay-hold.ts` holds every update of the session and of its
subagent sessions that is not the replay, and their permission requests
and elicitations, and sends them after `replay_complete` in the order
they were sent. `V2Agent.send` is the one place where v2 session updates
leave the agent, so the hold sits there.

The replay runs in one synchronous step, so what a session sends during
that step is its replay. Nothing else tells the two apart. The comment
in the module says so.

A resume of an active session now reads the transcript before its other
steps, so the history ends as close to the request as it can.

## Already compliant, checked

- Initial config values: no notice or mode update before the setup
response, and a value that Claude Code refuses is skipped.
- `auth/logout` is idempotent, because `claude auth logout` is.
- A `tool_call/cancel` or `terminal/cancel` sent again after the item
ended gets `-32602`.
- The subagent clarifications: no assumed `senderSessionId`, session
references sent again with new tool call content, and `unknown` for a
child that can no longer be observed.
- `thought_level` values go from lowest to highest. This rests on Claude
Code's order, which a comment now says.

## Not covered

- An active session that streams while it is resumed with a replay: if
Claude Code writes a block to the transcript during the few milliseconds
of the read, the held chunks of that block reach the client twice. I
found no cheap way to close that window.
- The new RFD features are left for separate PRs: the `speed` config
category for Fast mode, `prompt_suggestions_update`, v2 skills, and
`path` on markdown plans (the `file` plan type is gone, and the adapter
never sent it).
- I did not run the integration tests against the real CLI.

## Tests

- `create-session-options.test.ts` (v1) and `v2.test.ts` (v2): a fork
sets its `configOptions`, and rejects duplicates before the copy.
- `v2.test.ts`: `replay_complete` for an empty history and none without
`replayFrom`. What an active session sends during a replay goes out
after `replay_complete`, a permission request too, and goes out without
one when the replay fails. The same for a live subagent's session.
- The existing replay tests and the `session-load-replay` golden file
now include `replay_complete`.

`npm run build`, `npm run check` and `npm run test:run` pass (4142
tests).
2026-11-14 16:36:26 +00:00
Ben Brandt
7e857d59ec fix: end a v2 turn once when Claude Code folds a prompt into it (#1618)
Fixes #1611.

## Problem

On ACP v2, a prompt sent while the session works gets its reply twice.
The client sees:

1. the reply, streamed under the model's `msg_` id
2. `state_update` `idle` with `stopReason: end_turn` and zero usage
3. `state_update` `running`
4. the same reply again, under a UUID
5. `state_update` `idle` with the real usage

This happens whenever Claude Code folds the prompt into running work.
The work can be a cycle that Claude Code started on its own, as in the
issue, or the turn of an earlier prompt.

## Cause

Claude Code sends one result, not two. The order of its frames differs
for a folded prompt (CLI 2.1.323):

| Prompt | Order |
| --- | --- |
| started the work | `result`, then `command_lifecycle` `completed` |
| folded into the work | `command_lifecycle` `completed`, then `result`
|

`V2Session.lifecycle` took every `completed` frame of the last started
prompt as the end of a turn that had no result, and closed the turn. The
result then found no open turn. It opened a new one, saw no streamed
text in it, and sent `result.result` as the reply.

## Fix

The session remembers which prompt started Claude Code's current cycle
(`cycleCommand`). Only that prompt's `completed` frame closes a turn
that had no result. A folded prompt's `completed` frame leaves the turn
open, and the result ends it.

A result ends the cycle, so the next prompt of a turn that stays open
(the `/clear` and the plan prompt of a fresh context) starts its own.

The `cancelled` frame is unchanged: it still closes the turn for the
prompt that started last.

## Tests

- `v2.test.ts`: one `it.each` with the frames in the CLI's order, for a
prompt folded into another prompt's turn and into a cycle that Claude
Code started on its own. Both fail without the fix with `running, idle,
running, idle`.
- `v2-integration.test.ts`: one case against the bundled CLI. It passes
with the fix.
- Live, with the issue's steps: one reply and one `idle` with the real
usage.

## Not covered

- I did not capture what Claude Code sends when a cancel arrives during
work with a folded prompt.
- I observed the frame order on CLI 2.1.323 only.

ACP v1 is not affected: it does not end a turn at a `completed` frame.
2026-11-13 13:48:52 +00:00
acp-release-bot[bot]
c5c120dba9 chore(main): release 0.107.0 (#1595)
🤖 I have created a release *beep* *boop*
---


##
[0.107.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.106.0...v0.107.0)
(2026-11-13)


### Features

* report the turn's rate limit in rate-limit failure errors
([#1610](https://github.com/agentclientprotocol/claude-agent-acp/issues/1610))
([4f474d6](4f474d655b))
* report unknown subagent state at a conversation reset and reference
children from tool calls
([#1608](https://github.com/agentclientprotocol/claude-agent-acp/issues/1608))
([4804917](4804917a6f))
* say the cause of an api retry in the AIR warning details
([#1594](https://github.com/agentclientprotocol/claude-agent-acp/issues/1594))
([4f690e1](4f690e129c))


### Bug Fixes

* assume a 1M context window until Claude Code reports it
([#1613](https://github.com/agentclientprotocol/claude-agent-acp/issues/1613))
([9619805](9619805306))
* end the tool calls of a response that Claude Code took back
([#1616](https://github.com/agentclientprotocol/claude-agent-acp/issues/1616))
([21f3e04](21f3e0430b))
* explain why Claude Code turns Fast mode off
([#1602](https://github.com/agentclientprotocol/claude-agent-acp/issues/1602))
([c331e17](c331e178a5))
* follow Claude Code's rule for managed deniedModels in the model picker
([#1615](https://github.com/agentclientprotocol/claude-agent-acp/issues/1615))
([c78bcc7](c78bcc7f41))
* log a managed policy source that did not load
([#1614](https://github.com/agentclientprotocol/claude-agent-acp/issues/1614))
([ca46b41](ca46b412f5))
* report a mid-turn API error notice where the response broke off
([#1599](https://github.com/agentclientprotocol/claude-agent-acp/issues/1599))
([4df6999](4df69996ca))
* say why the login failed in the v2 authRequired error
([#1598](https://github.com/agentclientprotocol/claude-agent-acp/issues/1598))
([ecd066c](ecd066c870))
* update to @anthropic-ai/claude-agent-sdk 0.3.323
([#1612](https://github.com/agentclientprotocol/claude-agent-acp/issues/1612))
([ddee24e](ddee24ef8f))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-13 13:34:19 +00:00
Eric Holk
4f474d655b feat: report the turn's rate limit in rate-limit failure errors (#1610)
When a turn fails with `errorKind: "rate_limit"`, the error's `data` now
also carries the turn's latest `rate_limit_event` info as `rateLimit`:

```json
"data": {
  "errorKind": "rate_limit",
  "rateLimit": { "status": "rejected", "rateLimitType": "five_hour", "resetsAt": 1763002200 }
}
```

## Why

ACP clients may want to handle a rate-limit failure better than showing
its message, for example by showing when the limit resets or offering to
continue the turn then. That needs the reset time as data. Today the
adapter forwards `rate_limit_event` info only on a `usage_update`
(`_meta["_claude/rateLimit"]`). A message sent while the account is
already over its limit is refused before its first usage, so no
`usage_update` goes out and the client gets only:

```json
"error": { "code": -32603, "message": "Internal error: You've hit your 5-hour limit · resets 5:30pm (America/Los_Angeles)", "data": { "errorKind": "rate_limit" } }
```

Without this change, the only way to get the reset time is parsing that
text.

## What changed

- `turnErrorData` in `src/result-end.ts` builds the `data` of the error
that fails a turn. It adds `rateLimit` only for a `rate_limit` failure
in a turn that saw a `rate_limit_event`. Other failures keep their
current data.
- v2: `TurnReport` records the turn's latest `rate_limit_event` info and
clears it on `reset()`. `idleOutcome` passes it to `turnErrorData`.
- v1: the prompt loop tracks `turnRateLimit` alongside
`lastAssistantError`, resets it with the other per-turn scratch state,
and passes it at the three result-failure sites that used
`errorKindData(lastAssistantError)`.

## Testing

- New v1 and v2 tests: a `rate_limit_event` followed by a `rate_limit`
failure puts `rateLimit` in the error data.
- `npm run build`, `npm run check` and `npm run test:run` pass.
- Manually tested with a locally built binary: a client received
`rateLimit` in the error for a message refused at the 5-hour limit.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:31:11 +00:00
Ben Brandt
21f3e0430b fix: end the tool calls of a response that Claude Code took back (#1616)
## Summary

Follow-up to #1612. When a model refuses, Claude Code takes back the
response it already sent and retries on the fallback model. A tool call
of that response which has no result yet is stopped, and no result ever
comes for it. The adapter never read which messages were taken back, so
that tool call stayed open:

- **v1:** until the turn's end, where the prompt then failed with
`incomplete_tool_call`, although the retry had answered.
- **v2:** past the turn's idle, since a call that ran is left open for
its result.

Both cores now end the call as soon as it is named: `failed` on v1,
`cancelled` on v2, with a text that says why.

## What Claude Code sends

Read from the code of CLI 2.1.323. A refusal fallback cannot be produced
on demand, so none of this was observed live.

- The refused response reaches the host as usual: its stream and its
`assistant` frames, which can hold `tool_use` blocks, and the results of
tools that had finished.
- Claude Code then stops the tools that had not finished and sends no
result for them.
- It names the messages it took back, by the `uuid` their frames were
sent with, in two places: `retracted_message_uuids` of the
`model_refusal_fallback` notice, and `supersedes` of the first
`assistant` frame of the retry.

Since 2.1.323 `supersedes` also names a response whose tool call could
not be parsed. Such a response has stop reason `tool_use` and no
`tool_use` block, so it leaves no tool call open, and this change does
nothing for it.

## What changes

- `RetractedToolCalls` in `src/tool-calls/retracted.ts` (new) keeps the
tool uses of each assistant frame by `uuid`, for the last 1,000 frames,
and gives the tool calls of the messages that a frame takes back. It
reads both signals and gives each tool call once.
- `AcpToolCallRenderer.unfinished` gains a `retracted` case with its own
text: "Claude Code replaced the response that made this tool call, and
stopped the call. If it had started, some of its effects may have
happened."
- v1 closes through the existing `closeOpenToolCalls`, which now also
takes the tool call id. The change in `src/v1/acp-agent.ts` is wiring.
- v2 adds `SessionOutput.closeRetracted`, which shares one private
`close` with `closeUnfinished`.

Only a call that is still open is closed. A call that already has its
result is left alone, and a result that arrives after the close changes
nothing.

## Not in this PR

- **Superseded text stays in the transcript.** ACP v1 has no way to take
a message back. On v2 the `agent_message` upsert could clear one
(`content: []`), but that leaves an empty message whose rendering is up
to the client, and v1 and v2 would then differ. This needs a decision,
so it is left as it is.
- A tool use that streamed but whose `assistant` frame never arrived has
no `uuid` to match, so it is not closed by this.
- No scenario-harness case: its plain and Zed recordings must match the
origin/main baseline, so a deliberate difference there needs a
documented exception first.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,128 tests
pass)
- `src/tests/retracted-tool-calls.test.ts` for the shared class
- One `it.each` in `src/tests/v1/acp-agent.test.ts` and one in
`src/tests/v2/acp-v2.test.ts`, with one row per signal. The v1 rows fail
on main with `incomplete_tool_call`.
- The doubles follow the frames as read from the CLI's code, since the
case cannot be reproduced against the real CLI.
2026-11-13 14:27:16 +01:00
Ben Brandt
c78bcc7f41 fix: follow Claude Code's rule for managed deniedModels in the model picker (#1615)
## Summary

Follow-up to #1612. With an `availableModels` allowlist, the model
picker rebuilds its rows from the allowlist entries and drops the ones a
managed `deniedModels` list blocks. It decided that with its own rule
(`isDeniedModel`), which differed from Claude Code's in both directions.
The rule is now the SDK's `matchDeniedModels()` (alpha, 0.3.323).

This only affects a session that has both an `availableModels` allowlist
and a managed `deniedModels` list. Without an allowlist the picker shows
Claude Code's own list, which Claude Code has filtered already.

## What Claude Code really does

Measured with CLI 2.1.323: sessions started with `managedSettings: {
deniedModels }`, then `setModel(id)` for each id. No prompt was sent.
The deny check runs before the "not found" check, so a refusal that says
"is restricted by your organization's settings" means the list blocks
the id.

| Entry | Model id | `setModel` | SDK matcher | Old adapter rule |
| --- | --- | --- | --- | --- |
| `claude-opus-5-5` | `vertex_ai/claude-opus-5-5` | refused | denied |
offered |
| `claude-opus-5-5` | `anthropic/claude-opus-5.5`,
`claude-opus-5-5:free` | refused | not denied | hidden |
| `claude-opus-5-5` | `openrouter/anthropic/claude-opus-5.5` | refused |
not denied | offered |
| `claude-opus-5` | `claude-opus-5-5` | refused | denied | hidden |
| `claude-opus-4.5` | `claude-opus-4-5` | allowed | not denied | hidden
|
| `claude-opus-4.5` | `anthropic/claude-opus-4.5` | refused | not denied
| hidden |
| `claude-haiku` | `claude-haiku-5-5` | allowed | not denied | hidden |
| `my-model` | `gateway/my-model` | refused | not denied | offered |
| `my-model` | `my-model:free` | not blocked | not denied | hidden |
| `default`, `opusplan` | the same name | allowed | not denied | hidden
|

Over 169 ids in 30 sessions:

- the old rule offered 14 ids that `setModel` refuses, and hid 27 that
the list does not block;
- `matchDeniedModels` alone missed 33 refused ids. Its doc says so: it
compares an id with the entries, and the CLI also judges path tails and
a model's other names;
- the new rule agrees on all 169.

## The rule

`deniedModelIds` in `src/session-model.ts` asks `matchDeniedModels`
about three spellings of each id, so the entry rules stay the SDK's:

- the id itself;
- its last path segment, because an exact-name entry also blocks
`gateway/my-model`;
- its version spelling: everything from the first `:` dropped, and `5.5`
written `5-5`.

**Workaround to note.** The version spelling is asked behind a fixed
path, `version-of/`. The SDK ignores a path for a versioned id, and the
path keeps the spelling from equalling an exact-name entry. Without it,
the entry `my-model` would block `my-model:free`, which Claude Code
allows. This leans on how the SDK function treats paths, which nothing
documents. The tests hold recorded CLI answers and fail if the path is
removed or if only the id itself is asked.

`isDeniedModel` and its own rule are removed.
`applyAvailableModelsAllowlist` is async now, because the SDK function
is; v1 (`src/v1/acp-agent.ts`) and v2 (`src/v2/setup.ts`) each gain one
`await`. The SDK call takes under 1 ms.

## Not verified

- A custom name such as `gpt-5` answers "not found" on a first-party
account. That is read as "not denied" from the order of the checks; no
gateway was available to confirm it.
- `modelOverrides` targets were checked as plain ids given to
`setModel`.
- `matchDeniedModels().warnings` are not logged: `/status` and `claude
doctor` already list them.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,125 tests
pass)
- The `isDeniedModel` tests became one `it.each` in
`src/tests/model-resolution.test.ts`. Every id in it is a recorded CLI
answer.
- A second, independent run against the real CLI reproduced nine of the
recorded answers.
2026-11-13 14:26:13 +01:00
Ben Brandt
ca46b412f5 fix: log a managed policy source that did not load (#1614)
## Summary

Follow-up to #1612. Logs when a machine policy source may be there and
did not load, using `machinePolicy.didNotLoad` (alpha) that
`resolveSettings()` reports since SDK 0.3.323.

## Why

`resolveSettings()` shows a policy source that it could not read (a
macOS MDM profile, the Windows registry policy, the managed-settings
file) as absent. The adapter then applies nothing from it, and nothing
said so:

- at start-up, `applyManagedPolicyEnv` copies no env vars from it into
the process;
- in `SettingsManager`, the session's settings and model list (managed
`deniedModels`, `availableModels`, `modelOverrides`) do not reflect it.

Claude Code reads the policy itself, so its own read is not affected.
The log line only explains why the adapter's side looks as if no policy
were set.

## What changes

- `unloadedPolicySources` in `src/managed-policy.ts` names the sources
for a log line. It is undefined when every source loaded, and for an SDK
that does not report the member.
- `applyManagedPolicyEnv` writes one line to stderr and still applies
the env vars of the sources that did load.
- `SettingsManager` logs once per change, because it resolves the
settings again after every settings file edit.

Not in this PR: reading the policy again later. The env vars are applied
once at start-up, so a source that loads later is picked up for env vars
only by a restart, which the message says.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,126 tests
pass)
- The real SDK reports `machinePolicy: { didNotLoad: false }` on this
machine; the doubles use that shape.
2026-11-13 14:16:33 +01:00
Ben Brandt
9619805306 fix: assume a 1M context window until Claude Code reports it (#1613)
## Summary

Follow-up to #1612. The context window that `usage_update.size` reports
before Claude Code has said what the window is changes from 200K to 1M,
and the "1m" text heuristic that upgraded it is removed.

## Why

The adapter takes the window from Claude Code: a background
`getContextUsage` at session creation and at every model switch, then
each result's `modelUsage`. Until the first of those lands it reports a
placeholder, `DEFAULT_CONTEXT_WINDOW`.

Since Claude Code 2.1.323 that placeholder is the less likely value.
Asked directly (`getContextUsage`, no prompt sent):

| Model | Window |
| --- | --- |
| An id Claude Code does not know (`my-gateway-model`, `gpt-5`) |
1,000,000 |
| `opus`, `sonnet`, `haiku` | 1,000,000 |
| `claude-haiku-4-5`, `claude-sonnet-4-5` | 200,000 |
| An unknown id or `sonnet` with `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` |
200,000 |

So 1M is what Claude Code itself assumes when it knows nothing about a
model, and what it reports for its current aliases.

## What changes

- `DEFAULT_CONTEXT_WINDOW` is 1,000,000.
- `inferContextWindowFromModel` is gone, with its two callers: the seed
in `immediateContextWindow` and the `message_start` upgrade in the v1
and v2 cores. It only ever turned 200K into 1M for a model whose id,
resolved id, name or description held a "1m" token. With a 1M default it
has nothing left to do, and the table shows that a model's names do not
give its window (`sonnet` is 1M, or 200K under the environment
variable).
- Nothing changes in how the real window is learned: the background
read, the per-result update and the cross-session cache are as before.

For a client: the first `usage_update` of a session or after a model
switch can carry `size: 1000000` where it carried `200000`, until the
read lands (0.2 to 0.6 s in the probe above) or, if the read fails,
until the first result. A model with a 200K window shows 1M for that
moment; before, a model with a 1M window showed 200K.

## Tests

- The session double (`mockSessionState`) starts with the default
window, as a real session does. It held 200K with
`contextWindowAuthoritative: false`, which can no longer occur.
- Tests of the heuristic are removed. Tests that tell a learned window
from the default now use values that differ from 1M.
- The scenario recordings are unchanged: their scripted Claude Code
reports a 200K window, and the read lands before the first turn.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,115 tests
pass; 6 tests of the removed heuristic are gone)
- Real CLI: the `getContextUsage` reads in the table above
2026-11-13 14:15:51 +01:00
Ben Brandt
ddee24ef8f fix: update to @anthropic-ai/claude-agent-sdk 0.3.323 (#1612)
## Summary

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.322 to 0.3.323, which
bundles Claude Code 2.1.323. The new version needs two adapter fixes,
both included here:

- the session index reads titles by the SDK's new rule;
- the heartbeat of a long-running hook no longer lands on a tool call.

Also bumps these dev dependencies: `@anthropic-ai/sdk` 1.7.0 → 1.8.0,
`@tsconfig/node22` 22.0.6 → 22.0.7 and `prettier` 3.9.10 → 3.10.1.

`npm update` brings the in-range lockfile bumps: `rolldown` 1.2.18 →
1.2.19, `vite` 8.3.7 → 8.3.8, `hono` 4.13.17 → 4.13.18,
`@hono/node-server` 2.1.6 → 2.1.8, and patch releases of
`@babel/runtime`, `brace-expansion`, `encodeurl`,
`@jridgewell/resolve-uri` and `@rolldown/pluginutils`. `rolldown` 1.2.19
lists its wasm32 binding as an optional dependency, so the lockfile
gains `@rolldown/binding-wasm32-wasi`, `@napi-rs/wasm-runtime`,
`@emnapi/core` and `@emnapi/runtime` (2.0.0-beta.2),
`@emnapi/wasi-threads`, `@tybys/wasm-util` and `tslib`. All are dev-only
and optional.

TypeScript stays at 6.0.3: 7.0.2 is out, but `@typescript-eslint/parser`
8.72.2 still requires `typescript <6.1.0`.

## Session titles

`getSessionInfo` and `listSessions` of SDK 0.3.323 read titles
differently, and neither changelog says so. The session index mirrors
the SDK's rule (`sdkTitles` in `src/session-index/transcript-scan.ts`),
so it has to follow.

- Before: the SDK took the last `"customTitle":"…"` text of the tail or
the head, wherever it stood.
- Now: it parses each line that names the field, from the last one back,
and takes the top-level string of the record. For `customTitle` and
`aiTitle` the record must be of type `custom-title` or `ai-title`.
`lastPrompt` and `summary` may be on a record of any type.

What changes for a client:

- A `customTitle` or `lastPrompt` inside a message is no title. A tool
result that shows a transcript no longer renames the session.
- A `custom-title` record that the start of the 64 KB tail window cuts
is not read. The old rule still found its title text.
- A `custom-title` record appended to a line whose write was cut off is
read.

Checked against the real SDK: a differential run of `sdkTitles` against
`getSessionInfo` over 1,800 generated transcripts gave no mismatch. The
old rule mismatched on 371 of 600. The run is not part of this PR; the
tests in `src/tests/v1/session-index.test.ts` compare each case above
with `getSessionInfo`.

## Hook heartbeats

Since Claude Code 2.1.323, a hook that runs long sends a `tool_progress`
beat every 30 seconds. Recorded from the real CLI:

```json
{
  "type": "tool_progress",
  "tool_use_id": "hook-PreToolUse-toolu_01X…-heartbeat-0",
  "tool_name": "PreToolUse",
  "parent_tool_use_id": "toolu_01X…",
  "elapsed_time_seconds": 30,
  "heartbeat": true
}
```

For a PreToolUse or PostToolUse hook, `parent_tool_use_id` is the tool
call. For a UserPromptSubmit or Stop hook it is an id that names no tool
call. The PostToolUse beats come before the tool result.

Both cores send a beat under an unknown id to the call that
`parent_tool_use_id` names. So without a change, a slow PreToolUse or
PostToolUse hook:

- marked the tool call `in_progress` before it ran, on v1 and v2;
- restarted its elapsed time with the hook's (30 → 1 → 2 → 3 → 30 in the
scenario);
- named the call `PreToolUse` in `_meta.claudeCode.toolName` for a plain
or Zed client.

The adapter now drops these beats. This matches how it already ignores
`hook_started`, `hook_progress` and `hook_response`: hooks have no ACP
surface. The rule that picks the tool call of a beat was written twice,
in `src/v1/acp-agent.ts` and `src/v2/stream.ts`. It is now one function,
`progressToolCallId` in `src/tool-calls/renderer.ts`, which holds the
new rule too.

The `tool-progress` scenario carries a PreToolUse and a PostToolUse
beat. Its recordings for the plain, Zed, AIR and v2 clients are
unchanged, and all four fail without the fix.

## Changelog review

Read the SDK changelog for 0.3.323 and the Claude Code changelog for
2.1.323. No other entry needs a code change:

- **Types.** Doc text and new optional members only, plus one new
`SDKStartupFailureReason` (`managed_settings_not_delivered`).
`startupFailureError` treats a reason it does not list as an internal
error with the CLI's message.
- **Context window of an unknown model id**, 200K → 1M. The adapter
reads the window from Claude Code (`getContextUsage`) at session
creation and at every model switch, so it reports the new value. Its own
200K is only the placeholder until that read lands.
- **`canUseTool` suggestions** no longer hold a Bash allow rule for a
write to `.git` or `.claude`. The adapter then offers no "always allow"
option.
- **`init.plugin_errors`** also lists load errors of plugins that
managed settings enable. The adapter only logs them.
- **`forkSession` with `upToMessageId`** and **`getSessionMessages`**
compaction fixes. Picked up as they are: the adapter has no workaround
for the old behavior.
- **A subagent's WebSearch result can carry `tool_use_result`.** The
code reads only fields that this result does not have. One comment in
`src/async-tasks.ts` said that no subagent result carries one; it now
says Bash results.
- **A permission check that fails after a PreToolUse hook allowed the
call** goes to `canUseTool`, which the adapter always provides.

## Not in this PR

Left for follow-ups, because each is its own change:

- The 200K placeholder for the context window. 1M is now the more likely
value, and with it the "1m" text heuristic has nothing left to do.
- `matchDeniedModels()` (alpha). The adapter's own `isDeniedModel`
disagrees with it on 23 of 875 model and entry pairs.
- `supersedes` on the retry of a response whose tool call could not be
parsed. The adapter does not act on `supersedes`.
- `machinePolicy.didNotLoad` (alpha) of `resolveSettings()`.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,121 tests
pass)
- Real CLI: one short session with slow hooks and
`CLAUDE_CODE_HOOK_HEARTBEAT_INTERVAL_MS=1000`, to record the heartbeat
frames and their order
- Real CLI: `getContextUsage` for unknown and known model ids, without a
prompt
2026-11-13 13:56:39 +01:00
Ben Brandt
4804917a6f feat: report unknown subagent state at a conversation reset and reference children from tool calls (#1608)
Brings the RFD form of subagent reporting in line with the ACP [Subagent
Sessions RFD](https://agentclientprotocol.com/rfds/subagents), which is
moving to Preview in agentclientprotocol/agent-client-protocol#2800. The
related RFD clarifications merged in
agentclientprotocol/agent-client-protocol#2801. AIR output is unchanged,
and no scenario snapshots changed.

## Changes

- **`unknown` at a conversation reset.** A child that is still working
at `conversation_reset` now reports `unknown` and `capabilities: null`,
not `idle`. The adapter forgets its children at reset, so it can no
longer observe or stop them. v1 reports it on the parent's
`subagent_update`. v2 also sends `state_update` `unknown` on the child.
- Stream end, stream error, `queryEnded`/`retire`, and `worker_restart`
keep `idle`, because the work is known to have stopped.
- In v2, the forgotten child's unfinished tool calls keep their last
status. They are no longer forced to `failed`.
- **`session` tool call content.** Added live and in replay, for the v1
RFD form and v2, only when the child is already announced:
  - `TaskStop` whose `task_id` is a child's agent id.
  - `SendMessage` that stays visible and targets a child's agent id.
- v1 only: an Agent/Task launch that a permission request keeps visible.
- The reference is repeated on every update that carries content,
because `content` replaces the whole array.
- **Docs.** The README's subagent section matches the code: SendMessage
is hidden and reported as linked messages, `unknown` at reset, `session`
content, and no `session_message_chunk`. Three stale comments are fixed.

## Workarounds and limits

- **Post-response ordering still uses `setTimeout(0)`.** SDK 2.6.0 gives
`onRequest` handlers no responder or after-response hook. The comments
in `src/v2/agent.ts` and `src/v1/acp-agent.ts` now state what the
ordering relies on: the response is queued in the microtask after the
handler returns, and `Connection.sendMessage` is first-in, first-out.
The SDK does not promise this.
- **The `unknown` change assumes Claude Code keeps subagents running
across `/clear`.** That comes from the existing v2 comment and test
double. It was not checked against the real CLI.
- No reference is added when a tool names a child by agent name, or for
v2 launch calls that a permission request shows.
- A child that is idle at reset keeps its `cancel` capability. Unchanged
here.
- A stream error with a client-supplied `spawnClaudeCodeProcess` still
reports `idle`, although closing may not stop a remote CLI.

## Testing

- `npm run build`: clean.
- `npm run check`: clean.
- `npm run test:run`: 73 files passed, 5 skipped. 4117 tests passed, 33
skipped.
- Integration tests against the real CLI were not run.
2026-11-12 15:48:47 +00:00
Mark Tkachenko
c331e178a5 fix: explain why Claude Code turns Fast mode off (#1602)
When the user turns Fast mode on, Claude Code can report
`fast_mode_state: "off"` on the next turn's `system`/init. The adapter
mirrored that into the option but explained it only for reasons listed
in `FAST_MODE_UNAVAILABLE_EXPLANATIONS`. `preference`, `unknown` and any
newer code were dropped, so the toggle snapped off with no reason. This
happens on every turn behind an API gateway that authenticates with
`ANTHROPIC_AUTH_TOKEN` only: Claude Code treats Fast mode as disabled by
the organization (`preference`) without asking the server.

Changes:
- `preference` ("not enabled for your organization or API gateway") and
`unknown` ("currently unavailable") are explained. A reason code the SDK
adds later gets a generic `not available (<code>)`.
- Only `sdk_opt_in_required` (every SDK session starts there; the toggle
is the opt-in) and `pending` (eligibility still resolving) stay
unexplained.
- The notice rule is unchanged: Fast mode was on, then off with an
explained reason. Off without a reason stays quiet, because a `result`
can carry the state from the start of the turn.
- One shared function in `session-fast-mode.ts` serves v1 and v2. In
`src/v1/acp-agent.ts` only comments change.

Limitation: the adapter still offers the toggle up front. Until a
session opts in, Claude Code reports `sdk_opt_in_required` and hides the
account or organization blocker, so the adapter can't tell in advance
that Fast mode will be refused.

Tests: unit tests for each reason, plus v1 and v2 flow tests (set `fast`
on, prompt, init reports off/`preference`). The flow tests fail without
the fix.
2026-11-11 17:28:40 +01:00
Mark Tkachenko
830f05a0ac refactor: move the v1 session fingerprint out of acp-agent.ts (#1601)
Moves `computeSessionFingerprint` and its helpers (`normalizeSkills`,
`OPTION_REBUILDS_SESSION`, `canonicalJson`) verbatim from
`src/v1/acp-agent.ts` into `src/v1/session-fingerprint.ts`. No behaviour
change.

- Only `computeSessionFingerprint` is exported, as before; the helpers
stay private to the new module.
- `session-fingerprint.ts` imports nothing from `acp-agent.ts`. The test
that used `computeSessionFingerprint` now imports it from the new
module.
- Emitted JS differs from `main` only in `dist/v1/acp-agent.js` (one
import, the moved code removed) plus the new module.

Review with `git diff --color-moved` to see the move.
2026-11-11 15:31:40 +01:00
Ben Brandt
4df69996ca fix: report a mid-turn API error notice where the response broke off (#1599)
## Problem

When a response stream drops after some blocks arrived, Claude Code
keeps the partial response and writes its own message into the
conversation, e.g. "API Error: Connection lost mid-response. The
response above may be incomplete."

If the partial response contained tool calls, Claude Code runs them and
the turn goes on. Since #1582 the v2 agent sends this text as a
`notice`, but only at the turn's result. In a turn that goes on, the
notice arrived after all the later work, so "the response above" pointed
at the wrong output.

## Change

The v2 agent sends the pending notice as soon as the main conversation
goes on past the failed request: at the next tool result, stream event
or assistant message.

A turn that ends at the failed request behaves as before: the idle's
`error` carries it when the turn fails, and a notice goes out at the
turn's end otherwise.

## Not changed

- v1 keeps its current behaviour, as in #1582.
- `session/load` replay still shows these messages as text.

## Testing

- New v2 case: a kept tool call, the API error message, the tool result,
then more output. The notice comes before the later text. It fails
without the change.
- The test double follows the message shape and order read from the
bundled CLI's code. Not run against a real dropped connection.
- `npm run check`, `npm run build` and `npm run test:run` pass.
2026-11-11 13:45:06 +00:00
Ben Brandt
ecd066c870 fix: say why the login failed in the v2 authRequired error (#1598)
## Problem

When an API request fails authentication, the v2 agent hides the message
Claude Code writes for it (#1582) and fails the turn with a bare
`Authentication required`. The reason is lost, for example:

> Failed to authenticate: this login reached its time limit and cannot
be renewed. Run `claude auth login` to sign in again, or use `claude
setup-token` and set CLAUDE_CODE_OAUTH_TOKEN for unattended jobs

A client can then only say that the agent is signed out, not why.

## Change

The turn's `authRequired` error now carries the result's error text in
its message: `Authentication required: <text>`. The code and `data` are
unchanged, so a client that starts its own sign-in from the code behaves
as before.

Text that tells the user to run `/login` is still left out, as that
instruction is for Claude Code's terminal (#863). Only the v2 agent
changes.

## Testing

`npm run check`, `npm run build` and `npm run test:run` pass. The v2
tests now pin both messages: the plain one for the `/login` text, and
the one with the reason for an authentication failure reported on the
assistant message.

Not checked against a real expired login.
2026-11-11 13:34:58 +00:00
Mark Tkachenko
a22a797db2 refactor: move the v1 steering and async task stop requests out of acp-agent.ts (#1581)
Moves the `_session/steering` and `_session/async_task/stop` request
definitions verbatim from `src/v1/acp-agent.ts`, like
`goal-extension.ts` does for goals. No behaviour change.

- `src/v1/steering.ts`: `STEER_METHOD`, the steer priorities,
`SteerRequest`, `SteerResponse`, `parseSteerRequest`.
- `src/v1/async-task-stop.ts`: `ASYNC_TASK_STOP_METHOD`, its request and
response types, `parseAsyncTaskStopRequest`.
- Neither module imports `acp-agent.ts`. The one test that imported
`SteerRequest` from `acp-agent.js` now imports it from `steering.js`.
- Emitted JS differs from `main` only in `dist/v1/acp-agent.js` (imports
and the moved code) plus the two new modules.

Review with `git diff --color-moved` to see the move.
2026-11-11 14:20:55 +01:00
nikita-ashihmin
4f690e129c feat: say the cause of an api retry in the AIR warning details (#1594)
## Summary

The AIR warning for an SDK `api_retry` message had only a title, such as
`Retrying Claude, attempt 2 of 10.`. The user did not see why Claude
retries or how long the next attempt waits. The warning now carries
`details` with the cause and the wait.

## Changes

- `apiRetryWarning(message)` in `src/session-failure-extension.ts`
builds the title and the details. The title text does not change. The
`api_retry` case of `src/v1/acp-agent.ts` only calls it.
- The cause:
  - `HTTP 529 (overloaded).` when the CLI sends a status;
- `Connection error: no HTTP response.` for a null status with the
`unknown` kind;
- `No HTTP status (overloaded).` for a null status with a kind. The CLI
sends `overloaded` with no status for an SSE `overloaded_error` event
after HTTP 200, so "no HTTP response" would be wrong there.
- The wait: `Next attempt now.` for 0 ms (a `no_response` retry), `Next
attempt in 8s.`, and whole minutes from 120 s (a background rate-limit
wait), e.g. `Next attempt in 30m.`.
- The `no_response` wait stays in the title only.
- The kind label map has the type
`Record<Exclude<SDKAssistantMessageError, "unknown">, string>`, so a new
SDK kind fails typecheck. A missing `error` reads as `unknown`.
- The 401 skip, the actions and the terminal failures do not change. The
subagent retry path sends a `tool_progress` update and no session
failure, so it does not change. v2 has no `api_retry` session failure.

## Tests

- `src/tests/session-failure-extension.test.ts` (new): 0 ms, minutes,
the 119 s / 2 m boundary, a null status with `cloud_credential_error`,
and a missing `error`.
- `src/tests/v1/acp-agent.test.ts`: the warning details on the wire,
revision 2 replaces the details, and the terminal revision has none. The
test doubles use status and kind pairs and delays that the bundled CLI
really sends.
- `npm run build`, `npm run check`: clean.
- `npx vitest run src/tests/session-failure-extension.test.ts
src/tests/v1/acp-agent.test.ts`: 766 passed, 9 skipped.
- `npm run test:run`: 17 tests in `create-session-options.test.ts`,
`providers.test.ts` and `acp-v2.test.ts` fail on `main` without this
change too. They read the model list of the local environment.
2026-11-11 14:19:41 +04:00
246 changed files with 27532 additions and 3445 deletions

View File

@@ -36,7 +36,7 @@ jobs:
# Generating a GitHub token, so that PRs and tags created by
# the release-please-action can trigger actions workflows.
- name: Generate GitHub token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc
id: generate-token
with:
# GitHub App ID secret name
@@ -292,7 +292,7 @@ jobs:
exit 1
- name: Generate token scoped to the registry repo
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc
id: registry-token
with:
app-id: ${{ secrets.REGISTRY_UPDATER_APP_ID }}

View File

@@ -1,3 +1,3 @@
{
".": "0.106.0"
".": "0.113.0"
}

View File

@@ -1,5 +1,177 @@
# Changelog
## [0.113.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.112.0...v0.113.0) (2026-11-26)
### Features
* serve /plugin in ACP sessions ([#1716](https://github.com/agentclientprotocol/claude-agent-acp/issues/1716)) ([0f095f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/0f095f678dac9cf4a7ca3623261fa3f6729e73b0))
* start Remote Control with the session when Claude Code asks for it ([#1523](https://github.com/agentclientprotocol/claude-agent-acp/issues/1523)) ([893f768](https://github.com/agentclientprotocol/claude-agent-acp/commit/893f7680c7ed57be7fc7be7f4e9abac268884ff2))
### Bug Fixes
* **background:** keep a tool call whose task joins the live set after its result ([#1639](https://github.com/agentclientprotocol/claude-agent-acp/issues/1639)) ([677a6d9](https://github.com/agentclientprotocol/claude-agent-acp/commit/677a6d9afab3c7bad41fdf2587a24b2414236b29))
## [0.112.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.111.0...v0.112.0) (2026-11-24)
### Features
* rewind the same provider session on an edited message ([#1704](https://github.com/agentclientprotocol/claude-agent-acp/issues/1704)) ([f2897d6](https://github.com/agentclientprotocol/claude-agent-acp/commit/f2897d6687f594220c07836c3e3528de552e30ef))
### Bug Fixes
* stop holding an MCP request that Claude Code gave up ([#1711](https://github.com/agentclientprotocol/claude-agent-acp/issues/1711)) ([d5be0e5](https://github.com/agentclientprotocol/claude-agent-acp/commit/d5be0e5827fb111e5e95020d76920fe8a59e671b))
## [0.111.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.110.1...v0.111.0) (2026-11-24)
### Features
* name the session and tool call of MCP requests sent over ACP ([#1705](https://github.com/agentclientprotocol/claude-agent-acp/issues/1705)) ([fa02bc2](https://github.com/agentclientprotocol/claude-agent-acp/commit/fa02bc239ff3f3557b1797d1137a9bc34bd4d339))
### Bug Fixes
* start a session without the MCP servers that Claude Code refuses ([#1708](https://github.com/agentclientprotocol/claude-agent-acp/issues/1708)) ([f6525de](https://github.com/agentclientprotocol/claude-agent-acp/commit/f6525de507f9f628d4e3e8781eb61488f965b7de))
* update to @anthropic-ai/claude-agent-sdk 0.3.331 ([#1707](https://github.com/agentclientprotocol/claude-agent-acp/issues/1707)) ([9062779](https://github.com/agentclientprotocol/claude-agent-acp/commit/9062779cda651aaeaf8a07a8ea2c8edeb76924fa))
* write error messages as plain text ([#1709](https://github.com/agentclientprotocol/claude-agent-acp/issues/1709)) ([2c37f97](https://github.com/agentclientprotocol/claude-agent-acp/commit/2c37f979b60e0db2a069f99fdc85da3c8822dc1e))
## [0.110.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.110.0...v0.110.1) (2026-11-23)
### Bug Fixes
* Closing the gaps for the ACP v2 support ([#1542](https://github.com/agentclientprotocol/claude-agent-acp/issues/1542)) ([105e1c3](https://github.com/agentclientprotocol/claude-agent-acp/commit/105e1c38daf76bc832e872e95904be6dabd32372))
* preserve existing line endings in ACP v2 terminal output ([#1697](https://github.com/agentclientprotocol/claude-agent-acp/issues/1697)) ([9ca8984](https://github.com/agentclientprotocol/claude-agent-acp/commit/9ca8984d55132991b2eec0f87c45acbb820b38a3))
## [0.110.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.109.1...v0.110.0) (2026-11-23)
### Features
* name each model's effort levels in its model option entry for AIR ([#1692](https://github.com/agentclientprotocol/claude-agent-acp/issues/1692)) ([130fbbc](https://github.com/agentclientprotocol/claude-agent-acp/commit/130fbbc02ab4771443b2f365f2af1659ceb0c591))
## [0.109.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.109.0...v0.109.1) (2026-11-21)
### Bug Fixes
* announce a live subagent again when its session is loaded or resumed ([#1688](https://github.com/agentclientprotocol/claude-agent-acp/issues/1688)) ([b977017](https://github.com/agentclientprotocol/claude-agent-acp/commit/b977017ed88148fbbc8bdd6e24cd275313c546e6))
* apply a provider's route to the running session ([#1691](https://github.com/agentclientprotocol/claude-agent-acp/issues/1691)) ([988a58b](https://github.com/agentclientprotocol/claude-agent-acp/commit/988a58b908d55a933e9d297c142e9040d478bd69))
* give a forked skill's child session its tool calls and text ([#1677](https://github.com/agentclientprotocol/claude-agent-acp/issues/1677)) ([1c90fb9](https://github.com/agentclientprotocol/claude-agent-acp/commit/1c90fb959a003eba1eed1dac94400c9cdef63195))
* keep built-in web-fetch and claude-code-guide agents out of the Agent picker ([#1672](https://github.com/agentclientprotocol/claude-agent-acp/issues/1672)) ([eb4c16f](https://github.com/agentclientprotocol/claude-agent-acp/commit/eb4c16f10a753925090289c21f2d95bd902a7b63))
* match v1 session/options to resume when workspace roots change ([#1679](https://github.com/agentclientprotocol/claude-agent-acp/issues/1679)) ([184b7df](https://github.com/agentclientprotocol/claude-agent-acp/commit/184b7df993c0c64df593188f15bb0e5206f3e6fb))
* reject requests that name a replayed subagent session with -32602 ([#1686](https://github.com/agentclientprotocol/claude-agent-acp/issues/1686)) ([3304ca7](https://github.com/agentclientprotocol/claude-agent-acp/commit/3304ca724c25c7258c837cc0394adb4111ea8987))
* report unusable Claude subscriptions as unauthenticated ([#1678](https://github.com/agentclientprotocol/claude-agent-acp/issues/1678)) ([a4f0f78](https://github.com/agentclientprotocol/claude-agent-acp/commit/a4f0f78bb31539005d0d54ab69f7e28f91443b14))
* send a replayed subagent's configuration after the replay, not inside it ([#1685](https://github.com/agentclientprotocol/claude-agent-acp/issues/1685)) ([6a760cb](https://github.com/agentclientprotocol/claude-agent-acp/commit/6a760cbca64adc72634274088914e99a51da084a))
* show readable titles for MCP tool calls ([#1674](https://github.com/agentclientprotocol/claude-agent-acp/issues/1674)) ([80440d8](https://github.com/agentclientprotocol/claude-agent-acp/commit/80440d8b8294f9d4cd086d7cba39c716107657f0))
* update to @agentclientprotocol/sdk 2.9.0 ([#1687](https://github.com/agentclientprotocol/claude-agent-acp/issues/1687)) ([022ff53](https://github.com/agentclientprotocol/claude-agent-acp/commit/022ff532449371198a0d715a921578e27c101532))
* update to @agentclientprotocol/sdk 2.9.1 ([#1690](https://github.com/agentclientprotocol/claude-agent-acp/issues/1690)) ([85a0d6c](https://github.com/agentclientprotocol/claude-agent-acp/commit/85a0d6c6f111119855b0e199801a9f71b60f50bf))
* update to @anthropic-ai/claude-agent-sdk 0.3.330 ([#1689](https://github.com/agentclientprotocol/claude-agent-acp/issues/1689)) ([6d9e276](https://github.com/agentclientprotocol/claude-agent-acp/commit/6d9e2766c74dcd9ccd5c5a83b8523b65c234041f))
## [0.109.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.1...v0.109.0) (2026-11-19)
### Features
* announce session cursors on v2 and fork at a cursor ([#1658](https://github.com/agentclientprotocol/claude-agent-acp/issues/1658)) ([5075d2e](https://github.com/agentclientprotocol/claude-agent-acp/commit/5075d2e0dffed68c4c1417d67c1c1e3ed43e6549))
* insert one message per idempotencyKey on v2 session/prompt ([#1657](https://github.com/agentclientprotocol/claude-agent-acp/issues/1657)) ([1c0792e](https://github.com/agentclientprotocol/claude-agent-acp/commit/1c0792ea8cbdfb96ac2afb1f675e4309446d0e5c))
* order config options as model, effort, fast, ultracode, mode, agent ([#1666](https://github.com/agentclientprotocol/claude-agent-acp/issues/1666)) ([f31da7f](https://github.com/agentclientprotocol/claude-agent-acp/commit/f31da7f9f5264eb2b57fbda577ac35141eb530c8))
* report Fast mode in the speed config option category ([#1659](https://github.com/agentclientprotocol/claude-agent-acp/issues/1659)) ([8990c24](https://github.com/agentclientprotocol/claude-agent-acp/commit/8990c2441d3d45cb4781cd81316b3ffbafee85ee))
* send the predicted next prompt as prompt_suggestions_update ([#1660](https://github.com/agentclientprotocol/claude-agent-acp/issues/1660)) ([f20ed1d](https://github.com/agentclientprotocol/claude-agent-acp/commit/f20ed1d96ac786af36b6bee3b4d5925a85b6d7ae))
### Bug Fixes
* send a session's settings to Claude Code over stdin ([#1669](https://github.com/agentclientprotocol/claude-agent-acp/issues/1669)) ([a768a9f](https://github.com/agentclientprotocol/claude-agent-acp/commit/a768a9f50c65b66b9f2d5806909a1db643fe3b6e))
* update to @anthropic-ai/claude-agent-sdk 0.3.328 ([#1668](https://github.com/agentclientprotocol/claude-agent-acp/issues/1668)) ([6e30711](https://github.com/agentclientprotocol/claude-agent-acp/commit/6e307116d461af22fb5d42eb4b8fbdb3643c6d6c))
## [0.108.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.0...v0.108.1) (2026-11-18)
### Bug Fixes
* answer -32602 on v1 for a request that names a subagent's session ([#1656](https://github.com/agentclientprotocol/claude-agent-acp/issues/1656)) ([253cd84](https://github.com/agentclientprotocol/claude-agent-acp/commit/253cd84ed84efd38fd9d90faaf954690d1610677))
* close a server tool call whose reply Claude Code gave up on, once its next reply starts ([#1604](https://github.com/agentclientprotocol/claude-agent-acp/issues/1604)) ([3205f0b](https://github.com/agentclientprotocol/claude-agent-acp/commit/3205f0bf0211f9346dad8583944f007bd0ef73c2))
* end a v1 turn at its result for a client in the subagents RFD form ([#1603](https://github.com/agentclientprotocol/claude-agent-acp/issues/1603)) ([c4b64f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/c4b64f628d1fad37ed1d56016b91eefc59df5052))
* reject session setup for an incompatible model provider ([#1506](https://github.com/agentclientprotocol/claude-agent-acp/issues/1506)) ([90070d6](https://github.com/agentclientprotocol/claude-agent-acp/commit/90070d6cbf29f5425e4e08828552f91493dd3e59))
* start a session without an MCP-over-ACP server whose local endpoint cannot open ([#1653](https://github.com/agentclientprotocol/claude-agent-acp/issues/1653)) ([96dd2bb](https://github.com/agentclientprotocol/claude-agent-acp/commit/96dd2bb10d838aeb39d75bb0cfde1c7b4eae958a)), closes [#1651](https://github.com/agentclientprotocol/claude-agent-acp/issues/1651)
* update to @agentclientprotocol/sdk 2.8.0 ([#1655](https://github.com/agentclientprotocol/claude-agent-acp/issues/1655)) ([b6167a8](https://github.com/agentclientprotocol/claude-agent-acp/commit/b6167a82dba9864a13dad31a7cad151704badf5e))
## [0.108.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.3...v0.108.0) (2026-11-17)
### Features
* stream the output of foreground Bash commands ([#1587](https://github.com/agentclientprotocol/claude-agent-acp/issues/1587)) ([378e85d](https://github.com/agentclientprotocol/claude-agent-acp/commit/378e85d06027f5fa1802e94535548747a0feccc9))
* support MCP servers that the client serves over the ACP connection (MCP-over-ACP) ([#1645](https://github.com/agentclientprotocol/claude-agent-acp/issues/1645)) ([20aeb46](https://github.com/agentclientprotocol/claude-agent-acp/commit/20aeb46ecedc60fef26ca8b1439b37e3bbd9b27a))
### Bug Fixes
* an autonomous result naming the original prompt must not end a steered turn early ([#1451](https://github.com/agentclientprotocol/claude-agent-acp/issues/1451)) ([edab713](https://github.com/agentclientprotocol/claude-agent-acp/commit/edab7135028d83efaeaa38d0f8efe62ea7ddf203))
* do not count a confirmWithUser question as an unfinished tool call ([#1644](https://github.com/agentclientprotocol/claude-agent-acp/issues/1644)) ([bcd3cda](https://github.com/agentclientprotocol/claude-agent-acp/commit/bcd3cdad35e4356247303870ac3137675e401227))
* handle invalid file paths in tool reports ([#1419](https://github.com/agentclientprotocol/claude-agent-acp/issues/1419)) ([0073280](https://github.com/agentclientprotocol/claude-agent-acp/commit/0073280b977a69934fb56670943d1ef42e7b687e))
* keep a workflow agent's tool call out of the turn's unfinished tools ([#1638](https://github.com/agentclientprotocol/claude-agent-acp/issues/1638)) ([451bc04](https://github.com/agentclientprotocol/claude-agent-acp/commit/451bc04ae022ef02473bdd92740cf19d8ceb5f3c))
* offer clearing the context on plan approval only when Claude Code's setting is on ([#1627](https://github.com/agentclientprotocol/claude-agent-acp/issues/1627)) ([9d71d12](https://github.com/agentclientprotocol/claude-agent-acp/commit/9d71d12336c392c28967c600f8409841deaab7e0))
* send MCP servers to Claude Code over stdin, not on its command line ([#1647](https://github.com/agentclientprotocol/claude-agent-acp/issues/1647)) ([c4dd80d](https://github.com/agentclientprotocol/claude-agent-acp/commit/c4dd80d7392b035f331b50bfdd802cfb3e144d37))
* update to @anthropic-ai/claude-agent-sdk 0.3.326 ([#1646](https://github.com/agentclientprotocol/claude-agent-acp/issues/1646)) ([4a07639](https://github.com/agentclientprotocol/claude-agent-acp/commit/4a076397c6e785a8dd9166e8ea1df14fe17c52ed))
## [0.107.3](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.2...v0.107.3) (2026-11-16)
### Bug Fixes
* allow Claude Enterprise accounts under --hide-claude-auth ([#1641](https://github.com/agentclientprotocol/claude-agent-acp/issues/1641)) ([be2219c](https://github.com/agentclientprotocol/claude-agent-acp/commit/be2219cef1f5b2b93129d5eef4b80574f57bdb1b))
* pass a model id the picker does not list to Claude Code ([#1630](https://github.com/agentclientprotocol/claude-agent-acp/issues/1630)) ([dc769c1](https://github.com/agentclientprotocol/claude-agent-acp/commit/dc769c132cacc8bbc7aff0d512e5ab587a1802e3))
## [0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2) (2026-11-16)
### Bug Fixes
* end the turn task of a cycle that has no turn to claim its result ([#1622](https://github.com/agentclientprotocol/claude-agent-acp/issues/1622)) ([8de4981](https://github.com/agentclientprotocol/claude-agent-acp/commit/8de49818f1172c5187496a736f721dc6d2ba3fec))
* keep Fast mode on when it is turned on after a model switch or mid-turn ([#1637](https://github.com/agentclientprotocol/claude-agent-acp/issues/1637)) ([81650db](https://github.com/agentclientprotocol/claude-agent-acp/commit/81650db3d3ca6f7b640fd5e1bbb5e1ff45f62fb7))
* list a live Monitor whose task Claude Code reports as local_bash ([#1607](https://github.com/agentclientprotocol/claude-agent-acp/issues/1607)) ([41417f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/41417f6eeeb5010c0eb439e256032cd7e9a44e37))
* read the Claude Code stream after a query restart, not at the next prompt ([#1636](https://github.com/agentclientprotocol/claude-agent-acp/issues/1636)) ([c03b66c](https://github.com/agentclientprotocol/claude-agent-acp/commit/c03b66cc9f1aa6aa5e56668ac05e5a7f48418850))
* read the Claude Code stream after every session setup, not at the first prompt ([#1623](https://github.com/agentclientprotocol/claude-agent-acp/issues/1623)) ([7d9e1f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/7d9e1f6135b2c85cd8bdd0e76bc2bcf00795e6c9))
* reject the SDK no-token sentinel in auth guards ([#1609](https://github.com/agentclientprotocol/claude-agent-acp/issues/1609)) ([c203b91](https://github.com/agentclientprotocol/claude-agent-acp/commit/c203b919ecca8a58e11bebb72274a5a203653d88))
* update to @anthropic-ai/claude-agent-sdk 0.3.325 ([#1634](https://github.com/agentclientprotocol/claude-agent-acp/issues/1634)) ([db54135](https://github.com/agentclientprotocol/claude-agent-acp/commit/db5413513cbe58c045885e6bb015abfdb76be524))
## [0.107.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.0...v0.107.1) (2026-11-16)
### Bug Fixes
* end a v2 turn once when Claude Code folds a prompt into it ([#1618](https://github.com/agentclientprotocol/claude-agent-acp/issues/1618)) ([7e857d5](https://github.com/agentclientprotocol/claude-agent-acp/commit/7e857d59ec777356969ab615af83eef02ac43e59))
* resolve a model preference without a version to the newest listed row ([#1633](https://github.com/agentclientprotocol/claude-agent-acp/issues/1633)) ([e73d790](https://github.com/agentclientprotocol/claude-agent-acp/commit/e73d7909ce0295bfa351da49940e067da02ea0e4))
* send v2 terminal output with CR LF, as a PTY would ([#1632](https://github.com/agentclientprotocol/claude-agent-acp/issues/1632)) ([29dde36](https://github.com/agentclientprotocol/claude-agent-acp/commit/29dde3633a13cb9f32fca6c1578a9d95b9e6c08e))
* update to @agentclientprotocol/sdk 2.7.0 ([#1629](https://github.com/agentclientprotocol/claude-agent-acp/issues/1629)) ([b1c1987](https://github.com/agentclientprotocol/claude-agent-acp/commit/b1c198754d1cb4e086de6c6bc6a9659ae3351a0a))
## [0.107.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.106.0...v0.107.0) (2026-11-13)
### Features
* report the turn's rate limit in rate-limit failure errors ([#1610](https://github.com/agentclientprotocol/claude-agent-acp/issues/1610)) ([4f474d6](https://github.com/agentclientprotocol/claude-agent-acp/commit/4f474d655b88a075ec7d0124d45cafa0f5565af7))
* report unknown subagent state at a conversation reset and reference children from tool calls ([#1608](https://github.com/agentclientprotocol/claude-agent-acp/issues/1608)) ([4804917](https://github.com/agentclientprotocol/claude-agent-acp/commit/4804917a6fa7050490d1d62c6689e78c231c752a))
* say the cause of an api retry in the AIR warning details ([#1594](https://github.com/agentclientprotocol/claude-agent-acp/issues/1594)) ([4f690e1](https://github.com/agentclientprotocol/claude-agent-acp/commit/4f690e129c01f22e2c2a87e0e0a3c5b503241f15))
### Bug Fixes
* assume a 1M context window until Claude Code reports it ([#1613](https://github.com/agentclientprotocol/claude-agent-acp/issues/1613)) ([9619805](https://github.com/agentclientprotocol/claude-agent-acp/commit/96198053067cf4d7b7440c52036174ad4f54183e))
* end the tool calls of a response that Claude Code took back ([#1616](https://github.com/agentclientprotocol/claude-agent-acp/issues/1616)) ([21f3e04](https://github.com/agentclientprotocol/claude-agent-acp/commit/21f3e0430b693e6b04750ab3018e1eaf726af173))
* explain why Claude Code turns Fast mode off ([#1602](https://github.com/agentclientprotocol/claude-agent-acp/issues/1602)) ([c331e17](https://github.com/agentclientprotocol/claude-agent-acp/commit/c331e178a5df47448be1a3ed2f71270c3aad2433))
* follow Claude Code's rule for managed deniedModels in the model picker ([#1615](https://github.com/agentclientprotocol/claude-agent-acp/issues/1615)) ([c78bcc7](https://github.com/agentclientprotocol/claude-agent-acp/commit/c78bcc7f417fc8d3da66f51021b43f4528826ec0))
* log a managed policy source that did not load ([#1614](https://github.com/agentclientprotocol/claude-agent-acp/issues/1614)) ([ca46b41](https://github.com/agentclientprotocol/claude-agent-acp/commit/ca46b412f51cdb7b5a303c751f5d48c216700887))
* report a mid-turn API error notice where the response broke off ([#1599](https://github.com/agentclientprotocol/claude-agent-acp/issues/1599)) ([4df6999](https://github.com/agentclientprotocol/claude-agent-acp/commit/4df69996ca74adff6c42fc60e4b9b742f2d3fdf5))
* say why the login failed in the v2 authRequired error ([#1598](https://github.com/agentclientprotocol/claude-agent-acp/issues/1598)) ([ecd066c](https://github.com/agentclientprotocol/claude-agent-acp/commit/ecd066c8700955e3456dd9387e6b8317f024e26c))
* update to @anthropic-ai/claude-agent-sdk 0.3.323 ([#1612](https://github.com/agentclientprotocol/claude-agent-acp/issues/1612)) ([ddee24e](https://github.com/agentclientprotocol/claude-agent-acp/commit/ddee24ef8fd0abc0401fb32d567914030fbf6944))
## [0.106.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.105.0...v0.106.0) (2026-11-10)

120
README.md
View File

@@ -16,9 +16,11 @@ This tool implements an ACP agent by using the official [Claude Agent SDK](https
- Nested subagent transcripts
- Interactive (and background) terminals
- Custom [Slash commands](https://docs.anthropic.com/en/docs/claude-code/slash-commands)
- Client MCP servers
- 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"`). Where an organization's managed settings (`disableSideloadFlags`) keep them out, a session starts without them and says so in a notice
- 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
- `/plugin` (aliases `/plugins`, `/marketplace`) in the chat: the adapter runs `claude plugin …` for install, uninstall, enable, disable, update, and list, and `marketplace add|list|remove|update`, because Claude Code refuses `/plugin` in SDK mode, then reloads the session's plugins. It is not available in remote (`sdk-url`) sessions
- 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)
@@ -46,6 +48,10 @@ Claude CLI (`claude`) it runs. Keep them in the same directory; a symlink to
instead, set `CLAUDE_CODE_EXECUTABLE`. On Alpine, install `libgcc` and
`libstdc++` first.
A CLI named with `CLAUDE_CODE_EXECUTABLE` gets a session's MCP servers on its
command line, where other users of the machine can read their `env` and
`headers`. The CLI that comes with the adapter gets them over stdin.
To build one for your machine (needs [Bun](https://bun.sh)) and check it:
```sh
@@ -53,97 +59,43 @@ npm run build:binary
npm run smoke:binary # add `-- --full` to drive a real session; needs a Claude login
```
### Subagent sessions
### ACP v2 (Preview)
A client that declares `clientCapabilities.subagents`, other than JetBrains AIR, gets each Agent or
Task subagent as its own child session, following the [subagents RFD](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/docs/rfds/subagents.mdx):
- `subagent_update` on the parent announces the child before any of its traffic, with the
parent's `title` and `description` for it, and reports its work state: `running`,
`requires_action` while one of its requests is open (and `running` again when the last one ends,
unless a cancel withdrew it: the child is stopping then), and `idle` when its work ends, with
`end_turn` or `cancelled` when the SDK gives the reason. A failure is `idle` with the `error`
stop reason and the SDK's error text as its `error`. The child keeps its session for every
delegation to it.
- A child that runs outside its parent's working directory, such as an Agent call with
`isolation: "worktree"`, gets its `cwd` on `subagent_update` before its first tool call. The
adapter takes it from the `cwd` of the child's own hooks: its SubagentStart hook runs before its
first model request. It sends `cwd: null` when the child is back in its parent's directory. A
child in its parent's directory gets no `cwd`, and no child gets `additionalDirectories`: Claude
Code gives a subagent the session's additional directories, so it inherits them. A replay
announces a child with the `cwd` that its transcript recorded, and clears it after the response
when that directory no longer exists.
- Session messages replace the Agent or Task call that launches the child, which its parent is
not shown:
- The launch's prompt is a `session_message` in both transcripts: the parent's outgoing view and
the child's incoming one. Both use the launch's tool use id, and each names the other with the
draft RFD's `recipientMessageId` and `senderMessageId`.
- A foreground child's answer, from the launch's result, is the child's `session_message` to
the parent. In Claude Code's hand-back mode, the child's `SubagentHandback` call is its
message to the parent instead, in both transcripts and linked the same way.
- A launch whose child is never exposed is shown as a tool call after all, with its final
status.
- The message of a SendMessage call that resumes the child is a `session_message` in the child's
transcript. The SendMessage call stays a tool call of the session that made it.
- `session/cancel` on the parent interrupts Claude Code, which stops the foreground children that
the turn waits on. Background children keep running, as the RFD prefers; a client stops one with
its own `cancel`. Each stopped child reports `idle` with `cancelled` from Claude Code's own
events, and its open requests are withdrawn. The adapter ends no child at a cancel itself, so a
child that keeps running keeps its open requests and its open tool calls. To spare background
children, the adapter declares the SDK option `perTaskStopAffordance`, which a client can turn
off in `_meta.claudeCode.options`. That option spares background workflows too, which a client
cannot stop, so the adapter stops them after the interrupt, as Claude Code did without it.
Background commands keep running after a cancel either way. A tool call of a stopped child that Claude Code reports no
result for, such as the command it was running, ends in the child's session before the cancelled
prompt resolves. When Claude Code stops a background child after that, or while no prompt runs,
the tool call ends right after the child reports `idle`. A child that still runs when Claude Code
exits is `idle` with no stop reason.
- A child whose parent is not yet known when it ends is not exposed, since the RFD forbids
guessing its parent.
- A replay restores each child under its live session id, from its own transcript, with the same
session messages as live, and its end is an `idle` before the response.
A launch without Claude Code's metadata file for the child stays an ordinary tool call of the
parent, and a notice, for a client that takes notices, says that subagent history is missing.
- After a load or resume, with or without replay, a SendMessage that resumes an agent from before
it runs that agent in its session from before. Before the agent's traffic, each of its ancestors
that the client was not told about in this connection is announced, parent before child and
with no work state, as the RFD requires. An agent whose launch the session's history does not
record stays unexposed.
- Each running child is announced with the `cancel` capability. `session/cancel` with the child's
session id stops that child's current work, through the SDK's `Query.stopTask`, and not its
parent's: Claude Code also stops the foreground children it waits on, and the parent's turn goes
on. Each stopped child reports `idle` with `cancelled` from Claude Code's own events, and its
requests that the stop withdraws report no `running` first. A replayed child, which no longer
runs, gets no capabilities. A client cannot prompt or otherwise change a child.
An [ACP v2](#experimental-acp-v2) client gets the same without declaring anything, since subagents
are part of v2's baseline. Each child also reports its work state as its own `state_update`, right
after the parent's copy.
JetBrains AIR keeps the earlier draft of the RFD (`subagent_spawned`, `subagent_state_update`),
which it enables with `nativeSubagentSessions` in `_meta.jetbrains.air.capabilities`. See
[AIR extensions](docs/air-extensions.md#native-subagent-sessions).
Without either signal, Agent and Task stay ordinary tool calls and child interactions stay on the
root session. Clients that use the historical `_meta["subagent-transcript"]` capability or the
`forwardSubagentText` session option retain the flattened child transcript.
### Experimental ACP v2
The adapter also serves the [draft ACP v2](https://agentclientprotocol.com/protocol/v2/overview):
a client that asks for protocol version 2 or later in `initialize` gets v2, and every other client
gets v1. The draft can still change, and this surface changes with it.
The adapter also serves [ACP v2](https://agentclientprotocol.com/protocol/v2/overview), which is in
Preview: a client that asks for protocol version 2 or later in `initialize` gets v2, and every other
client gets v1. v2 is not frozen yet, and this surface changes with it.
`CLAUDE_AGENT_ACP_PROTOCOL` limits the adapter to one version. With `v1`, a client that asks
for v2 is negotiated down to v1. With `v2`, the adapter rejects the `initialize` of a v1 client.
`auto`, the default, serves both.
On v2 the adapter serves the session baseline (`session/new`, `session/list`, `session/resume`
with replay, `session/close`, `session/prompt`, `session/cancel`), `session/delete`,
`session/fork`, `session/status`, `session/options` (with initial `configOptions` on `session/new` and
`session/resume`), `session/set_title`, additional directories, config options (the mode is one), plans, notices,
with replay, which `replay_complete` ends, `session/close`, `session/prompt`, `session/cancel`), `session/delete`,
`session/fork`, `session/status`, `session/options` (with initial `configOptions` on `session/new`,
`session/resume` and `session/fork`), `session/set_title`, additional directories, config options (the mode is one), plans, notices,
compaction, display terminals for commands, permission requests, elicitation, providers, auth, and
[subagents](#subagent-sessions). Steering is v1 only for now.
[subagents](docs/subagent-sessions.md). Steering is v1 only for now.
On v2, the `command` of a stdio MCP server must be an absolute path, such as `/usr/local/bin/npx`.
`session/new`, `session/resume` and `session/fork` fail with `-32602` for a relative one, such as
`npx`. A v1 client can still send one.
`session/prompt` takes an `idempotencyKey`: a prompt that a client sends again with the same key
is inserted once, and the retry gets the first `messageId`. The key is known for as long as Claude
Code stores the message, also after a restart. A prompt that Claude Code does not store, such as a
local command, keeps its key until `session/close` or the end of the connection.
The adapter announces a session cursor (`cursor_update`) before each user message that follows
another entry of the conversation, live and in a replay. `session/fork` with its `cursorId` copies
the history before that message, and fails with `-32602` for any other `cursorId`. A v1 client gets
cursors only when it declares `clientCapabilities.session.cursors`. A v1 replay (`session/load`)
anchors each cursor `before` its replayed user message. A live v1 prompt is not reported to the
client that sent it, so its cursor is anchored `after` the last agent message, thought, tool call or
compaction before it, with the same `cursorId` that a later replay issues. A session that was
resumed without a replay has no such entity, so its live prompts get no cursor until it replays.
When a v1 turn reports no entity (it was cancelled or failed before any output, or it was a slash
command), the next prompt's cursor has the same `after <entity>` anchor as the previous prompt's
cursor, with a different `cursorId`: the client uses the latest.
v2 is served by the v2 agent in `src/v2/`, which runs straight on Claude
Code instead of translating to v1. A v2 client that declares JetBrains AIR

View File

@@ -22,6 +22,7 @@ It describes only this adapter.
- [Goal](#goal)
- [Predicted follow-up prompt](#predicted-follow-up-prompt)
- [Recommended config values](#recommended-config-values)
- [Model reasoning efforts](#model-reasoning-efforts)
- [Async tasks](#async-tasks)
- [Agent file-change report](#agent-file-change-report)
- [Session failure](#session-failure)
@@ -32,6 +33,7 @@ It describes only this adapter.
- [Question custom answers](#question-custom-answers)
- [Load replay end](#load-replay-end)
- [Session fork point](#session-fork-point)
- [Session rewind](#session-rewind)
- [Presentation hints](#presentation-hints)
- [Removed keys](#removed-keys)
@@ -147,11 +149,17 @@ The response to a client that is not AIR has no `_meta.jetbrains` key.
### ACP v2
A busy `session/prompt` steers the current turn on ACP v2.
It waits while a root or child permission request or elicitation is open.
The adapter does not advertise `claudeCode.promptQueueing` on v2.
On ACP v1, an ordinary `session/prompt` queues behind the current turn.
The separate `_session/steering` request steers that turn.
The v2 core (`src/v2/`) serves an AIR client only the extensions that ACP v2 does not cover.
Its `initialize` response lists `agentFileChangeReport` and `recommendedValue`.
It also serves the [permission presentation](#permission-presentation), the [question custom answers](#question-custom-answers), the [predicted follow-up prompt](#predicted-follow-up-prompt), and [load replay end](#load-replay-end).
The [agent file-change report](#agent-file-change-report) goes out at the end of the turn that serves the prompt, before the turn's idle `state_update`, because a v2 `session/prompt` is answered when Claude Code takes the prompt in.
ACP v2 covers subagents, background work, file plans, patches, compaction, the system prompt, and turn failures itself, so the v2 core serves no `nativeSubagentSessions`, `backgroundSubagents`, `asyncTasks`, `planFile`, `diffPatch`, `contextCompaction`, `customInstructions`, or `sessionFailure`.
ACP v2 covers subagents, background work, plans, patches, compaction, the system prompt, and turn failures itself, so the v2 core serves no `nativeSubagentSessions`, `backgroundSubagents`, `asyncTasks`, `planFile`, `diffPatch`, `contextCompaction`, `customInstructions`, or `sessionFailure`.
It does not serve the [tool call contract](#tool-call-contract) yet.
### Capabilities
@@ -172,6 +180,7 @@ It does not serve the [tool call contract](#tool-call-contract) yet.
| `sessionRename` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that it supports `_session/rename`. | [Rename](#rename) |
| `sessionListSubscribe` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that it supports `_session/list/subscribe`. | [List subscription](#list-subscription) |
| `sessionWorktrees` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that rows carry `agentWorktree` for a worktree Claude Code made. | [List response](#list-response) |
| `sessionRewind` | on request | Accepts `_session/rewind`, and announces its session cursors with the `rewind` capability. | [Session rewind](#session-rewind) |
| `loadReplayEnd` | no | Sends one `session_info_update` after the whole history replay of a loaded session. | [Load replay end](#load-replay-end) |
| `rawInputRendering` | no | Sends no display copy of readable input in `content`. The client renders `rawInput`. | [Tool call contract](#tool-call-contract) |
@@ -195,6 +204,7 @@ The adapter sends these keys only to an AIR client. "AIR" in the Gate column mea
| `diffPatch` | tool call and permission request `content[]` of type `diff`, `_meta.jetbrains.air` | `{version: 1, format: "git_patch", text}` | `diffPatch` |
| `permission` | `session/request_permission` request `_meta.jetbrains.air` | `{version: 1, title, description?, defaultToNo?}` | AIR |
| `recommendedValue` | `model` and effort config options, `_meta.jetbrains.air` | option value string | `recommendedValue` |
| `reasoningEfforts` | entry of the `model` config option, `_meta.jetbrains.air` | `{values: string[], recommended: string}` | AIR |
| `asyncTasks` | Bash `tool_call_update._meta.jetbrains.air` | `{backgrounded: true}` | `asyncTasks` |
| `agentFileChangeReportRequest` | `session/prompt` request `_meta.jetbrains.air` (client to agent) | `{version: 1, requestId}` | `agentFileChangeReport` |
| `agentFileChangeReport` | `session_info_update._meta.jetbrains.air` | report object | `agentFileChangeReport` |
@@ -205,6 +215,7 @@ The adapter sends these keys only to an AIR client. "AIR" in the Gate column mea
| `mcp` | MCP tool call `_meta.jetbrains.air` | `{server, tool}` | AIR |
| `contextCompaction` | compaction tool call or `compaction_update`, `_meta.jetbrains.air` | `{version: 1, trigger?, preTokens?, postTokens?, durationMs?, error?}` | AIR |
| `customAnswer` | elicitation schema property `_meta.jetbrains.air` | `{questionId, isCustomAnswer: true}` | AIR, when the client supports form elicitation |
| `customAnswerFields` | elicitation request `_meta.jetbrains.air` | companion field keys | AIR, when the client supports form elicitation |
| `kind` | session mode `_meta.jetbrains.air` and mode config option value `_meta.jetbrains.air` | `standard`, `plan`, `auto_review`, or `full_access` | AIR |
| `kind` | available command `_meta.jetbrains.air` of a skill | `skill` | AIR, when the skill's `SKILL.md` is found; not for a built-in command or an MCP prompt |
| `skillPath` | available command `_meta.jetbrains.air` of a skill | absolute path of the skill's `SKILL.md` | AIR, together with `kind: "skill"` |
@@ -228,7 +239,9 @@ The adapter keeps them where they are.
## Auth source display
The connection-scoped `_auth/status_update` continues to report agent-owned authentication, not client-owned `providers/set` routing. The adapter also reports the same identity through the ACP `auth/status` method and `auth/status_update` notification (advertised as `auth.status`), with `kind`, `detail` and `plan` under the account's `_meta.claudeCode`. The account's `description` carries the `detail` too, e.g. `label: "Anthropic API key"` with `description: "ANTHROPIC_API_KEY"`. Each notification is sent when its own payload changed. `auth/status` answers with the identity last reported and starts a new read, whose change arrives as a notification. When the active key source is `apiKeyHelper`, the adapter reads the effective helper command through SDK `resolveSettings` / the session's `SettingsManager`, including programmatic settings overrides.
The connection-scoped `_auth/status_update` reports agent-owned authentication, not client-owned `providers/set` routing. The adapter also reports that login through the ACP `auth/status` method and `auth/status_update` notification (advertised as `auth.status`). Under `--hide-claude-auth`, a subscription the integration cannot use is `unauthenticated`, with no active account; the legacy notification still describes the stored login. Enterprise subscriptions, API keys, and setup tokens remain usable.
For a reported account, `_meta.claudeCode` carries `kind`, `detail` and `plan`. The account's `description` carries the `detail` too, e.g. `label: "Anthropic API key"` with `description: "ANTHROPIC_API_KEY"`. Each notification is sent when its own payload changed. `auth/status` answers with the identity last reported and starts a new read, whose change arrives as a notification. When the active key source is `apiKeyHelper`, the adapter reads the effective helper command through SDK `resolveSettings` / the session's `SettingsManager`, including programmatic settings overrides.
A command containing the whole word `central` and the word sequence `proxy start` is displayed as:
@@ -344,11 +357,11 @@ For every tool, a client that is not AIR also gets these upstream fields:
| `Skill` | `kind: other`, `title: "Load skill: <name>"`. | `_meta.jetbrains.air.skill`. | none |
| `TodoWrite`, `TaskCreate`, `TaskUpdate`, `TaskList`, `TaskGet` | The stream reports them as a standard `plan` with entries. Only a permission request shows them as a tool call. | A plan that repeats the previous plan is not sent. | Every plan goes out. |
| `ReportFindings` | `kind: think`, `title: "Report <n> findings"`. | With `rawInputRendering`, no copy of the findings in `content`. | none |
| MCP tools (`mcp__*`) and other tools | `kind: other`, `title` is the tool name. The result text goes to `content`. | `_meta.is_mcp_tool_call` for MCP, and `_meta.jetbrains.air.mcp = {server, tool}`. | none |
| MCP tools (`mcp__*`) and other tools | `kind: other`, `title` is `server: tool` for a complete MCP name, otherwise the tool name. Result text goes to `content`. | `_meta.is_mcp_tool_call` for MCP, and `_meta.jetbrains.air.mcp = {server, tool}`. | none |
| Context compaction | `compaction_update` when the client declares `session.compaction`. Otherwise a synthetic tool call. | Both forms carry `_meta.jetbrains.air.contextCompaction`. | See [Context compaction](#context-compaction). |
| Background work that is not a subagent | none | With `asyncTasks`, async task updates. | none |
`_meta.jetbrains.air.mcp` comes from the tool name `mcp__<server>__<tool>`, on `tool_call` and on a `tool_call_update` that changes it.
The standard `name` stays `mcp__<server>__<tool>`. AIR also gets those parts in `_meta.jetbrains.air.mcp` on `tool_call` and on a `tool_call_update` that changes it.
`server` is the part up to the next `__`. `tool` is the whole rest and can contain `__`, as in Claude Code.
A name that does not split (`mcp__x`) gets no `mcp` key, and `_meta.is_mcp_tool_call` still marks it.
@@ -701,7 +714,7 @@ When `matchedAskRule` is present, the adapter offers no persistent choice. A con
| WebFetch | One-time allow; a generated `domain:<hostname>` local rule; reject. |
| Skill | One-time allow; exact skill and optional `prefix:*` local rules; reject. |
| EnterPlanMode | Enter plan mode once, or reject and continue. |
| ExitPlanMode | One keep-context and one clear-context elevated mode (`auto` before bypass before accept edits), manual approval, or reject. |
| ExitPlanMode | One keep-context elevated mode, one clear-context mode (with `showClearContextOnPlanAccept` on), manual approval, or reject. |
| SandboxNetworkAccess | One-time allow; the exact SDK host rule when representable; reject. |
| Computer Use MCP | One-time allow; an exact representable SDK allow suggestion; reject. |
| MCP | One-time allow; an exact representable SDK allow suggestion for that tool; reject. |
@@ -726,7 +739,9 @@ A host removes `Bypass permissions` with `_meta.claudeCode.options.allowDangerou
A `bypassPermissions` settings default then falls back to `default`.
`ExitPlanMode` offers one elevated keep-context choice by priority: `auto`, then `bypassPermissions`, then `acceptEdits`.
A non-empty plan also gets one clear-context choice with the same priority.
When Claude Code's `showClearContextOnPlanAccept` setting is on, a non-empty plan also gets one clear-context choice with the same priority.
The setting is off by default, as in Claude Code.
The adapter reads it as Claude Code does: managed settings first, then the `settings` option of the session, then the user, project, and local settings files.
After that choice, the adapter stops the old private Claude query and hides that internal rejection.
It starts a new private query under the same ACP session.
It continues the turn with `Implement the following plan:` and the complete plan.
@@ -857,8 +872,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
{
@@ -867,9 +883,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.
@@ -880,6 +907,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`.
@@ -963,6 +995,58 @@ RUN_INTEGRATION_TESTS=true npx vitest run src/tests/model-presentation.test.ts
Review the changes to the Opus entries and labels before you update the version guard.
The live test only initializes the SDK. It sends no model prompt.
## Model reasoning efforts
The `reasoningEfforts` key lets a client show the effort levels of a model before the client selects that model.
The effort option shows only the levels of the current model.
### Activation
The adapter sends the key to every AIR client.
The key has no capability, because it only adds data.
A client that is not AIR gets no `reasoningEfforts`.
The key does not depend on `recommendedValue`.
### Entry metadata
Each entry of the `model` option gets the levels of its model at `_meta.jetbrains.air.reasoningEfforts`:
```json
{
"value": "claude-opus-5-5",
"name": "Opus 5.5",
"_meta": {
"jetbrains": {
"air": {
"version": 1,
"reasoningEfforts": {
"values": ["low", "medium", "high", "xhigh", "max"],
"recommended": "medium"
}
}
}
}
}
```
`values` are the `supportedEffortLevels` of the SDK `ModelInfo` of the entry, in the SDK order.
The effort option lists the same levels in the same order.
`values` never contain the `default` row of the effort option.
`recommended` is `medium` when the model offers it, else the first level.
The SDK names no recommended effort, so the adapter uses the rule of the effort option.
For the current model, `recommended` is the `recommendedValue` of the effort option.
The adapter finds the `ModelInfo` of an entry by its value.
The `default` entry gets the levels of the listed model that its `resolvedModel` names.
When no listed model has that `resolvedModel`, the `default` entry gets no `reasoningEfforts`.
A running model that the picker does not list gets its own entry, with the same lookup.
A model without effort support, or with no levels, gets no `reasoningEfforts`.
The entries carry the metadata in each answer that carries config options, on ACP v1 and v2.
These are `session/new`, `session/load` on v1, `session/resume`, `session/fork`, `session/set_config_option`, and `config_option_update`.
The `model` option of a subagent's session has no `reasoningEfforts`.
## Async tasks
Claude can run work in the background, for example a backgrounded Bash command or a workflow.
@@ -1279,7 +1363,7 @@ A client without the capability gets the original transcript and no typed record
## Native subagent sessions
The adapter implements the draft [ACP subagent RFD](https://github.com/agentclientprotocol/agent-client-protocol/pull/1992).
The adapter implements ACP's [subagents](https://agentclientprotocol.com/protocol/v1/subagents).
This section covers only the AIR bridge.
- The canonical client field is `clientCapabilities.subagents: {}`.
@@ -1294,6 +1378,10 @@ This section covers only the AIR bridge.
The source is the `task_started` prompt, else the Agent or Task input `prompt`.
A resumed generation gets the SendMessage `message` text.
The field is absent when the adapter has no prompt. The adapter does not truncate it.
- A forked skill (`context: fork`, such as `/code-review`) is a child session too, without an Agent or Task call.
The parent of one that Claude runs with the Skill tool is the session that made the Skill call, which stays a tool call.
The parent of one that the user types is the root session.
Claude Code sends the output of a typed one only when the command ends: its `subagent_state_update` follows that output.
- Without either signal, Agent and Task stay ordinary tool calls. AIR gets `_meta.jetbrains.air.subagent: true` on them.
Child interactions stay on the root session.
- A client that uses the older `_meta["subagent-transcript"]` capability or the `forwardSubagentText` session option keeps the flat child transcript.
@@ -1643,7 +1731,7 @@ Claude Code sends the result of the turn when the main agent stops, also while s
### Hold without the capability
A client that does not declare `backgroundSubagents` gets the hold of issues #864 and #866.
A client that does not declare `backgroundSubagents` gets the hold of issues #864 and #866, unless it gets the RFD form of [subagent sessions](subagent-sessions.md).
The adapter keeps the `session/prompt` request open while a subagent that the turn started or resumed runs.
The subagent output, its permission requests and the followup summary of the model then go out inside the turn.
The turn ends at the followup result, at an `idle` with no live subagent, at `session/cancel`, or when the next prompt starts.
@@ -1672,7 +1760,7 @@ The request has no clear-context option, because the fresh query must continue a
"No, keep planning" stops only the followup cycle. There is no turn to end.
A prompt turn owns the request when the turn is active, or when Claude Code asks before the echo of its prompt.
Then the request has the clear-context option.
Then the request has the clear-context option, when `showClearContextOnPlanAccept` is on.
A turn that took over a followup cycle also owns the request of that cycle, and the accepted plan continues in that turn.
## Context compaction
@@ -1730,10 +1818,23 @@ For AIR, the companion field also carries the same value under the root key `_me
Released AIR versions read only that key.
A client that is not AIR gets neither key.
For AIR on both protocol versions, the request also lists the companion field keys in `_meta.jetbrains.air.customAnswerFields`:
```json
{ "jetbrains": { "air": { "version": 1, "customAnswerFields": ["question_0_custom"] } } }
```
The Kotlin ACP SDK property models do not retain `_meta`.
The TypeScript v2 schema supports property metadata.
AIR reads the request list to show the companion with its question.
The field keys and the response content stay the same in both versions.
A client that is not AIR gets no `customAnswerFields` key.
## Load replay end
ACP has no signal that the history replay of `session/load` is over, other than the response.
ACP v1 has no signal that the history replay of `session/load` is over, other than the response.
The adapter replays the transcript while the Claude Code CLI starts, so the history can arrive long before the response.
ACP v2 has the `replay_complete` update for this, which the adapter sends to every v2 client.
The client declares `loadReplayEnd` in its capabilities. The agent does not advertise it.
After the history replay of the loaded session, the agent then sends one more update for that session:
@@ -1751,7 +1852,7 @@ After the history replay of the loaded session, the agent then sends one more up
- The update has no `title` and no `updatedAt`. A `null` there would clear the value.
- It comes after every replayed update, the subagent history that the replay sends to the child sessions included, and before the `session/load` response.
- It comes also for an empty history.
- It comes for `session/load` of a new or an already live session, and for the ACP v2 `session/resume` with `replayFrom: {type: "start"}`.
- It comes for `session/load` of a new or an already live session, and for the ACP v2 `session/resume` with `replayFrom: {type: "start"}`. On v2 it comes right after the session's `replay_complete`, which marks the same point.
- It does not come when the replay stops or fails. The replay stops when the CLI start fails during the replay.
- It does not come for a live update, and it does not come to a client without the capability.
- The `session/load` can still fail after it, for example when the CLI start fails after the replay. The event means that the recorded history arrived whole. The client decides what to do with the failed load.
@@ -1791,6 +1892,48 @@ It adds this object to the `session/fork` request:
- With or without this object, the forked session runs once the response arrives, so the client can prompt it without `session/load` or `session/resume`.
A later load replays its history into it, and a later resume returns it. A load or resume with other settings (`cwd`, MCP servers, additional directories, or the session options in `_meta`) restarts it, as for any loaded session.
## Session rewind
AIR edits a user message by removing that message and everything after it from the provider's context, in the same session: same session id, no fork.
`_session/rewind` asks the agent for that, at a session cursor:
```json
{ "sessionId": "0f7c…", "cursorId": "before:<uuid of the user message>" }
```
The response is `{ "rewound": true }`, which means that the cut is live and persisted, or `{ "rewound": false, "reason": "<reason>" }` when the conversation was left as it was.
The client keeps its own history then.
- ACP v1 only. The agent advertises `sessionRewind` to a client that declares it, and then announces each `cursor_update` with the capabilities `{ "fork": {}, "rewind": {} }`, except a cursor whose resume point is before the newest compaction (`beforeCompaction`) and every cursor of a session whose context was cleared (`clearedContext`): those get `{ "fork": {} }`. Every other client gets `{ "fork": {} }` on all cursors, and the method is not found (`-32601`) for it. ACP v2 does not list `sessionRewind` and has no `_session/rewind`; it only honours a cut that v1 made.
- `cursorId` is one that the session announced with `rewind`: the cursor before a user message of its history. The first user message has no cursor, since Claude Code has no entry before it to resume at, so a client offers no edit for it.
- The adapter resumes the stored conversation of the session at the entry before the cursor's message (`resumeSessionAt`). The agent replaces its query with that resume and restores the model, mode, effort, agent and Fast mode as the user left them. Claude Code deletes nothing: the dropped entries stay in the transcript as an orphan branch, and the agent records the cut in `rewind.json` beside the session's `subagents/` directory before it replaces the query, and puts the file back as it was when the cut does not happen (`busy`, `backgroundWork` or `providerRefused` after the file was written). When putting it back fails, the request fails with an internal error instead of `rewound: false`: the rewind did not happen and its point could not be removed, so the next load of the session applies the cut. A failed cut then still resumes the conversation first, so the session can be prompted. A crash between the two leaves the point on disk: the next resume of the session applies the cut, and the client's next load replays the cut history.
- A live prompt is not reported to the client that sent it, so its cursor is anchored `after` the last entity the client holds. After a rewind it is the entity the client held before the removed message; if the agent holds no such record, the next prompt gets no cursor. When a turn reports no entity (it was cancelled or failed before any output, or it was a slash command), the next prompt's cursor has the same `after <entity>` anchor as the previous prompt's cursor, with a different `cursorId`: the client uses the latest.
- The cut also removes the cursors at and after it: the session no longer announces them, and a request that names one fails as an unknown cursor.
- The cut holds until the next prompt stores a branch from it. Until then, the agent applies `rewind.json` wherever it reads or resumes the session: a `session/load` (v1) or `session/resume` with a replay (v2) replays the history before the cut, with its cursors only; a restart of the query, a later load or resume, and a v2 resume continue at the cut; `session/fork` copies the history before it, also without a `cursorId`, and rejects a `cursorId` or `jetbrains.air.fork` message from the removed part with `-32602`. The first resume after that prompt removes the file. `session/options` neither reads nor writes it. When the cut cannot be prepared (the stored history or `rewind.json` cannot be read, or `rewind.json` is not a valid record), the load, resume, replay or fork fails with an internal error instead of using the whole conversation, and the client can retry; the point stays on disk.
- A rewind keeps the task list and the published session failures of the session. Its token totals start again, as they do after any restart of the query.
- No file change is reverted. The files stay as the removed turns left them.
- A prompt sent while the rewind runs waits for it, and runs on the rewound conversation.
| `reason` | When |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `busy` | Claude is working, a prompt is queued, Claude Code runs a cycle on its own, or a `/remote-control` command is in flight. AIR stops the turn before it sends the request. |
| `backgroundWork` | A background task or subagent runs. Closing the query would end it. |
| `beforeCompaction` | The message is before the newest compaction of the conversation: Claude Code resumes from that compaction on and finds no entry before it. |
| `clearedContext` | The session's context was cleared when a plan was accepted: the conversation went on in another Claude Code session. |
| `providerRefused` | Claude Code refused the cut, or the query could not restart with it. The agent resumed the conversation as it was, once, and the session can be prompted. |
| `persistFailed` | `rewind.json` could not be written. The conversation and the rewind point are unchanged: the query was not replaced. The transcript can gain the `last-prompt` line that any resume writes. |
When the removed message is the last user message, Claude Code also checks the removed range and refuses a cut that would remove what the client never saw, such as a message the session absorbed mid-turn.
The refusal is deterministic, so the agent never retries it.
If the recovery resume fails too, the request fails with an internal error, the session ends, and the client loads it again. When it fails because the account needs a sign-in, the request fails with `authRequired` and the session stays: the next prompt after the sign-in resumes it.
The request fails with `-32602` for:
- a `cursorId` that the session's history does not hold: an unknown id, an id that is no cursor, the first message, a message before the newest compaction when the history before it cannot be read (the fallback in `src/resumed-session.ts`), or one that an earlier rewind removed;
- a session id that names a subagent's child session.
A `sessionId` that is not held by the agent fails with `-32002`.
## Presentation hints
Each session mode and each value of the mode config option carries `_meta.jetbrains.air.kind`:

View File

@@ -64,4 +64,6 @@ When an ACP client routes the agent through a gateway with `providers/set`, the
The model picker then offers only the SDK models whose resolved model the gateway lists, matched without dates, version suffixes (`-v1:0`), `-fast`, `@` suffixes, context hints (`[1m]`) and provider prefixes, after the `availableModels` allowlist above. On Bedrock, a model the CLI resolved to another region prefix is dropped as well. When the gateway does not list the model a session runs, that is the default model or a resumed session's last model, the session switches to the first remaining picker row.
A 4xx answer means the gateway has no listing: `providers/set` succeeds and nothing is narrowed. A failed listing (network error, a status other than 2xx or 4xx, unexpected body, the 10 s timeout, an invalid header, or a base URL with credentials) fails `providers/set` with a JSON-RPC internal error, and the previous provider stays in effect. A listing that matches no SDK model leaves the session with no model to offer: there is no model config option. Gateways set through `authenticate`, `vertex` providers, and native routing are not listed. Setting the same gateway again (the same protocol, base URL and headers) reuses its listing, unless it answered 4xx; `providers/set` and `providers/disable` apply in the order they arrive, and logout clears the routing after `claude auth logout`, including a `providers/set` still listing; `providers/disable` and logout drop it.
A 4xx answer means the gateway has no listing: `providers/set` succeeds and nothing is narrowed. A failed listing (network error, a status other than 2xx or 4xx, unexpected body, the 10 s timeout, an invalid header, or a base URL with credentials) fails `providers/set` with a JSON-RPC internal error, and the previous provider stays in effect. Gateways set through `authenticate`, `vertex` providers, and native routing are not listed. Setting the same gateway again (the same protocol, base URL and headers) reuses its listing, unless it answered 4xx; `providers/set` and `providers/disable` apply in the order they arrive, and logout clears the routing after `claude auth logout`, including a `providers/set` still listing; `providers/disable` and logout drop it.
If the listing matches none of the models Claude Code reports after the `availableModels` allowlist, session setup (`session/new`, `session/load`, `session/resume`, `session/fork`) fails with an internal error that says to choose a different provider. Open sessions also fail when they restart under that provider: v1 drops them and sends a session failure update to clients with AIR's `sessionFailure` capability; v2 stops their queries and answers later requests with that error and an instruction to resume the session. After choosing a compatible provider, use `session/resume` to continue a stopped v2 session. When no model matches, session setup still succeeds with no model config option if Claude Code reports no models or any allowed model row has no `resolvedModel` (for example an `availableModels` entry Claude Code does not report).

147
docs/subagent-sessions.md Normal file
View File

@@ -0,0 +1,147 @@
# Subagent sessions
A client that declares `clientCapabilities.subagents`, other than JetBrains AIR, gets each Agent or
Task subagent as its own child session, following ACP's [subagents](https://agentclientprotocol.com/protocol/v1/subagents):
- `subagent_update` on the parent announces the child before any of its traffic, with the
parent's `title` and `description` for it, and reports its work state: `running`,
`requires_action` while one of its requests is open (and `running` again when the last one ends,
unless a cancel withdrew it: the child is stopping then), and `idle` when its work ends, with
`end_turn` or `cancelled` when the SDK gives the reason. A failure is `idle` with the `error`
stop reason and the SDK's error text as its `error`. The child keeps its session for every
delegation to it.
- A child that still works when Claude Code starts a fresh conversation, such as for `/clear`, is
`unknown`, and loses its `cancel` capability. Claude Code can keep such a child running, but the
adapter forgets the children of the old conversation, so it reports nothing more for it and
cannot stop it. Its unfinished tool calls keep their status. An idle child keeps its state.
- A child that runs outside its parent's working directory, such as an Agent call with
`isolation: "worktree"`, gets its `cwd` on `subagent_update` before its first tool call. The
adapter takes it from the `cwd` of the child's own hooks: its SubagentStart hook runs before its
first model request. It sends `cwd: null` when the child is back in its parent's directory. A
child in its parent's directory gets no `cwd`, and no child gets `additionalDirectories`: Claude
Code gives a subagent the session's additional directories, so it inherits them. A replay
announces a child with the `cwd` that its transcript recorded, and clears it with the child's
current state (see below) when that directory no longer exists.
- Session messages replace the Agent or Task call that launches the child, which its parent is
not shown:
- The launch's prompt is a `session_message` in both transcripts: the parent's outgoing view and
the child's incoming one. Both use the launch's tool use id, and each names the other with the
RFD's `recipientMessageId` and `senderMessageId`.
- A foreground child's answer, from the launch's result, is the child's `session_message` to
the parent. In Claude Code's hand-back mode, the child's `SubagentHandback` call is its
message to the parent instead, in both transcripts and linked the same way.
- A launch whose child is never exposed is shown as a tool call after all, with its final
status.
- A forked skill (a skill with `context: fork`, such as `/code-review`) is a child session too.
Claude Code runs it as a subagent that no Agent or Task call launched:
- When Claude runs it with the Skill tool, the child is announced on the session that made the
Skill call, once Claude Code reports its task. The Skill call stays a tool call of that session,
with the skill's result. The skill's prompt is a `session_message` in the child's transcript
only, with the Skill call's tool use id.
- When the user types it, there is no call: the child is announced on the root session, and the
command's output is the root's message. Claude Code (2.1.328) sends such a child's messages
only when the command ends, after it reports the task's end. The adapter keeps the child
`running` until they came, so its `idle` follows its tool calls and text. They all arrive at
once: the child's transcript is not live.
- A subagent that a typed skill launches gets no session: Claude Code reports the end of its
task before the Agent call that launched it. That call is a tool call of the skill's child,
with its final status.
- After a `session/cancel` of the root session, a typed skill's messages are the output of
stopped work, which the adapter drops: the child reports `idle` with `cancelled` and no more.
After a `session/cancel` of the child itself, they still go to the child, before its `idle`
with `cancelled`.
- A replay shows no child for a forked skill. The Skill call stays a tool call.
- On v1, the parent's prompt turn ends at its result, also while a background child that it
launched or resumed still runs. The child's updates and requests follow the prompt response: the
RFD has a client keep receiving child events after it. The parent's summary when the child ends
comes from a followup cycle out of a turn. Its result ends no turn, and a plan approval it asks
for has no clear-context option.
- A SendMessage call that resumes the child is not shown either. Its message is a
`session_message` in both transcripts, the sender's outgoing view and the child's incoming one,
linked like a launch's prompt. A SendMessage call whose message resumes no announced child,
such as one to the parent, is shown as a tool call, with its final status.
- Every message is one whole `session_message`. The adapter sends no `session_message_chunk`: it
has each message's full text before it reports it, from the input or the result of the tool call
that sent it.
- A tool call that the client is shown and that operates on an announced child of another session
carries the RFD's `session` content, `{ "type": "session", "sessionId": "<child>" }`, after its
other content: a TaskStop call whose `task_id`, or a SendMessage call whose `to`, is the child's
agent id; a SendMessage call that resumed the child and stays shown because a permission request
showed it first; on v1, an Agent or Task call that stays shown for the same reason; and the
Skill call that launched a forked skill's child. A `tool_call_update` without content carries
none, since it would replace the content the client holds. A call that names the child by its
name gets no reference: Claude Code resolves the name, and the adapter cannot tell which agent it
picked.
- `session/cancel` on the parent interrupts Claude Code, which stops the foreground children that
the turn waits on. Background children keep running, as the RFD prefers; a client stops one with
its own `cancel`. Each stopped child reports `idle` with `cancelled` from Claude Code's own
events, and its open requests are withdrawn. The adapter ends no child at a cancel itself, so a
child that keeps running keeps its open requests and its open tool calls. To spare background
children, the adapter declares the SDK option `perTaskStopAffordance`, which a client can turn
off in `_meta.claudeCode.options`. That option spares background workflows too, which a client
cannot stop, so the adapter stops them after the interrupt, as Claude Code did without it.
Background commands keep running after a cancel either way. A tool call of a stopped child that Claude Code reports no
result for, such as the command it was running, ends in the child's session before the cancelled
prompt resolves. When Claude Code stops a background child after that, or while no prompt runs,
the tool call ends right after the child reports `idle`. A child that still runs when Claude Code
exits is `idle`, since its work ended with the process: with no stop reason on v1, and on v2
with the `error` stop reason and the error that ends the root's work.
- A child whose parent is not yet known when it ends is not exposed, since the RFD forbids
guessing its parent.
- A replay restores each child under its live session id, from its own transcript, with the same
session messages and `session` references as live, and its end is an `idle` before the response.
Each replayed child's current state follows the response: on v1, the response is what separates
a replayed child state from a current one.
A replay sends no `config_option_update` of a child, since one that arrives before the response
is a past value to the client. Each replayed child's configuration follows its current state:
the configuration of a child that still runs, else its `model` option with the model of the
latest response in its transcript, as the session's `model` option names it. A child that
neither runs nor has a response gets none.
A launch without Claude Code's metadata file for the child stays an ordinary tool call of the
parent, and a notice, for a client that takes notices, says that subagent history is missing.
- A session that is loaded or resumed with the same settings while it runs keeps its children's
runs. After the response, each child that works and that no replay announced is announced
again on its parent, with its labels, the `cancel` capability and its state, and then gets the
configuration that the client last had for it: every working child after a `session/resume`,
which replays nothing, and after a `session/load` a child whose launch the history does not
have, such as a forked skill's. A child that no longer works but has a working child of its own
is named first, with its labels only.
- After a load or resume, with or without replay, a SendMessage that resumes an agent from before
it runs that agent in its session from before. Before the agent's traffic, each of its ancestors
that the client was not told about in this connection is announced, parent before child and
with no work state, as the RFD requires. An agent whose launch the session's history does not
record stays unexposed.
- Each running child is announced with the `cancel` capability. `session/cancel` with the child's
session id stops that child's current work, through the SDK's `Query.stopTask`, and not its
parent's: Claude Code also stops the foreground children it waits on, and the parent's turn goes
on. Each stopped child reports `idle` with `cancelled` from Claude Code's own events, and its
requests that the stop withdraws report no `running` first. A replayed child, which no longer
runs, gets no capabilities, and a `session/cancel` of it does nothing. A client cannot prompt or
otherwise change a child: any other request that names a child fails with `-32602` (Invalid
params), `session/close` and `session/delete` too. That holds for every child that a
`subagent_update` announced, while it ran or in a replay, until the client closes the child's
root session: also after `/clear` and after a restart of the root's Claude Code process.
An [ACP v2](../README.md#acp-v2-preview) client gets the same without declaring anything, since subagents
are part of v2's baseline. Each child also reports its work state as its own `state_update`, right
after the parent's copy. A replay ends each child's history with a `replay_complete` on the child's
session. On v2, the parent's `replay_complete` is what separates a replayed child state from a
current one, so each replayed child's current state follows the root session's `replay_complete`
and comes before the response: on its parent, with the cleared `cwd`, and then as the child's own
`idle`. The child's configuration follows it there, since v2 asks an agent not to replay a past
`config_option_update`. The notice that subagent history is missing follows the root's
`replay_complete` too.
On v2, a resume of the active session that replays can meet a child that the stored history does
not launch: a forked skill's child, or a subagent that Claude launched after the history was written.
Such a child is announced again right after the root's `replay_complete`, when it works, when its
parent lists it, or when the replay held one of its updates. Its own `replay_complete` follows at
once, since its replay is empty, and then come the updates that the replay held.
JetBrains AIR keeps the earlier draft of the RFD (`subagent_spawned`, `subagent_state_update`),
which it enables with `nativeSubagentSessions` in `_meta.jetbrains.air.capabilities`. See
[AIR extensions](air-extensions.md#native-subagent-sessions).
Without either signal, Agent and Task stay ordinary tool calls and child interactions stay on the
root session. Clients that use the historical `_meta["subagent-transcript"]` capability or the
`forwardSubagentText` session option retain the flattened child transcript.

648
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.106.0",
"version": "0.113.0",
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
"main": "dist/lib.js",
"types": "dist/lib.d.ts",
@@ -68,25 +68,25 @@
"node": ">=22"
},
"dependencies": {
"@agentclientprotocol/sdk": "2.6.0",
"@anthropic-ai/claude-agent-sdk": "0.3.322",
"@agentclientprotocol/sdk": "2.12.0",
"@anthropic-ai/claude-agent-sdk": "0.3.331",
"diff": "9.0.0",
"zod": "4.6.7"
},
"devDependencies": {
"@anthropic-ai/sdk": "1.7.0",
"@anthropic-ai/sdk": "1.13.0",
"@eslint/js": "10.0.1",
"@tsconfig/node22": "22.0.6",
"@tsconfig/node22": "22.0.7",
"@types/node": "26.6.6",
"@typescript-eslint/eslint-plugin": "8.72.2",
"@typescript-eslint/parser": "8.72.2",
"@typescript-eslint/eslint-plugin": "8.74.0",
"@typescript-eslint/parser": "8.74.0",
"ajv": "8.20.0",
"ajv-formats": "3.0.1",
"eslint": "10.14.0",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.8",
"globals": "17.14.0",
"prettier": "3.9.10",
"prettier": "3.10.1",
"typescript": "6.0.3",
"vitest": "5.1.0"
"vitest": "5.1.1"
}
}

View File

@@ -3,12 +3,14 @@ import type {
CompleteElicitationNotification,
CreateElicitationRequest,
CreateElicitationResponse,
McpServerAcp,
ReadTextFileRequest,
ReadTextFileResponse,
RequestPermissionResponse,
WriteTextFileRequest,
WriteTextFileResponse,
} from "@agentclientprotocol/sdk/unstable";
import type { McpHttpServerConfig } from "@anthropic-ai/claude-agent-sdk";
import type { AcpSessionNotification } from "./acp-subagents.js";
import type { AcpPermissionRequest } from "./permissions/presentation.js";
@@ -43,4 +45,10 @@ export interface AcpClient {
authStatusUpdate(params: AuthStatusUpdateNotification): Promise<void>;
/** Send a custom (extension) notification, e.g. `_claude/sdkMessage`. */
extNotification(method: string, params: Record<string, unknown>): Promise<void>;
/**
* The SDK config of an MCP server that the client serves over this
* connection (`"type": "acp"`): an endpoint that sends each MCP request to
* the client as `mcp/message` (see `McpOverAcp` in `mcp-servers.ts`).
*/
mcpServerOverAcp(server: McpServerAcp): Promise<McpHttpServerConfig>;
}

View File

@@ -1,7 +1,8 @@
import type {
ClientCapabilities,
SessionCapabilities,
SessionNotification,
import {
RequestError,
type ClientCapabilities,
type SessionCapabilities,
type SessionNotification,
} from "@agentclientprotocol/sdk/unstable";
import {
AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY,
@@ -24,6 +25,71 @@ export { AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY } from "./air-extension.js";
*/
export type SubagentForm = "rfd" | "air";
/**
* The error of a client's request that names a child session, other than
* `session/cancel`: invalid params (-32602), as the RFD asks, not the -32002
* of an unknown session. `method` completes "the client cannot … it".
*/
export function restrictedChild(sessionId: string, method: string): RequestError {
return RequestError.invalidParams(
{ sessionId },
`${sessionId} is a subagent session: the client cannot ${method} it. Its parent session runs it.`,
);
}
/**
* The child sessions that the sessions of one connection announced with
* `subagent_update`, while they run or in the replay of a `session/load` or
* `session/resume`. The client knows such a session, so a request that names
* it fails as {@link restrictedChild} says, and not as a request of an unknown
* session.
*
* A child is known from its announcement until the client ends its root
* session ({@link rootClosed}): with `session/close`, or a request that closes
* the session too, such as `session/delete`. Nothing else removes it: after a
* conversation reset (`/clear`), a restart of the root's query or the end of
* the root's Claude Code process, the client still holds the child.
*
* AIR's draft announces a child with `subagent_spawned` and keeps its own
* rules, so its children are never known here.
*/
export class AnnouncedChildren {
/** The root session of each announced child session, by the child's id. */
private readonly rootByChild = new Map<string, string>();
/**
* Takes a session update that goes to the client. A `subagent_update`
* announces the child session it names, or reports on one that is known
* already. The update's own session is the child's parent, which can be a
* child itself: its root is the child's too.
*/
sending(notification: {
sessionId: string;
update: { sessionUpdate: string; sessionId?: unknown };
}): void {
const { sessionId: parent, update } = notification;
if (update.sessionUpdate !== "subagent_update" || typeof update.sessionId !== "string") return;
this.rootByChild.set(update.sessionId, this.rootByChild.get(parent) ?? parent);
}
/** Whether `sessionId` is a child session that the client knows. */
has(sessionId: string): boolean {
return this.rootByChild.has(sessionId);
}
/** The root session of the child session `sessionId`, when the client knows it. */
rootOf(sessionId: string): string | undefined {
return this.rootByChild.get(sessionId);
}
/** The client ended the session `rootSessionId`, and can no longer name its children. */
rootClosed(rootSessionId: string): void {
for (const [child, root] of this.rootByChild) {
if (root === rootSessionId) this.rootByChild.delete(child);
}
}
}
/** The form of native subagent sessions that the client gets, or none. */
export function subagentForm(capabilities?: ClientCapabilities | null): SubagentForm | undefined {
if (!clientSupportsSubagents(capabilities)) return undefined;

146
src/adapter-command.ts Normal file
View File

@@ -0,0 +1,146 @@
/**
* The commands the adapter serves itself instead of passing to Claude Code
* (`/remote-control` and `/plugin`), in one place so that the command list and
* the dispatch in the v1 and v2 cores apply the same rule.
*/
import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
import type { Query, SlashCommand } from "@anthropic-ai/claude-agent-sdk";
import { claudeCliPath, isRemoteSession } from "./claude-cli.js";
import type { NewSessionMeta } from "./new-session-meta.js";
import {
parsePluginCommand,
pluginCommandMarkdown,
PLUGIN_AVAILABLE_COMMAND,
PLUGIN_COMMAND_NAME,
runPluginCommand,
} from "./plugin-command.js";
import {
adapterRemoteControlCommand,
claudeCodeOffersCommand,
parseRemoteControlCommand,
REMOTE_CONTROL_COMMAND_NAME,
type RemoteControlCommand,
runRemoteControlCommand,
supportsRemoteControl,
} from "./remote-control.js";
type PromptContent = ReadonlyArray<{ type: string; text?: unknown }>;
export interface AdapterCommand {
readonly name: typeof REMOTE_CONTROL_COMMAND_NAME | typeof PLUGIN_COMMAND_NAME;
/** The `RequestError` text while Claude is working. */
readonly busyMessage: string;
/** The `RequestError` text while another adapter command runs. */
readonly inFlightMessage: string;
/** What `/remote-control` was asked to do. A core records it before the
* command runs, so that a restart of the query keeps what the user chose
* (see `RemoteControlAtStartup.commandRan`). */
readonly remoteControl?: RemoteControlCommand;
/** Returns the reply text. A failure is in the text: this never throws. */
run(signal: AbortSignal): Promise<string>;
}
export interface AdapterCommandContext {
cwd: string;
env: Record<string, string | undefined>;
/** The session runs Claude Code remotely (`sdk-url`). */
remoteSession: boolean;
query: () => Query | undefined;
logError: (message: string) => void;
}
/** The session's client options (`_meta.claudeCode.options`) that decide where
* an adapter command runs: the CLI's `env`, and whether Claude Code is remote. */
export function sessionAdapterOptions(creationParams: { _meta?: unknown } | undefined): {
env: Record<string, string | undefined>;
remoteSession: boolean;
} {
const options = (creationParams?._meta as NewSessionMeta | undefined)?.claudeCode?.options;
return {
env: { ...process.env, ...options?.env },
remoteSession: isRemoteSession(options?.extraArgs),
};
}
const REMOTE_CONTROL_ENTRY: AvailableCommand = {
name: REMOTE_CONTROL_COMMAND_NAME,
description:
"Continue this session from claude.ai/code or the Claude mobile app; `off` disconnects",
input: { hint: "[session name | off]" },
};
/** A cheap synchronous check for the cores, before any await: the prompt has
* the form of an adapter command. Whether the adapter serves it is
* {@link adapterCommand}'s decision. */
export function mayBeAdapterCommand(prompt: PromptContent): boolean {
return parseRemoteControlCommand(prompt) !== null || parsePluginCommand(prompt) !== null;
}
/** The adapter command of `prompt` that the adapter runs, or `null` for a
* prompt that goes to Claude Code. */
export async function adapterCommand(
prompt: PromptContent,
query: Query,
terminalCommands: readonly string[] | undefined,
context: AdapterCommandContext,
): Promise<AdapterCommand | null> {
const remoteControl = await adapterRemoteControlCommand(prompt, query, terminalCommands);
if (remoteControl) {
return {
name: REMOTE_CONTROL_COMMAND_NAME,
busyMessage:
"Remote Control can't be changed while Claude is working. Try again when the turn ends.",
inFlightMessage: "Remote Control is already being changed. Try again in a moment.",
remoteControl: remoteControl.command,
run: () =>
runRemoteControlCommand(remoteControl.query, remoteControl.command, context.logError),
};
}
const command = parsePluginCommand(prompt);
// A session with `sdk-url` runs Claude Code on another machine; the CLI that
// the adapter would start here changes the plugins of this machine instead.
if (!command || context.remoteSession) return null;
const typed = typedCommandName(prompt);
if (claudeCodeOffersCommand(await query.supportedCommands(), terminalCommands, typed)) {
return null;
}
return {
name: PLUGIN_COMMAND_NAME,
busyMessage: "/plugin can't run while Claude is working. Try again when the turn ends.",
inFlightMessage: "Another command is still running. Try again in a moment.",
run: async (signal) =>
pluginCommandMarkdown(
await runPluginCommand(command, {
cliPath: claudeCliPath,
cwd: context.cwd,
env: context.env,
signal,
query: context.query,
logError: context.logError,
}),
),
};
}
/** The name the user typed: `plugin`, `plugins` or `marketplace`. */
function typedCommandName(prompt: PromptContent): string {
const text = typeof prompt[0]?.text === "string" ? prompt[0].text : "";
return /^\/([^\s]+)/.exec(text.trim())?.[1] ?? PLUGIN_COMMAND_NAME;
}
/** The entries of `available_commands_update` that the adapter serves,
* without those that Claude Code offers under the same name. */
export function adapterAvailableCommands(
commands: readonly SlashCommand[],
terminalCommands: readonly string[] | undefined,
query: Query | undefined,
{ remoteSession }: { remoteSession: boolean },
): AvailableCommand[] {
const entries: AvailableCommand[] = [];
if (query && supportsRemoteControl(query)) entries.push(REMOTE_CONTROL_ENTRY);
if (!remoteSession) entries.push(PLUGIN_AVAILABLE_COMMAND);
return entries.filter(
(entry) => !claudeCodeOffersCommand(commands, terminalCommands, entry.name),
);
}

View File

@@ -48,6 +48,13 @@ export const AIR_SESSION_LIST_SUBSCRIBE_CAPABILITY = "sessionListSubscribe";
* {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not declare it.
*/
export const AIR_SESSION_WORKTREES_CAPABILITY = "sessionWorktrees";
/**
* `_session/rewind`: removes a user message and everything after it from the
* context of the same session (see `docs/air-extensions.md#session-rewind`).
* The client declares it; the agent advertises it only to such a client, and
* then announces its session cursors with the `rewind` capability.
*/
export const AIR_SESSION_REWIND_CAPABILITY = "sessionRewind";
/**
* The client wants to know when the history replay of a loaded session is
* whole. After the last replayed update, the agent sends one
@@ -69,6 +76,14 @@ export const AIR_KIND_KEY = "kind";
export const AIR_SKILL_PATH_KEY = "skillPath";
export const AIR_PERMISSION_KEY = "permission";
export const AIR_CUSTOM_ANSWER_KEY = "customAnswer";
/**
* The `_meta.jetbrains.air` key of a `model` option entry: the effort levels
* of the model and the recommended one, `{values, recommended}`. Every AIR
* client gets it, without a capability: the key only adds data.
*/
export const AIR_REASONING_EFFORTS_KEY = "reasoningEfforts";
/** The companion field keys in an ACP form elicitation request. */
export const AIR_CUSTOM_ANSWER_FIELDS_KEY = "customAnswerFields";
/** The `_meta.jetbrains.air` key of the update that ends a whole history replay. */
export const AIR_LOAD_REPLAY_END_KEY = "loadReplayEnd";
/**

View File

@@ -879,7 +879,7 @@ function recordPublished(task: AsyncTask, fields: Record<string, unknown>): void
* its tool result. The text of a tool result never gives a task id: a
* foreground command can print any text.
*
* Claude Code sends no `tool_use_result` with a subagent's tool results. For
* Claude Code sends no `tool_use_result` with a subagent's Bash results. For
* those, `startedTaskOf` gives the background `local_bash` task whose
* `task_started` named the Bash call, which comes before the result.
*/

View File

@@ -20,13 +20,19 @@ import {
AUTH_STATUS_PROBE_TIMEOUT_MS,
type AuthStatus,
type AuthStatusKind,
cliAuthIdentity,
fromAccountInfo,
fromCliStatus,
mergeAuthStatus,
parseCliAuthStatus,
sameAuthStatus,
toAcpAuthStatus,
} from "./auth-status.js";
import { claudeCliPath } from "./claude-cli.js";
import {
claudeAuthRefusal,
isClaudeEnterprisePlan,
shouldHideClaudeAuth,
} from "./hide-claude-auth.js";
import type { SettingsManager } from "./settings.js";
const execFileAsync = promisify(execFile);
@@ -81,8 +87,7 @@ export class AuthStatusReporter {
private probeRuns = 0;
/** The latest-started probe run that published its read. */
private publishedRun = 0;
/** The last `auth/status_update` payload sent, as JSON. */
private sentAcp?: string;
private acpStatus: AcpAuthStatus = { state: "unknown" };
constructor(private readonly options: AuthStatusReporterOptions) {}
@@ -100,28 +105,24 @@ export class AuthStatusReporter {
* reach here at all (see the epoch check in the probe and the guards at
* session create).
*/
set(next: AuthStatus | undefined): void {
set(next: AuthStatus | undefined, refused = false): void {
if (!next) {
return;
}
if (sameAuthStatus(this.current, next)) {
if (!sameAuthStatus(this.current, next)) {
this.current = next;
// Older clients still get the actual identity, including one the guard refused.
void Promise.resolve()
.then(() => this.options.push(next))
.catch((error) => {
this.options.logger.error("Failed to send _auth/status_update:", error);
});
}
const acp = toAcpAuthStatus(next, refused);
if (JSON.stringify(acp) === JSON.stringify(this.acpStatus)) {
return;
}
this.current = next;
// ACP notifications get no reply, and clients that do not know the method
// drop it silently — send unconditionally and never fail a caller on it.
void Promise.resolve()
.then(() => this.options.push(next))
.catch((error) => {
this.options.logger.error("Failed to send _auth/status_update:", error);
});
// Compared on its own payload: two identities can map to the same one.
const acp = toAcpAuthStatus(next);
const sent = JSON.stringify(acp);
if (sent === this.sentAcp) {
return;
}
this.sentAcp = sent;
this.acpStatus = acp;
void Promise.resolve()
.then(() => this.options.pushAcp(acp))
.catch((error) => {
@@ -152,7 +153,7 @@ export class AuthStatusReporter {
} else {
await this.probe();
}
return toAcpAuthStatus(this.current);
return this.acpStatus;
}
/** A login or a logout: any probe already running read the world before it. */
@@ -224,8 +225,11 @@ export class AuthStatusReporter {
return;
}
const fromSession = fromAccountInfo(account, apiKeyHelper);
if (fromSession) {
this.set(mergeAuthStatus(this.current, fromSession, "session"));
if (account && fromSession) {
this.set(
mergeAuthStatus(this.current, fromSession, "session"),
shouldHideClaudeAuth() && claudeAuthRefusal(account) !== undefined,
);
} else if (!this.loggedUninformativeAccount) {
this.loggedUninformativeAccount = true;
this.options.logger.log(
@@ -308,19 +312,20 @@ export class AuthStatusReporter {
}
stdout = failed.stdout;
}
let status = fromCliStatus(stdout, apiKeyHelper);
const cli = parseCliAuthStatus(stdout);
if (!cli) {
logger.error("claude auth status returned unparseable output");
return undefined;
}
let status = cliAuthIdentity(cli, apiKeyHelper);
if (!context && status?.kind === "api_key" && status.detail === "API key helper") {
try {
const resolved = await resolveSettings({ cwd: process.cwd() });
status = fromCliStatus(stdout, filterEscalatingDefaultMode(resolved).apiKeyHelper);
status = cliAuthIdentity(cli, filterEscalatingDefaultMode(resolved).apiKeyHelper);
} catch {
logger.error("Could not resolve auth source settings");
}
}
if (!status) {
logger.error("claude auth status returned unparseable output");
return undefined;
}
if (epoch !== this.epoch) {
// A login or logout landed while this probe was running; the newer
// state wins and this answer is discarded, never published.
@@ -338,7 +343,14 @@ export class AuthStatusReporter {
// same login (no organization, say). Keep those extra fields rather than
// regressing the payload; a different identity replaces it wholesale.
const merged = mergeAuthStatus(this.current, status, "cli");
this.set(merged);
// The CLI names the effective credential, not the SDK's accountInfo tokenSource.
// An OAuth setup token can carry a plan but, like an API key, is allowed.
const refused =
shouldHideClaudeAuth() &&
status.kind === "account" &&
cli.authMethod !== "oauth_token" &&
!isClaudeEnterprisePlan(cli.subscriptionType);
this.set(merged, refused);
this.options.onProbe?.(status.kind);
return merged;
}

View File

@@ -109,14 +109,14 @@ export type AcpAuthStatus = Pick<AuthStatusResponse, "state" | "accounts">;
* `_meta.claudeCode` carries the `kind` and `plan`, and the `detail` again
* for clients that read it there.
*
* `--hide-claude-auth` does not change the payload: it reports the login the
* CLI holds, also when the subscription guard refuses to use it.
* The legacy extension still reports a refused identity for display. ACP
* reports that sign-in is needed instead of listing it as an active account.
*/
export function toAcpAuthStatus(status: AuthStatus | undefined): AcpAuthStatus {
export function toAcpAuthStatus(status: AuthStatus | undefined, refused = false): AcpAuthStatus {
if (!status) {
return { state: "unknown" };
}
if (status.kind === "none") {
if (refused || status.kind === "none") {
return { state: "unauthenticated" };
}
const account: AuthAccount = { label: status.label, active: true };
@@ -236,10 +236,8 @@ export function fromAccountInfo(
});
}
/** Pre-session mapping from `claude auth status --json` stdout. Returns
* `undefined` when the output is not the expected JSON object, so callers can
* report "not known" instead of guessing. */
export function fromCliStatus(stdout: string, apiKeyHelper?: string): AuthStatus | undefined {
/** An unreadable `claude auth status --json` result is unknown, not signed out. */
export function parseCliAuthStatus(stdout: string): CliAuthStatus | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(stdout);
@@ -253,6 +251,10 @@ export function fromCliStatus(stdout: string, apiKeyHelper?: string): AuthStatus
if (typeof status.loggedIn !== "boolean") {
return undefined;
}
return status;
}
export function cliAuthIdentity(status: CliAuthStatus, apiKeyHelper?: string): AuthStatus {
// `loggedIn` tracks the claude.ai login only. On a 3P backend (Bedrock,
// Vertex, …) it is false while the credentials live outside the agent, so the
// backend must decide the kind before the logged-out shortcut runs.

View File

@@ -129,3 +129,166 @@ export class BackgroundOutputTail {
await this.publish({ text, replaces });
}
}
/** What Claude Code's `get_task_output` returns: the end of a shell task's output. */
export interface TaskOutput {
/** At most the last 8 KiB of the output, decoded as UTF-8. */
output: string;
/** The size of the whole output in bytes. */
total_bytes: number;
/** Whether `output` holds only the end of the output. */
truncated: boolean;
}
/**
* The most bytes at the start of a truncated `output` that may not match the
* command's bytes: a character that the 8 KiB cut split decodes as U+FFFD.
*/
const CUT_CHARACTER_BYTES = 4;
/**
* Follows the output of a command that runs in the foreground, read with
* `read` (Claude Code's `get_task_output`), and hands each piece of new text
* to `publish`, in order. Claude Code streams no output of a foreground Bash
* command either: the output arrives in the tool result. Claude Code writes
* the output to the command's task before then, and `get_task_output` reads
* it, though the task's `task_started` names no output file.
*
* The new text is the output past the bytes already sent. When `output` does
* not hold all of it, or its bytes may not match the command's (not UTF-8),
* the whole `output` replaces the terminal's output, as a snapshot. A read
* that ends in U+FFFD may have cut a character that the command is still
* writing, so it is sent only at the next read.
*
* Once the command ends, Claude Code drops its output: the task then reads as
* empty (`total_bytes: 0`, CLI 2.1.325), up to the tool result that carries
* the whole output. A read that holds less than was sent is that end, so it
* stops the poll and publishes nothing: an empty snapshot would clear the
* terminal.
*
* One read runs at a time: a poll that comes during a read is skipped, so a
* read that Claude Code never answers queues nothing behind it. A read that
* fails is tried again at the next poll. `publish` must not reject.
*/
export class TaskOutputPoll {
private sentBytes = 0;
private sent = false;
private stopped = false;
/** A read is in progress, or the publish of its text. */
private busy = false;
/** The publish in progress, or the last one. */
private publishing: Promise<void> = Promise.resolve();
private readonly timer: ReturnType<typeof setInterval>;
constructor(
private readonly read: () => Promise<TaskOutput>,
private readonly publish: (output: BackgroundOutput) => Promise<void>,
) {
this.timer = setInterval(() => void this.poll(), BACKGROUND_OUTPUT_POLL_MS);
// A command that runs on must not keep the agent process alive.
this.timer.unref();
}
/**
* Stops, once a publish in progress is out. Returns whether any text was
* published: the tool result then replaces it with the whole output.
*
* A read in progress is not waited for. It publishes nothing after this,
* and Claude Code may never answer it.
*/
async finish(): Promise<boolean> {
this.stop();
await this.publishing;
return this.sent;
}
/**
* Stops now and returns whether any text was published, for a caller whose
* `publish` sends in the same synchronous step (v2), so none is in progress.
*/
end(): boolean {
this.stop();
return this.sent;
}
/** Stops without waiting: the command's task, the query or the session ended. */
stop(): void {
clearInterval(this.timer);
this.stopped = true;
}
private async poll(): Promise<void> {
if (this.stopped || this.busy) return;
this.busy = true;
try {
const read = await this.read();
if (this.stopped) return;
if (read.total_bytes < this.sentBytes) {
this.stop();
return;
}
const output = this.newText(read);
if (output === undefined) return;
this.sentBytes = read.total_bytes;
this.sent = true;
this.publishing = this.publish(output);
await this.publishing;
} catch {
// The read failed: try again at the next poll.
} finally {
this.busy = false;
}
}
/**
* The text that `read` adds to what was sent, or undefined when it adds none
* yet. `read` holds at least the bytes that were sent.
*/
private newText({ output, total_bytes, truncated }: TaskOutput): BackgroundOutput | undefined {
if (total_bytes === this.sentBytes || output.endsWith("\uFFFD")) return undefined;
const bytes = Buffer.from(output, "utf8");
const added = total_bytes - this.sentBytes;
const exact = truncated
? added <= bytes.length - CUT_CHARACTER_BYTES
: bytes.length === total_bytes;
// `sentBytes` ends a read that ended in a whole character, so the cut is
// at a character boundary.
if (exact) {
return { text: bytes.subarray(bytes.length - added).toString("utf8"), replaces: false };
}
return { text: output, replaces: true };
}
}
/**
* The id of the tool call whose command the task `started` runs in the
* foreground, or undefined for any other task. Claude Code starts the task of
* a foreground command once the command has run for a few seconds (3.1 s with
* CLI 2.1.325). A faster command gets no task, and its output comes with its
* tool result, as before.
*/
export function foregroundCommandToolCall(started: {
task_type?: string;
is_backgrounded?: boolean;
tool_use_id?: string;
}): string | undefined {
return started.task_type === "local_bash" && started.is_backgrounded === false
? started.tool_use_id
: undefined;
}
/** Whether a call of the tool `name` runs a command that a terminal shows. */
export function isCommandTool(name: string | undefined): boolean {
return name === "Bash" || name === "PowerShell";
}
/**
* Claude Code's `get_task_output` on the SDK's query. Like `mcpAuthenticate`,
* it is on the query object but not in the public `Query` declaration yet,
* though the SDK types its control request (`SDKControlGetTaskOutputRequest`).
*/
export type TaskOutputQuery = { getTaskOutput(taskId: string): Promise<TaskOutput> };
export function supportsTaskOutput<T extends object>(query: T): query is T & TaskOutputQuery {
return typeof (query as Partial<TaskOutputQuery>).getTaskOutput === "function";
}

View File

@@ -1,5 +1,6 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import type { Options } from "@anthropic-ai/claude-agent-sdk";
const CLI_FILE_NAME = process.platform === "win32" ? "claude.exe" : "claude";
@@ -30,6 +31,51 @@ export async function claudeCliPath(): Promise<string> {
return installedClaudeCliPath();
}
/** How an option reaches the Claude CLI: in a flag, or over stdin in the SDK's initialize request. */
type Delivery = NonNullable<Options["mcpServersDelivery"]>;
/** Whether the client's `extraArgs` name `sdk-url`: a remote session. */
export function isRemoteSession(clientExtraArgs: Options["extraArgs"]): boolean {
return Object.keys(clientExtraArgs ?? {}).some(
(name) => name === "sdk-url" || name.startsWith("sdk-url="),
);
}
/**
* The SDK options that say how a session's MCP servers and its `settings`
* reach the CLI of {@link claudeCliPath}. A client's own options replace them.
*
* - `'initialize'` for the CLI that the adapter ships: over stdin, in the
* SDK's initialize request.
* - `'argv'` for a CLI that `CLAUDE_CODE_EXECUTABLE` names: in the
* `--mcp-config` and `--settings` flags, as before SDK 0.3.326. Its version
* is not known, and a CLI that cannot take them over stdin fails the session
* at startup (2.1.323: "too old to read MCP servers from the initialize
* request", "unknown option '--initialize-fields=settings'").
* - `settings` stay `'argv'` when the client's `extraArgs` hold `settings`:
* Claude Code refuses to start with both ("--initialize-fields=settings
* cannot be used with --settings"), and in the flag the `settings` option
* replaces that argument. They also stay `'argv'` with `sdk-url` in the
* `extraArgs`: such a session cannot read the request at launch, and the SDK
* sends its MCP servers in the flag for the same reason.
*
* The SDK reads `settingsDelivery` (0.3.328) but does not declare it in
* `sdk.d.ts`, so nothing fails to compile if a later SDK drops it. The v2
* integration tests check the delivery against the real CLI.
*
* `mcpServersDelivery` is always set. The adapter names the CLI to start
* (`pathToClaudeCodeExecutable`), and for such an app the SDK prints a
* `DeprecationWarning` when a session has MCP servers and the option is unset.
*/
export function cliDelivery(clientExtraArgs: Options["extraArgs"]): {
mcpServersDelivery: Delivery;
settingsDelivery: Delivery;
} {
const delivery = process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize";
const settingsInFlag = "settings" in (clientExtraArgs ?? {}) || isRemoteSession(clientExtraArgs);
return { mcpServersDelivery: delivery, settingsDelivery: settingsInFlag ? "argv" : delivery };
}
function bundledClaudeCliPath(directory: string): string {
const path = join(directory, CLI_FILE_NAME);
// Without this check, spawning a missing CLI fails with a bare ENOENT.

View File

@@ -1,5 +1,5 @@
/**
* The client-provided system prompt of the unstable `systemPrompt` field on
* The client-provided system prompt of the `systemPrompt` field on
* `session/new`, `session/load`, `session/resume`, and `session/fork`.
*
* - `append` keeps the Claude Code preset and adds the text after it, the
@@ -10,7 +10,7 @@
*
* The CLI records the system prompt of a conversation on its first request
* and reuses it on resume, so a different `systemPrompt` on a later
* `session/resume` takes effect at the next compaction. The RFD allows this
* `session/resume` takes effect at the next compaction. ACP allows this
* deferral.
*/
import type { Options } from "@anthropic-ai/claude-agent-sdk";
@@ -30,8 +30,10 @@ export type ClientSystemPrompt = { mode: "append" | "override"; text: string };
/**
* The mode and text of a `systemPrompt`, or `undefined` when the request has
* none. Throws `invalid_params` for a mode other than `append` and `override`
* and for a content block other than text: the RFD requires an error, and no
* session, for a prompt the agent cannot apply.
* and for a content block other than text: ACP requires an error, and no
* session, for a prompt the agent cannot apply. Also for an empty `content`
* list, which a client must not send: the v2 schema rejects it before this
* runs, and a v1 client gets the same answer.
*/
export function clientSystemPrompt(
systemPrompt: SystemPrompt | null | undefined,
@@ -44,6 +46,12 @@ export function clientSystemPrompt(
`Unsupported systemPrompt mode: ${mode}`,
);
}
if (content.length === 0) {
throw RequestError.invalidParams(
{ systemPrompt: { content } },
"systemPrompt content is empty. Send at least one text block, or leave systemPrompt out.",
);
}
const text: string[] = [];
for (const block of content) {
if (block.type !== "text") {

View File

@@ -382,9 +382,10 @@ export class ContextCompactionLifecycle {
status: terminalStatus,
...(summary !== undefined ? { summary: [{ type: "text", text: summary }] } : {}),
...(terminalStatus === "failed" && metadata.error ? { error: metadata.error } : {}),
// `_meta` is a replace-patch: seed it with the first terminal, then
// only re-send it when the boundary adds facts, so a status-only
// duplicate can't wipe the token counts.
// A `_meta` that is sent replaces the facts a client holds (the
// whole `_meta` on v1, its `jetbrains` key on v2): seed it with the
// first terminal, then only re-send it when the boundary adds facts,
// so a status-only duplicate can't wipe the token counts.
// The standard `error` field carries the error, so `_meta` does not.
// Only AIR gets the compaction facts.
...(this.airClient && (firstTerminal || hasMetadata)

View File

@@ -5,7 +5,7 @@
* `getContextUsage`, and learned from each result's `modelUsage`.
*/
import type { ModelInfo, Query } from "@anthropic-ai/claude-agent-sdk";
import { DEFAULT_CONTEXT_WINDOW, inferContextWindowFromModel } from "./session-usage.js";
import { DEFAULT_CONTEXT_WINDOW } from "./session-usage.js";
/** Cross-session cache of authoritative context windows, keyed by
* `${providerCacheKey}\0${modelId}` (see {@link contextWindowCacheKey}).
@@ -61,8 +61,8 @@ const PROVIDER_ROUTING_ENV_VARS = [
* Header/credential values can be secrets; the key only ever lives as an
* in-memory Map key and is never logged or surfaced. Over-keying is the safe
* side: a var change that didn't really change the backend costs one cache
* miss (heuristic seed until the next result), while under-keying would serve
* one backend's window for another's. */
* miss (the default window until Claude Code reports it), while under-keying
* would serve one backend's window for another's. */
export function providerCacheKeyFor(env: Record<string, string | undefined>): string {
return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
}
@@ -107,31 +107,24 @@ export function cacheResultContextWindow(
/** The context window to report *right now* for a model, with NO IPC on the
* critical path: the cached authoritative value if we've learned it (from a
* prior turn's `result.modelUsage`, this or any session on the same backend),
* else the text heuristic over the model row's identity strings, else the
* default. Derives the cache key itself — `modelInfo?.resolvedModel ?? modelId`,
* the same rule at every seed site — so read keys can't drift from the write
* site's spelling. `authoritative` reports whether the value came from the
* cache: an authoritative window can legitimately equal
* DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the caller. */
* else DEFAULT_CONTEXT_WINDOW. The model's names do not give the window:
* Claude Code 2.1.323 reports 1M for `sonnet`, and 200K for it under
* `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. Derives the cache key itself —
* `modelInfo?.resolvedModel ?? modelId`, the same rule at every seed site — so
* read keys can't drift from the write site's spelling. `authoritative`
* reports whether the value came from the cache: an authoritative window can
* legitimately equal DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the
* caller. */
export function immediateContextWindow(
providerCacheKey: string,
modelId: string,
modelInfo?: Pick<ModelInfo, "resolvedModel" | "displayName" | "description">,
modelInfo?: Pick<ModelInfo, "resolvedModel">,
): { size: number; authoritative: boolean } {
const cached = contextWindowCache.get(
contextWindowCacheKey(providerCacheKey, modelInfo?.resolvedModel ?? modelId),
);
if (cached !== undefined) return { size: cached, authoritative: true };
return {
size:
inferContextWindowFromModel(
modelId,
modelInfo?.resolvedModel,
modelInfo?.displayName,
modelInfo?.description,
) ?? DEFAULT_CONTEXT_WINDOW,
authoritative: false,
};
return { size: DEFAULT_CONTEXT_WINDOW, authoritative: false };
}
/** Forgets the learned windows, as a logout asks: 1M-context entitlement is

View File

@@ -18,6 +18,7 @@ import type {
AskUserQuestionOutput,
} from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
import {
AIR_CUSTOM_ANSWER_FIELDS_KEY,
AIR_CUSTOM_ANSWER_KEY,
LEGACY_AIR_CUSTOM_ANSWER_KEY,
withAirMeta,
@@ -257,6 +258,15 @@ export function askUserQuestionsToCreateRequest(
...(toolCallId ? { toolCallId } : {}),
message,
requestedSchema,
...(airClient && questions.length > 0
? {
_meta: withAirMeta(
undefined,
AIR_CUSTOM_ANSWER_FIELDS_KEY,
questions.map((_, index) => questionCustomFieldKey(index)),
),
}
: {}),
};
}
@@ -587,6 +597,17 @@ export async function answerMcpElicitation(
}
}
/**
* Whether `toolUseID` is the id of a question that Claude Code asks on its own
* (its `confirmWithUser`), such as whether to download a connector's file. It
* asks through `canUseTool` as AskUserQuestion under a `confirm_<uuid>` id,
* and reads the answer from the callback's result: no tool_use and no
* tool_result of the stream carry that id.
*/
export function isConfirmQuestion(toolUseID: string): boolean {
return toolUseID.startsWith("confirm_");
}
/**
* Presents the AskUserQuestion tool's questions as a form elicitation of
* `sessionId` through `elicit`, and returns the answers as the tool's

View File

@@ -10,6 +10,13 @@ import {
} from "@anthropic-ai/claude-agent-sdk";
import { createHash } from "node:crypto";
import { loadFullSessionHistory } from "./resumed-session.js";
import { forkPointOf } from "./session-cursors.js";
import {
cutAtRewindPoint,
loadRewindableHistory,
pendingRewindEnd,
withoutRewoundBranch,
} from "./session-rewind.js";
import { assistantMessageText } from "./session-failure-extension.js";
import { SessionTiming } from "./session-timing.js";
@@ -176,6 +183,15 @@ function isUnknownSessionError(error: unknown, sessionId: string): boolean {
);
}
/**
* Copies the transcript of `params.sessionId` into a new session: all of it,
* or with a `cursorId` the history before that session cursor (see
* `session-cursors.ts`).
*
* Fails with invalid params (-32602) for a `cursorId` that is no cursor of
* the session's stored history. ACP forbids forking the whole session, or at
* another position, in its place.
*/
export async function forkSession(
params: ForkSessionRequest,
dependencies: ForkSessionDependencies,
@@ -195,11 +211,32 @@ async function forkTranscript(
dependencies: ForkSessionDependencies,
): Promise<ForkSessionResponse> {
const timing = new SessionTiming(dependencies.logger, "fork", params.sessionId);
if (params.cursorId != null) {
// The history as a replay reads it, which announces the cursors: cut at a
// pending rewind, so a cursor of a dropped turn is no cursor.
const { visible: history } = await loadRewindableHistory(params.sessionId);
const upToMessageId = forkPointOf(params.cursorId, history);
timing.phase("cursor", ` resolution=${upToMessageId ? "found" : "missing"}`);
if (upToMessageId === undefined) {
throw RequestError.invalidParams(
{ cursorId: params.cursorId },
`Session ${params.sessionId} has no cursor ${params.cursorId} that a fork can start at. Use a cursor that the session announced with the fork capability, or send the request without cursorId to fork the whole session.`,
);
}
const forked = await forkClaudeSession(params.sessionId, { upToMessageId });
timing.phase("sdk-fork");
return { sessionId: forked.sessionId };
}
const point = forkPoint(params._meta);
// SDK `dir` scopes source lookup, not the fork's working directory. Search
// all projects: params.cwd can name a different workspace for the new session.
if (!point) {
const forked = await forkClaudeSession(params.sessionId);
// A pending rewind ends the conversation at its point, not at the newest leaf.
const rewoundEnd = await pendingRewindEnd(params.sessionId);
const forked = await forkClaudeSession(
params.sessionId,
...(rewoundEnd ? [{ upToMessageId: rewoundEnd }] : []),
);
timing.phase("sdk-fork", " resolution=latest");
return { sessionId: forked.sessionId };
}
@@ -208,7 +245,9 @@ async function forkTranscript(
const liveUuid = candidateIds
.map((candidateId) => dependencies.liveMessageIdToUuid?.get(candidateId))
.find(Boolean);
const history = liveUuid ? undefined : await getSessionMessages(params.sessionId);
const history = liveUuid
? undefined
: await cutAtRewindPoint(params.sessionId, await getSessionMessages(params.sessionId));
timing.phase("active-history", ` resolution=${liveUuid ? "live" : "pending"}`);
const messageUuid =
liveUuid ??
@@ -225,7 +264,10 @@ async function forkTranscript(
const fullHistoryUuid = messageUuid
? undefined
: resolveFromFullHistory(
await loadFullSessionHistory(params.sessionId),
await withoutRewoundBranch(
params.sessionId,
await loadFullSessionHistory(params.sessionId),
),
candidateIds,
point,
dependencies.messageIdForGrouping,

View File

@@ -1,9 +1,11 @@
/**
* `--hide-claude-auth`: this integration must never bill a claude.ai
* subscription. Under the flag the agent hides the claude.ai login method from
* `initialize`, and refuses with `authRequired` every session and every turn
* that a subscription would pay for. `v1/acp-agent.ts` decides when the guard
* applies (flag on, no provider override); this module decides what it refuses.
* subscription, except a Claude Enterprise plan. Under the flag the agent hides
* the claude.ai login method from `initialize`, and refuses with `authRequired`
* every session and every turn that a Free, Pro, Max or Team plan would pay
* for. `v1/acp-agent.ts` and `v2/subscription-guard.ts` decide when the guard
* applies (flag on, no provider override); {@link claudeAuthRefusal} decides
* what it refuses.
*
* The guard judges the `AccountInfo` that the SDK caches at `initialize`. That
* cache never changes during the life of a query, but the CLI itself picks up
@@ -77,6 +79,11 @@ const API_KEY_SOURCES_ABOVE_SUBSCRIPTION: ReadonlySet<string> = new Set([
"/login managed key",
]);
/** `none` is the SDK's explicit no-token source. */
function hasTokenSource(account: AccountInfo): boolean {
return Boolean(account.tokenSource && account.tokenSource !== "none");
}
/**
* True when a turn on this account is paid by a claude.ai subscription.
*
@@ -85,8 +92,8 @@ const API_KEY_SOURCES_ABOVE_SUBSCRIPTION: ReadonlySet<string> = new Set([
* proves it, and an unknown value keeps the guard on.
*
* - `subscriptionType` must be set. Without it the CLI reports no subscription.
* - `tokenSource` must be absent. The CLI sets it in place of the subscription
* when a bearer or OAuth environment token pays for the turn.
* - `tokenSource` must be absent, empty, or `none`. A bearer or OAuth
* environment token takes precedence over the subscription.
* - `apiProvider` must be absent or `firstParty`. The SDK documents that the
* Anthropic OAuth login applies only to `firstParty`; for a third-party
* backend such as `bedrock`, `vertex`, `foundry` or `gateway` the other
@@ -99,7 +106,7 @@ export function billsClaudeSubscription(account: AccountInfo | undefined): boole
if (!account?.subscriptionType) {
return false;
}
if (account.tokenSource) {
if (hasTokenSource(account)) {
return false;
}
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
@@ -108,6 +115,20 @@ export function billsClaudeSubscription(account: AccountInfo | undefined): boole
return !API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
}
/**
* True when `subscriptionType` names a Claude Enterprise plan, which the flag
* lets pay for turns: Anthropic allows an Enterprise plan in third-party
* integrations.
*
* The SDK's `AccountInfo` carries the CLI's display name, "Claude Enterprise";
* older CLIs report the raw plan, "enterprise". Any other value is refused,
* including a "Claude <name>" built from a custom `plan_display_name` in the
* claude.ai profile: the guard cannot tell which plan that name belongs to.
*/
export function isClaudeEnterprisePlan(subscriptionType: string | undefined): boolean {
return /^(claude\s+)?enterprise$/i.test(subscriptionType?.trim() ?? "");
}
/**
* True when the account already holds a credential this integration accepts:
* a third-party backend, a bearer or OAuth environment token, or one of the
@@ -125,12 +146,33 @@ export function holdsNonSubscriptionCredential(account: AccountInfo | undefined)
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
return true;
}
if (account.tokenSource) {
if (hasTokenSource(account)) {
return true;
}
return API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
}
/**
* The refusal the flag gives a session or turn on `account`, or `undefined`
* when the account may run it:
*
* - a subscription pays, and it is not {@link isClaudeEnterprisePlan}:
* {@link claudeSubscriptionNotSupportedError};
* - no subscription pays and the account holds no other credential (signed
* out): {@link claudeLoginRequiredError}.
*
* Session creation on v1 and v2 and the per-turn guard all decide through
* this function.
*/
export function claudeAuthRefusal(account: AccountInfo): RequestError | undefined {
if (billsClaudeSubscription(account)) {
return isClaudeEnterprisePlan(account.subscriptionType)
? undefined
: claudeSubscriptionNotSupportedError();
}
return holdsNonSubscriptionCredential(account) ? undefined : claudeLoginRequiredError();
}
export function claudeSubscriptionNotSupportedError(): RequestError {
return RequestError.authRequired(
{ reason: CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON satisfies AuthRequiredReason },
@@ -214,8 +256,8 @@ type GuardOptions = {
* real account. This guard does not see the residual case the module header
* names either.
*
* A turn is refused when the account bills a subscription, and also when it
* holds nothing this integration accepts, which is the user signing out in
* A turn is refused when the account bills a subscription other than Claude
* Enterprise, and also when it holds nothing this integration accepts, which is the user signing out in
* mid-session. The refusal mirrors the signed-out path exactly (see
* `failActiveWithSessionFailure` for `auth_required` in `v1/acp-agent.ts`): every
* client gets the `authRequired` JSON-RPC rejection that starts its own auth
@@ -257,13 +299,7 @@ async function evaluateGuard(options: GuardOptions): Promise<RequestError | unde
error instanceof Error ? error.message : String(error),
);
}
if (billsClaudeSubscription(account)) {
return claudeSubscriptionNotSupportedError();
}
if (!holdsNonSubscriptionCredential(account)) {
return claudeLoginRequiredError();
}
return undefined;
return claudeAuthRefusal(account);
}
/** The account the SDK cached at `initialize`. `undefined` when the query

View File

@@ -8,7 +8,8 @@ import type { Logger } from "./logger.js";
/**
* What a core advertises as `options` in its session capabilities:
* `session/options`, and `configOptions` on its setup requests.
* `session/options`, and `configOptions` on its setup requests, `session/fork`
* included.
*/
export const SESSION_OPTIONS_CAPABILITY = {};
@@ -27,7 +28,7 @@ export function initialConfigOptions<E extends { configId: string }>(
if (seen.has(configId)) {
throw RequestError.invalidParams(
{ configId },
`\`configOptions\` sets ${configId} more than once. Send one entry for each config option.`,
`configOptions sets ${configId} more than once. Send one entry for each config option.`,
);
}
seen.add(configId);

View File

@@ -1,5 +1,28 @@
import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
/** The machine policy sources that `machinePolicy.didNotLoad` names. */
const POLICY_SOURCES: Record<string, string> = {
profile: "the macOS MDM profile",
registry: "the Windows registry policy",
file: "the managed-settings file",
};
/**
* The machine policy sources that may be there and did not load
* (`machinePolicy.didNotLoad`, SDK 0.3.323), named for a log line: "the macOS
* MDM profile, the managed-settings file". The resolved settings show such a
* source as absent, so the adapter applies nothing from it, and Claude Code
* reads the policy itself. Undefined when every source loaded, and when the
* SDK does not report it.
*/
export function unloadedPolicySources(
resolved: Pick<Awaited<ReturnType<typeof resolveSettings>>, "machinePolicy">,
): string | undefined {
const unloaded = resolved.machinePolicy?.didNotLoad;
if (!unloaded || unloaded.length === 0) return undefined;
return unloaded.map((kind) => POLICY_SOURCES[kind] ?? kind).join(", ");
}
/**
* Applies the managed-policy tier's env vars to `process.env` before any SDK
* call, so the SDK subprocess inherits them. Going through `resolveSettings`
@@ -28,6 +51,13 @@ export async function applyManagedPolicyEnv(
console.error("Failed to resolve managed policy settings:", error);
return;
}
const unloaded = unloadedPolicySources(policy);
if (unloaded) {
console.error(
`Managed settings did not load from ${unloaded}: its env vars are not applied. ` +
"Restart the agent to read it again.",
);
}
for (const [key, value] of Object.entries(policy.effective.env ?? {})) {
env[key] = value;
}

View File

@@ -1,6 +1,6 @@
import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
import type { McpServerStatus, Query } from "@anthropic-ai/claude-agent-sdk";
import { escapeMarkdown } from "./usage-markdown.js";
import { codeSpan, escapeMarkdown } from "./usage-markdown.js";
import { raceTimeoutAndAbort } from "./utils.js";
/** The `/mcp` entry of `available_commands_update`. The adapter shows the
@@ -105,20 +105,6 @@ function needsReconnect(status: McpServerStatus): boolean {
);
}
/** The text as a Markdown code span. The fence is longer than the longest
* backtick run in the text, so the span shows the text unchanged. The user
* can copy a server name from it into `/mcp reconnect`. */
function codeSpan(text: string): string {
const longestRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
const fence = "`".repeat(longestRun + 1);
// CommonMark strips one space from each end of a span that is not all spaces
// (line endings count as spaces), so a pad keeps the text unchanged. Plain
// string checks, not one regex: `^ .*[^ ].* $` backtracks quadratically.
const strippedByCommonMark = text.startsWith(" ") && text.endsWith(" ") && /[^ \r\n]/.test(text);
const pad = text.startsWith("`") || text.endsWith("`") || strippedByCommonMark ? " " : "";
return `${fence}${pad}${text}${pad}${fence}`;
}
function isErrorCode(segment: string): boolean {
return /^-?\d+$/.test(segment);
}

View File

@@ -1,16 +1,106 @@
import type { McpServer } from "@agentclientprotocol/sdk/unstable";
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
import {
isMcpServerAcp,
McpOverAcpCaller,
type HasConnectionContext,
type McpServer,
type McpServerAcp,
type ToolCallStatus,
} from "@agentclientprotocol/sdk/unstable";
import {
McpOverAcpHttpBridge,
type McpHttpRequestAttribution,
type McpHttpRequestInfo,
} from "@agentclientprotocol/sdk/experimental/mcp-http";
import type {
HookCallbackMatcher,
McpHttpServerConfig,
McpServerConfig,
} from "@anthropic-ai/claude-agent-sdk";
import { AnnouncedChildren } from "./acp-subagents.js";
import { startupFailureReasonOf } from "./startup-failure.js";
import { isFinalToolCallStatus } from "./tool-calls/renderer.js";
/**
* The SDK configs of a session's ACP MCP servers, by name. HTTP and SSE
* servers keep their URL and headers; a server without `type` is stdio. A
* server of any other transport is left out: the session's `initialize`
* advertises none.
* Where Claude Code's MCP client (2.1.330) puts the id of the tool use in the
* `params._meta` of the `tools/call` that it sends for it. Its other requests,
* such as `server/discover` and `tools/list`, have none.
*/
export function sdkMcpServers(
const TOOL_USE_ID_META = "claudecode/toolUseId";
/**
* The `agent_type` in the hooks of an agent that a workflow runs (Claude Code
* 2.1.330). Such an agent gets no `task_started` and never a child session,
* and its tool uses do not stream: the root session shows its work on the
* Workflow call. A user can give an agent definition the same name: its
* agents are ordinary subagents.
*/
const WORKFLOW_AGENT_TYPE = "workflow-subagent";
/**
* How long an MCP request of a subagent waits for the `subagent_update` of
* the subagent's child session, before it goes out without a session (see
* {@link McpOverAcp.announcementWaitMs}).
*
* The wait covers a session that reads Claude Code's stream after the
* request arrives. With a scripted model, which answers at once, a session
* sent the report of a subagent's tool call 1.5 to 12 ms before the request
* of that tool use arrived (15 runs with Claude Code 2.1.330 on one machine),
* and it sends the child's announcement before that report. So the session
* is ahead by milliseconds when it is not busy. 500 ms is about 40 times the
* largest of these gaps, as room for a session that is.
*
* A longer wait would cost more where it cannot help: a replay can hold an
* announcement for longer than any wait, and an agent that the adapter
* cannot tell from a subagent, but that never gets a child session, waits
* this long for each of its tool uses.
*/
const ANNOUNCEMENT_WAIT_MS = 500;
/**
* The hook matcher of the tools of the MCP servers `names`. Claude Code
* (2.1.330) matches it against the whole name of a tool, which is
* `mcp__<server>__<tool>` with `_` for each character of the server's name
* outside `[A-Za-z0-9_-]`: `mcp__my_tools__echo` for the server `my tools`.
*/
function mcpToolsMatcher(names: readonly string[]): string {
const servers = names.map((name) => name.replace(/[^A-Za-z0-9_-]+/g, "_+"));
return `mcp__(?:${servers.join("|")})__.*`;
}
/**
* Makes the SDK config of an MCP server that the client serves over the ACP
* connection (`"type": "acp"`): {@link McpOverAcp.sdkConfig} for a connection.
*/
export type McpOverAcpConfig = (server: McpServerAcp) => Promise<McpHttpServerConfig>;
/**
* A client MCP server that Claude Code is not given, so it lists no entry for
* it. This is the entry it would list: `failed`, with the error.
*/
export type UnservedMcpServer = { name: string; status: "failed"; error: string };
/** A session's ACP MCP servers, as {@link sdkMcpServers} sorts them. */
export type SdkMcpServers = {
/** The SDK configs of the servers that Claude Code gets, by name. */
configs: Record<string, McpServerConfig>;
/** The `acp` servers that `overAcp` made no config for. */
unserved: UnservedMcpServer[];
};
/**
* The SDK configs of a session's ACP MCP servers. HTTP and SSE servers keep
* their URL and headers; a server without `type` is stdio; an `acp` server
* gets the config that `overAcp` makes. When `overAcp` rejects, the server is
* in `unserved` with the error and the session starts without it, as it
* starts without a server that Claude Code cannot connect to. A server of any
* other transport is left out: the session's `initialize` advertises none.
*/
export async function sdkMcpServers(
servers: readonly McpServer[] | null | undefined,
): Record<string, McpServerConfig> {
overAcp: McpOverAcpConfig,
): Promise<SdkMcpServers> {
const configs: Record<string, McpServerConfig> = {};
const unserved: UnservedMcpServer[] = [];
for (const server of servers ?? []) {
if ("type" in server && (server.type === "http" || server.type === "sse")) {
configs[server.name] = {
@@ -20,6 +110,16 @@ export function sdkMcpServers(
? Object.fromEntries(server.headers.map((e) => [e.name, e.value]))
: undefined,
};
} else if ("type" in server && server.type === "acp") {
try {
configs[server.name] = await overAcp(server);
} catch (error) {
unserved.push({
name: server.name,
status: "failed",
error: error instanceof Error ? error.message : String(error),
});
}
} else if (!("type" in server)) {
configs[server.name] = {
type: "stdio",
@@ -29,5 +129,583 @@ export function sdkMcpServers(
};
}
}
return configs;
return { configs, unserved };
}
/**
* What the user is told of each MCP server that a managed
* `disableSideloadFlags` keeps out of a session.
*/
const NOT_FROM_AN_APPROVED_SOURCE =
"Your organization's managed settings (disableSideloadFlags) let Claude Code use MCP servers only from sources that your administrator approved.";
/**
* The names of a session's MCP servers: its ACP servers, and the servers of
* the client's SDK options (`_meta.claudeCode.options.mcpServers`).
*/
export function mcpServerNames(
servers: readonly object[] | null | undefined,
sdkServers: Record<string, unknown> | undefined,
): string[] {
return [
// A v2 server of an extension transport (`type: "_…"`) needs no name.
...(servers ?? []).flatMap((server) =>
"name" in server && typeof server.name === "string" ? [server.name] : [],
),
...Object.keys(sdkServers ?? {}),
];
}
/**
* A session's MCP servers when Claude Code refuses to start with them (see
* {@link startAroundRefusedMcpServers}): Claude Code gets none, and each is
* unserved with the reason. `names` are the session's {@link mcpServerNames}.
*/
export function refusedMcpServers(names: Iterable<string>): SdkMcpServers {
return {
configs: {},
unserved: [...new Set(names)].map((name) => ({
name,
status: "failed",
error: NOT_FROM_AN_APPROVED_SOURCE,
})),
};
}
/**
* Runs `start(false)`, the start of a session's query. With a managed
* `disableSideloadFlags`, Claude Code takes MCP servers and plugins only from
* sources that the administrator approved, and refuses a start that brings
* others (`sideload_flags_disabled`, SDK 0.3.331). When it refuses a start
* that has MCP servers, this runs `start(true)`: the same start without them
* (see {@link refusedMcpServers}).
*
* Claude Code decides at every start. The adapter reads no policy of its own,
* so a session gets its servers back at its next start once the setting is
* gone. The second start can be refused too, e.g. over the client's
* `plugins`: that error is thrown.
*/
export async function startAroundRefusedMcpServers<T>(
hasMcpServers: boolean,
start: (withoutMcpServers: boolean) => Promise<T>,
): Promise<T> {
try {
return await start(false);
} catch (error) {
if (!hasMcpServers || startupFailureReasonOf(error) !== "sideload_flags_disabled") throw error;
return start(true);
}
}
/**
* Serves the MCP servers that a client declares with `"type": "acp"` to Claude
* Code (MCP-over-ACP). Claude Code's MCP client connects to a command or a
* URL, so each server gets an MCP 2026-07-28 HTTP endpoint on 127.0.0.1 that
* sends every MCP request to the client as an `mcp/message` request (the ACP
* SDK's `McpOverAcpHttpBridge`). The `acp` servers of a connection share one
* listener, which closes with the connection. A request needs the bearer
* token of its server, which only that server's config carries.
*
* The endpoint takes no `initialize`. Claude Code (2.1.325) sends
* `server/discover` to an HTTP server first, unless
* `MCP_PROTOCOL_NEGOTIATION=legacy` or its
* `tengu_mcp_protocol_negotiation_http` flag turns that off. Then it sends
* `initialize`, and the server is listed as failed.
*
* An `mcp/message` request names the ACP session and the tool call that it is
* sent for (`sessionId` and `toolCallId`), when the adapter knows them. An
* HTTP request does not say them. It carries the id of its tool use (see
* {@link TOOL_USE_ID_META}), and the adapter learns each tool use of an `acp`
* server's tool from a PreToolUse hook, before Claude Code runs the tool
* ({@link toolUseHooks}). Both cores report a tool call under the id of its
* tool use, so that id is the `toolCallId`.
*
* When a `session/update` reported a tool call of that id ({@link sending}),
* the request names the session of that report, and the tool call. Before
* the report, and without one, it names by the agent that runs the tool:
*
* - the main conversation: the root session, and the tool call;
* - a subagent with an announced child session: that session, and the tool
* call;
* - a subagent of a client without child sessions: the root session, which
* reports the subagent's tool calls, and the tool call;
* - an agent that never gets a child session: the root session, whose work
* it does, and no tool call, since no session reports one. These are an
* agent that a workflow runs, and any agent of a client without child
* sessions that the core does not know as a subagent;
* - a subagent whose child session is not announced yet, because the session
* has not read its start or a replay holds its `subagent_update`: the
* request waits for that announcement, for at most
* {@link announcementWaitMs}, and then names the child session and the tool
* call. When the time passes first, it names nothing;
* - any other agent: nothing, without a wait. The core forgot its child
* session, or no `subagent_update` announces one for it.
*
* The root session never stands in for a child session.
*
* A request names neither when one of these holds:
*
* - it has no tool use id, as `server/discover` and `tools/list` have none;
* - no PreToolUse hook reported its tool use, as for a server that a resume
* gave the session's running query ({@link sessionServersChanged}), or the
* tool use ended;
* - the client closed the root session, or its last setup request did not
* declare the request's server;
* - the session of the agent is a child session that no `subagent_update`
* announced to the client: one of AIR's draft, one that a conversation
* reset made the core forget, or one whose announcement did not go out
* within {@link announcementWaitMs};
* - the agent has the type of a workflow's agents, the client gets child
* sessions, and the session defines an agent of that name: the agent can
* be a subagent whose child session is not announced yet.
*
* Nothing orders the tool call's report before the request. Claude Code
* streams a tool use before it runs the tool, but the session can read its
* stream after the HTTP request arrives. The request then names a tool call
* that the client does not hold yet.
*/
export class McpOverAcp {
private readonly caller = new McpOverAcpCaller();
private readonly bridge = new McpOverAcpHttpBridge(this.caller, {
attribution: (request) => this.attribution(request),
});
/** The `acp` servers of each active session that has any, or whose query started with any. */
private readonly sessions = new Map<string, SessionServers>();
/** The child sessions that a `subagent_update` announced to the client (see {@link sending}). */
private readonly children = new AnnouncedChildren();
/** The tool uses of `acp` servers' tools that Claude Code runs, by id (see {@link toolUseHooks}). */
private readonly toolUses = new Map<string, ToolUse>();
/**
* The session of each tool call that the client holds without a final
* status, by tool call id (see {@link sending}).
*/
private readonly toolCalls = new Map<string, string>();
/**
* The requests that wait for the announcement of their agent's child
* session, by tool use id: what ends each one's wait (see {@link held}).
*/
private readonly waiting = new Map<string, Set<() => void>>();
/**
* How long a request waits for the announcement of its agent's child
* session (see {@link ANNOUNCEMENT_WAIT_MS}). Mutable so tests can change it.
*/
announcementWaitMs: number = ANNOUNCEMENT_WAIT_MS;
/**
* Hands an `mcp/message` notification of the client (such as the progress
* of a tool call) to the HTTP response of the MCP request that it names. An
* agent app registers it for `methods.agent.mcp.message`.
*/
readonly handleNotification = this.caller.handleNotification;
/**
* The SDK config of `server` for the sessions of the connection behind
* `client`. A server gets the same config every time for as long as the
* connection lives, so a session that restarts or resumes with the same
* servers sees no change. Rejects when the listener cannot open (e.g.
* `listen EPERM` where the process may not open a socket), or the
* connection is closed. The next call tries to open the listener again.
*/
async sdkConfig(
client: HasConnectionContext,
server: McpServerAcp,
): Promise<McpHttpServerConfig> {
let http;
try {
http = await this.bridge.toHttp(client, { ...server, type: "acp" });
} catch (error) {
throw new Error(
`The adapter could not open the local endpoint that serves it to Claude Code (${
error instanceof Error ? error.message : String(error)
}). A new session tries again.`,
{ cause: error },
);
}
return {
type: "http",
url: http.url,
headers: Object.fromEntries(http.headers.map((header) => [header.name, header.value])),
};
}
/**
* A setup request (`session/new`, `load`, `resume` or `fork`) made the
* session `sessionId` active with `servers`, on a query that started with
* the hooks of {@link toolUseHooks} for them.
*/
sessionStarted(sessionId: string, servers: readonly McpServer[] | null | undefined): void {
const acp = (servers ?? []).filter(isMcpServerAcp);
if (acp.length === 0) {
this.sessions.delete(sessionId);
return;
}
this.sessions.set(sessionId, {
declared: new Set(acp.map((server) => server.serverId)),
hooked: new Set(acp.map((server) => server.name)),
});
}
/**
* A setup request gave the active session `sessionId` the servers
* `servers` in place of its earlier ones, on its running query. Returns
* the names of the `acp` servers among them that the query did not start
* with. Its hooks cannot change, so no hook reports the tool uses of these
* servers, and their requests name no session until the session's next
* query starts.
*/
sessionServersChanged(
sessionId: string,
servers: readonly McpServer[] | null | undefined,
): string[] {
const acp = (servers ?? []).filter(isMcpServerAcp);
const hooked = this.sessions.get(sessionId)?.hooked ?? new Set<string>();
if (acp.length === 0 && hooked.size === 0) this.sessions.delete(sessionId);
else {
this.sessions.set(sessionId, {
declared: new Set(acp.map((server) => server.serverId)),
hooked,
});
}
return acp.flatMap((server) => (hooked.has(server.name) ? [] : [server.name]));
}
/**
* The client ended the session `sessionId` (`session/close`, or a request
* that closes it too, such as `session/delete`): its requests and those of
* its child sessions name no session from now on. Forgets its servers, its
* announced children, its tool uses and its tool calls.
*/
sessionClosed(sessionId: string): void {
for (const [toolUseId, toolUse] of this.toolUses) {
if (toolUse.rootSessionId !== sessionId) continue;
this.toolUses.delete(toolUseId);
this.release(toolUseId);
}
for (const [toolCallId, session] of this.toolCalls) {
if (this.rootOf(session) === sessionId) this.toolCalls.delete(toolCallId);
}
this.children.rootClosed(sessionId);
this.sessions.delete(sessionId);
}
/**
* Takes a session update that goes to the client. A `subagent_update`
* announces a child session. A `tool_call`, or a `tool_call_update` with a
* status, reports a tool call of its session, which is kept until an update
* of that session or of another one under the same root gives the tool call
* a final status. That update also ends the tool use of the same id. An
* announcement, and a tool call's report, end the wait of the requests
* that they let name a session (see {@link held}).
*
* Only the tool calls of an active session with `acp` servers
* ({@link sessionStarted}) and of its announced child sessions are kept. The
* tool calls of a child session of AIR's draft, which a `subagent_spawned`
* announces, are not.
*/
sending(notification: SentUpdate): void {
this.children.sending(notification);
const { sessionId, update } = notification;
const { sessionUpdate, toolCallId, status } = update;
if (sessionUpdate === "subagent_update") {
for (const toolUseId of [...this.waiting.keys()]) {
if (this.toolUses.get(toolUseId)?.awaits === update.sessionId) this.release(toolUseId);
}
}
if (sessionUpdate !== "tool_call" && sessionUpdate !== "tool_call_update") return;
if (typeof toolCallId !== "string") return;
const root = this.rootOf(sessionId);
if (isFinalToolCallStatus(status as ToolCallStatus | null | undefined)) {
this.toolEnded(toolCallId, root);
} else if ((sessionUpdate === "tool_call" || status != null) && this.sessions.has(root)) {
this.toolCalls.set(toolCallId, sessionId);
// A request that waits can name the session of this report.
this.release(toolCallId);
}
}
/**
* The hooks of the query of the root session `sessionId`, which starts with
* `servers`, or undefined when none of them is an `acp` server: such a
* query has no MCP request to name a session for. They record each tool
* use of a tool of the `acp` servers before Claude Code runs it
* (PreToolUse), with the session of the agent that runs it (see the class
* doc), until the tool returned or failed (PostToolUse,
* PostToolUseFailure). Claude Code runs them for no other tool, and they
* make no decision.
*
* A tool use that neither hook ends, such as one that Claude Code does not
* run after all, stays until its tool call gets a final status
* ({@link sending}) or the client closes the session
* ({@link sessionClosed}).
*/
toolUseHooks(
sessionId: string,
servers: readonly McpServer[] | null | undefined,
agents: SessionAgents,
): Record<"PreToolUse" | "PostToolUse" | "PostToolUseFailure", HookCallbackMatcher> | undefined {
const acp = (servers ?? []).filter(isMcpServerAcp);
if (acp.length === 0) return undefined;
const matcher = mcpToolsMatcher(acp.map((server) => server.name));
const starts: HookCallbackMatcher = {
matcher,
hooks: [
async (input, toolUseId) => {
if (toolUseId !== undefined) {
this.toolUses.set(toolUseId, {
rootSessionId: sessionId,
...agentSession(sessionId, input, agents, (child) => this.children.has(child)),
});
}
return { continue: true };
},
],
};
const ends: HookCallbackMatcher = {
matcher,
hooks: [
async (_input, toolUseId) => {
if (toolUseId !== undefined) this.toolEnded(toolUseId, sessionId);
return { continue: true };
},
],
};
return { PreToolUse: starts, PostToolUse: ends, PostToolUseFailure: ends };
}
/** The root session of the announced child session `sessionId`, or `sessionId` itself. */
private rootOf(sessionId: string): string {
return this.children.rootOf(sessionId) ?? sessionId;
}
/**
* Forgets the tool use `id` and its tool call, when they are of the root
* session `root`, and ends the wait of the tool use's requests. A fork
* replays the tool calls of its original under their ids: its updates
* leave those of the original alone.
*/
private toolEnded(id: string, root: string): void {
if (this.toolUses.get(id)?.rootSessionId === root) {
this.toolUses.delete(id);
this.release(id);
}
const reportedIn = this.toolCalls.get(id);
if (reportedIn !== undefined && this.rootOf(reportedIn) === root) this.toolCalls.delete(id);
}
/**
* Resolves when a request of the tool use `toolUseId` need wait no longer
* for the announcement of its agent's child session: {@link release} ended
* the wait, {@link announcementWaitMs} passed, or `abandoned` aborted. It
* never rejects.
*
* `abandoned` is the bridge's signal for the request. It aborts when Claude
* Code closes the request's HTTP connection or the ACP connection closes.
* The bridge then sends nothing, whatever the request names.
*
* Nothing that an announcement needs waits for the request. The hook that
* recorded the tool use has answered. The session reads Claude Code's
* stream whatever its tools do, and Claude Code wrote the subagent's start
* to that stream before it ran the subagent's tool. A replay ends without
* the request too.
*/
private held(toolUseId: string, abandoned: AbortSignal): Promise<void> {
if (abandoned.aborted) return Promise.resolve();
return new Promise((resolve) => {
const waiters = this.waiting.get(toolUseId) ?? new Set<() => void>();
this.waiting.set(toolUseId, waiters);
const end = () => {
clearTimeout(timer);
abandoned.removeEventListener("abort", end);
waiters.delete(end);
if (waiters.size === 0 && this.waiting.get(toolUseId) === waiters) {
this.waiting.delete(toolUseId);
}
resolve();
};
const timer = setTimeout(end, this.announcementWaitMs);
// The request's HTTP connection keeps the process alive, not this timer.
timer.unref();
abandoned.addEventListener("abort", end, { once: true });
waiters.add(end);
});
}
/**
* Ends the wait of the requests of the tool use `toolUseId` ({@link held}):
* its agent's child session is announced, its tool call is reported, or it
* ended, also with the close of its session. Each request then names what
* it can.
*/
private release(toolUseId: string): void {
for (const end of [...(this.waiting.get(toolUseId) ?? [])]) end();
}
/**
* The session and tool call that the `mcp/message` request of the MCP
* request `request` names, or undefined when it names none (see the class
* doc). A request of a subagent whose child session is not announced yet
* resolves once it is, or names nothing after {@link announcementWaitMs}.
* It neither throws nor rejects: the bridge would answer Claude Code with
* HTTP 500 instead of sending the request.
*
* It does not read `request.connection`. Each agent app (`v1AgentApp`,
* `v2AgentApp`) makes its own `McpOverAcp` for its one connection, so every
* request and every recorded session is of that connection.
*/
private attribution({
serverId,
params,
signal,
}: McpHttpRequestInfo):
McpHttpRequestAttribution | undefined | Promise<McpHttpRequestAttribution | undefined> {
const meta = params?._meta;
const toolUseId =
typeof meta === "object" && meta !== null
? (meta as Record<string, unknown>)[TOOL_USE_ID_META]
: undefined;
if (typeof toolUseId !== "string") return undefined;
const now = this.named(toolUseId, serverId);
if (now !== "unannounced") return now;
return this.held(toolUseId, signal).then(() => {
const then = this.named(toolUseId, serverId);
return then === "unannounced" ? undefined : then;
});
}
/**
* What a request of the tool use `toolUseId` to the server `serverId` names
* now, or `unannounced` when it names nothing because the child session of
* its agent, which a `subagent_update` announces, is not announced yet.
*/
private named(
toolUseId: string,
serverId: string,
): McpHttpRequestAttribution | undefined | "unannounced" {
const toolUse = this.toolUses.get(toolUseId);
if (!toolUse) return undefined;
const root = toolUse.rootSessionId;
if (!this.sessions.get(root)?.declared.has(serverId)) return undefined;
// The session that reported the tool call names it. A tool call of
// another root has the same id in a fork's replayed history.
const reportedIn = this.toolCalls.get(toolUseId);
if (reportedIn !== undefined && this.rootOf(reportedIn) === root) {
return { sessionId: reportedIn, toolCallId: toolUseId };
}
const { sessionId, awaits } = toolUse;
if (sessionId !== undefined && this.rootOf(sessionId) === root) {
return toolUse.reportsToolCall ? { sessionId, toolCallId: toolUseId } : { sessionId };
}
// Not the root, and no announced child of it. Once the child session of
// its agent is announced, that session reports the agent's tool calls.
if (awaits === undefined) return undefined;
return this.rootOf(awaits) === root
? { sessionId: awaits, toolCallId: toolUseId }
: "unannounced";
}
}
/**
* What {@link McpOverAcp.toolUseHooks} asks the core of a session about the
* agents of its query.
*/
export type SessionAgents = {
/**
* Whether the client gets a child session per subagent. Without child
* sessions, the root session's updates carry the work of every agent.
*/
childSessions: boolean;
/**
* The session whose updates report the tool calls of the subagent `agentId`
* as the core routes them now: its announced child session, or the root
* session for a client without child sessions. Undefined for an agent that
* the core does not know as a subagent (it has not read its
* `task_started`, which an agent that a workflow runs never gets), and for
* one whose child session is not announced.
*/
reporting(agentId: string): string | undefined;
/**
* The id of the child session that a `subagent_update` announces for the
* subagent `agentId`, whether it went out yet or not. Undefined for a
* client that gets no child session from a `subagent_update`: one without
* child sessions, or with those of AIR's draft.
*/
childSessionId(agentId: string): string | undefined;
/** Whether the session had an agent definition of the name `name` when its query started. */
definesAgent(name: string): boolean;
};
/**
* The session of the agent that runs the tool use of the PreToolUse hook
* `input`, for a query of the root session `root`, whether that session
* reports the tool use as a tool call, and the child session whose
* announcement a request of the tool use waits for (see the class doc of
* {@link McpOverAcp}). `announced` says whether a `subagent_update` announced
* a child session.
*/
function agentSession(
root: string,
input: { agent_id?: string; agent_type?: string },
agents: SessionAgents,
announced: (child: string) => boolean,
): Pick<ToolUse, "sessionId" | "reportsToolCall" | "awaits"> {
// A session reports the tool calls of the messages that it reads, but for
// the work that a cancel stopped: it drops that work's tool uses, and its
// tool can run all the same. Nothing tells that at this point, so the
// request of such a tool use names a tool call that the client never gets.
if (input.agent_id === undefined) return { sessionId: root, reportsToolCall: true };
const reporting = agents.reporting(input.agent_id);
const child = agents.childSessionId(input.agent_id);
if (reporting !== undefined) {
// A child session whose `subagent_update` has not gone out, as a replay
// can hold it: a request waits for it.
return {
sessionId: reporting,
reportsToolCall: true,
...(reporting === child ? { awaits: child } : {}),
};
}
// No session reports the tool calls of this agent. Its work is the root's
// when it cannot be a child session: the client gets none, or a workflow
// runs it. An agent definition of the workflow agents' type makes that
// type say nothing: its agent can be a child that is not announced yet.
const workflowType = input.agent_type === WORKFLOW_AGENT_TYPE;
if (!agents.childSessions || (workflowType && !agents.definesAgent(WORKFLOW_AGENT_TYPE))) {
return { sessionId: root, reportsToolCall: false };
}
// The core does not know the agent as a subagent. One whose start it has
// not read yet gets its child session next: a request waits for it. Not an
// agent of the workflow agents' type, which mostly gets none, and not one
// whose child session was announced before: the core forgot that child at
// a conversation reset, and reports nothing of it any more.
const awaits = child !== undefined && !workflowType && !announced(child) ? child : undefined;
return { sessionId: undefined, reportsToolCall: false, ...(awaits ? { awaits } : {}) };
}
/** The `acp` servers of an active session. */
type SessionServers = {
/** The `serverId`s of the session's last setup request. */
declared: ReadonlySet<string>;
/** The names of the ones that its query started with, whose tool uses its hooks report. */
hooked: ReadonlySet<string>;
};
/** A tool use that Claude Code runs. */
type ToolUse = {
/** The root session whose query runs it. */
rootSessionId: string;
/** The session of the agent that runs it, when it has one that a request can name. */
sessionId: string | undefined;
/** Whether that session reports it as a tool call, under its id. */
reportsToolCall: boolean;
/**
* The child session of its agent that a request of it waits for while no
* `subagent_update` has announced it, and names once one has.
*/
awaits?: string;
};
/** A session update that goes to the client, as far as {@link McpOverAcp.sending} reads it. */
type SentUpdate = {
sessionId: string;
update: { sessionUpdate: string; sessionId?: unknown; toolCallId?: unknown; status?: unknown };
};

View File

@@ -3,12 +3,13 @@ import {
type SessionConfigOption,
type SessionNotification,
} from "@agentclientprotocol/sdk/unstable";
import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
import { realpath } from "node:fs/promises";
import path from "node:path";
import type { AcpSessionNotification, SubagentForm, SubagentState } from "./acp-subagents.js";
import { AIR_SUBAGENT_KEY, airExtensionMeta } from "./air-extension.js";
import { orderedConfigOptions } from "./session-config-options.js";
import { MODEL_CONFIG_ID } from "./session-model.js";
import { orderedSubagentConfiguration } from "./subagent-configuration.js";
import { isFinalToolCallStatus } from "./tool-calls/renderer.js";
/** The work state of a child, as the RFD's `subagent_update.state` carries it. */
@@ -56,8 +57,16 @@ export type NativeSubagent = {
promptIds?: Set<string>;
/** The RFD form: the calls that delegated to the child, whose runs ended. */
endedRuns?: Set<string>;
/** The RFD form: the calls that delegated to the child, whose runs handed back a report. */
/** The calls that delegated to the child, whose runs handed back a report. */
handedBack?: Set<string>;
/** Whether a message of it came (see `NativeSubagentRuntime.messageCame`). */
heard?: boolean;
/**
* The RFD form: the call that launched it is no Agent or Task call, such as
* the Skill call of a forked skill. The client is shown that call, so the
* prompt does not replace it.
*/
launchShown?: boolean;
announced?: boolean;
/**
* The RFD form: the `cwd` that the client holds for the child. Undefined or
@@ -117,10 +126,17 @@ export type TaskEnd = {
/** The SDK's reason for an unusual end, such as `worker_restart`. */
reason?: string;
/**
* The adapter knows that the work ended, but not why: the stream ended, or
* the conversation was reset, with the task still running.
* The adapter knows that the work ended, but not why: the stream ended
* with the task still running.
*/
unexplained?: boolean;
/**
* The adapter stops following the task, which may still run: the
* conversation was reset, and the runtime forgets its children.
*/
unobservable?: boolean;
/** Whether the task ran in the foreground of its parent's work when it ended. */
foreground?: boolean;
};
type TaskStarted = {
@@ -129,8 +145,52 @@ type TaskStarted = {
subagentType?: unknown;
description?: unknown;
prompt?: unknown;
/** The name of the tool of the call `toolUseId`, when the session has that call. */
launchTool?: string;
/** The task of the subagent that started this one. None means the root session. */
parentTaskId?: string;
};
/**
* Whether the end of a subagent's run waits for its messages. Claude Code
* (2.1.328) holds the messages of a forked skill that the user typed, such as
* `/code-review`, and writes them after its next `init` or before its next
* result: most or all of them come after the task's end. Nothing but that
* order tells such a subagent apart: no tool call launched it, and it ran in
* the foreground.
*/
export function endWaitsForMessages(run: { launched: boolean; foreground: boolean }): boolean {
return !run.launched && run.foreground;
}
/**
* Whether `message` ends the wait of an agent's end (see
* {@link endWaitsForMessages}):
*
* - the turn's result, which Claude Code writes after the agent's messages;
* - Claude Code's `idle`, for a turn that ends without a result;
* - once a message of the agent came (`heard`), the first message of the main
* conversation (`parent_tool_use_id: null`). Another subagent's message
* ends no wait: Claude Code holds the messages of the subagents that the
* agent launched along with the agent's own.
*
* Without a message, no more come: the turn or the query ended, or the
* conversation was reset.
*/
export function endsMessageWait(
message:
{ type: string; subtype?: unknown; state?: unknown; parent_tool_use_id?: unknown } | undefined,
heard: boolean,
): boolean {
if (message === undefined || message.type === "result") return true;
if (message.type === "system") {
return message.subtype === "session_state_changed" && message.state === "idle";
}
const conversation =
message.type === "assistant" || message.type === "user" || message.type === "stream_event";
return conversation && heard && message.parent_tool_use_id === null;
}
export type SubagentIdentity = {
name?: string;
description?: string;
@@ -199,6 +259,8 @@ export class NativeSubagentRuntime {
*/
private readonly childByToolCall = new Map<string, NativeSubagent>();
private readonly taskFinishPromises = new Map<string, Promise<void>>();
/** The ends that wait for their tasks' messages (see {@link finishTask}), by task id. */
private readonly heldEnds = new Map<string, { status: unknown; end?: TaskEnd }>();
/** The session that made each SendMessage call. */
private readonly senderByToolUse = new Map<string, string>();
/**
@@ -225,6 +287,11 @@ export class NativeSubagentRuntime {
string,
{ initial: AcpSessionNotification; message?: string; delegationId?: string }
>();
/**
* The RFD form: the agent that each TaskStop or SendMessage call names (see
* {@link targetAgentId}), until the call's final update.
*/
private readonly targetByToolCall = new Map<string, string>();
private readonly generationByTaskId = new Map<string, number>();
private readonly pending = new Map<string, AcpSessionNotification[]>();
private pendingCount = 0;
@@ -280,7 +347,10 @@ export class NativeSubagentRuntime {
const routed = await this.routeUpdate(notification, deliver, forcedSessionId);
if (!routed) return routed;
this.rememberSendMessage(routed);
return this.form === "rfd" ? this.routeRfdSendMessage(routed, forcedSessionId) : routed;
if (this.form !== "rfd") return routed;
this.rememberTarget(routed);
const shown = this.routeRfdSendMessage(routed, forcedSessionId);
return shown && this.withTarget(shown);
}
/**
@@ -334,6 +404,58 @@ export class NativeSubagentRuntime {
return JSON.parse(published) as SessionConfigOption[];
}
/**
* The RFD form: what is current of the children that work now, for the
* time after a `session/load` or `session/resume` of the session that runs
* them. The client discarded the state and the capabilities it held for
* them, and need not keep their place in the session tree, so each one is
* announced again on its parent: with its labels, its `cwd`, the `cancel`
* capability and its state, then the configuration that the client last
* got for it. `covered` names the children that the load's replay reports
* instead (see `RfdSubagentReplay.currentStates`).
*
* An announced child that no longer works but has one that does, such as a
* background child of its own, is announced first, with its labels and
* `cwd` only: nothing of it is current, but its child's updates name it.
* Parents come before their children.
*/
currentChildren(covered: (sessionId: string) => boolean): AcpSessionNotification[] {
if (this.form !== "rfd") return [];
const bySession = new Map<string, NativeSubagent>();
for (const child of this.children.values()) {
if (child.announced && !covered(child.sessionId)) bySession.set(child.sessionId, child);
}
const ordered: NativeSubagent[] = [];
const add = (child: NativeSubagent) => {
if (ordered.includes(child)) return;
const parent = bySession.get(child.parentSessionId);
if (parent) add(parent);
ordered.push(child);
};
for (const child of bySession.values()) if (isWorking(child)) add(child);
return ordered.flatMap((child): AcpSessionNotification[] => {
const announcement = rfdAnnouncement(child, child.reportedCwd);
if (!isWorking(child)) return [{ sessionId: child.parentSessionId, update: announcement }];
const configOptions = this.configurationOf(child.sessionId);
const state: WorkState =
child.workState === "requires_action" ? { state: "requires_action" } : { state: "running" };
return [
{
sessionId: child.parentSessionId,
update: { ...announcement, capabilities: { cancel: {} }, state },
},
...(configOptions
? [
{
sessionId: child.sessionId,
update: { sessionUpdate: "config_option_update" as const, configOptions },
},
]
: []),
];
});
}
/**
* Takes configuration options of the child `agentId`: an SDK agent id, as a
* hook names it, or a child session id. Hook observations can precede the
@@ -389,7 +511,7 @@ export class NativeSubagentRuntime {
// so a delayed publication cannot replace newer settings with older ones.
const publishing = config.publishing.then(async () => {
if (this.configBySession.get(child.sessionId) !== config || ended()) return;
const configOptions = orderedSubagentConfiguration(config.options.values());
const configOptions = orderedConfigOptions(config.options.values());
const snapshot = JSON.stringify(configOptions);
if (config.published === snapshot) return;
await this.publish({
@@ -592,8 +714,8 @@ export class NativeSubagentRuntime {
await this.reportConfiguration(announcedChild.sessionId, update.configOptions, update._meta);
return null;
}
if (this.form === "rfd" && announcedChild?.announced) {
const handback = await this.routeRfdHandback(notification, announcedChild);
if (announcedChild?.announced) {
const handback = await this.routeHandback(notification, announcedChild);
if (handback !== undefined) return handback;
}
if (owner) return this.toChild(owner, notification, toolCallId);
@@ -616,6 +738,131 @@ export class NativeSubagentRuntime {
return notification;
}
/**
* Takes a message of the query, before its updates are routed.
*
* A subagent's message names it by `agent_id`. A child that no tool call
* launched has no id that its updates could go by: a forked skill that the
* user typed sends `forked-command-<skill>` as `parent_tool_use_id`, for
* every run of the skill. From this message on, the updates under that id
* are the child's, and no longer those of an earlier run's child.
*
* It also ends the runs whose ends waited for their messages (see
* {@link finishTask} and {@link endsMessageWait}). Only then does it return
* a promise, for the caller to await: a caller that awaited every message
* would let a cancel run between a message and its handling.
*/
messageCame(
message: {
type: string;
subtype?: unknown;
state?: unknown;
parent_tool_use_id?: unknown;
agent_id?: unknown;
},
deliver: Publish,
): Promise<void> | undefined {
if (!this.enabled) return undefined;
const { parent_tool_use_id: launchId, agent_id: agentId } = message;
const child = typeof agentId === "string" ? this.children.get(agentId) : undefined;
if (child && typeof agentId === "string" && typeof launchId === "string") {
child.heard = true;
if (
child.parentToolUseId === undefined &&
this.childByParentToolUse.get(launchId) !== child
) {
this.taskByToolUse.set(launchId, agentId);
this.childByParentToolUse.set(launchId, child);
}
}
return this.releaseHeldEnds(deliver, message);
}
/**
* Ends the runs whose wait `message` ends; without a message, all of them.
* Undefined when it ends none.
*/
private releaseHeldEnds(
deliver: Publish,
message?: Parameters<typeof endsMessageWait>[0],
): Promise<void> | undefined {
if (this.heldEnds.size === 0) return undefined;
const ended = [...this.heldEnds].filter(([taskId]) =>
endsMessageWait(message, this.children.get(taskId)?.heard === true),
);
if (ended.length === 0) return undefined;
return (async () => {
for (const [taskId, held] of ended) {
this.heldEnds.delete(taskId);
await this.finishTask(taskId, held.status, deliver, undefined, held.end);
}
})();
}
/**
* The session of the call that launched `task`, when the session has that
* call and it is no Agent, Task or SendMessage call, such as the Skill call
* of a forked skill: the session of the subagent that made it, once that
* one is announced, or the root session.
*/
private shownLaunchParent(task: TaskStarted): string | undefined {
if (
!task.toolUseId ||
task.launchTool === undefined ||
task.launchTool === "SendMessage" ||
isNativeSubagentControlTool(task.launchTool)
) {
return undefined;
}
if (task.parentTaskId === undefined) return this.rootSessionId;
const parent = this.children.get(task.parentTaskId);
return parent?.announced ? parent.sessionId : undefined;
}
/** A launch result can carry the report even when the SDK sends no child stream. */
async toolResult(message: SDKUserMessage): Promise<void> {
if (!this.enabled || !Array.isArray(message.message.content)) return;
const results = message.message.content.filter((block) => block.type === "tool_result");
const result = results[0];
if (results.length !== 1 || result?.type !== "tool_result" || result.is_error) return;
const text = handbackReportText(message.tool_use_result);
if (text === undefined) return;
const launchId = result.tool_use_id;
const child = this.childByParentToolUse.get(launchId);
if (!child) return;
await this.announce(child);
if (child.handedBack?.has(launchId)) return;
await this.publishHandback(child, launchId, text, `${launchId}:handback`);
}
private async publishHandback(
child: NativeSubagent,
delegationId: string,
text: string,
messageId: string,
): Promise<void> {
(child.handedBack ??= new Set()).add(delegationId);
if (this.form === "air") {
await this.publish({
sessionId: child.sessionId,
update: {
sessionUpdate: "agent_message_chunk",
messageId,
content: { type: "text", text },
},
});
} else {
for (const view of linkedSessionMessages(
messageId,
child.sessionId,
child.parentSessionId,
text,
)) {
await this.publish(view);
}
}
}
async taskStarted(task: TaskStarted, deliver: Publish): Promise<void> {
if (!this.enabled) return;
const known =
@@ -665,9 +912,11 @@ export class NativeSubagentRuntime {
// A SendMessage resume reuses the finished generation's tool id, whose
// control state is already cleaned up.
const shownLaunchParent = this.shownLaunchParent(task);
const knownParentSessionId =
(task.toolUseId ? this.parentByToolUse.get(task.toolUseId) : undefined) ??
(previous && this.resumedParentSessionId(previous));
(previous && this.resumedParentSessionId(previous)) ??
shownLaunchParent;
const identity = task.toolUseId ? this.identityByToolUse.get(task.toolUseId) : undefined;
// A nested child must wait for the spawning Agent/Task frame to establish
// its immediate parent. Root children without a tool id can be announced.
@@ -693,6 +942,7 @@ export class NativeSubagentRuntime {
identity?.subagentType ?? task.subagentType,
identity?.description ?? task.description,
),
...(shownLaunchParent !== undefined ? { launchShown: true } : {}),
},
!!knownParentSessionId || !task.toolUseId,
deliver,
@@ -791,6 +1041,8 @@ export class NativeSubagentRuntime {
/**
* Reports that the SDK ended the task's work. `end` has what the SDK says
* about it: its text for a failure, and its reason for an unusual end.
* The end of a child whose messages Claude Code holds until after it (see
* {@link endWaitsForMessages}) is reported once they came.
*/
async finishTask(
taskId: string,
@@ -821,6 +1073,23 @@ export class NativeSubagentRuntime {
if (this.form === "rfd") await this.supplyError(child, state, end?.error);
return;
}
const held = this.heldEnds.get(taskId);
if (held) {
// A second report of an end that waits can give the text of its failure.
if (end?.error && !held.end?.error) held.end = { ...held.end, error: end.error };
return;
}
if (
child.announced &&
endWaitsForMessages({
launched: child.parentToolUseId !== undefined,
foreground: end?.foreground === true,
})
) {
// The run ends once its messages came (see `messageCame`).
this.heldEnds.set(taskId, { status, end: { ...end, foreground: false } });
return;
}
const finish = Promise.resolve().then(async () => {
try {
@@ -828,7 +1097,10 @@ export class NativeSubagentRuntime {
if (child.parentToolUseId) {
for (const pending of this.takePending(child.parentToolUseId)) await deliver(pending);
}
if (this.form === "rfd") {
if (this.form === "rfd" && end?.unobservable) {
// The child's `cancel` goes with it: a forgotten child cannot be stopped.
await this.reportState(child, { state: "unknown" }, { capabilities: null });
} else if (this.form === "rfd") {
await this.reportState(child, rfdEndState(state, end));
child.missingError = state === "failed" && !end?.error && !end?.unexplained;
if (child.parentToolUseId) (child.endedRuns ??= new Set()).add(child.parentToolUseId);
@@ -853,14 +1125,39 @@ export class NativeSubagentRuntime {
/**
* Ends every child that still runs, because the stream ended or the
* conversation was reset. AIR's draft reports `state` for each. In the RFD
* form the cause of each child's end is unknown, so it is idle with no stop
* reason: a child that a cancel stopped already reported it from the SDK's
* events, and a background child that outlived the cancel was not cancelled.
* conversation was reset. AIR's draft reports `state` for each.
*
* The RFD form, at the end of the stream: Claude Code's process ran the
* children and is gone, or the caller closes the query next, which
* terminates it, so their work ended. Its cause is unknown, so each is idle with no stop reason: a
* child that a cancel stopped already reported it from the SDK's events,
* and a background child that outlived the cancel was not cancelled.
*
* The RFD form, at a conversation reset (`mayStillRun`): Claude Code can
* keep the old conversation's subagents running, and the caller forgets
* them next (`clear`), so no later event of theirs is reported. Their work
* did not end as far as the adapter knows, so each is `unknown`, as the
* RFD requires when a child can no longer be observed, and loses its
* `cancel` capability. A child that is idle keeps its state.
*/
async finishAll(state: SubagentState, deliver: Publish): Promise<void> {
async finishAll(
state: SubagentState,
deliver: Publish,
{ mayStillRun = false }: { mayStillRun?: boolean } = {},
): Promise<void> {
const errors: unknown[] = [];
const end = this.form === "rfd" ? { unexplained: true } : undefined;
const end: TaskEnd | undefined =
this.form !== "rfd"
? undefined
: mayStillRun
? { unobservable: true }
: { unexplained: true };
try {
// An end that waited for its task's messages is that task's end.
await this.releaseHeldEnds(deliver);
} catch (error) {
errors.push(error);
}
try {
for (const taskId of [...this.children.keys()].reverse()) {
try {
@@ -910,14 +1207,21 @@ export class NativeSubagentRuntime {
* of this runtime. AIR's draft grants no `cancel`.
*/
async cancelChild(sessionId: string, stop: (taskId: string) => Promise<void>): Promise<boolean> {
if (this.form !== "rfd") return false;
for (const [taskId, child] of this.children) {
if (child.sessionId !== sessionId || !child.announced) continue;
child.cancels = (child.cancels ?? 0) + 1;
await stop(taskId);
return true;
const announced = this.announcedChild(sessionId);
if (!announced) return false;
const [taskId, child] = announced;
child.cancels = (child.cancels ?? 0) + 1;
await stop(taskId);
return true;
}
/** The RFD form: the announced child session `sessionId`, with its task id. */
private announcedChild(sessionId: string): [string, NativeSubagent] | undefined {
if (this.form !== "rfd") return undefined;
for (const entry of this.children) {
if (entry[1].sessionId === sessionId && entry[1].announced) return entry;
}
return false;
return undefined;
}
/**
@@ -1235,13 +1539,25 @@ export class NativeSubagentRuntime {
await this.publishConfiguration(child);
}
/** The RFD form: publishes the work state of `child` on its parent. */
private async reportState(child: NativeSubagent, state: WorkState): Promise<void> {
/**
* The RFD form: publishes the work state of `child` on its parent, with
* `capabilities` when the child's change with it.
*/
private async reportState(
child: NativeSubagent,
state: WorkState,
capabilities?: { capabilities: null },
): Promise<void> {
child.workState = state.state;
child.missingError = false;
await this.publish({
sessionId: child.parentSessionId,
update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, state },
update: {
sessionUpdate: "subagent_update",
sessionId: child.sessionId,
...capabilities,
state,
},
});
}
@@ -1359,12 +1675,12 @@ export class NativeSubagentRuntime {
}
/**
* The RFD form: an update of a SubagentHandback call of the announced
* `child`, which its report replaces: the child's message to its parent,
* see {@link linkedSessionMessages}. A failed call delivered nothing, so the
* An update of a SubagentHandback call of the announced `child`, which its
* report replaces. RFD also sends the parent an incoming session message.
* A failed call delivered nothing, so the
* child is shown the call after all. `undefined` for any other update.
*/
private async routeRfdHandback(
private async routeHandback(
notification: AcpSessionNotification,
child: NativeSubagent,
): Promise<AcpSessionNotification | null | undefined> {
@@ -1387,15 +1703,12 @@ export class NativeSubagentRuntime {
if (!isFinalToolCallStatus(update.status)) return null;
this.handbacks.delete(update.toolCallId);
if (update.status === "completed" && handback.message) {
for (const view of linkedSessionMessages(
update.toolCallId,
child.sessionId,
child.parentSessionId,
await this.publishHandback(
child,
handback.delegationId ?? update.toolCallId,
handback.message,
)) {
await this.publish(view);
}
if (handback.delegationId) (child.handedBack ??= new Set()).add(handback.delegationId);
update.toolCallId,
);
return null;
}
return unexposedControlFallback(handback.initial, notification, child.sessionId);
@@ -1439,6 +1752,44 @@ export class NativeSubagentRuntime {
return unexposedControlFallback(sendMessage.initial, notification, sendMessage.sender);
}
/** The RFD form: remembers the agent that a TaskStop or SendMessage call names. */
private rememberTarget({ update }: AcpSessionNotification): void {
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return;
const claudeMeta = update._meta?.claudeCode as { toolName?: unknown } | undefined;
const agentId = targetAgentId(claudeMeta?.toolName, update.rawInput);
if (agentId !== undefined) this.targetByToolCall.set(update.toolCallId, agentId);
}
/**
* The RFD form: `notification`, an update that the client is shown, with
* the RFD's `session` reference when it is of a tool call that operates on
* an announced child of another session (see {@link withSessionReference}):
*
* - a TaskStop or SendMessage call that names the child by its agent id;
* - a SendMessage call that resumed the child, and stays shown because a
* permission request showed it;
* - an Agent/Task call that launched the child, and stays shown for the
* same reason;
* - the call that launched a child and is no Agent/Task call, such as the
* Skill call of a forked skill, which always stays shown.
*
* The RFD requires the announcement before the reference, so a call whose
* child is not announced yet gets none.
*/
private withTarget(notification: AcpSessionNotification): AcpSessionNotification {
const { update } = notification;
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
return notification;
}
const agentId = this.targetByToolCall.get(update.toolCallId);
if (isFinalToolCallStatus(update.status)) this.targetByToolCall.delete(update.toolCallId);
const child =
this.childByParentToolUse.get(update.toolCallId) ??
(agentId !== undefined ? this.children.get(agentId) : undefined);
if (!child?.announced || child.sessionId === notification.sessionId) return notification;
return withSessionReference(notification, child.sessionId);
}
/** Whether `update` is of an Agent/Task call, by its tool name or, in the
* RFD form, by the id of a call the client is not shown. */
private isControlUpdate(
@@ -1500,10 +1851,12 @@ export class NativeSubagentRuntime {
this.cwdBySession.clear();
this.childByParentToolUse.clear();
this.taskFinishPromises.clear();
this.heldEnds.clear();
this.senderByToolUse.clear();
this.hiddenLaunches.clear();
this.hiddenSendMessages.clear();
this.handbacks.clear();
this.targetByToolCall.clear();
this.generationByTaskId.clear();
this.pending.clear();
this.pendingCount = 0;
@@ -1598,6 +1951,7 @@ export class NativeSubagentRuntime {
| "title"
| "role"
| "description"
| "launchShown"
>,
announce: boolean,
deliver: Publish,
@@ -1691,6 +2045,24 @@ export function responseModelEntry(
return models?.entry(model) ?? { value: model, name: models?.name(model) ?? model };
}
/**
* The RFD form: the `subagent_update` that names `child` on its parent, with
* the parent's labels for it and `cwd`, its working directory when that is
* not its parent's.
*/
function rfdAnnouncement(
child: NativeSubagent,
cwd: string | null | undefined,
): Extract<AcpSessionNotification["update"], { sessionUpdate: "subagent_update" }> {
return {
sessionUpdate: "subagent_update",
sessionId: child.sessionId,
...(child.title ? { title: child.title } : {}),
...(child.description ? { description: child.description } : {}),
...(cwd ? { cwd } : {}),
};
}
/**
* Announces the child on its parent, once, before any update of the child.
* The RFD form announces it as running and then sends the prompt as the
@@ -1713,18 +2085,15 @@ export async function announceNativeSubagent(
await publish({
sessionId: child.parentSessionId,
update: {
sessionUpdate: "subagent_update",
sessionId: child.sessionId,
...(child.title ? { title: child.title } : {}),
...(child.description ? { description: child.description } : {}),
...(cwd ? { cwd } : {}),
...rfdAnnouncement(child, cwd),
capabilities: { cancel: {} },
state: { state: "running" },
},
});
if (cwd) child.reportedCwd = cwd;
child.announced = true;
// The immediate parent made the Agent/Task call that launched the child.
// The immediate parent made the call that launched the child. The
// prompt replaces an Agent/Task call, and not a call that stays shown.
if (child.prompt) {
await publishPrompt(
child,
@@ -1732,7 +2101,7 @@ export async function announceNativeSubagent(
child.parentToolUseId,
child.parentSessionId,
publish,
{ replacesCall: true },
{ replacesCall: !child.launchShown },
);
}
return;
@@ -1835,7 +2204,7 @@ async function publishPrompt(
* prompt goes from the parent to the child, a SendMessage call, whose message
* goes from its sender to a child, or a child's SubagentHandback call, whose
* report goes from the child to the parent. Both views use the
* call's tool use id, and each names the other with the draft RFD's
* call's tool use id, and each names the other with the RFD's
* `recipientMessageId` and `senderMessageId`.
*/
export function linkedSessionMessages(
@@ -1863,6 +2232,49 @@ export function linkedSessionMessages(
];
}
/**
* The RFD form: the agent that a tool call names as the one it operates on:
* the `task_id` of a TaskStop call, or the `to` of a SendMessage call. It is
* an agent only if it is the id of one: an agent's id is its child session's
* id. Both tools also take a name, which is not resolved here: Claude Code
* resolves it, and the adapter cannot tell which agent it picked. `undefined`
* for any other call.
*/
export function targetAgentId(toolName: unknown, rawInput: unknown): string | undefined {
if (typeof rawInput !== "object" || rawInput === null) return undefined;
const input = rawInput as { task_id?: unknown; to?: unknown };
if (toolName === "TaskStop") return nonBlankString(input.task_id);
if (toolName === "SendMessage") return nonBlankString(input.to);
return undefined;
}
/**
* The RFD form: `notification`, a tool call's report, with a `session`
* reference to `sessionId` after its content: `{ "type": "session",
* "sessionId": "..." }`, which links the call to the session it operates on.
* A `tool_call_update` replaces the content that the client holds, so the
* reference goes on every report that carries content, and a
* `tool_call_update` without content is returned as it is.
*/
export function withSessionReference(
notification: AcpSessionNotification,
sessionId: string,
): AcpSessionNotification {
const { update } = notification;
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
return notification;
}
if (update.sessionUpdate === "tool_call_update" && update.content == null) return notification;
const content = update.content ?? [];
if (content.some((item) => item.type === "session" && item.sessionId === sessionId)) {
return notification;
}
return {
...notification,
update: { ...update, content: [...content, { type: "session", sessionId }] },
};
}
/**
* The tool with which a child hands its report to its parent, when Claude
* Code runs in hand-back mode. The Agent/Task result then only says that the
@@ -1871,6 +2283,15 @@ export function linkedSessionMessages(
*/
export const HANDBACK_TOOL = "SubagentHandback";
/** The report in an Agent result whose text only points to the hand-back message. */
export function handbackReportText(result: unknown): string | undefined {
const report = result as
{ status?: unknown; handbackReport?: { text?: unknown } } | null | undefined;
if (report?.status !== "completed") return undefined;
const text = report.handbackReport?.text;
return typeof text === "string" && text.trim() ? text : undefined;
}
/** The report of a SubagentHandback call, from its input. */
export function handbackMessage(input: unknown): string | undefined {
const message = (input as { message?: unknown } | null | undefined)?.message;
@@ -1953,6 +2374,9 @@ function isWorking(child: NativeSubagent): boolean {
* A task that a worker restart orphaned, or that was still running when the
* stream ended, is idle with no stop reason: its work ended, but the adapter
* did not see a cancellation or a failure, which the RFD forbids claiming.
*
* A child that the adapter can no longer observe and that may still run is
* not idle but `unknown` (see `NativeSubagentRuntime.finishAll`).
*/
export function rfdEndState(state: SubagentState, end: TaskEnd | undefined): WorkState {
if (end?.unexplained || end?.reason === "worker_restart") return { state: "idle" };

View File

@@ -33,6 +33,9 @@ export interface PermissionOptionContext {
/** False when no ACP turn can continue an accepted plan in a fresh
* context. Then an ExitPlanMode request offers no clear-context option. */
allowContextReset?: boolean;
/** Claude Code's `showClearContextOnPlanAccept` setting. An ExitPlanMode
* request offers the clear-context option only when it is true. */
showClearContextOnPlanAccept?: boolean;
}
export function allowOnce(name = "Yes"): PermissionOption {

View File

@@ -70,7 +70,11 @@ export function buildExitPlanModePermissionOptions(
: (["auto", "bypassPermissions"] as const)
).filter((mode) => modes.has(mode));
const preferredMode = elevatedModes[0] ?? "acceptEdits";
if (context.allowContextReset !== false && plainString(context.input.plan)) {
if (
context.showClearContextOnPlanAccept === true &&
context.allowContextReset !== false &&
plainString(context.input.plan)
) {
const usage =
context.contextUsedPercent === undefined ? "" : ` (${context.contextUsedPercent}% used)`;
options.push(

View File

@@ -1,8 +1,8 @@
/**
* The session updates that show the session's plans. A client with the `plan`
* capability (every v2 client, and a v1 client that asks for it) tracks plans
* by ID and gets `plan_update` and `plan_removed`; any other client gets the
* legacy `plan` update, which holds one ID-less plan per session.
* The session updates that show the session's plans. A v2 client, and a v1
* client that advertises the `plan` capability, tracks plans by ID and gets
* `plan_update` and `plan_removed`; any other v1 client gets the legacy `plan`
* update, which holds one ID-less plan per session.
*/
import type {
PlanEntry,

793
src/plugin-command.ts Normal file
View File

@@ -0,0 +1,793 @@
/**
* `/plugin` (aliases `/plugins`, `/marketplace`), which the adapter serves
* itself. Claude Code's own `/plugin` is an interactive terminal screen and
* answers "/plugin isn't available in this environment." in a session without
* a terminal, which is every ACP session. The adapter instead runs the CLI's
* `claude plugin ...` commands, which have a `--json` form, and then reloads
* the live session so the new plugin's commands, skills and MCP servers appear.
*
* Plugins bring hooks and MCP servers that run as the user, so the set of
* commands and flags below is an allowlist, and it is the only guard. Anything
* outside it, such as `-y`, `--accept-command` or `--json`, gets the usage
* text and never reaches the CLI. Shared by the v1 core and the v2 core.
*/
import { execFile } from "node:child_process";
import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
import type { Query } from "@anthropic-ai/claude-agent-sdk";
import { codeSpan, escapeMarkdown } from "./usage-markdown.js";
/** The content blocks of a prompt, in v1 or v2 form: the command is one text block. */
type PromptContent = ReadonlyArray<{ type: string; text?: unknown }>;
export const PLUGIN_COMMAND_NAME = "plugin";
/** The `/plugin` entry of `available_commands_update`. */
export const PLUGIN_AVAILABLE_COMMAND: AvailableCommand = {
name: PLUGIN_COMMAND_NAME,
description: "Manage Claude Code plugins and marketplaces",
input: { hint: "[install|uninstall|enable|disable|update|list|marketplace …] …" },
};
/** The CLI operations that the adapter runs. */
export type PluginCliOperation =
| "list"
| "install"
| "uninstall"
| "enable"
| "disable"
| "update"
| "marketplace-add"
| "marketplace-list"
| "marketplace-remove"
| "marketplace-update";
export type PluginOperation = PluginCliOperation | "overview" | "usage";
export type PluginCommand =
/** Bare `/plugin` and `/plugin help`: usage, installed plugins and marketplaces. */
| { kind: "overview" }
/** Anything outside the allowlist, or a missing argument. `reason` says which. */
| { kind: "usage"; reason?: string }
/** One CLI run. `argv` is what follows `claude plugin`, without `--json`.
* `target` is the plugin or marketplace name the command is about, if it has one. */
| { kind: "cli"; operation: PluginCliOperation; argv: string[]; target?: string };
const SCOPES = ["user", "project", "local"];
type FlagKind = "bool" | "value" | "list" | "variadic";
interface FlagSpec {
/** The flag's names, such as `["-s", "--scope"]`. The first is its key. */
names: string[];
kind: FlagKind;
/** The allowed values; any value if absent. */
values?: string[];
}
interface Scanned {
positionals: string[];
/** Per flag key: `true` for a bool, else the values in the order given. */
flags: Map<string, true | string[]>;
}
const SCOPE_FLAG: FlagSpec = { names: ["-s", "--scope"], kind: "value", values: SCOPES };
/** Splits `tokens` into positionals and the flags of `specs`. Any other token
* that starts with `-` is an error, so no user text becomes a CLI option. */
function scan(tokens: string[], specs: FlagSpec[]): Scanned | { error: string | undefined } {
const positionals: string[] = [];
const flags = new Map<string, true | string[]>();
for (let i = 0; i < tokens.length; i++) {
let token = tokens[i]!;
if (!token.startsWith("-")) {
positionals.push(token);
continue;
}
if (token === "-h" || token === "--help") return { error: undefined };
let inline: string | undefined;
const equals = token.startsWith("--") ? token.indexOf("=") : -1;
if (equals > 0) {
inline = token.slice(equals + 1);
token = token.slice(0, equals);
if (inline.startsWith("-")) return { error: `\`${token}\` needs a value.` };
}
const spec = specs.find((candidate) => candidate.names.includes(token));
if (!spec) return { error: `\`${token}\` is not supported here.` };
const key = spec.names[0]!;
if (spec.kind === "bool") {
if (inline !== undefined) return { error: `\`${token}\` takes no value.` };
flags.set(key, true);
continue;
}
const values: string[] = [];
if (inline !== undefined) {
values.push(inline);
} else if (spec.kind === "variadic") {
while (i + 1 < tokens.length && !tokens[i + 1]!.startsWith("-")) values.push(tokens[++i]!);
} else if (i + 1 < tokens.length && !tokens[i + 1]!.startsWith("-")) {
values.push(tokens[++i]!);
}
if (values.length === 0 || values.some((value) => value === "")) {
return { error: `\`${token}\` needs a value.` };
}
if (spec.values && !values.every((value) => spec.values!.includes(value))) {
return { error: `\`${token}\` takes one of ${spec.values.join(", ")}.` };
}
const previous = flags.get(key);
if (previous !== undefined && spec.kind !== "list" && spec.kind !== "variadic") {
return { error: `\`${token}\` is given twice.` };
}
flags.set(key, [...(Array.isArray(previous) ? previous : []), ...values]);
}
return { positionals, flags };
}
function flagArgs(scanned: Scanned, specs: FlagSpec[]): string[] {
const args: string[] = [];
for (const spec of specs) {
const key = spec.names[0]!;
const value = scanned.flags.get(key);
if (value === undefined) continue;
const flag = spec.names.find((name) => name.startsWith("--")) ?? key;
if (value === true) args.push(flag);
else if (spec.kind === "list") for (const item of value) args.push(flag, item);
else args.push(flag, ...value);
}
return args;
}
const USAGE_PLUGIN_ARGUMENT = "Give a plugin name, as `name` or `name@marketplace`.";
/** Parses the arguments of a CLI subcommand into a `cli` command. */
function parseSubcommand(
operation: PluginCliOperation,
words: string[],
specs: FlagSpec[],
prefix: string[],
options: { positional: "none" | "one" | "optional"; missing?: string },
): PluginCommand {
const scanned = scan(words, specs);
if ("error" in scanned) return { kind: "usage", reason: scanned.error };
const max = options.positional === "none" ? 0 : 1;
if (scanned.positionals.length > max) {
return { kind: "usage", reason: `Unexpected argument \`${scanned.positionals[max]}\`.` };
}
if (options.positional === "one" && scanned.positionals.length === 0) {
return { kind: "usage", reason: options.missing };
}
const target = scanned.positionals[0];
return {
kind: "cli",
operation,
argv: [...prefix, ...scanned.positionals, ...flagArgs(scanned, specs)],
...(target === undefined ? {} : { target }),
};
}
const LIST_FLAGS: FlagSpec[] = [{ names: ["--available"], kind: "bool" }];
const INSTALL_FLAGS: FlagSpec[] = [
SCOPE_FLAG,
{ names: ["--marketplace"], kind: "value" },
{ names: ["--config"], kind: "list" },
];
const UNINSTALL_FLAGS: FlagSpec[] = [SCOPE_FLAG, { names: ["--keep-data"], kind: "bool" }];
const ENABLE_FLAGS: FlagSpec[] = [SCOPE_FLAG];
const DISABLE_FLAGS: FlagSpec[] = [SCOPE_FLAG, { names: ["-a", "--all"], kind: "bool" }];
const MARKETPLACE_ADD_FLAGS: FlagSpec[] = [SCOPE_FLAG, { names: ["--sparse"], kind: "variadic" }];
function parseMarketplace(words: string[]): PluginCommand {
const [sub, ...rest] = words;
switch (sub) {
case "add":
return parseSubcommand(
"marketplace-add",
rest,
MARKETPLACE_ADD_FLAGS,
["marketplace", "add"],
{
positional: "one",
missing: "Give a marketplace source: a GitHub `owner/repo`, a git URL, or a path.",
},
);
case "list":
case "ls":
return parseSubcommand("marketplace-list", rest, [], ["marketplace", "list"], {
positional: "none",
});
case "remove":
case "rm":
return parseSubcommand("marketplace-remove", rest, [SCOPE_FLAG], ["marketplace", "remove"], {
positional: "one",
missing: "Give the name of the marketplace to remove.",
});
case "update":
return parseSubcommand("marketplace-update", rest, [], ["marketplace", "update"], {
positional: "optional",
});
default:
return { kind: "usage" };
}
}
/**
* Parses `/plugin ...` (also `/plugins ...` and `/marketplace ...`, which are
* aliases: `/marketplace marketplace add x` is `/plugin marketplace add x`,
* and `/marketplace add x` is usage, like `/plugin add x`) from a single-text
* prompt. `null` for any other prompt, which goes to Claude Code.
*/
export function parsePluginCommand(prompt: PromptContent): PluginCommand | null {
const [first] = prompt;
if (prompt.length !== 1 || first?.type !== "text" || typeof first.text !== "string") return null;
// Check the first word before splitting, so a long prompt is not split into words.
const text = first.text.trim();
if (!/^\/(?:plugins?|marketplace)(?:\s|$)/.test(text)) return null;
const [, ...words] = text.split(/\s+/);
const [sub, ...rest] = words;
switch (sub) {
case undefined:
case "help":
return { kind: "overview" };
case "list":
case "ls":
return parseSubcommand("list", rest, LIST_FLAGS, ["list"], { positional: "none" });
case "install":
case "i":
return parseSubcommand("install", rest, INSTALL_FLAGS, ["install"], {
positional: "one",
missing: USAGE_PLUGIN_ARGUMENT,
});
case "uninstall":
case "remove":
case "rm":
return parseSubcommand("uninstall", rest, UNINSTALL_FLAGS, ["uninstall"], {
positional: "one",
missing: USAGE_PLUGIN_ARGUMENT,
});
case "enable":
return parseSubcommand("enable", rest, ENABLE_FLAGS, ["enable"], {
positional: "one",
missing: USAGE_PLUGIN_ARGUMENT,
});
case "disable": {
const command = parseSubcommand("disable", rest, DISABLE_FLAGS, ["disable"], {
positional: "optional",
});
if (command.kind !== "cli") return command;
const all = command.argv.includes("--all");
if (all === (command.target !== undefined)) {
return {
kind: "usage",
reason: all
? "Give either a plugin name or `--all`, not both."
: `${USAGE_PLUGIN_ARGUMENT} Or use \`--all\` to disable every plugin.`,
};
}
return command;
}
case "update":
return parseSubcommand("update", rest, [SCOPE_FLAG], ["update"], {
positional: "one",
missing: USAGE_PLUGIN_ARGUMENT,
});
case "marketplace":
case "market":
return parseMarketplace(rest);
default:
return { kind: "usage", reason: `Unknown subcommand \`${sub}\`.` };
}
}
export type PluginReload = {
status: "applied" | "busy" | "failed" | "unavailable";
/** The names of the plugins the session has after a reload; with `applied`. */
plugins?: string[];
/** Why the reload failed; with `failed`. */
error?: string;
};
export interface PluginCommandResult {
ok: boolean;
operation: PluginOperation;
/** The CLI's own message, or the adapter's when the CLI did not run or did not answer. */
message: string;
/** The CLI's `failureCode`, such as `not_found` or `command_source_refused`. */
failureCode?: string;
/** With `command_source_refused`: the command that the marketplace declares as the install. */
shownCommand?: string;
/** With `shownCommand`: the terminal command that lets the user confirm it. */
terminalCommand?: string;
/** The parsed `--json` output of a list: an array, or `{installed, available}`; for an overview, `{plugins, marketplaces}` plus `pluginsError` or `marketplacesError` for a list that failed. */
data?: unknown;
reload?: PluginReload;
}
export interface ExecOptions {
cwd: string;
env: Record<string, string | undefined>;
signal: AbortSignal;
timeoutMs: number;
}
export interface ExecOutput {
stdout: string;
stderr: string;
/** The exit code. A run that ends with a non-zero code is a result, not an error. */
code: number;
}
/** Runs a program without a shell. Rejects when it cannot start, is aborted,
* times out, or prints too much. */
export type ExecLike = (file: string, args: string[], options: ExecOptions) => Promise<ExecOutput>;
export interface PluginCommandDeps {
cliPath: () => Promise<string>;
cwd: string;
env: Record<string, string | undefined>;
signal: AbortSignal;
/** Read after the CLI ends: the session's query can be replaced while it runs. */
query: () => Query | undefined;
logError: (message: string) => void;
exec?: ExecLike;
}
/** The time that one CLI run can take. A git clone of a marketplace is the slow case. */
const PLUGIN_CLI_TIMEOUT_MS = 5 * 60_000;
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const defaultExec: ExecLike = (file, args, options) =>
new Promise((resolve, reject) => {
const child = execFile(
file,
args,
{
cwd: options.cwd,
env: options.env,
signal: options.signal,
timeout: options.timeoutMs,
maxBuffer: MAX_OUTPUT_BYTES,
encoding: "utf8",
},
(error, stdout, stderr) => {
if (!error) return resolve({ stdout, stderr, code: 0 });
if (typeof error.code === "number") return resolve({ stdout, stderr, code: error.code });
if (error.killed && !options.signal.aborted) {
return reject(new Error(`Timed out after ${options.timeoutMs / 60_000} minutes.`));
}
reject(error);
},
);
// The CLI must not wait on a terminal that does not exist.
child.stdin?.end();
});
/** The operations after which the live session reloads its plugins. */
const RELOADING_OPERATIONS: ReadonlySet<PluginOperation> = new Set([
"install",
"uninstall",
"enable",
"disable",
"update",
"marketplace-remove",
]);
type CliRun =
| { type: "cancelled" }
| { type: "error"; message: string }
| { type: "done"; code: number; stdout: string; stderr: string };
interface CliJson {
outcome?: unknown;
message?: unknown;
failureCode?: unknown;
alreadyInGoalState?: unknown;
shownCommand?: unknown;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** The result line of a `--json` run: the last non-empty line of stdout. The
* CLI can print human-readable lines before it. */
function lastJsonLine(stdout: string): CliJson | undefined {
const lines = stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
const last = lines[lines.length - 1];
if (last === undefined) return undefined;
try {
const parsed: unknown = JSON.parse(last);
return isRecord(parsed) ? (parsed as CliJson) : undefined;
} catch {
return undefined;
}
}
/** The whole of stdout as JSON: a list prints an indented array or object. */
function wholeJson(stdout: string): unknown {
try {
return JSON.parse(stdout.trim());
} catch {
return undefined;
}
}
const MAX_TEXT_LENGTH = 1500;
function plainText(text: string): string {
// eslint-disable-next-line no-control-regex
const stripped = text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "").trim();
return stripped.length > MAX_TEXT_LENGTH ? `${stripped.slice(0, MAX_TEXT_LENGTH)}…` : stripped;
}
function isJsonOptionUnknown(run: { stdout: string; stderr: string }): boolean {
return /unknown option.*--json/i.test(`${run.stderr}\n${run.stdout}`);
}
/** Whether the CLI takes `--json` for the command: `marketplace update` without a name does not. */
function takesJson(command: Extract<PluginCommand, { kind: "cli" }>): boolean {
return !(command.operation === "marketplace-update" && command.target === undefined);
}
async function runCli(
deps: PluginCommandDeps,
exec: ExecLike,
env: Record<string, string | undefined>,
argv: string[],
json: boolean,
): Promise<CliRun> {
if (deps.signal.aborted) return { type: "cancelled" };
const run = async (args: string[]): Promise<CliRun> => {
try {
const file = await deps.cliPath();
const output = await exec(file, args, {
cwd: deps.cwd,
env,
signal: deps.signal,
timeoutMs: PLUGIN_CLI_TIMEOUT_MS,
});
return { type: "done", ...output };
} catch (error) {
if (deps.signal.aborted) return { type: "cancelled" };
const message = error instanceof Error ? error.message : String(error);
deps.logError(`Failed to run \`claude plugin ${argv.join(" ")}\`: ${message}`);
return { type: "error", message: `Could not run the Claude CLI: ${message}` };
}
};
const first = await run(["plugin", ...argv, ...(json ? ["--json"] : [])]);
// A CLI named by CLAUDE_CODE_EXECUTABLE can predate `--json`. It rejects the
// flag before doing anything, so the run is repeated for its text and exit code.
if (json && first.type === "done" && first.code !== 0 && isJsonOptionUnknown(first)) {
return run(["plugin", ...argv]);
}
return first;
}
function cancelled(operation: PluginOperation): PluginCommandResult {
return { ok: false, operation, message: "Cancelled." };
}
function failedToRun(operation: PluginOperation, run: CliRun): PluginCommandResult {
return run.type === "cancelled"
? cancelled(operation)
: { ok: false, operation, message: run.type === "error" ? run.message : "" };
}
function describeCliRun(
command: Extract<PluginCommand, { kind: "cli" }>,
run: Extract<CliRun, { type: "done" }>,
): PluginCommandResult {
const { operation } = command;
const isList = operation === "list" || operation === "marketplace-list";
const json = lastJsonLine(run.stdout);
if (isList) {
const data = wholeJson(run.stdout);
if (run.code === 0 && data !== undefined && typeof data === "object" && data !== null) {
return { ok: true, operation, message: "", data };
}
}
if (!json || typeof json.outcome !== "string") {
const text = plainText(run.code === 0 ? run.stdout || run.stderr : run.stderr || run.stdout);
return {
ok: run.code === 0,
operation,
message: text || (run.code === 0 ? "Done." : `The Claude CLI exited with code ${run.code}.`),
};
}
const message =
typeof json.message === "string" && json.message.trim() !== ""
? plainText(json.message)
: run.code === 0
? "Done."
: `The Claude CLI exited with code ${run.code}.`;
const ok = json.alreadyInGoalState === true || (json.outcome !== "failed" && run.code === 0);
const result: PluginCommandResult = { ok, operation, message };
if (!ok && typeof json.failureCode === "string") result.failureCode = json.failureCode;
if (!ok && isRecord(json.shownCommand) && typeof json.shownCommand.command === "string") {
result.shownCommand = json.shownCommand.command;
if (operation === "install" || operation === "update") {
result.terminalCommand = `claude plugin ${command.argv.map(shellQuote).join(" ")}`;
}
}
return result;
}
// terminalCommand is pasted into a POSIX shell, and argv values are arbitrary
// text: `&` would background, `*` glob and `$(x)` expand unless quoted.
function shellQuote(arg: string): string {
return /^[A-Za-z0-9@%+=:,./_-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
}
async function reloadSession(deps: PluginCommandDeps): Promise<PluginReload> {
const query = deps.query();
if (!query) return { status: "unavailable" };
try {
const response = await query.reloadPlugins({ refuseIfBusy: true });
return { status: "applied", plugins: response.plugins.map((plugin) => plugin.name) };
} catch (error) {
if ((error as { errorCode?: unknown } | null)?.errorCode === "reload_plugins_busy") {
return { status: "busy" };
}
const message = error instanceof Error ? error.message : String(error);
deps.logError(`Failed to reload plugins after /plugin: ${message}`);
return { status: "failed", error: message };
}
}
/** Whether `plugin` (`name` or `name@marketplace`) is among the installed plugin ids. */
function isInstalled(installed: unknown[], plugin: string): boolean {
return installed.some((entry) => {
const id = isRecord(entry) ? entry.id : undefined;
if (typeof id !== "string") return false;
return plugin.includes("@") ? id === plugin : id.split("@")[0] === plugin;
});
}
/**
* Runs a parsed `/plugin` command and, after a change, reloads the session's
* plugins. A failure is in the result: this never throws.
*/
export async function runPluginCommand(
command: PluginCommand,
deps: PluginCommandDeps,
): Promise<PluginCommandResult> {
if (command.kind === "usage") {
return {
ok: false,
operation: "usage",
message: command.reason ?? "",
};
}
const exec = deps.exec ?? defaultExec;
const env = { ...deps.env };
delete env.CLAUDECODE;
delete env.CLAUDE_CODE_CHILD_SESSION;
if (command.kind === "overview") {
const [plugins, marketplaces] = await Promise.all([
runCli(deps, exec, env, ["list"], true),
runCli(deps, exec, env, ["marketplace", "list"], true),
]);
if (plugins.type === "cancelled" || marketplaces.type === "cancelled") {
return cancelled("overview");
}
const read = (run: CliRun): { value?: unknown; error?: string } => {
if (run.type === "error") return { error: run.message };
if (run.type === "done" && run.code === 0) {
const value = wholeJson(run.stdout);
return Array.isArray(value)
? { value }
: { error: "The Claude CLI did not return a list." };
}
const text = run.type === "done" ? plainText(run.stderr || run.stdout) : "";
return {
error: text || `The Claude CLI exited with code ${run.type === "done" ? run.code : "?"}.`,
};
};
const listed = { plugins: read(plugins), marketplaces: read(marketplaces) };
const errors = [listed.plugins.error, listed.marketplaces.error].filter((e) => e !== undefined);
return {
ok: errors.length === 0,
operation: "overview",
message: errors.join("\n"),
data: {
plugins: listed.plugins.value,
marketplaces: listed.marketplaces.value,
pluginsError: listed.plugins.error,
marketplacesError: listed.marketplaces.error,
},
};
}
const { operation } = command;
if (operation === "enable" && command.target !== undefined) {
const listing = await runCli(deps, exec, env, ["list"], true);
if (listing.type === "cancelled") return cancelled(operation);
// When the list cannot be read (an old CLI), the enable runs as typed.
const installed =
listing.type === "done" && listing.code === 0 ? wholeJson(listing.stdout) : undefined;
if (Array.isArray(installed) && !isInstalled(installed, command.target)) {
return {
ok: false,
operation,
message: `Plugin ${command.target} is not installed, so it can't be enabled. Install it first.`,
failureCode: "not_installed",
};
}
}
const run = await runCli(deps, exec, env, command.argv, takesJson(command));
if (run.type !== "done") return failedToRun(operation, run);
const result = describeCliRun(command, run);
if (result.ok && RELOADING_OPERATIONS.has(operation)) {
if (deps.signal.aborted) return cancelled(operation);
result.reload = await reloadSession(deps);
}
return result;
}
const USAGE_LINES = [
"- `/plugin list [--available]`",
"- `/plugin install <plugin>[@marketplace] [--scope user|project|local] [--marketplace <source>] [--config key=value]`",
"- `/plugin uninstall <plugin> [--scope …] [--keep-data]`",
"- `/plugin enable <plugin> [--scope …]`",
"- `/plugin disable <plugin>|--all [--scope …]`",
"- `/plugin update <plugin> [--scope …]`",
"- `/plugin marketplace add <source> [--scope …] [--sparse <path>…]`",
"- `/plugin marketplace list`",
"- `/plugin marketplace remove <name> [--scope …]`",
"- `/plugin marketplace update [<name>]`",
];
function usageMarkdown(): string {
return ["**Usage**", "", ...USAGE_LINES].join("\n");
}
/** Escapes CLI or plugin text. A `claude plugin X` hint in backticks becomes
* the `/plugin X` that works in this chat. */
function renderCliText(text: string): string {
return text
.split(/\r?\n/)
.filter((line) => line.trim() !== "")
.map((line) =>
line
.split(/(`[^`\n]+`)/)
.map((part, index) => {
if (index % 2 === 0) return escapeMarkdown(part);
const code = part.slice(1, -1).replace(/^claude plugins? /, "/plugin ");
return codeSpan(code);
})
.join(""),
)
.join("\n\n");
}
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function installedLine(entry: unknown): string | undefined {
if (!isRecord(entry)) return undefined;
const id = str(entry.id);
if (!id) return undefined;
const details = [
str(entry.version) && `v${str(entry.version)}`,
str(entry.scope) && `${str(entry.scope)} scope`,
entry.enabled === false ? "disabled" : "enabled",
].filter((part): part is string => typeof part === "string");
return `- ${codeSpan(id)} — ${escapeMarkdown(details.join(", "))}`;
}
function availableLine(entry: unknown): string | undefined {
if (!isRecord(entry)) return undefined;
const id = str(entry.pluginId) ?? str(entry.name);
if (!id) return undefined;
const description = str(entry.description);
return `- ${codeSpan(id)}${description ? ` — ${escapeMarkdown(description)}` : ""}`;
}
function marketplaceLine(entry: unknown): string | undefined {
if (!isRecord(entry)) return undefined;
const name = str(entry.name);
if (!name) return undefined;
const source = str(entry.repo) ?? str(entry.url) ?? str(entry.path) ?? str(entry.source);
return `- ${codeSpan(name)}${source ? ` — ${escapeMarkdown(source)}` : ""}`;
}
/** The most available plugins that a reply lists. The official directory has hundreds. */
const MAX_AVAILABLE_LISTED = 40;
function section(title: string, lines: (string | undefined)[], empty: string): string {
const shown = lines.filter((line): line is string => line !== undefined);
return shown.length === 0 ? `**${title}**\n\n${empty}` : `**${title}**\n\n${shown.join("\n")}`;
}
function installedSection(data: unknown): string {
return section(
"Installed plugins",
Array.isArray(data) ? data.map(installedLine) : [],
"None. Run `/plugin install <plugin>` to add one.",
);
}
function marketplacesSection(data: unknown): string {
return section(
"Marketplaces",
Array.isArray(data) ? data.map(marketplaceLine) : [],
"None. Run `/plugin marketplace add <source>` to add one.",
);
}
function availableSection(entries: unknown[]): string {
const lines = entries.map(availableLine).filter((line) => line !== undefined);
const more = lines.length - MAX_AVAILABLE_LISTED;
if (more > 0) lines.splice(MAX_AVAILABLE_LISTED, more, `- … and ${more} more`);
return section("Available plugins", lines, "None.");
}
function reloadLine(reload: PluginReload): string {
if (reload.status === "applied") {
const plugins = reload.plugins ?? [];
return plugins.length === 0
? "Reloaded: the session now has no plugins."
: `Reloaded: the session now has ${plugins.map(codeSpan).join(", ")}.`;
}
if (reload.status === "busy") {
return "The session is busy, so the change was not loaded into it. It applies to new sessions.";
}
if (reload.status === "failed") {
return `Reloading the session's plugins failed${reload.error ? `: ${escapeMarkdown(reload.error)}` : ""}. The change applies to new sessions.`;
}
return "The change applies to new sessions.";
}
/** The chat reply for a result of {@link runPluginCommand}. */
export function pluginCommandMarkdown(result: PluginCommandResult): string {
const blocks: string[] = [];
const data = result.data;
switch (result.operation) {
case "usage":
if (result.message) blocks.push(renderCliText(result.message));
blocks.push(usageMarkdown());
return blocks.join("\n\n");
case "overview": {
const parts = isRecord(data) ? data : {};
const failure = (title: string, error: unknown): string =>
`**${title}**\n\nCould not list: ${renderCliText(String(error))}`;
return [
typeof parts.pluginsError === "string"
? failure("Installed plugins", parts.pluginsError)
: installedSection(parts.plugins),
typeof parts.marketplacesError === "string"
? failure("Marketplaces", parts.marketplacesError)
: marketplacesSection(parts.marketplaces),
usageMarkdown(),
].join("\n\n");
}
case "list":
if (result.ok && isRecord(data)) {
blocks.push(installedSection(data.installed));
blocks.push(availableSection(Array.isArray(data.available) ? data.available : []));
} else if (result.ok && data !== undefined) {
blocks.push(installedSection(data));
}
break;
case "marketplace-list":
if (result.ok && data !== undefined) blocks.push(marketplacesSection(data));
break;
default:
break;
}
if (blocks.length === 0 && result.message) blocks.push(renderCliText(result.message));
if (result.shownCommand !== undefined) {
blocks.push(
`The marketplace declares that this plugin is installed by running a command. The adapter does not run it:\n\n${codeSpan(result.shownCommand)}`,
);
if (result.terminalCommand) {
blocks.push(
`To confirm that command, run ${codeSpan(result.terminalCommand)} in a terminal.`,
);
}
}
if (result.reload) blocks.push(reloadLine(result.reload));
return blocks.join("\n\n");
}

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

@@ -4,7 +4,9 @@
* `providers/disable`, and the legacy gateway logins (`authenticate` or
* `auth/login` with `gateway` or `gateway-bedrock`). Each core holds its own
* {@link ProviderConfig} and gateway login, and builds the query env of its
* sessions with {@link createEnvForProvider}.
* sessions with {@link createEnvForProvider}. It holds that route above the
* user's and the project's settings with {@link providerRouteSettings} and
* {@link applyProviderRoute}.
*/
import {
RequestError,
@@ -15,6 +17,7 @@ import {
type ProviderInfo,
type SetProviderRequest,
} from "@agentclientprotocol/sdk/unstable";
import type { Query } from "@anthropic-ai/claude-agent-sdk";
import {
GatewayListingError,
listBedrockModels,
@@ -187,6 +190,50 @@ export function createEnvForProvider(config: ProviderConfig | null): Record<stri
};
}
/** A provider's route as settings of Claude Code (see {@link providerRouteSettings}). */
export type ProviderRouteSettings = { apiKeyHelper: ""; env: Record<string, string> };
/**
* The route of a provider as settings of Claude Code, for the tier of the
* `settings` option. `env` is the result of {@link createEnvForProvider}.
*
* Claude Code applies the `env` of settings files after the process env, so
* without this tier the user's or the project's settings could restore another
* `ANTHROPIC_BASE_URL`. The empty `apiKeyHelper` turns off a helper of theirs.
*/
export function providerRouteSettings(env: Record<string, string>): ProviderRouteSettings {
return { apiKeyHelper: "", env };
}
/**
* Sends `route` to the running session, into the tier of the `settings`
* option (`applyFlagSettings`). Call it right after the query's initialize
* response, before a request of the session reaches the provider:
* `getContextUsage()` sends one (`count_tokens`).
*
* The `settings` option holds the route too, in one object with the client's
* settings and the model configuration. Claude Code loads that object as a
* whole or not at all: one value that fails validation, e.g.
* `permissions.allow: "Bash"`, leaves all of it out. This call does not depend
* on that object. When the object did load, the call changes nothing: Claude
* Code merges `env` key by key.
*
* Throws when Claude Code refuses the route. The caller must close the query.
*/
export async function applyProviderRoute(
query: Pick<Query, "applyFlagSettings">,
route: ProviderRouteSettings,
): Promise<void> {
try {
await query.applyFlagSettings(route);
} catch (error) {
throw RequestError.internalError(
{ details: error instanceof Error ? error.message : String(error) },
"The session was not started, because Claude Code did not take its provider or gateway route. Try again, or set the provider or the gateway login again.",
);
}
}
function sameHeaders(a: Record<string, string>, b: Record<string, string>): boolean {
const aKeys = Object.keys(a);
return aKeys.length === Object.keys(b).length && aKeys.every((key) => b[key] === a[key]);
@@ -253,13 +300,13 @@ export function validatedGatewayAuthRequest(params: AuthenticateRequest): Gatewa
if (typeof gateway !== "object" || !isValidBaseUrl(gateway.baseUrl)) {
throw RequestError.invalidParams(
{ baseUrl: (gateway as { baseUrl?: unknown }).baseUrl },
"`_meta.gateway.baseUrl` must be a non-empty absolute http(s) URL.",
"_meta.gateway.baseUrl must be a non-empty absolute http(s) URL.",
);
}
if (gateway.headers !== undefined && typeof gateway.headers !== "object") {
throw RequestError.invalidParams(
undefined,
"`_meta.gateway.headers` must be an object of header names to values.",
"_meta.gateway.headers must be an object of header names to values.",
);
}
}
@@ -348,7 +395,7 @@ export function providerConfigFromSetRequest(params: SetProviderRequest): Provid
) {
throw RequestError.invalidParams(
undefined,
"vertex apiType requires non-empty `_meta.claudeCode.vertex.projectId` and `_meta.claudeCode.vertex.region`.",
"vertex apiType requires non-empty _meta.claudeCode.vertex.projectId and _meta.claudeCode.vertex.region.",
);
}
config.vertex = { projectId: vertex.projectId, region: vertex.region };

View File

@@ -1,5 +1,6 @@
/**
* `/remote-control`, which the adapter serves itself, and the messages that a
* `/remote-control`, which the adapter serves itself, Remote Control at the
* start of a session when Claude Code asks for it, and the messages that a
* person types in another client of the session (claude.ai or the Claude
* mobile app, over Remote Control). Shared by the v1 core and the v2
* core, which run the command each in their own turn model.
@@ -9,10 +10,13 @@ type PromptContent = ReadonlyArray<{ type: string; text?: unknown }>;
import type {
Query,
SDKControlInitializeResponse,
SDKUserMessage,
SDKUserMessageReplay,
SlashCommand,
} from "@anthropic-ai/claude-agent-sdk";
import type { Logger } from "./logger.js";
import type { SessionNotice } from "./session-notices.js";
/** Runtime Remote Control control exposed by the pinned Agent SDK. Like
* `mcpAuthenticate`, it is not in the public `Query` declaration yet. The CLI's
@@ -115,6 +119,129 @@ export async function runRemoteControlCommand(
}
}
/** The `initialize` result with `remote_control_auto_enable`, which Claude Code
* resolves from `remoteControlAtStartup` in the settings, else the policy
* default, else a rollout, so it can be on although the user never turned it
* on. An SDK host reads it to start Remote Control with the session as the
* terminal does. Like `enableRemoteControl`, it is not in the public
* declaration yet. */
type RemoteControlInitializeResponse = SDKControlInitializeResponse & {
remote_control_auto_enable?: boolean;
};
/** Whether Claude Code asks for Remote Control to start with the session:
* `remoteControlAtStartup` in the settings, else the policy default, else a
* rollout (see `RemoteControlInitializeResponse`). `false` when the field is
* missing, as from a CLI that predates it. */
export function startsWithRemoteControl(
initializationResult: SDKControlInitializeResponse,
): boolean {
return (
(initializationResult as RemoteControlInitializeResponse).remote_control_auto_enable === true
);
}
/** Starts Remote Control for a session that starts with it, and returns the
* notice that tells the user how it went. A notice cannot be withdrawn once
* sent, so its title reports the connection as an event rather than a state
* that `/remote-control off` would make untrue. A refusal, such as Remote
* Control being disabled by policy, comes back as a warning instead of a
* throw. */
export async function startRemoteControl(
query: RemoteControlQuery,
logger: { error: (...args: unknown[]) => void },
): Promise<SessionNotice> {
try {
const { session_url } = await query.enableRemoteControl(true);
const link = session_url
? `Continue this session from claude.ai/code or the Claude mobile app: ${session_url}`
: "Claude Code did not return a session URL.";
return {
severity: "info",
title: "Remote Control connected",
description: `${link}\nRun /remote-control off to disconnect.`,
};
} catch (error) {
logger.error(`Failed to enable Remote Control: ${error}`);
return {
severity: "warning",
title: "Could not start Remote Control",
description: error instanceof Error ? error.message : String(error),
};
}
}
/** What starting Remote Control with a query needs of the query's session. */
export type RemoteControlAtStartupSession = {
readonly sessionId: string;
readonly logger: Logger;
/** The session's query, or `undefined` when it has none to start Remote Control on. */
query(): Query | undefined;
/** Whether the session is busy in its core's sense, such as Claude working. */
working(): boolean;
};
/**
* Remote Control at the start of a query that Claude Code asked to start with
* it (see {@link startsWithRemoteControl}). Each core keeps one per query and
* connects it after the query's setup response and after a restart, whose new
* query asks again: closing the old query ended its Remote Control. Unless the
* user turned it off: a restart carries the user's last `/remote-control` into
* the new query (see {@link restartedFrom}). A session that a failed restart
* lost carries nothing: the client sets it up again, and that setup asks
* afresh. Holding prompts back and sending the notice are each core's own, as
* they follow the core's turn model.
*/
export class RemoteControlAtStartup {
/** Whether the user's last `/remote-control` on this query turned it off. */
private turnedOff = false;
constructor(private asked: boolean) {}
/**
* The user ran `command` on this query. Recorded before its request goes
* out, so a restart that overlaps the request already knows.
*/
commandRan(command: RemoteControlCommand): void {
this.turnedOff = command.action === "disconnect";
}
/**
* A restart replaced the query of `previous` with this one. Remote Control
* that the user turned off there stays off: this query asks again only
* because the setting does, and the setting can come from a rollout the user
* never chose.
*/
restartedFrom(previous: RemoteControlAtStartup | undefined): void {
if (!previous?.turnedOff) return;
this.turnedOff = true;
this.asked = false;
}
/**
* Starts Remote Control on the first call, and resolves the notice that
* tells the user how it went. When nothing starts, it returns `undefined`
* rather than a promise, so a core can hold its prompts back in the same
* synchronous step: Claude Code did not ask, the user turned it off before
* a restart, an earlier call ran, the query is closed or has no Remote
* Control, or the session is busy, as the notice would land inside that
* work. `/remote-control` still connects the session then.
*/
connect(session: RemoteControlAtStartupSession): Promise<SessionNotice> | undefined {
if (!this.asked) return undefined;
this.asked = false;
const query = session.query();
if (!query || !supportsRemoteControl(query)) return undefined;
if (session.working()) {
session.logger.log(
`Session ${session.sessionId} is busy, so Remote Control does not start with it. /remote-control starts it.`,
);
return undefined;
}
return startRemoteControl(query, session.logger);
}
}
/** A top-level message a person typed in another client of the session, such
* as claude.ai or the Claude mobile app over Remote Control. Tool results and
* the CLI's own synthetic messages are user-role too, but carry no human

View File

@@ -8,9 +8,26 @@
import type {
SDKMessage,
SDKMessageOrigin,
SDKRateLimitInfo,
SDKResultMessage,
} from "@anthropic-ai/claude-agent-sdk";
/**
* The `data` of the error that fails a turn, for clients to dispatch on
* without matching its text: the assistant message's `errorKind`, and for a
* `rate_limit` failure the turn's latest `rate_limit_event` info as
* `rateLimit`, whose `resetsAt` says when the account can run again. A turn
* refused before its first usage sends no `usage_update` to carry that info.
* `undefined` without an error kind.
*/
export function turnErrorData<K extends string>(
errorKind: K | undefined,
rateLimit: SDKRateLimitInfo | undefined,
): { errorKind: K; rateLimit?: SDKRateLimitInfo } | undefined {
if (!errorKind) return undefined;
return errorKind === "rate_limit" && rateLimit ? { errorKind, rateLimit } : { errorKind };
}
export type ResultEnd =
| { stopReason: "refusal" | "max_tokens" | "end_turn" | "max_turn_requests" }
/**

View File

@@ -51,7 +51,7 @@ export function serveAcp(
/**
* Routes a connection to the protocol version that the client negotiates in
* `initialize`. With `auto`, a client that requests version 2 or later gets
* the draft ACP v2, and every other client gets ACP v1. With `v1`, a v2
* ACP v2, and every other client gets ACP v1. With `v1`, a v2
* client is negotiated down to v1. With `v2`, the router rejects the
* `initialize` of a v1 client as an unsupported protocol version. `onAgent`
* receives the agent of a v1 connection (`ClaudeAcpAgent`) once the router

View File

@@ -1,7 +1,8 @@
/**
* The config options of a session, as both the v1 core and the v2 core
* build them: mode, model, effort, Fast mode, ultracode and the main-thread
* agent.
* build them: model, effort, Fast mode, ultracode, mode and the main-thread
* agent. A client gets them in that order (`orderedConfigOptions`), for a
* root session and for a subagent's session.
*/
import {
RequestError,
@@ -15,7 +16,7 @@ import {
AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY,
clientSupportsAirCapability,
} from "./air-extension.js";
import { AGENT_CONFIG_ID, DEFAULT_AGENT_ID } from "./session-config-ids.js";
import { AGENT_CONFIG_ID, DEFAULT_AGENT_ID, EFFORT_CONFIG_ID } from "./session-config-ids.js";
import { buildEffortConfigOption } from "./session-effort.js";
import {
createFastModeConfigOption,
@@ -43,12 +44,25 @@ import {
// personas, so we filter them out and only surface the Agent picker when the
// user (or a plugin/project) has configured custom agents. Update this set if
// the SDK's built-in roster changes.
//
// The set is matched by name because `AgentInfo` does not say where an agent
// comes from. `getContextUsage().agents` lists only the agents that are not
// built in, but session setup does not wait for that request (see
// `readContextWindow`).
//
// Claude Code does not list two of them in every session: `web-fetch` only
// where its staged rollout or `CLAUDE_CODE_WEB_FETCH_AGENT=1` turns it on, and
// `claude-code-guide` only where the adapter's environment sets
// `CLAUDE_CODE_ENTRYPOINT` (the SDK sets `sdk-ts` when it is unset, and Claude
// Code leaves the agent out for that value).
export const BUILTIN_AGENT_NAMES = new Set([
"claude",
"claude-code-guide",
"general-purpose",
"Explore",
"Plan",
"statusline-setup",
"web-fetch",
]);
// Value of the synthetic "Default" entry in the agent picker, which maps to the
@@ -103,8 +117,41 @@ export type ConfigOptionPresentation = {
/** Replace ambiguous `default` rows with concrete values and advertise the
* SDK/adapter recommendation as `_meta.jetbrains.air.recommendedValue`. */
useRecommendedValue: boolean;
/** The client is AIR: each `model` option entry names its model's effort
* levels at `_meta.jetbrains.air.reasoningEfforts`. */
airClient?: boolean;
};
/**
* The ids of a session's config options, in the order a client gets them.
* An option is ranked by its id and not by its `category`, which the agent
* option lacks.
*/
const CONFIG_OPTION_ORDER: readonly string[] = [
MODEL_CONFIG_ID,
EFFORT_CONFIG_ID,
FAST_MODE_CONFIG_ID,
ULTRACODE_CONFIG_ID,
MODE_CONFIG_ID,
AGENT_CONFIG_ID,
];
/**
* `options` as a client gets them, for a root session and for a subagent's
* session: in {@link CONFIG_OPTION_ORDER}'s order, then each option with
* another id, in the order it came.
*/
export function orderedConfigOptions(
options: Iterable<SessionConfigOption>,
): SessionConfigOption[] {
const rank = (option: SessionConfigOption) => {
const index = CONFIG_OPTION_ORDER.indexOf(option.id);
return index < 0 ? CONFIG_OPTION_ORDER.length : index;
};
return [...options].sort((left, right) => rank(left) - rank(right));
}
/** The config options of a root session, in the order a client gets them. */
export function buildConfigOptions(
modes: SessionModeState,
models: SessionModelState,
@@ -116,12 +163,17 @@ export function buildConfigOptions(
presentation?: ConfigOptionPresentation,
ultracode?: UltracodeOptionState,
): SessionConfigOption[] {
const options: SessionConfigOption[] = [SessionModeManager.configOption(modes)];
const options: SessionConfigOption[] = [];
// A gateway that lists none of the SDK's models leaves no model to offer, so
// there is no model option at all.
if (models.availableModels.length > 0) {
options.push(
buildModelConfigOption(models, modelInfos, presentation?.useRecommendedValue === true),
buildModelConfigOption(
models,
modelInfos,
presentation?.useRecommendedValue === true,
presentation?.airClient === true,
),
);
}
const effort = buildEffortConfigOption(
@@ -151,6 +203,8 @@ export function buildConfigOptions(
options.push(createUltracodeConfigOption(ultracode.enabled, ultracode.useBooleanOption));
}
options.push(SessionModeManager.configOption(modes));
// Only surface the Agent picker when there's a real choice — i.e. the user
// has configured at least one custom agent (built-ins are filtered out in
// discoverCustomAgents). With none configured, "Default" would be the only
@@ -173,7 +227,9 @@ export function buildConfigOptions(
});
}
return options;
// The statements above already follow CONFIG_OPTION_ORDER. Sorting by it
// keeps this list and a subagent's list on the one definition.
return orderedConfigOptions(options);
}
/**
@@ -192,12 +248,20 @@ export function buildConfigOptions(
* a fallback for resolutions that don't map back onto a selectable option
* (e.g. a fuzzy hit on an out-of-picker verbatim entry). `value` is then the
* canonical option value, the model id rather than the alias.
*
* With `passUnlisted`, a model value that resolves to none of the entries is
* returned as it is, marked `unlisted`, for Claude Code to decide: the CLI's
* picker leaves out models it runs, such as `claude-fable-5-2` before a CLI
* lists it, or `claude-opus-4-6` once a newer Opus replaces it.
* {@link setSelectedModel} refuses it with invalid params when Claude Code
* does. Without it, such a value is refused here.
*/
export function configOptionValue(
option: SessionConfigOption,
params: SetSessionConfigOptionRequest,
modelInfos: ModelInfo[],
): { enabled: boolean } | { value: string } {
passUnlisted = false,
): { enabled: boolean } | { value: string; unlisted?: true } {
const expectedType = option.type === "boolean" ? "boolean" : "string";
if (typeof params.value !== expectedType) {
throw RequestError.invalidParams(
@@ -233,6 +297,9 @@ export function configOptionValue(
}));
validValue = toOptionValue(resolveModelPreference(optionInfos, requested));
}
if (!validValue && passUnlisted && requested.trim() !== "") {
return { value: requested.trim(), unlisted: true };
}
}
if (!validValue) {
throw RequestError.invalidParams(
@@ -242,3 +309,59 @@ export function configOptionValue(
}
return { value: validValue.value };
}
/**
* The codes with which Claude Code's `setModel` refuses a model id that the
* session cannot use: an id it does not know (`not_found`,
* `catalog_unknown`), one that settings restrict (`restricted_by_org`: an
* `availableModels` allowlist, a managed `deniedModels` entry), one the
* account or this CLI does not offer, and a `[1m]` form that is turned off or
* that the model lacks.
*
* Claude Code sends the code as `error_code` of its answer and the SDK
* (0.3.325) copies it to `errorCode` of the error that `setModel()` rejects
* with. The SDK's types do not declare it.
*/
const UNUSABLE_MODEL_ERROR_CODES: ReadonlySet<string> = new Set([
"not_found",
"catalog_unknown",
"restricted_by_org",
"unavailable_for_account",
"not_offered",
"alias_1m_disabled",
"alias_1m_unsupported",
]);
/** Whether `setModel()` rejected with `error` because the session cannot use the model id. */
function refusesModelId(error: unknown): error is Error {
if (!(error instanceof Error)) return false;
const code = (error as { errorCode?: unknown }).errorCode;
return typeof code === "string" && UNUSABLE_MODEL_ERROR_CODES.has(code);
}
/**
* Switches `query` to the model that {@link configOptionValue} selected.
*
* When Claude Code refuses an `unlisted` id as one the session cannot use
* (see {@link UNUSABLE_MODEL_ERROR_CODES}), that is invalid params with Claude
* Code's reason ("Model 'gpt-4' not found"), as for a value the option lacks.
* Every other failure is thrown as it is and reaches the client as an
* internal error: a failed switch to a listed value, and a failure that does
* not judge the id, such as `auth_failed`, `rate_limit`, `check_unreachable`
* (the API did not answer), `blocked_by_hook`, a closed query, or a refusal
* without a code.
*/
export async function setSelectedModel(
query: Pick<Query, "setModel">,
selected: { value: string; unlisted?: true },
): Promise<void> {
try {
await query.setModel(selected.value);
} catch (error) {
if (!selected.unlisted || !refusesModelId(error)) throw error;
throw RequestError.invalidParams(
undefined,
`Invalid value for config option ${MODEL_CONFIG_ID}: ${selected.value}. ${error.message}`,
);
}
}

225
src/session-cursors.ts Normal file
View File

@@ -0,0 +1,225 @@
/**
* Session cursors (the unstable session cursors RFD): the positions of a
* session that a method can act at.
*
* The adapter announces one kind: the position before a user message that the
* session's history stores, with the `fork` capability. `session/fork` with
* its `cursorId` copies the history before that message, so a client can edit
* the message or ask again from there. The first entry of a history has no
* cursor: nothing is before it, and Claude Code forks at an entry, not before
* the first one.
*
* A `cursorId` is derived from the uuid of its user message, which Claude Code
* stores. So it is the same live, in every replay and after a restart, and
* the adapter keeps no cursors of its own: a fork finds the position in the
* stored history.
*/
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
import { isCompactSummaryMessage } from "./context-compaction.js";
import { isReplayHiddenMetaMessage, stripLocalCommandMetadata } from "./message-filters.js";
/** What the cursor ids start with. The rest is the uuid of the user message. */
const BEFORE_MESSAGE = "before:";
/** The entity that a cursor is anchored to. */
export type CursorEntity =
| { type: "user_message" | "agent_message" | "agent_thought"; messageId: string }
| { type: "tool_call"; toolCallId: string }
| { type: "compaction"; compactionId: string };
/** The side of its {@link CursorEntity} that a cursor lies on. */
export type CursorAnchor = CursorEntity & { position: "before" | "after" };
/** The `cursor_update` of the cursor before the user message `messageId`. */
export function forkCursorUpdate(messageId: string) {
return {
...forkCursorBase(messageId),
anchor: { type: "user_message" as const, messageId, position: "before" as const },
};
}
/**
* The cursor before the user message `messageId` for a client that holds no
* such user message: `anchor` places it (see {@link LastReportedEntity}), and the
* `cursorId` stays that of the message.
*/
export function anchoredForkCursorUpdate(messageId: string, anchor: CursorAnchor) {
return { ...forkCursorBase(messageId), anchor };
}
/**
* `update` with the `rewind` capability added: the cursor is also a position
* that `_session/rewind` accepts. For a client that declared `sessionRewind`.
*/
export function withRewindCapability<U extends { capabilities: { fork: object } }>(
update: U,
): U & { capabilities: { fork: object; rewind: object } } {
return { ...update, capabilities: { ...update.capabilities, rewind: {} } };
}
/** The uuid of the user message that `cursorId` lies before, or undefined for an id that is no cursor. */
export function cursorMessageId(cursorId: string): string | undefined {
return cursorId.startsWith(BEFORE_MESSAGE) ? cursorId.slice(BEFORE_MESSAGE.length) : undefined;
}
function forkCursorBase(messageId: string) {
return {
sessionUpdate: "cursor_update" as const,
cursorId: `${BEFORE_MESSAGE}${messageId}`,
capabilities: { fork: {} },
};
}
/**
* The last entity per session that a client can anchor a cursor to: an agent
* message or thought with a `messageId`, a tool call, a compaction or a user
* message with a `messageId`. v1 does not report a prompt that the client
* sent, so its cursor lies `after` the entity before it. Each session update
* that goes to the client passes through {@link sending}, a replay too.
* Output of a subagent (a `parentToolUseId` in its `_meta`) is not on the
* session's own timeline and is left out.
*
* It also records, for each cursor that the agent announces, the entity that
* the client held right before that position ({@link recordCursor}). A rewind
* to the cursor leaves the client with exactly that entity.
*/
export class LastReportedEntity {
private readonly bySession = new Map<string, CursorEntity>();
/** Per session, in announcement order: the entity before each announced cursor. */
private readonly beforeCursor = new Map<string, Map<string, CursorEntity | undefined>>();
sending(notification: {
sessionId: string;
update: { sessionUpdate: string; _meta?: unknown } & Record<string, unknown>;
}): void {
const { sessionId, update } = notification;
const meta = update._meta as { claudeCode?: { parentToolUseId?: unknown } } | null | undefined;
if (meta?.claudeCode?.parentToolUseId) return;
const messageId = typeof update.messageId === "string" ? update.messageId : undefined;
switch (update.sessionUpdate) {
case "user_message_chunk":
if (messageId) this.bySession.set(sessionId, { type: "user_message", messageId });
break;
case "agent_message_chunk":
if (messageId) this.bySession.set(sessionId, { type: "agent_message", messageId });
break;
case "agent_thought_chunk":
if (messageId) this.bySession.set(sessionId, { type: "agent_thought", messageId });
break;
case "tool_call":
if (typeof update.toolCallId === "string") {
this.bySession.set(sessionId, { type: "tool_call", toolCallId: update.toolCallId });
}
break;
case "compaction_update":
if (typeof update.compactionId === "string") {
this.bySession.set(sessionId, { type: "compaction", compactionId: update.compactionId });
}
break;
default:
}
}
/** The position after the last entity of the session, if the client holds one. */
after(sessionId: string): CursorAnchor | undefined {
const entity = this.bySession.get(sessionId);
return entity && { ...entity, position: "after" };
}
/** The last entity of the session that the client holds, if any. */
last(sessionId: string): CursorEntity | undefined {
return this.bySession.get(sessionId);
}
/** The agent announces `cursorId`; `before` is the entity the client holds right before it. */
recordCursor(sessionId: string, cursorId: string, before: CursorEntity | undefined): void {
let records = this.beforeCursor.get(sessionId);
if (!records) this.beforeCursor.set(sessionId, (records = new Map()));
records.set(cursorId, before);
}
/**
* The session is rewound to `cursorId`: the client drops the entities from
* there on, so the entity recorded for the cursor is its last one (none for
* a cursor that has no record: the next prompt then gets no cursor). The
* records of the cursors at and after the cut go too.
*/
rewind(sessionId: string, cursorId: string): void {
const records = this.beforeCursor.get(sessionId);
const before = records?.get(cursorId);
if (before) this.bySession.set(sessionId, before);
else this.bySession.delete(sessionId);
if (!records?.has(cursorId)) return;
let cut = false;
for (const id of [...records.keys()]) {
cut ||= id === cursorId;
if (cut) records.delete(id);
}
}
/** The client no longer holds the session's entities: it closed, or a replay rebuilds them. */
forget(sessionId: string): void {
for (const map of [this.bySession, this.beforeCursor]) {
for (const id of map.keys()) {
if (id === sessionId || id.startsWith(`${sessionId}:`)) map.delete(id);
}
}
}
}
/**
* Whether a prompt with this content gets a cursor when it is inserted live.
* A slash command does not: Claude Code stores a command as command metadata
* or not at all, so a replay shows no user message for it and a fork finds no
* cursor (see {@link hasForkCursor}). Text that only starts like a command
* gets its cursor in the next replay.
*/
export function promptGetsCursor(prompt: ReadonlyArray<{ type: string; text?: unknown }>): boolean {
const first = prompt.find((block) => block.type === "text");
return !(typeof first?.text === "string" && first.text.trimStart().startsWith("/"));
}
/**
* Whether the entry `index` of the stored history `messages` is a user
* message with a cursor before it: one that a replay shows as a user message
* under its uuid, and that follows an entry that a fork can end with. A
* replay announces the cursor of each such message, and a fork accepts no
* other.
*/
export function hasForkCursor(messages: readonly SessionMessage[], index: number): boolean {
const message = messages[index];
if (!message || !messages[index - 1]?.uuid) return false;
return isShownUserMessage(message);
}
/** Whether a replay shows `message` as a user message of the session's own conversation. */
function isShownUserMessage(message: SessionMessage): boolean {
if (message.type !== "user" || !message.uuid) return false;
if (message.parent_tool_use_id !== null) return false;
if (isReplayHiddenMetaMessage(message) || isCompactSummaryMessage(message)) return false;
// `null`: the message was command metadata alone, which a replay does not show.
const content = stripLocalCommandMetadata(
(message.message as { content?: unknown } | undefined)?.content,
);
if (typeof content === "string") return content.length > 0;
// A message of tool results alone is no user message.
return (
Array.isArray(content) &&
content.some((block) => (block as { type?: unknown } | null)?.type !== "tool_result")
);
}
/**
* The uuid of the entry that a fork at `cursorId` ends with: the entry before
* the cursor's user message in the stored history `messages`. Undefined for
* an id that is no cursor of that history (see {@link hasForkCursor}).
*/
export function forkPointOf(
cursorId: string,
messages: readonly SessionMessage[],
): string | undefined {
if (!cursorId.startsWith(BEFORE_MESSAGE)) return undefined;
const messageId = cursorId.slice(BEFORE_MESSAGE.length);
const index = messages.findIndex((message) => message.uuid === messageId);
return hasForkCursor(messages, index) ? messages[index - 1]!.uuid : undefined;
}

View File

@@ -1,6 +1,10 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
import type { EffortLevel, ModelInfo, Settings } from "@anthropic-ai/claude-agent-sdk";
import { AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, withAirMeta } from "./air-extension.js";
import {
AIR_REASONING_EFFORTS_KEY,
AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY,
withAirMeta,
} from "./air-extension.js";
import { EFFORT_CONFIG_ID } from "./session-config-ids.js";
export { EFFORT_CONFIG_ID } from "./session-config-ids.js";
@@ -103,21 +107,51 @@ export function effortLevelName(level: string): string {
.join(" ");
}
/**
* The effort levels of `model`, or `[]` when it has no effort support. They
* are in Claude Code's order, which lists the levels from lowest to highest
* ("low" to "max"), as ACP v2 asks of a `thought_level` select. Nothing here
* sorts them.
*/
export function supportedEffortLevels(model: ModelInfo | undefined): string[] {
return model?.supportsEffort ? [...(model.supportedEffortLevels ?? [])] : [];
}
/**
* The effort that the adapter recommends of `levels`: "medium" when the model
* offers it, else the first level. The SDK names no recommended effort.
*/
export function recommendedEffortLevel(levels: readonly string[]): string | undefined {
return levels.includes("medium") ? "medium" : levels[0];
}
/**
* The `_meta` of a `model` option entry for `model`: its effort levels and
* the recommended one, at `_meta.jetbrains.air.reasoningEfforts`. They match
* the effort option that {@link buildEffortConfigOption} builds for the
* model, without its `default` row. Undefined for a model without effort
* levels.
*/
export function modelReasoningEffortsMeta(
model: ModelInfo | undefined,
): Record<string, unknown> | undefined {
const values = supportedEffortLevels(model);
const recommended = recommendedEffortLevel(values);
if (recommended === undefined) return undefined;
return withAirMeta(undefined, AIR_REASONING_EFFORTS_KEY, { values, recommended });
}
export function buildEffortConfigOption(
modelInfos: ModelInfo[],
currentModelId: string,
currentEffortLevel: string | undefined,
useRecommendedValue: boolean,
): SessionConfigOption | undefined {
const currentModelInfo = modelInfos.find((model) => model.value === currentModelId);
const supportedLevels = currentModelInfo?.supportsEffort
? (currentModelInfo.supportedEffortLevels ?? [])
: [];
if (supportedLevels.length === 0) return undefined;
const recommendedEffort = (supportedLevels as string[]).includes("medium")
? "medium"
: supportedLevels[0];
const supportedLevels = supportedEffortLevels(
modelInfos.find((model) => model.value === currentModelId),
);
const recommendedEffort = recommendedEffortLevel(supportedLevels);
if (recommendedEffort === undefined) return undefined;
const options = [
...(useRecommendedValue ? [] : [{ value: "default", name: "Default" }]),
...supportedLevels.map((level) => ({
@@ -126,7 +160,7 @@ export function buildEffortConfigOption(
})),
];
const includes = (level: string) =>
(!useRecommendedValue && level === "default") || (supportedLevels as string[]).includes(level);
(!useRecommendedValue && level === "default") || supportedLevels.includes(level);
const currentValue =
currentEffortLevel && includes(currentEffortLevel)
? currentEffortLevel

View File

@@ -1,6 +1,7 @@
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
import {
getSessionMessages,
type SDKAPIRetryMessage,
type SDKAssistantMessageError,
USAGE_LIMIT_ERROR_PREFIXES,
} from "@anthropic-ai/claude-agent-sdk";
@@ -446,6 +447,84 @@ export class SessionFailureController {
}
}
/** Formats a wait in whole seconds, at least 1s: `8000` → `"8s"`. */
function retrySeconds(ms: number): string {
return `${Math.max(1, Math.round(ms / 1000))}s`;
}
/** The wait before the next attempt: `0` → `"now"`, `8000` → `"in 8s"`, and
* from 120 s whole minutes rounded up: `1_800_000` → `"in 30m"`. The CLI sends
* `0` for a `no_response` retry and minutes for a background rate-limit wait. */
function nextAttemptDelay(ms: number): string {
const seconds = Math.round(ms / 1000);
if (seconds <= 0) return "now";
if (seconds < 120) return `in ${seconds}s`;
return `in ${Math.ceil(ms / 60_000)}m`;
}
/** Plain-English names of the SDK error kinds. `unknown` has none: it adds
* nothing to the HTTP status or the connection error. */
const RETRY_ERROR_KIND_LABELS: Record<Exclude<SDKAssistantMessageError, "unknown">, string> = {
authentication_failed: "authentication failed",
oauth_org_not_allowed: "organization not allowed",
account_on_hold: "account on hold",
verification_required: "verification required",
billing_error: "billing error",
rate_limit: "rate limited",
overloaded: "overloaded",
invalid_request: "invalid request",
model_not_found: "model not found",
server_error: "server error",
max_output_tokens: "output token limit",
cloud_credential_error: "cloud credential error",
};
/** The `api_retry` message fields the warning reads. `error` is optional
* because an older CLI can omit it; the warning then treats it as `unknown`. */
type ApiRetryWarningInput = Pick<
SDKAPIRetryMessage,
"attempt" | "max_retries" | "error_status" | "retry_delay_ms" | "no_response"
> & { error?: SDKAssistantMessageError };
/** The cause of a retry. A null `error_status` with a kind is not always a
* lost connection: the CLI maps an SSE `overloaded_error` event after HTTP 200
* to `overloaded` with no status. */
function apiRetryCause(message: ApiRetryWarningInput): string {
const kind = message.error ?? "unknown";
const label =
kind === "unknown"
? undefined
: (RETRY_ERROR_KIND_LABELS[kind] ?? String(kind).replaceAll("_", " "));
if (message.error_status !== null) {
return `HTTP ${message.error_status}${label ? ` (${label})` : ""}.`;
}
return label ? `No HTTP status (${label}).` : "Connection error: no HTTP response.";
}
/** The title and the `details` of an `api_retry` warning. The title says the
* attempt and, for a `no_response` retry, how long the CLI waited and will
* wait. The details say the cause and the wait before the next attempt, e.g.
* "HTTP 529 (overloaded). Next attempt in 8s." The details do not repeat the
* `no_response` wait. */
export function apiRetryWarning(message: ApiRetryWarningInput): {
title: string;
details: string;
} {
// `no_response` (SDK 0.3.261+): the API sent no response headers
// within the first-byte window, so this retry waits longer for
// them. Say so — "attempt 1 of 1" alone reads like a final
// failure, and the wait is what the user is about to sit through.
const noResponse = message.no_response
? ` No response after ${retrySeconds(message.no_response.waited_ms)}; waiting up to ${retrySeconds(message.no_response.retry_wait_ms)}.`
: "";
const title =
message.error_status === null
? `Reconnecting to Claude, attempt ${message.attempt} of ${message.max_retries}.${noResponse}`
: `Retrying Claude, attempt ${message.attempt} of ${message.max_retries}.${noResponse}`;
const delay = nextAttemptDelay(message.retry_delay_ms);
return { title, details: `${apiRetryCause(message)} Next attempt ${delay}.` };
}
export function providerFailureCategory(
errorKind?: SDKAssistantMessageError,
isUsageLimit = false,

View File

@@ -28,16 +28,9 @@ export function fastModeStateEnabled(state: FastModeState): boolean {
return state !== "off";
}
/** User-facing explanations for the SDK's `fast_mode_disabled_reason` values
* that a user can act on (or at least wants to know about). Deliberately
* partial — the omitted reasons are not worth surfacing:
* - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
* opt-in), so it describes the default, not a problem.
* - `preference`: the user turned Fast mode off themselves.
* - `pending`: eligibility is still resolving; the next report supersedes it.
* - `unknown`: nothing meaningful to say.
* Unknown future reasons fall through the same way (open set — the SDK's docs
* say to ignore values you don't handle). */
/** User-facing explanations for the SDK's `fast_mode_disabled_reason` values.
* Every reason is explained except the two in {@link FAST_MODE_UNEXPLAINED_REASONS};
* a code missing here gets the generic text from {@link explainFastModeDisabledReason}. */
const FAST_MODE_UNAVAILABLE_EXPLANATIONS: Partial<Record<FastModeDisabledReason, string>> = {
free: "not available on the free plan",
extra_usage_disabled: "requires extra usage to be enabled for this account",
@@ -45,24 +38,51 @@ const FAST_MODE_UNAVAILABLE_EXPLANATIONS: Partial<Record<FastModeDisabledReason,
not_first_party: "not available on this API provider",
disabled_by_env: "disabled by environment configuration",
network_error: "eligibility could not be verified (network error)",
preference: "not enabled for your organization or API gateway",
unknown: "currently unavailable",
};
/** Reasons that are never explained:
* - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
* opt-in), so it describes the default, not a problem.
* - `pending`: eligibility is still resolving; the next report supersedes it. */
const FAST_MODE_UNEXPLAINED_REASONS: ReadonlySet<FastModeDisabledReason> = new Set([
"sdk_opt_in_required",
"pending",
]);
/** The user-facing explanation of a `fast_mode_disabled_reason`: `undefined`
* for no reason, `sdk_opt_in_required` or `pending`; the table text when there
* is one; else a generic text naming the code (a reason a newer SDK added). */
export function explainFastModeDisabledReason(
reason: FastModeDisabledReason | undefined,
): string | undefined {
if (reason === undefined || FAST_MODE_UNEXPLAINED_REASONS.has(reason)) return undefined;
return FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ?? `not available (${reason})`;
}
/** Normalize an SDK-reported `fast_mode_disabled_reason` to the one we retain:
* a reason we have an explanation for, else `undefined`. Keeping only
* explainable reasons means state comparisons (see `fastModeStateChange`) track
* exactly what the user can see, so routine reports like
* `sdk_opt_in_required` never churn the config option. */
* a reason {@link explainFastModeDisabledReason} explains (including codes a
* newer SDK adds), else `undefined`. State comparisons (see
* `fastModeStateChange`) then track exactly what the user can see, so
* `sdk_opt_in_required` and `pending` never churn the config option. */
export function normalizeFastModeDisabledReason(
reason: FastModeDisabledReason | undefined,
): FastModeDisabledReason | undefined {
return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? reason : undefined;
return explainFastModeDisabledReason(reason) !== undefined ? reason : undefined;
}
/** Build the Fast mode config option. When the Client supports boolean config
* options we expose a native `type: "boolean"` toggle; otherwise we degrade to
* a two-value `select` ("on"/"off") so older Clients still get a usable
* a two-value `select` ("off"/"on") so older Clients still get a usable
* control.
*
* Its category is `speed`, the unstable ACP category of an option that
* changes how fast the model responds, in v1 and v2. A category needs no
* capability: a Client that does not know `speed` handles it as any unknown
* category. ACP asks for a `speed` select's values from slowest to fastest,
* so the fallback lists off before on.
*
* `disabledReason` (the SDK's `fast_mode_disabled_reason`) is folded into the
* description while the toggle reads off, so a user whose account or provider
* can't serve Fast mode sees why instead of a switch that silently refuses to
@@ -73,14 +93,12 @@ export function createFastModeConfigOption(
useBooleanOption: boolean,
disabledReason?: FastModeDisabledReason,
): SessionConfigOption {
const explanation = enabled
? undefined
: disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
const explanation = enabled ? undefined : explainFastModeDisabledReason(disabledReason);
const base = {
id: FAST_MODE_CONFIG_ID,
name: "Fast mode",
description: explanation ? `${FAST_MODE_DESCRIPTION} — ${explanation}` : FAST_MODE_DESCRIPTION,
category: "model_config",
category: "speed",
} as const;
if (useBooleanOption) {
@@ -92,8 +110,8 @@ export function createFastModeConfigOption(
type: "select",
currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
options: [
{ value: FAST_MODE_ON, name: "On" },
{ value: FAST_MODE_OFF, name: "Off" },
{ value: FAST_MODE_ON, name: "On" },
],
};
}
@@ -118,6 +136,27 @@ export function resolveFastModeEnabled(params: SetSessionConfigOptionRequest): b
);
}
/** Set the Fast mode flag on Claude Code, through `applyFlagSettings`.
*
* Turning it on sends `fastMode: false` first, a workaround for Claude Code
* (CLI 2.1.325): it acts on `fastMode: true` only when its flag does not hold
* `true` already, and ignores a repeat. Its flag stays `true` while it stops
* serving Fast mode at a model switch (Fable 5.2 and Mythos 5.2 take only a
* Fast mode that was turned on while they were selected) and reports
* `fast_mode_state: "off"`. Without the reset, turning the toggle back on
* changes nothing there, and the next `system`/init turns it off again.
*
* A refusal of the reset changes nothing. If Claude Code takes the reset and
* refuses `true`, it is left off; the caller's option keeps its value, and the
* next `system`/init turns off an option that reads on. */
export async function applyFastModeFlag(
applyFlagSettings: (settings: { fastMode: boolean }) => Promise<void>,
enabled: boolean,
): Promise<void> {
if (enabled) await applyFlagSettings({ fastMode: false });
await applyFlagSettings({ fastMode: enabled });
}
/** Per-model Fast mode state threaded into `buildConfigOptions`. The
* option is only surfaced when the current model `supported`s fast mode. */
export type FastModeOptionState = {
@@ -141,15 +180,19 @@ export type FastModeOptionState = {
* off), or the same state with the same explainable reason.
*
* `reason` is the SDK's `fast_mode_disabled_reason`, reported alongside the
* state. Only explainable reasons are retained (see
* {@link normalizeFastModeDisabledReason}), so a routine
* `sdk_opt_in_required` report on every turn's result can't churn the
* option, while a real blocker updates the description even when the
* state. Every reason except `sdk_opt_in_required` and `pending` is retained
* (see {@link normalizeFastModeDisabledReason}; unknown future codes get the
* generic text), so `sdk_opt_in_required` on every turn's result can't churn
* the option, while a real blocker updates the description even when the
* toggle's own value is unchanged.
*
* `notice` is set when the user had Fast mode on and the SDK turned it off
* for an explainable reason: the description carries the same explanation,
* but a toggle silently snapping back is worth saying out loud once. */
* with a retained reason: the description carries the same explanation, but a
* toggle silently snapping back is worth saying out loud once. Off with no
* reason, `sdk_opt_in_required` or `pending` stays quiet: a report can carry
* the flag as it was before a request of ours (see
* {@link fastModeResultIsNews}), so a notice there would falsely say "turned
* off". */
export function fastModeStateChange(
current: { enabled: boolean; disabledReason?: FastModeDisabledReason },
state: FastModeState | undefined,
@@ -163,8 +206,7 @@ export function fastModeStateChange(
// so it can't decorate the option the next time fast mode goes off.
const disabledReason = enabled ? undefined : normalizeFastModeDisabledReason(reason);
if (enabled === current.enabled && disabledReason === current.disabledReason) return undefined;
const explanation =
disabledReason !== undefined ? FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason] : undefined;
const explanation = explainFastModeDisabledReason(disabledReason);
if (!current.enabled || enabled || explanation === undefined) {
return { enabled, disabledReason };
}
@@ -182,6 +224,41 @@ export function fastModeStateChange(
};
}
/** A Fast mode report of Claude Code: the `fast_mode_state` and
* `fast_mode_disabled_reason` of a `system`/init or of a result. */
export type FastModeReport = {
state: FastModeState | undefined;
reason: FastModeDisabledReason | undefined;
};
/** Whether a result's Fast mode report says something that `init`, the report
* of its turn's `system`/init, did not.
*
* Claude Code (CLI 2.1.325) reads the `fastMode` flag once when a turn starts
* and builds that turn's init and result from the one reading. A result that
* repeats its init therefore predates a `session/set_config_option` that
* arrived in between: mirroring it would turn the toggle back, until the next
* turn's init. What a result adds is what Claude Code evaluates when it sends
* it: a refusal by the account or the model, or the end of one.
*
* Reasons compare as retained ({@link normalizeFastModeDisabledReason}):
* turning Fast mode on mid-turn drops `sdk_opt_in_required` from the result,
* which is no news. True without an init, as for a result whose turn sent none.
*
* Not covered: a request that Claude Code applies after it read the flag and
* before it sent the init. That init reports the earlier value too, and the
* next turn's init corrects the toggle. */
export function fastModeResultIsNews(
init: FastModeReport | undefined,
result: FastModeReport,
): boolean {
if (init === undefined) return true;
return (
result.state !== init.state ||
normalizeFastModeDisabledReason(result.reason) !== normalizeFastModeDisabledReason(init.reason)
);
}
/** The notice of Fast mode that the SDK turned off, and its transcript line
* for a client without `notice` updates. */
export type FastModeOffNotice = {

View File

@@ -138,7 +138,7 @@ function archivedFilter(list: Record<string, unknown>): ArchivedFilter {
if (!ARCHIVED_FILTERS.includes(value as ArchivedFilter)) {
throw RequestError.invalidParams(
{ archived: value },
'`_meta.jetbrains.air.list.archived` must be "unarchived", "archived" or "all"',
'_meta.jetbrains.air.list.archived must be "unarchived", "archived" or "all"',
);
}
return value as ArchivedFilter;
@@ -150,7 +150,7 @@ function optionalBoolean(list: Record<string, unknown>, key: string): boolean {
if (typeof value !== "boolean") {
throw RequestError.invalidParams(
{ [key]: value },
`\`_meta.jetbrains.air.list.${key}\` must be a boolean`,
`_meta.jetbrains.air.list.${key} must be a boolean`,
);
}
return value;
@@ -165,7 +165,7 @@ export function parseListOptions(meta: unknown): ListOptions {
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) {
throw RequestError.invalidParams(
{ limit: raw },
"`_meta.jetbrains.air.list.limit` must be an integer of at least 1",
"_meta.jetbrains.air.list.limit must be an integer of at least 1",
);
}
return {

View File

@@ -550,7 +550,55 @@ function stringFields(text: string, key: string): string[] {
return values;
}
const lastField = (text: string, key: string) => stringFields(text, key).at(-1) || undefined;
/** The string `field` of the JSON record `line`, which is of `type` when one
* is given. `null` when the line is no JSON. */
function recordField(line: string, field: string, type?: string): string | null | undefined {
let record: unknown;
try {
record = JSON.parse(line);
} catch {
return null;
}
if (typeof record !== "object" || record === null) return undefined;
if (type !== undefined && (record as Entry).type !== type) return undefined;
const value = (record as Entry)[field];
return typeof value === "string" ? value : undefined;
}
/**
* The top-level string `field` of the last record of `text` that has one,
* as the SDK reads a session's metadata since 0.3.323: it parses each line
* that names the field, from the last one back. A `"customTitle":"…"` inside
* a message, such as a tool result that shows a transcript, is no title.
*
* With `type`, only a record of that `type` counts, and a line that names
* the type but is no JSON is read from its last `{"type":"<type>"` that does
* not follow `:`, `,` or `[`: a record appended to a line whose write was cut
* off. The record that the start of the tail window cuts has no such start
* in the window, and is not read.
*
* Undefined when the field of that record is empty: older records are not
* searched.
*/
function lastRecordField(text: string, field: string, type?: string): string | undefined {
const fieldMarker = `"${field}":`;
const typeMarkers = type === undefined ? undefined : [`"type":"${type}"`, `"type": "${type}"`];
const lines = text.split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i]!;
if (!line.includes(fieldMarker)) continue;
if (typeMarkers && !typeMarkers.some((marker) => line.includes(marker))) continue;
let value = recordField(line, field, type);
if (value === null && typeMarkers) {
const start = line.lastIndexOf(`{${typeMarkers[0]}`);
if (start > 0 && !":,[".includes(line[start - 1]!)) {
value = recordField(line.slice(start), field, type);
}
}
if (typeof value === "string") return value || undefined;
}
return undefined;
}
/** Whether the first record of the transcript is a sidechain one, which the
* SDK never lists. */
@@ -560,9 +608,10 @@ export function isSidechainTranscript(head: string): boolean {
return first.includes('"isSidechain":true') || first.includes('"isSidechain": true');
}
/** The last `customTitle` of the tail, as the SDK reads it. */
/** The title of the last `custom-title` record of the tail, as the SDK reads
* it (see {@link lastRecordField}). */
export function tailCustomTitle({ tail, sdkTail }: HeadTail): string | undefined {
return lastField(sdkTail ?? tail, "customTitle");
return lastRecordField(sdkTail ?? tail, "customTitle", "custom-title");
}
/** The last non-blank top-level `agentName` of the records of `text`, the
@@ -607,22 +656,23 @@ export function sdkTitles(
): SdkTitles {
const tail = sdkTail ?? wholeLines;
const customTitle =
lastField(tail, "customTitle") ??
lastRecordField(tail, "customTitle", "custom-title") ??
sidecarTitle ??
lastField(head, "customTitle") ??
lastField(tail, "aiTitle") ??
lastField(head, "aiTitle");
lastRecordField(head, "customTitle", "custom-title") ??
lastRecordField(tail, "aiTitle", "ai-title") ??
lastRecordField(head, "aiTitle", "ai-title");
return { customTitle, summary: customTitle ?? generatedTitle({ head, tail }) };
}
/** The title of a transcript without a custom title, in the SDK's order: AI
* title, last prompt, summary, first prompt. */
* title, last prompt, summary, first prompt. The last prompt and the summary
* are the field of a record of any type. */
export function generatedTitle({ head, tail }: HeadTail): string | undefined {
return (
lastField(tail, "aiTitle") ??
lastField(head, "aiTitle") ??
lastField(tail, "lastPrompt") ??
lastField(tail, "summary") ??
lastRecordField(tail, "aiTitle", "ai-title") ??
lastRecordField(head, "aiTitle", "ai-title") ??
lastRecordField(tail, "lastPrompt") ??
lastRecordField(tail, "summary") ??
(firstPrompt(head) || mediaPrompt(head) || undefined)
);
}

View File

@@ -1,7 +1,16 @@
import { RequestError } from "@agentclientprotocol/sdk/unstable";
import { PROVIDER_ID } from "./providers.js";
import type { SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
import type { ModelInfo, Query, Settings } from "@anthropic-ai/claude-agent-sdk";
// matchDeniedModels is marked @alpha in the SDK; API may shift in a future release.
import {
matchDeniedModels,
type ModelInfo,
type Query,
type Settings,
} from "@anthropic-ai/claude-agent-sdk";
import { AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, withAirMeta } from "./air-extension.js";
import { bedrockRegionPrefix } from "./gateway-models.js";
import { modelReasoningEffortsMeta } from "./session-effort.js";
export const MODEL_CONFIG_ID = "model";
@@ -105,7 +114,7 @@ function containsWords(haystack: string, needle: string): boolean {
}
/** `id` without the gateway spellings that `normalizeModelId` keeps for
* `deniedModels` and gateway listings: path segments before `claude-`
* gateway listings: path segments before `claude-`
* (`vertex_ai/`, `openrouter/anthropic/`, `publishers/anthropic/models/`)
* and the Anthropic API's `-latest` suffix (`claude-3-5-haiku-latest`). */
function withoutGatewaySpelling(id: string): string {
@@ -140,6 +149,8 @@ function modelCoversTokens(model: ModelInfo, tokens: string[]): boolean {
* of its model words, preferring one with the same context hint ("sonnet[1m]"
* for "claude-sonnet-5-1m"). The fuzzy tiers need a compatible version, and
* words match whole: "not-a-model", "son" and "foo-sonnet" name no entry.
* For a preference without a version, the fuzzy tiers take the entry of the
* newest version: "opus[1m]" gives "claude-opus-5-5", not "claude-opus-4-5".
*/
export function resolveModelPreference(models: ModelInfo[], preference: string): ModelInfo | null {
const trimmed = preference.trim();
@@ -169,27 +180,58 @@ export function resolveModelPreference(models: ModelInfo[], preference: string):
const preferenceHint = contextHintOf(trimmed);
const tokens = modelPreferenceTokens(trimmed);
const includesMatch = models.find((model) => {
if (!modelVersionsCompatible(trimmed, model)) return false;
if (contextHintOf(model.value) !== preferenceHint) return false;
return (
containsWords(model.value, trimmed) ||
containsWords(model.displayName, trimmed) ||
(containsWords(trimmed, model.value) && modelCoversTokens(model, tokens))
);
});
// A preference without a version (`opus`, `opus[1m]`) runs its family's
// newest model in the CLI, so the fuzzy tiers pick the newest row, not the
// first: an allowlist lists `claude-opus-4-5-20251101` before `claude-opus-5-5`.
const pick =
extractModelFamilyVersion(trimmed) === null
? newestModel
: (rows: ModelInfo[]): ModelInfo | undefined => rows[0];
const includesMatch = pick(
models.filter((model) => {
if (!modelVersionsCompatible(trimmed, model)) return false;
if (contextHintOf(model.value) !== preferenceHint) return false;
return (
containsWords(model.value, trimmed) ||
containsWords(model.displayName, trimmed) ||
(containsWords(trimmed, model.value) && modelCoversTokens(model, tokens))
);
}),
);
if (includesMatch) return includesMatch;
const candidates = models.filter(
(model) => modelVersionsCompatible(trimmed, model) && modelCoversTokens(model, tokens),
);
return (
candidates.find((model) => contextHintOf(model.value) === preferenceHint) ??
candidates[0] ??
pick(candidates.filter((model) => contextHintOf(model.value) === preferenceHint)) ??
pick(candidates) ??
null
);
}
/** The row of `models` that runs the newest family version, the first one of
* equal versions. A row of an unknown version (`my-model`) ranks below each
* row of a known one. */
function newestModel(models: ModelInfo[]): ModelInfo | undefined {
let newest: ModelInfo | undefined;
let newestVersion: { major: number; minor: number } | null = null;
for (const model of models) {
const version = familyVersionOf(normalizeModelId(model.resolvedModel ?? model.value));
const newer =
newest === undefined ||
(version !== null &&
(newestVersion === null ||
version.major > newestVersion.major ||
(version.major === newestVersion.major && version.minor > newestVersion.minor)));
if (newer) {
newest = model;
newestVersion = version;
}
}
return newest;
}
export function matchResumedModel(models: ModelInfo[], liveModel: string): ModelInfo {
const live = canonicalizeModelId(liveModel);
const defaultEntry = models.find((model) => model.value === "default");
@@ -221,8 +263,17 @@ export function buildModelConfigOption(
models: SessionModelState,
modelInfos: ModelInfo[],
useRecommendedValue: boolean,
/** The client is AIR: each entry names its model's effort levels (see
* {@link modelReasoningEffortsMeta}). A client that is not AIR gets no AIR key. */
airClient = false,
): SessionConfigOption {
const defaultInfo = modelInfos.find((model) => model.value === "default");
// The listed model that the `default` row runs, which names the row.
const defaultTarget = defaultInfo?.resolvedModel
? modelInfos.find(
(info) => info.value !== "default" && info.resolvedModel === defaultInfo.resolvedModel,
)
: undefined;
const selectableIds = new Set(models.availableModels.map((model) => model.modelId));
const concreteInfos = modelInfos.filter(
(model) => model.value !== "default" && selectableIds.has(model.value),
@@ -246,25 +297,25 @@ export function buildModelConfigOption(
concreteRecommendation && models.currentModelId === "default"
? recommended.value
: models.currentModelId;
const options: Array<{ value: string; name: string; description?: string }> = available.map(
(model) => {
if (model.modelId === "default" && defaultInfo?.resolvedModel) {
const named = modelInfos.find(
(info) => info.value !== "default" && info.resolvedModel === defaultInfo.resolvedModel,
);
return {
value: model.modelId,
name: model.name,
description: named?.displayName ?? defaultInfo.resolvedModel,
};
}
const options: Array<{
value: string;
name: string;
description?: string;
_meta?: Record<string, unknown>;
}> = available.map((model) => {
if (model.modelId === "default" && defaultInfo?.resolvedModel) {
return {
value: model.modelId,
name: model.name,
description: model.description ?? undefined,
description: defaultTarget?.displayName ?? defaultInfo.resolvedModel,
};
},
);
}
return {
value: model.modelId,
name: model.name,
description: model.description ?? undefined,
};
});
// ACP requires `currentValue` to be one of `options`. A session can run a
// model the picker does not list: resumed onto a model excluded by the
// `availableModels` allowlist, or switched by a refusal fallback. List that
@@ -278,6 +329,18 @@ export function buildModelConfigOption(
description: info?.description || undefined,
});
}
if (airClient) {
// The `default` row runs the model it resolves to; without one, it
// names no efforts.
for (const option of options) {
const meta = modelReasoningEffortsMeta(
option.value === "default"
? defaultTarget
: modelInfos.find((info) => info.value === option.value),
);
if (meta) option._meta = meta;
}
}
return {
id: MODEL_CONFIG_ID,
@@ -376,8 +439,8 @@ export function aliasResumedModelRow(
/** A model id without the spellings that name the same model: provider
* prefixes, dates, version suffixes, `:variant` suffixes, dotted versions,
* `-fast` and context hints. `deniedModels` and gateway listings both match on
* it. OpenRouter lists `anthropic/claude-opus-5.5:batch[1m]`, which normalizes
* `-fast` and context hints. Gateway listings match on it. OpenRouter lists
* `anthropic/claude-opus-5.5:batch[1m]`, which normalizes
* to `claude-opus-5-5`; `anthropic/openai/gpt-5` keeps its `openai/` prefix and
* matches no Claude id. */
function normalizeModelId(value: string): string {
@@ -401,24 +464,56 @@ function normalizeModelId(value: string): string {
);
}
/** A path that no model id starts with. Nothing enforces that no
* `deniedModels` entry names it (see {@link deniedModelSpellings}). */
const VERSION_SPELLING_PATH = "version-of/";
/**
* Whether managed `deniedModels` blocks a model id, following the CLI's rules
* closely enough for the picker: a family alias blocks the whole family, and a
* model id blocks that version in every spelling plus the later minor versions
* it prefixes (`claude-opus-5` also blocks `claude-opus-5-5`). Entries share
* `normalizeModelId`, so `claude-opus-4.5` or `anthropic/claude-opus-4.5` also
* blocks `claude-opus-4-5`, which the CLI may still allow. The CLI stays the
* enforcer; this only keeps the picker from offering a refused row.
* The spellings of `id` to ask the SDK's `matchDeniedModels` about. That
* function compares an id with the entries alone. The CLI blocks more
* (`setModel` against CLI 2.1.323):
* - a last path segment that an exact-name entry names: `my-model` blocks
* `gateway/my-model`;
* - a version behind a `:variant` suffix or written with a dot:
* `claude-opus-5-5` blocks `claude-opus-5-5:free` and
* `anthropic/claude-opus-5.5`.
*
* An exact-name entry does not block a `:variant`: `my-model` leaves
* `my-model:free` allowed. So the version spelling goes behind a path, which
* the SDK ignores for a versioned id and which keeps the spelling from
* equalling an exact name.
*/
export function isDeniedModel(modelId: string, deniedModels: readonly string[]): boolean {
const id = normalizeModelId(modelId);
if (!id) return false;
return deniedModels.some((entry) => {
const denied = normalizeModelId(entry);
if (!denied) return false;
if (MODEL_FAMILY_ALIASES.has(denied)) return id === denied || id.includes(`-${denied}`);
return id === denied || id.startsWith(`${denied}-`);
});
function deniedModelSpellings(id: string): string[] {
const lastSegment = id.slice(id.lastIndexOf("/") + 1);
const version = lastSegment.replace(/:.*$/, "").replace(/(?<=\d)\.(?=\d)/g, "-");
return [id, lastSegment, `${VERSION_SPELLING_PATH}${version}`];
}
/**
* Which of `ids` a managed `deniedModels` list blocks, by the CLI's own entry
* rules: the SDK's `matchDeniedModels`, asked about each of the
* {@link deniedModelSpellings} of an id.
* - A family alias (`opus`) blocks the family.
* - A model id blocks that version in every spelling, and the later minor
* versions when it names none (`claude-opus-5` also blocks `claude-opus-5-5`).
* - Any other entry (`claude-opus-4.5`, `my-model`) blocks only that name,
* alone or as the last path segment (`gateway/my-model`).
* - `default`, `best` and `opusplan` block nothing.
*
* The CLI stays the enforcer; this only keeps the picker from offering a row
* that `setModel` would refuse.
*/
export async function deniedModelIds(
ids: readonly string[],
deniedModels: readonly string[],
): Promise<Set<string>> {
if (ids.length === 0 || deniedModels.length === 0) return new Set();
const asked = ids.flatMap((id) => deniedModelSpellings(id).map((spelling) => ({ id, spelling })));
const { denied } = await matchDeniedModels(
asked.map(({ spelling }) => spelling),
deniedModels,
);
return new Set(asked.filter((_, index) => denied[index]).map(({ id }) => id));
}
/**
@@ -436,15 +531,16 @@ export function isDeniedModel(modelId: string, deniedModels: readonly string[]):
* - `undefined` is handled by the caller (no allowlist applied).
* - The Default option is unaffected by `availableModels` — it always remains
* available, even when the allowlist is `[]`.
* - Managed `deniedModels` wins over the allowlist, so a denied entry is
* dropped even though the CLI would otherwise leave it unmatched.
* - Managed `deniedModels` wins over the allowlist: an entry is dropped when
* the list blocks its name, its `modelOverrides` target, or the model of the
* row it resolves to (see {@link deniedModelIds}).
*/
export function applyAvailableModelsAllowlist(
export async function applyAvailableModelsAllowlist(
sdkModels: ModelInfo[],
allowlist: string[],
settingsModelOverrides?: Record<string, string>,
deniedModels: readonly string[] = [],
): ModelInfo[] {
): Promise<ModelInfo[]> {
// Default is always preserved per the docs. Synthesize one if the SDK
// didn't surface it so downstream code (e.g. `getAvailableModels` picking
// `models[0]` as a fallback) still has something to work with.
@@ -465,22 +561,21 @@ export function applyAvailableModelsAllowlist(
// opaque provider IDs) often won't textually resemble anything in
// `sdkModelsWithoutDefault`. Only the entry's surfaced `value` becomes the
// override target, so it's what `setModel` ends up passing to the API.
for (const entry of allowlist) {
const entries = allowlist.flatMap((entry) => {
const trimmed = entry.trim();
if (!trimmed || seen.has(trimmed)) continue;
const overridden = settingsModelOverrides?.[trimmed];
const effective = overridden ?? trimmed;
if (seen.has(effective)) continue;
if (!trimmed) return [];
const effective = settingsModelOverrides?.[trimmed] ?? trimmed;
const sdkMatch = resolveModelPreference(sdkModelsWithoutDefault, trimmed);
if (
[trimmed, effective, sdkMatch?.resolvedModel].some(
(id) => id != null && isDeniedModel(id, deniedModels),
)
) {
continue;
}
const ids = [trimmed, effective, ...(sdkMatch?.resolvedModel ? [sdkMatch.resolvedModel] : [])];
return [{ trimmed, effective, sdkMatch, ids }];
});
const denied = await deniedModelIds(
entries.flatMap(({ ids }) => ids),
deniedModels,
);
for (const { trimmed, effective, sdkMatch, ids } of entries) {
if (seen.has(trimmed) || seen.has(effective)) continue;
if (ids.some((id) => denied.has(id))) continue;
if (sdkMatch) {
result.push({ ...sdkMatch, value: effective });
} else {
@@ -524,7 +619,9 @@ export function applyAvailableModelsAllowlist(
*
* When no row matches by its model (a `default` row kept only for lacking a
* `resolvedModel` does not count), the gateway serves none of the SDK's
* models, and nothing is left: the session offers no model.
* models. If every row has a nonempty `resolvedModel`, session setup fails
* with an error to choose a different provider. An empty catalog or any row
* without a resolved model leaves no model config option instead.
*/
export function narrowToGatewayModels(
models: ModelInfo[],
@@ -544,9 +641,16 @@ export function narrowToGatewayModels(
if (model.value === "default") return true;
return MODEL_FAMILY_ALIASES.has(id) && [...listed].some((entry) => entry.includes(`-${id}`));
});
return narrowed.some((model) => listed.has(normalizeModelId(model.resolvedModel ?? model.value)))
? narrowed
: [];
if (narrowed.some((model) => listed.has(normalizeModelId(model.resolvedModel ?? model.value)))) {
return narrowed;
}
if (models.length > 0 && models.every((model) => model.resolvedModel?.trim())) {
throw RequestError.internalError(
{ providerId: PROVIDER_ID },
"The selected provider offers no compatible Claude models. Choose a different provider and try again.",
);
}
return [];
}
/**
@@ -568,10 +672,10 @@ export function narrowToGatewayModels(
* capability flag (current and future); the identity fields are overridden
* because the fuzzy-matched sibling's resolvedModel/displayName/description
* can describe a different context lane and would poison later resolvedModel
* matching (a model switch that the adapter did not make) and context-window
* inference if they traveled under this id. `allowlistedModelInfo` is the
* allowlisted entry alone, the only one whose identity strings are a
* trustworthy window signal.
* matching (a model switch that the adapter did not make) and the lookup of
* the learned context window (`immediateContextWindow`) if they traveled under
* this id. `allowlistedModelInfo` is the allowlisted entry alone, the only one
* whose `resolvedModel` that lookup may use.
*/
export function withCurrentModelInfo(
allowedModels: ModelInfo[],

View File

@@ -132,18 +132,23 @@ export function informationalNotice(message: { level: string; content: string })
};
}
/** The notice of a client MCP server that the `system/init` lists as not
* started: `failed`, or `needs-auth` when the client cannot run the OAuth
* flow (`oauthAvailable`). Undefined for any other status. */
/** The notice of a client MCP server that did not start: `failed`, or
* `needs-auth` when the client cannot run the OAuth flow (`oauthAvailable`).
* Undefined for any other status. A server of the `system/init` list has no
* `error`: `/mcp` shows it. An `UnservedMcpServer` is on no list of Claude
* Code, so the notice has its `error`. */
export function mcpServerStartupNotice(
server: { name: string; status: string },
server: { name: string; status: string; error?: string },
oauthAvailable: boolean,
): SessionNotice | undefined {
if (server.status === "failed") {
return {
severity: "warning",
title: `MCP server "${server.name}" failed to start`,
description: "Its tools are unavailable in this session. Run /mcp for the error.",
description:
server.error === undefined
? "Its tools are unavailable in this session. Run /mcp for the error."
: `Its tools are unavailable in this session. ${server.error}`,
};
}
if (server.status === "needs-auth" && !oauthAvailable) {
@@ -156,6 +161,44 @@ export function mcpServerStartupNotice(
return undefined;
}
/** A notice of {@link mcpServerStartupNotices} with the names of its servers. */
export type McpServerStartupNotice = { servers: string[]; status: string; notice: SessionNotice };
/**
* The notices of the client MCP servers that did not start, in the order of
* `servers` (see {@link mcpServerStartupNotice}). Servers that failed with the
* same `error` share one notice. Such are the servers that a managed
* `disableSideloadFlags` keeps out of a session, and the `acp` servers of a
* connection whose local endpoint cannot open.
*/
export function mcpServerStartupNotices(
servers: Iterable<{ name: string; status: string; error?: string }>,
oauthAvailable: boolean,
): McpServerStartupNotice[] {
const notices: McpServerStartupNotice[] = [];
const byError = new Map<string, McpServerStartupNotice>();
for (const server of servers) {
const error = server.status === "failed" ? server.error : undefined;
const shared = error === undefined ? undefined : byError.get(error);
if (shared && error !== undefined) {
shared.servers.push(server.name);
const names = shared.servers.map((name) => `"${name}"`);
shared.notice = {
severity: "warning",
title: `${names.length} MCP servers failed to start`,
description: `The tools of ${names.slice(0, -1).join(", ")} and ${names.at(-1)} are unavailable in this session. ${error}`,
};
continue;
}
const notice = mcpServerStartupNotice(server, oauthAvailable);
if (!notice) continue;
const entry = { servers: [server.name], status: server.status, notice };
notices.push(entry);
if (error !== undefined) byError.set(error, entry);
}
return notices;
}
/**
* What Claude Code's `model_refusal_fallback` tells the user: the SDK retried
* a refused turn on the fallback model.

595
src/session-rewind.ts Normal file
View File

@@ -0,0 +1,595 @@
/**
* `_session/rewind` (AIR -> agent): removes a user message and everything after
* it from the context of the same Claude session, the one the client holds. A
* fork would answer the same intent with a second session, so the edited
* message would no longer run in the conversation that the user is looking at.
*
* The position is a session cursor (see `session-cursors.ts`): the one before
* the user message to drop. The adapter resumes the stored conversation of the
* session at the entry before that message (`resumeSessionAt`). Claude Code
* deletes nothing: the dropped entries stay in the transcript as an orphan
* branch, and `rewind.json` records the cut until the next prompt writes a
* branch that descends from it.
*
* Every read of the stored history of a session cuts it at the point
* (`cutAtRewindPoint`: replays, forks, v2's prompt keys), and every resume of
* it stops there (`prepareRewoundResume`). The point is removed by the first
* resume after the CLI stored a prompt on the rewound branch; until then the
* file stays and cuts nothing, since the stored history no longer holds the
* dropped prompt. v1 and v2 share this: both resume through
* `prepareRewoundResume` and read through `cutAtRewindPoint`.
*/
import { RequestError } from "@agentclientprotocol/sdk/unstable";
import {
getSessionMessages,
type SessionMessage,
type SessionStoreEntry,
} from "@anthropic-ai/claude-agent-sdk";
import { randomBytes } from "node:crypto";
import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { isCompactSummaryMessage } from "./context-compaction.js";
import { isReplayHiddenMetaMessage } from "./message-filters.js";
import {
findTranscript,
loadFullSessionHistory,
readHistoryAcrossCompactions,
} from "./resumed-session.js";
import { cursorMessageId, forkPointOf } from "./session-cursors.js";
export const SESSION_REWIND_METHOD = "_session/rewind";
export type SessionRewindRequest = {
sessionId: string;
/** A cursor that the session announced, before the user message to drop. */
cursorId: string;
};
/** Why the conversation was left as it was. */
export type SessionRewindRefusal =
/** Claude is working, or a prompt is queued. */
| "busy"
/** A background task or subagent is running. */
| "backgroundWork"
/** The message is before the newest compaction of the conversation. */
| "beforeCompaction"
/** The session's context was cleared into another Claude session. */
| "clearedContext"
/** Claude Code refused the cut. The session goes on as it was. */
| "providerRefused"
/** The rewind point could not be written. Nothing changed. */
| "persistFailed";
export type SessionRewindResponse = {
rewound: boolean;
reason?: SessionRewindRefusal;
};
export function parseSessionRewindRequest(params: unknown): SessionRewindRequest {
if (!params || typeof params !== "object") {
throw RequestError.invalidParams(undefined, "rewind params must be an object");
}
const { sessionId, cursorId } = params as Record<string, unknown>;
if (typeof sessionId !== "string" || sessionId.length === 0) {
throw RequestError.invalidParams(undefined, "rewind params require a non-empty sessionId");
}
if (typeof cursorId !== "string" || cursorId.length === 0) {
throw RequestError.invalidParams(undefined, "rewind params require a non-empty cursorId");
}
return { sessionId, cursorId };
}
type Logger = { log: (...args: unknown[]) => void; error: (...args: unknown[]) => void };
/** The stored history of a session, as a replay shows it. */
export type RewindableHistory = {
/** Every message of the conversation the session continues, from its first
* prompt on, across compactions. A rewind cursor is one of this list. */
visible: readonly SessionMessage[];
/** The part of `visible` that the newest compaction left: where Claude Code
* can resume. */
current: readonly SessionMessage[];
};
/** What the rewind needs from the agent that holds the session. */
export type SessionRewindHost = {
logger: Logger;
/** The context of the session was cleared into another Claude session. */
clearedContext: boolean;
/** Whether Claude works, or a prompt is queued: `startTurn`'s check. */
claudeIsWorking(): boolean;
/** Whether a background task or subagent runs. Closing the query ends it. */
hasBackgroundWork(): boolean;
loadHistory(): Promise<RewindableHistory>;
/**
* Closes the query and recreates the same session by resuming its
* conversation, stopped at `resumeAt.resumeSessionAt` when it is set. Restores
* the user's model, mode, agent, effort and Fast mode, and starts the reader.
*/
replaceQuery(resumeAt?: { resumeSessionAt: string; resumeDropsTurn?: string }): Promise<void>;
/**
* The session is rewound to `cursorId`. The next prompt's cursor anchors to
* the entity that the client held before that cursor.
*/
rewound(cursorId: string): void;
/** Deals with a session whose query is closed and could not be resumed,
* and returns the error the rewind fails with. */
abandon(error: unknown): Promise<unknown>;
};
/**
* Drops the user message of `request.cursorId` and everything after it.
*
* `{ rewound: true }` means that the cut is live and recorded in `rewind.json`;
* `{ rewound: false, reason }` means that the conversation and the rewind point
* are unchanged. The transcript can still gain the `last-prompt` line that any
* resume writes: `prepareRewoundResume` runs before the refusals that follow
* it, and with a stale point that is not pending it also deletes `rewind.json`,
* as any resume does. A cursor that the session's history does not hold is a
* bad request (-32602): the rewind never acts at another position.
*
* The point is written before the query is replaced, and restored to what it
* was when the cut does not happen. A crash between the write and the cut
* leaves a point that the next resume applies. When the restore fails too, the
* request fails with an internal error instead of `rewound: false`, since the
* next resume applies a cut that was reported as not made.
*/
export async function rewindSession(
request: SessionRewindRequest,
host: SessionRewindHost,
): Promise<SessionRewindResponse> {
const { sessionId, cursorId } = request;
const refuse = (reason: SessionRewindRefusal): SessionRewindResponse => {
host.logger.log(`Rewind of session ${sessionId} refused: ${reason}`);
return { rewound: false, reason };
};
// AIR stops the turn before it rewinds. Work still running here would be
// killed with the query.
const busy = (): SessionRewindResponse | undefined =>
host.claudeIsWorking()
? refuse("busy")
: host.hasBackgroundWork()
? refuse("backgroundWork")
: undefined;
const refusal = busy();
if (refusal) return refusal;
// The transcript of the session holds the conversation from before the
// clear, which the cursor would be resolved against.
if (host.clearedContext) return refuse("clearedContext");
const history = await host.loadHistory();
const resumeSessionAt = forkPointOf(cursorId, history.visible);
const droppedPromptUuid = cursorMessageId(cursorId);
if (!resumeSessionAt || !droppedPromptUuid) {
throw RequestError.invalidParams(
{ cursorId },
`Cursor ${cursorId} is not a rewind position of session ${sessionId}`,
);
}
// Claude Code resumes a compacted conversation from its newest compaction on
// and finds no entry before it ("No message found with message.uuid of ...").
if (!history.current.some((message) => message.uuid === resumeSessionAt)) {
return refuse("beforeCompaction");
}
// Before the query closes: marks the branch a second rewind resumes on.
const earlierCut = await prepareRewoundResume(sessionId, host.logger);
// Read after the preparation, which removes a point that is no longer pending.
const previousPoint = await readRewindPoint(sessionId, host.logger);
const dropped = history.visible.findIndex((message) => message.uuid === droppedPromptUuid);
// `resumeDropsTurn` makes Claude Code refuse a cut that discards anything
// the named turn does not account for, so it can guard only the last turn:
// the turns after an earlier one are always in the discarded range.
const dropsOneTurn = !history.visible.slice(dropped + 1).some(startsTurn);
try {
await writeRewindPoint(sessionId, { resumeSessionAt, droppedPromptUuid });
} catch (error) {
host.logger.error(`Failed to record the rewind point of session ${sessionId}:`, error);
return refuse("persistFailed");
}
// Puts `rewind.json` back, for a cut that does not happen. A failure leaves
// the new point in place, which the next resume of the session applies.
const restorePoint = async () => {
try {
if (previousPoint) await writeRewindPoint(sessionId, previousPoint);
else await clearRewindPoint(sessionId);
return true;
} catch (error) {
host.logger.error(
`Failed to restore the rewind point of session ${sessionId}; the next resume applies the cut:`,
error,
);
return false;
}
};
const pointNotRemoved = () =>
RequestError.internalError(
undefined,
`The rewind of session ${sessionId} did not happen, but its rewind point could not be removed. The next load of the session applies the cut.`,
);
// Claude Code can start a cycle on its own while the transcript is read,
// prepared or the point is written. Nothing is awaited between this check
// and `replaceQuery`, whose first statement closes the query synchronously.
const lateRefusal = busy();
if (lateRefusal) {
if (!(await restorePoint())) throw pointNotRemoved();
return lateRefusal;
}
try {
await host.replaceQuery({
resumeSessionAt,
...(dropsOneTurn ? { resumeDropsTurn: droppedPromptUuid } : {}),
});
} catch (error) {
// Claude Code refuses a cut deterministically, so retrying fails again.
// Recover once into the conversation as it was: the query of the session is
// already closed, and a session the client cannot prompt is worse than one
// that was not rewound.
host.logger.log(
`Rewind of session ${sessionId} ${isRewindRefusal(error) ? "was refused by Claude Code" : `failed: ${error}`}; resuming the conversation as it was`,
);
// Before the recovery resume, which reads `rewind.json` and would stop at
// the new point. If the file cannot be restored, only the earlier cut is used.
const restored = await restorePoint();
try {
const recoveredCut = restored
? ((await prepareRewoundResume(sessionId, host.logger)) ?? earlierCut)
: earlierCut;
await host.replaceQuery(recoveredCut ? { resumeSessionAt: recoveredCut } : undefined);
} catch (recoveryError) {
throw await host.abandon(recoveryError);
}
// After the recovery, so the session can be prompted.
if (!restored) throw pointNotRemoved();
return { rewound: false, reason: "providerRefused" };
}
host.rewound(cursorId);
return { rewound: true };
}
/** Whether Claude Code refused the cut (see `resumeDropsTurn` of the SDK options). */
export function isRewindRefusal(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return message.includes("Resume rejected by --resume-drops-turn:");
}
/** Whether a message opens a turn: a prompt of the user, not a tool result or injected context. */
function startsTurn(message: SessionMessage): boolean {
if (
message.type !== "user" ||
message.parent_tool_use_id !== null ||
isReplayHiddenMetaMessage(message) ||
isCompactSummaryMessage(message)
) {
return false;
}
const content = (message.message as { content?: unknown } | undefined)?.content;
return !(
Array.isArray(content) &&
content.length > 0 &&
content.every((block) => (block as { type?: unknown } | null)?.type === "tool_result")
);
}
/**
* The history of `sessionId` that a cursor of it is resolved against: the
* conversation the session continues, cut at its rewind point.
*/
export async function loadRewindableHistory(
sessionId: string,
logger?: Logger,
): Promise<RewindableHistory> {
const current = await cutAtRewindPoint(sessionId, await getSessionMessages(sessionId), logger);
return { current, visible: await readHistoryAcrossCompactions(sessionId, current, logger) };
}
/**
* `stored`, the `getSessionMessages` chain of `sessionId`, without the branch
* that a pending rewind dropped. Cut before reading across compactions: the
* newest leaf is the last retained message.
*/
export async function cutAtRewindPoint<M extends { uuid?: string | null }>(
sessionId: string,
stored: readonly M[],
logger?: Logger,
): Promise<M[]> {
return activeSessionMessages(stored, await readRewindPoint(sessionId, logger));
}
/**
* The entry that a fork of the whole of `sessionId` ends at while a rewind is
* pending, or undefined when there is none: the newest leaf then still lies in
* the dropped branch.
*/
export async function pendingRewindEnd(
sessionId: string,
logger?: Logger,
): Promise<string | undefined> {
const point = await readRewindPoint(sessionId, logger);
if (!point) return undefined;
const stored = await getSessionMessages(sessionId);
return stored.some((message) => message.uuid === point.droppedPromptUuid)
? point.resumeSessionAt
: undefined;
}
/**
* `entries`, the records of the whole transcript of `sessionId` with its
* inactive branches, without the dropped prompt of a rewind and the records
* that descend from it. A record comes after its parent in the transcript.
*/
export async function withoutRewoundBranch(
sessionId: string,
entries: SessionStoreEntry[],
logger?: Logger,
): Promise<SessionStoreEntry[]> {
const point = await readRewindPoint(sessionId, logger);
if (!point) return entries;
const dropped = new Set<string>([point.droppedPromptUuid]);
return entries.filter((entry) => {
if (typeof entry.uuid !== "string") return true;
const parent = entry.parentUuid || entry.logicalParentUuid;
const inDropped =
entry.uuid === point.droppedPromptUuid || (typeof parent === "string" && dropped.has(parent));
if (inDropped) dropped.add(entry.uuid);
return !inDropped;
});
}
/**
* The messages of the conversation that a session continues, given its stored
* `history` and its `rewindPoint`. A rewind leaves the dropped branch in the
* transcript, and until the next prompt writes a branch from the point,
* `history` still ends in the dropped branch: it is cut before the dropped
* prompt. Once a branch descends from the point, `history` no longer holds the
* dropped prompt and is returned as it is.
*/
export function activeSessionMessages<M extends { uuid?: string | null }>(
history: readonly M[],
rewindPoint: RewindPoint | undefined,
): M[] {
const at = rewindPoint
? history.findIndex((message) => message.uuid === rewindPoint.droppedPromptUuid)
: -1;
return at === -1 ? [...history] : history.slice(0, at);
}
/** A rewind: the entry the session resumes at, and the prompt it dropped. */
export type RewindPoint = {
/** The last retained entry, for `resumeSessionAt`. */
resumeSessionAt: string;
/** The first entry of the dropped branch: the user prompt the rewind removed. */
droppedPromptUuid: string;
};
/** `<projectDir>/<sessionId>/rewind.json`, beside the session's `subagents/`. */
async function rewindPointFile(sessionId: string): Promise<string | undefined> {
const transcript = await findTranscript(sessionId);
return transcript && path.join(path.dirname(transcript), sessionId, "rewind.json");
}
/** Records the last rewind of a session. */
export async function writeRewindPoint(sessionId: string, point: RewindPoint): Promise<void> {
const target = await rewindPointFile(sessionId);
if (!target) throw new Error(`Session ${sessionId} has no transcript`);
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
const temporary = `${target}.tmp.${randomBytes(8).toString("hex")}`;
try {
await writeFile(temporary, JSON.stringify(point), { mode: 0o600, flag: "wx" });
await rename(temporary, target);
} catch (error) {
await rm(temporary, { force: true });
throw error;
}
}
/**
* The last rewind of a session, or undefined for one that has none (no
* `rewind.json`, ENOENT). A record that cannot be read (EACCES, EISDIR) or
* parsed fails with an internal error: reading it as "no rewind" would show or
* resume the dropped turns. The file stays, so the client can retry.
*/
export async function readRewindPoint(
sessionId: string,
logger?: Logger,
): Promise<RewindPoint | undefined> {
try {
const file = await rewindPointFile(sessionId);
if (!file) return undefined;
let point: Partial<RewindPoint>;
try {
point = JSON.parse(await readFile(file, "utf8"));
} catch (error) {
if ((error as { code?: unknown }).code === "ENOENT") return undefined;
throw error;
}
const { resumeSessionAt, droppedPromptUuid } = point ?? {};
if (typeof resumeSessionAt !== "string" || typeof droppedPromptUuid !== "string") {
throw new Error("rewind.json holds no resumeSessionAt and droppedPromptUuid");
}
return { resumeSessionAt, droppedPromptUuid };
} catch (error) {
logger?.error(`Failed to read the rewind point of session ${sessionId}:`, error);
throw RequestError.internalError(
undefined,
`Session ${sessionId} was rewound, but its rewind point cannot be read (${error instanceof Error ? error.message : String(error)}). Try again.`,
);
}
}
/** Removes the record of the last rewind. */
export async function clearRewindPoint(sessionId: string): Promise<void> {
const file = await rewindPointFile(sessionId);
if (file) await rm(file, { force: true });
}
/**
* Prepares the transcript of `sessionId` for a resume, and returns the entry
* that a pending rewind point makes the resume stop at, if any.
*
* Claude Code resumes the branch of the leaf that the last `last-prompt` line
* of the transcript names, and looks up `resumeSessionAt` on that branch only.
* A process that resumed at a rewind point keeps writing that line with the
* leaf it loaded until it exits, and a query restart starts the next process
* before the closed one has exited, so the line can name the branch that the
* rewind dropped. A second rewind then fails with "No message found with
* message.uuid of ...", and a plain resume brings the dropped turns back. So
* the line is written for the leaf of the session's conversation: explicit at
* a pending rewind point, whose dropped branch descends from it, and plain at
* the newest entry otherwise. Once the point is no longer pending, the plain
* line is all the next process needs, and `rewind.json` is removed.
*/
export async function prepareRewoundResume(
sessionId: string,
logger?: Logger,
): Promise<string | undefined> {
const point = await readRewindPoint(sessionId, logger);
if (!point) return undefined;
try {
const history = await loadFullSessionHistory(sessionId);
const byUuid = entriesByUuid(history);
const newest = newestMainChainUuid(history);
if (!newest) return undefined;
const active = chainUuids(newest, byUuid);
const pending = isPending(point, history, active);
const leaf = pending ? point.resumeSessionAt : newest;
await markResumedLeaf(sessionId, history, byUuid, leaf, pending);
if (!pending) await clearRewindPoint(sessionId);
return pending ? point.resumeSessionAt : undefined;
} catch (error) {
// A plain resume would bring the dropped turns back, so the resume fails
// instead and the client can retry.
logger?.error(`Failed to prepare the resume of rewound session ${sessionId}:`, error);
throw RequestError.internalError(
undefined,
`Session ${sessionId} was rewound, but the cut could not be prepared (${error instanceof Error ? error.message : String(error)}). Try again.`,
);
}
}
/**
* Whether the rewind is still to be applied: the dropped prompt is on the newest
* conversation chain, or that chain does not pass through the point's resume
* entry and holds nothing written after it (a branch from before the cut).
* A chain through the resume entry without the dropped prompt is the edited
* conversation, which a later entry of any other kind must not undo.
*/
function isPending(
point: RewindPoint,
history: SessionStoreEntry[],
active: ReadonlySet<string>,
): boolean {
const pointIndex = history.findIndex((entry) => entry.uuid === point.resumeSessionAt);
if (pointIndex < 0) return false;
if (active.has(point.droppedPromptUuid)) return true;
if (active.has(point.resumeSessionAt)) return false;
return !history.some((entry, index) => index > pointIndex && active.has(entry.uuid as string));
}
async function markResumedLeaf(
sessionId: string,
history: SessionStoreEntry[],
byUuid: Map<string, SessionStoreEntry>,
leaf: string,
explicit: boolean,
): Promise<void> {
const transcript = await findTranscript(sessionId);
if (!transcript) return;
const lines = (await readFile(transcript, "utf8")).split("\n");
for (let index = lines.length - 1; index >= 0; index--) {
const line = lines[index]!;
if (!line.includes('"last-prompt"')) continue;
try {
const record = JSON.parse(line);
if (record.type !== "last-prompt") continue;
if (record.leafUuid === leaf && (record.explicit === true) === explicit) return;
break;
} catch {
continue;
}
}
const branch = chainUuids(leaf, byUuid);
const lastPrompt = history
.filter((entry) => branch.has(entry.uuid as string) && entry.type === "user")
.map(promptText)
.findLast((text) => text !== undefined);
const record = {
type: "last-prompt",
...(lastPrompt !== undefined ? { lastPrompt } : {}),
leafUuid: leaf,
...(explicit ? { explicit: true } : {}),
sessionId,
};
const separator = lines.at(-1) === "" ? "" : "\n";
await appendFile(transcript, `${separator}${JSON.stringify(record)}\n`);
}
/** The text of a user entry that carries a prompt, undefined for any other. */
function promptText(entry: SessionStoreEntry): string | undefined {
if (entry.isMeta === true || isCompactSummaryMessage(entry)) return undefined;
const content = (entry.message as { content?: unknown } | undefined)?.content;
if (typeof content === "string") return content;
if (!Array.isArray(content)) return undefined;
if (content.some((block) => (block as { type?: unknown } | null)?.type === "tool_result")) {
return undefined;
}
const text = content
.map((block) => block as { type?: unknown; text?: unknown } | null)
.flatMap((block) =>
block?.type === "text" && typeof block.text === "string" ? [block.text] : [],
)
.join("");
return text.length > 0 ? text : undefined;
}
/** An entry of the main conversation: not a subagent's, and not the transcript of a tool. */
function isMainChainEntry(entry: SessionStoreEntry): boolean {
return (
entry.isSidechain !== true && entry.parent_tool_use_id == null && entry.parent_agent_id == null
);
}
/** The entry types that the SDK reads as the conversation's chain; other records
* (titles, tags, summaries) are metadata even when they carry a `uuid`. */
const CHAIN_ENTRY_TYPES: ReadonlySet<unknown> = new Set([
"user",
"assistant",
"system",
"attachment",
]);
/** The uuid of the newest entry of the main conversation: the leaf that
* `getSessionMessages` reads. Like it, skips `progress` entries. */
function newestMainChainUuid(entries: SessionStoreEntry[]): string | undefined {
return entries.findLast(
(entry) =>
typeof entry.uuid === "string" &&
CHAIN_ENTRY_TYPES.has(entry.type) &&
isMainChainEntry(entry),
)?.uuid;
}
/** The uuids of `leaf` and of every entry it descends from. A compaction
* boundary has no `parentUuid`; its `logicalParentUuid` carries the chain on. */
function chainUuids(
leaf: string | undefined,
byUuid: ReadonlyMap<string, SessionStoreEntry>,
): Set<string> {
const chain = new Set<string>();
let cursor = leaf;
while (cursor && !chain.has(cursor)) {
const entry = byUuid.get(cursor);
if (!entry) break;
chain.add(cursor);
const parent = entry.parentUuid || entry.logicalParentUuid;
cursor = typeof parent === "string" ? parent : undefined;
}
return chain;
}
function entriesByUuid(entries: SessionStoreEntry[]): Map<string, SessionStoreEntry> {
return new Map(
entries.flatMap((entry) => (typeof entry.uuid === "string" ? [[entry.uuid, entry]] : [])),
);
}

View File

@@ -30,7 +30,14 @@ export const ZERO_USAGE = Object.freeze({
cache_creation_input_tokens: 0,
});
export const DEFAULT_CONTEXT_WINDOW = 200000;
/**
* The context window reported for a model until Claude Code says what it is
* (see `context-window.ts`): 1M, the window Claude Code itself assumes for a
* model id it does not know (since 2.1.323). Claude Code reports 200K for an
* older model such as `claude-sonnet-4-5`, and for every model under
* `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`.
*/
export const DEFAULT_CONTEXT_WINDOW = 1_000_000;
/** `_meta.quota` for work that spent `usage` in its main agent loop and
* `modelUsage` by model (see `turnQuotaMeta` in `v1/acp-agent.ts`). */
@@ -212,26 +219,6 @@ function commonPrefixLength(a: string, b: string) {
return i;
}
/** Best-effort first guess of a model's context window, used to seed the
* window synchronously (via `immediateContextWindow`) until a `result` message
* arrives with the authoritative `modelUsage` value.
*
* Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
* model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
* matching things like "10m" or embedded substrings. Semantic aliases like
* `default` carry no such token in the ID, but their `resolvedModel` and the
* SDK's human-facing `displayName`/`description` can (e.g.
* "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
* This text scan can't catch every model — some resolve to extended-context
* models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
* ~1M). Such a miss falls back to the default window, is refined by the
* background `getContextUsage` (`refreshContextWindowInBackground`), and is
* corrected by `result.modelUsage` (and cached) within one turn. */
export function inferContextWindowFromModel(...texts: Array<string | undefined>): number | null {
if (texts.some((text) => text != null && /\b1m\b/i.test(text))) return 1_000_000;
return null;
}
export function getMatchingModelUsage(
modelUsage: Record<string, ModelUsage>,
currentModel: string,

View File

@@ -7,6 +7,7 @@ import {
resolveSettings,
type Settings,
} from "@anthropic-ai/claude-agent-sdk";
import { unloadedPolicySources } from "./managed-policy.js";
import { claudeConfigDir } from "./paths.js";
/**
@@ -62,6 +63,9 @@ export class SettingsManager {
private managedModelSettings: ModelSelectionSettings = {};
private managedApiKeyHelper?: string;
private managedCompactionSettings: CompactionSettings = {};
private managedShowClearContextOnPlanAccept?: boolean;
/** The policy sources last logged as not loaded (see {@link unloadedPolicySources}). */
private unloadedPolicy?: string;
private watchers: fs.FSWatcher[] = [];
private onChange?: () => void;
private logger: { log: (...args: any[]) => void; error: (...args: any[]) => void };
@@ -118,6 +122,17 @@ export class SettingsManager {
private async loadAllSettings(): Promise<void> {
try {
const resolved = await resolveSettings({ cwd: this.cwd });
// Once per change: a reload after each settings file edit would repeat it.
const unloaded = unloadedPolicySources(resolved);
if (unloaded !== this.unloadedPolicy) {
this.unloadedPolicy = unloaded;
if (unloaded) {
this.logger.error(
`Managed settings did not load from ${unloaded}: the session's settings ` +
"and model list do not reflect it. Claude Code reads the policy itself.",
);
}
}
this.effective = filterEscalatingDefaultMode(resolved);
// The CLI reads `deniedModels` from managed settings only.
this.managedDeniedModels = resolved.sources
@@ -146,6 +161,9 @@ export class SettingsManager {
?.autoCompactEnabled,
env: Object.assign({}, ...managed.map((tier) => tier.env)),
};
this.managedShowClearContextOnPlanAccept = managed.findLast(
(tier) => tier.showClearContextOnPlanAccept !== undefined,
)?.showClearContextOnPlanAccept;
} catch (error) {
this.logger.error("Failed to resolve settings:", error);
this.effective = {};
@@ -153,6 +171,7 @@ export class SettingsManager {
this.managedModelSettings = {};
this.managedApiKeyHelper = undefined;
this.managedCompactionSettings = {};
this.managedShowClearContextOnPlanAccept = undefined;
}
}
@@ -270,6 +289,21 @@ export class SettingsManager {
};
}
/**
* Whether an approved plan may be continued in a fresh context, as the CLI
* resolves `showClearContextOnPlanAccept`: managed settings outrank the
* `--settings` override, which outranks the user/project/local files. Off
* unless one of them sets it, like the CLI.
*/
getShowClearContextOnPlanAccept(settingsOverride?: Settings): boolean {
return (
this.managedShowClearContextOnPlanAccept ??
settingsOverride?.showClearContextOnPlanAccept ??
this.effective.showClearContextOnPlanAccept ??
false
);
}
/**
* `deniedModels` entries from the managed tier, the only tier the CLI
* honors them from.

View File

@@ -4,13 +4,9 @@
*/
import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
import type { Query, SlashCommand } from "@anthropic-ai/claude-agent-sdk";
import { adapterAvailableCommands } from "./adapter-command.js";
import { AIR_KIND_KEY, AIR_SKILL_PATH_KEY, withAirMeta } from "./air-extension.js";
import { MCP_AVAILABLE_COMMAND } from "./mcp-command.js";
import {
claudeCodeOffersCommand,
REMOTE_CONTROL_COMMAND_NAME,
supportsRemoteControl,
} from "./remote-control.js";
import { resolveSkillPath, type SkillScanCache } from "./tool-calls/reporters/interaction.js";
export function getAvailableSlashCommands(
@@ -29,6 +25,8 @@ export function getAvailableSlashCommands(
// A listed skill gets its path from here; one that is not listed, or has no
// path (remote connections), is looked up on disk.
skillFiles?: ReadonlyMap<string, { path?: string }>,
// A session that runs Claude Code remotely (`sdk-url`): the adapter cannot serve `/plugin` for it.
remoteSession = false,
): AvailableCommand[] {
// The container listings of this one pass, so a list of a hundred commands lists each container once.
const skillScans: SkillScanCache = new Map();
@@ -51,18 +49,6 @@ export function getAvailableSlashCommands(
"todos",
];
const remoteControlCommands: AvailableCommand[] =
query && supportsRemoteControl(query)
? [
{
name: REMOTE_CONTROL_COMMAND_NAME,
description:
"Continue this session from claude.ai/code or the Claude mobile app; `off` disconnects",
input: { hint: "[session name | off]" },
},
]
: [];
// The adapter replaces the terminal text of `/mcp` and runs its actions,
// even when Claude Code tags the command terminal-bound.
const advertised = commands
@@ -113,9 +99,7 @@ export function getAvailableSlashCommands(
return [
...advertised,
MCP_AVAILABLE_COMMAND,
...remoteControlCommands.filter(
(command) => !claudeCodeOffersCommand(commands, terminalCommands, command.name),
),
...adapterAvailableCommands(commands, terminalCommands, query, { remoteSession }),
].filter((command) => {
if (/\s/.test(command.name) || names.has(command.name)) return false;
names.add(command.name);

View File

@@ -40,3 +40,11 @@ export function startupFailureError(error: unknown): RequestError | undefined {
}
return RequestError.internalError(data, message);
}
/** The reason that {@link startupFailureError} put into `error`, if it made `error`. */
export function startupFailureReasonOf(error: unknown): string | undefined {
if (!(error instanceof RequestError)) return undefined;
const reason = (error.data as { startupFailureReason?: unknown } | undefined)
?.startupFailureReason;
return typeof reason === "string" ? reason : undefined;
}

4
src/steering-priority.ts Normal file
View File

@@ -0,0 +1,4 @@
/** An open permission or elicitation must settle before Claude Code takes in a steer. */
export function steeringPriority(hasOpenRequests: boolean): "later" | "now" {
return hasOpenRequests ? "later" : "now";
}

View File

@@ -2,7 +2,8 @@
* The configuration of a subagent's session, as its hooks report it. Both
* the v1 core (`ClaudeAcpAgent.subagentConfigurationHook`, for both forms of
* subagent sessions) and the v2 core (`v2/child-config.ts`)
* build a child's config options with these.
* build a child's config options with these, and send them in the root
* session's order (`orderedConfigOptions` in `session-config-options.ts`).
*/
import type { SessionConfigOption, SessionModeState } from "@agentclientprotocol/sdk/unstable";
import type { AgentInfo, HookInput } from "@anthropic-ai/claude-agent-sdk";
@@ -78,19 +79,3 @@ export function subagentHookOptions(
}
return options;
}
/**
* A child's configuration, as it goes to the client: every option it holds,
* the mode first, then the model, the effort and the model config, then the
* rest in the order they came.
*/
export function orderedSubagentConfiguration(
options: Iterable<SessionConfigOption>,
): SessionConfigOption[] {
const priority = ["mode", "model", "thought_level", "model_config"];
const rank = (option: SessionConfigOption) => {
const index = priority.indexOf(option.category ?? "");
return index < 0 ? priority.length : index;
};
return [...options].sort((left, right) => rank(left) - rank(right));
}

View File

@@ -20,13 +20,17 @@
* reached the call is that message too: the sender's outgoing view, at the
* call, and the child's incoming one, in the child's history. A child's
* history follows its launch, so a call to a child from its parent is always
* delivered first. Any other SendMessage call stays a tool call.
* delivered first. Any other SendMessage call stays a tool call. As live, a
* TaskStop or SendMessage call that the client is shown and that names a
* replayed child by its agent id carries the RFD's `session` reference to it
* (`ReplayTranscript.withTarget`).
*
* Right after its announcement, each child gets its `model` option: the model
* of its first response, in its transcript. A later response with another
* model sends it again. A child without responses gets none. After the load
* response, a model goes again only when the session's model list, which the
* replay can lack, maps it to another entry.
* The replay sends no `config_option_update` of a child: one that arrives
* before the load response is a past value to the client. Each child's
* configuration goes out after the response, with its current state
* (`currentStates`): the configuration of a child that still runs in this
* process, else the `model` option with the model of the latest response in
* its transcript. A child that neither runs nor has a response gets none.
*
* A launch without metadata has no known id, so it is not announced: the RFD
* forbids inventing one. Its Agent call stays an ordinary tool call of the
@@ -43,13 +47,14 @@ import {
isNativeSubagentControlTool,
launchReply,
linkedSessionMessages,
type ModelEntry,
nativeSubagentState,
responseModelEntry,
rfdEndState,
rfdLabels,
sameDirectory,
type SubagentModels,
targetAgentId,
withSessionReference,
type WorkState,
} from "./native-subagents.js";
import { noticeUpdate } from "./session-notices.js";
@@ -78,8 +83,6 @@ export type ReplayChild = {
promptSent: boolean;
/** Whether it handed a report to its parent with a SubagentHandback call. */
handedBack?: boolean;
/** The `model` option entry that the replay sent. */
model?: ModelEntry;
/** The model id of the latest response in its transcript. */
responseModel?: string;
};
@@ -97,15 +100,19 @@ export type SendMessageCall = {
outgoingSent: boolean;
};
/** A SubagentHandback call: its report, whether its result failed, and whether the replay sent it. */
type ReplayHandback = { message: string; failed: boolean; sent: boolean };
/** A SubagentHandback call, its result, and whether the replay sent its report. */
type ReplayHandback = {
message: string;
status: "pending" | "completed" | "failed";
sent: boolean;
};
/**
* What both replays read from the transcripts before they send anything: the
* What the v1 and v2 replays read from the transcripts before they send anything: the
* children that launches with metadata started, the launches without metadata
* (left out), the SendMessage calls, and the SubagentHandback calls. It sends
* nothing; `RfdSubagentReplay` (v1) and `src/v2/subagent-replay.ts` send the
* replay from it.
* nothing. The v1 AIR replay, `RfdSubagentReplay`, and the v2 replay send
* their updates from it.
*/
export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
/** The children by the id of the tool use that launched each. */
@@ -115,10 +122,30 @@ export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
/** Launches without metadata, which the replay leaves out. */
readonly omitted = new Set<string>();
/** The SubagentHandback calls, by tool use id. */
readonly handbacks = new Map<string, ReplayHandback>();
private readonly handbacks = new Map<string, ReplayHandback>();
/** The agent that each TaskStop or SendMessage call names (see `targetAgentId`), by tool use id. */
private readonly targets = new Map<string, string>();
constructor(private readonly history: SubagentHistory) {}
/**
* `notification`, a replayed tool call update that the client is shown on
* the session `shownOn`, with the RFD's `session` reference when the call
* names a child of another session by its agent id, as live
* (`NativeSubagentRuntime.withTarget`). Only a child that the replay
* announced before the update is referenced.
*/
withTarget(notification: AcpSessionNotification, shownOn: string): AcpSessionNotification {
const { update } = notification;
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
return notification;
}
const agentId = this.targets.get(update.toolCallId);
const child = agentId !== undefined ? this.byAgentId.get(agentId) : undefined;
if (!child?.announced || child.sessionId === shownOn) return notification;
return withSessionReference(notification, child.sessionId);
}
/**
* Registers the launches, the launch results, and the SendMessage calls in
* `messages`, the transcript of the session `ownerSessionId`.
@@ -127,11 +154,13 @@ export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
for (const message of messages) {
for (const block of contentBlocks(message)) {
if (block.type === "tool_use" && typeof block.id === "string") {
const agentId = targetAgentId(block.name, block.input);
if (agentId !== undefined) this.targets.set(block.id, agentId);
if (isNativeSubagentControlTool(block.name)) {
this.registerLaunch(block.id, inputOf(block), ownerSessionId);
} else if (block.name === HANDBACK_TOOL) {
const message = handbackMessage(block.input);
if (message) this.handbacks.set(block.id, { message, failed: false, sent: false });
if (message) this.handbacks.set(block.id, { message, status: "pending", sent: false });
} else if (block.name === "SendMessage") {
const input = inputOf(block);
if (typeof input.to === "string" && typeof input.message === "string") {
@@ -147,7 +176,7 @@ export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
}
} else if (block.type === "tool_result" && typeof block.tool_use_id === "string") {
const handback = this.handbacks.get(block.tool_use_id);
if (handback && block.is_error === true) handback.failed = true;
if (handback) handback.status = block.is_error === true ? "failed" : "completed";
const child = this.children.get(block.tool_use_id);
// A background launch answers at once; its result is not the end.
if (child && !child.record.background) {
@@ -158,6 +187,25 @@ export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
}
}
/**
* The report of a completed hand-back, once. `null` hides its other updates
* and unfinished calls. `undefined` leaves failed calls and other updates visible.
*/
handbackUpdate(
update: AcpSessionNotification["update"],
): { messageId: string; text: string } | null | undefined {
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
return undefined;
}
const handback = this.handbacks.get(update.toolCallId);
if (!handback || handback.status === "failed") return undefined;
if (handback.status !== "completed" || update.status !== "completed" || handback.sent) {
return null;
}
handback.sent = true;
return { messageId: update.toolCallId, text: handback.message };
}
private registerLaunch(
toolUseId: string,
input: Record<string, unknown>,
@@ -192,13 +240,12 @@ export class RfdSubagentReplay {
constructor(
private readonly history: SubagentHistory,
private readonly publish: Publish,
private readonly models?: SubagentModels,
/**
* Whether the replay maps a model to the session's model list as it goes.
* A load lacks the list until the CLI started, so it maps only in
* {@link currentStates}, after the load response.
* The session's model list, which {@link currentStates} maps each child's
* model to. A load can lack the list until the CLI started, so it is read
* after the load response.
*/
private readonly mapsDuringReplay = true,
private readonly models?: SubagentModels,
/** The working directory of the root session, which a child inherits unless it reports its own. */
private readonly rootCwd?: string,
) {
@@ -214,6 +261,11 @@ export class RfdSubagentReplay {
}
/** The child that the tool use `toolUseId` launched, when the replay shows it. */
/** See {@link ReplayTranscript.withTarget}. */
withTarget(notification: AcpSessionNotification, shownOn: string): AcpSessionNotification {
return this.transcript.withTarget(notification, shownOn);
}
childOfLaunch(toolUseId: string): ReplayChild | undefined {
return this.transcript.children.get(toolUseId);
}
@@ -221,10 +273,8 @@ export class RfdSubagentReplay {
/**
* Announces `child` on its parent, as live: running, with the parent's
* labels, and with its recorded `cwd` when that differs from its parent's.
* Then it sends `firstModel`, the model of the child's first response, when
* the transcript has one.
*/
async announce(child: ReplayChild, firstModel?: string): Promise<void> {
async announce(child: ReplayChild): Promise<void> {
if (child.announced) return;
const labels = rfdLabels(
child.record.name ?? child.input.name,
@@ -250,7 +300,6 @@ export class RfdSubagentReplay {
});
child.cwd = cwd;
child.announced = true;
await this.responseModel(child, firstModel);
}
/**
@@ -268,27 +317,9 @@ export class RfdSubagentReplay {
return this.rootCwd;
}
/**
* Takes the model of a replayed response of the child `owner`. A child
* whose model changes gets its `model` option again.
*/
async responseModel(owner: ReplayChild, model: string | undefined): Promise<void> {
const entry = responseModelEntry(model, this.mapsDuringReplay ? this.models : undefined);
if (!entry || !owner.announced) return;
owner.responseModel = model;
await this.sendModel(owner, entry);
}
private async sendModel(child: ReplayChild, model: ModelEntry): Promise<void> {
if (child.model?.value === model.value && child.model.name === model.name) return;
child.model = model;
await this.publish({
sessionId: child.sessionId,
update: {
sessionUpdate: "config_option_update",
configOptions: [childModelOption(model)],
},
});
/** Takes the model of a replayed response of the child `owner` (see {@link trackResponseModel}). */
responseModel(owner: ReplayChild, model: string | undefined): void {
trackResponseModel(owner, model);
}
/**
@@ -335,8 +366,8 @@ export class RfdSubagentReplay {
* Takes a replayed update of a tool call, from the transcript of `owner`
* when it is a child's. Returns whether the client is not shown it: an
* update of the launch of a child that the replay shows, of a SendMessage
* call whose message the replay already delivered, or of a successful
* SubagentHandback call of `owner`. A foreground launch's completed result
* call whose message the replay already delivered, or of a pending or
* successful SubagentHandback call of `owner`. A foreground launch's completed result
* goes out as the child's reply, a delivered SendMessage as the sender's
* outgoing message, and a hand-back as the child's message to its parent.
*/
@@ -367,16 +398,15 @@ export class RfdSubagentReplay {
}
return true;
}
const handback = owner ? this.transcript.handbacks.get(update.toolCallId) : undefined;
if (owner && handback && !handback.failed) {
if (!handback.sent) {
handback.sent = true;
const handback = owner ? this.transcript.handbackUpdate(update) : undefined;
if (owner && handback !== undefined) {
if (handback !== null) {
owner.handedBack = true;
for (const view of linkedSessionMessages(
update.toolCallId,
owner.sessionId,
owner.parentSessionId,
handback.message,
handback.text,
)) {
await this.publish(view);
}
@@ -430,11 +460,16 @@ export class RfdSubagentReplay {
}
}
/** Whether the replay announced the child session `sessionId`. */
announced(sessionId: string): boolean {
return this.transcript.byAgentId.get(sessionId)?.announced === true;
}
/**
* The current state of each announced child, to send after the load
* response. The RFD makes that response the freshness boundary: a client
* treats the replayed states before it as history, so they show no current
* activity and allow no cancel.
* The current state and configuration of each announced child, to send
* after the load response. The RFD makes that response the freshness
* boundary: a client treats the replayed states before it as history, so
* they show no current activity and allow no cancel.
*
* `live` gives the work state of a child that still runs in this process, as
* when a live session is loaded again. Such a child reports that state and
@@ -444,6 +479,10 @@ export class RfdSubagentReplay {
* A replayed `cwd` whose directory is gone, such as a worktree that Claude
* Code removed when the child finished, is cleared with `cwd: null`, as the
* RFD requires after a reconnection.
*
* Each child's configuration follows its state (see
* {@link currentChildConfiguration}). `liveConfiguration` gives the one
* that the client last got for a child that still runs in this process.
*/
currentStates(
live: (sessionId: string) => WorkState["state"] | undefined,
@@ -457,13 +496,11 @@ export class RfdSubagentReplay {
liveState === undefined || liveState === "idle"
? replayEndState(child)
: { state: liveState };
// The session's model list may be known only now, after the load response.
const entry = responseModelEntry(child.responseModel, this.models);
const replayed = child.model ? JSON.stringify([childModelOption(child.model)]) : undefined;
const current =
liveConfiguration?.(child.sessionId) ?? (entry ? [childModelOption(entry)] : undefined);
// A configuration that the replay already sent does not go again.
const configOptions = current && JSON.stringify(current) !== replayed ? current : undefined;
const configOptions = currentChildConfiguration(
child,
liveConfiguration?.(child.sessionId),
this.models,
);
return [
{
sessionId: child.parentSessionId,
@@ -552,14 +589,38 @@ export class RfdSubagentReplay {
}
}
/** The model of the first response in `messages`, a subagent's transcript. */
export function firstResponseModel(messages: readonly SessionMessage[]): string | undefined {
for (const message of messages) {
if (message.type !== "assistant") continue;
const model = (message.message as { model?: unknown } | undefined)?.model;
if (typeof model === "string" && model && model !== "<synthetic>") return model;
/**
* Takes `model`, the model id of a replayed response of `child`. The latest
* one is the child's model after the replay (see
* {@link currentChildConfiguration}). A response without a model id, or with
* `<synthetic>`, which marks a message that no model wrote, changes nothing.
*/
export function trackResponseModel(child: ReplayChild, model: unknown): void {
if (typeof model === "string" && responseModelEntry(model, undefined)) {
child.responseModel = model;
}
return undefined;
}
/**
* The configuration of the replayed `child` to send once the replay is over:
* after the load response on v1, after the root's `replay_complete` on v2. A
* child's `config_option_update` inside a replay is a past value to the
* client, so the replay sends none, and this one goes also when the client
* held the same configuration before.
*
* `live` is the configuration that the client last got for a child that still
* runs in this process. Any other child gets its `model` option, with the
* model of the latest response in its transcript, as the session's model list
* `models` names it. Undefined for such a child without responses.
*/
export function currentChildConfiguration(
child: ReplayChild,
live: SessionConfigOption[] | undefined,
models: SubagentModels | undefined,
): SessionConfigOption[] | undefined {
if (live) return live;
const entry = responseModelEntry(child.responseModel, models);
return entry ? [childModelOption(entry)] : undefined;
}
/**

View File

@@ -1,9 +1,9 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"AskUserQuestion"}},"content":[],"kind":"other","name":"AskUserQuestion","sessionUpdate":"tool_call","status":"pending","title":"Asking for your input","toolCallId":"toolu_ask"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"rawInput":{"questions":[{"header":"Database","multiSelect":false,"options":[{"description":"Relational","label":"Postgres","preview":"CREATE TABLE t ();"},{"description":"Key-value","label":"Redis"}],"question":"Which database?"}]},"sessionUpdate":"tool_call_update","toolCallId":"toolu_ask"}}}
{"kind":"createElicitation","payload":{"message":"Which database?","mode":"form","requestedSchema":{"properties":{"question_0":{"oneOf":[{"_meta":{"_claude/askUserQuestionOption":{"preview":"CREATE TABLE t ();"}},"const":"Postgres","description":"Relational","title":"Postgres"},{"const":"Redis","description":"Key-value","title":"Redis"}],"title":"Database","type":"string"},"question_0_custom":{"_meta":{"_askUserQuestionCustomAnswer":{"isCustomAnswer":true,"questionId":"question_0"},"jetbrains":{"air":{"customAnswer":{"isCustomAnswer":true,"questionId":"question_0"},"version":1}}},"description":"Type your own answer, or add a note to the option you chose above (optional).","title":"Other","type":"string"}},"type":"object"},"sessionId":"<session>","toolCallId":"toolu_ask"}}
{"kind":"createElicitation","payload":{"_meta":{"jetbrains":{"air":{"customAnswerFields":["question_0_custom"],"version":1}}},"message":"Which database?","mode":"form","requestedSchema":{"properties":{"question_0":{"oneOf":[{"_meta":{"_claude/askUserQuestionOption":{"preview":"CREATE TABLE t ();"}},"const":"Postgres","description":"Relational","title":"Postgres"},{"const":"Redis","description":"Key-value","title":"Redis"}],"title":"Database","type":"string"},"question_0_custom":{"_meta":{"_askUserQuestionCustomAnswer":{"isCustomAnswer":true,"questionId":"question_0"},"jetbrains":{"air":{"customAnswer":{"isCustomAnswer":true,"questionId":"question_0"},"version":1}}},"description":"Type your own answer, or add a note to the option you chose above (optional).","title":"Other","type":"string"}},"type":"object"},"sessionId":"<session>","toolCallId":"toolu_ask"}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":[{"content":{"text":"User has answered your questions: \"Which database?\"=\"Postgres\".","type":"text"},"type":"content"}],"sessionUpdate":"tool_call_update","status":"completed","toolCallId":"toolu_ask"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"cost":{"amount":0,"currency":"USD"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_1","canStop":true,"description":"Build assets","name":"Build assets","outputFilePath":"/tmp/tasks/workflow_1.output","sessionUpdate":"async_task_spawned","showInTranscript":true,"taskType":"workflow"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_1","sessionUpdate":"async_task_state_update","state":"completed","summary":"done"}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_3","canStop":true,"description":"Watch the logs","name":"Watch the logs","sessionUpdate":"async_task_spawned","showInTranscript":true,"taskType":"workflow","toolCallId":"toolu_workflow"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_3","sessionUpdate":"async_task_progress","summary":"first line","usage":{"durationMs":5,"toolUses":0,"totalTokens":0}}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_3","sessionUpdate":"async_task_progress","summary":"second line","usage":{"durationMs":6,"toolUses":0,"totalTokens":0}}}}

View File

@@ -1,3 +1,3 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"asyncTaskId":"workflow_2","canStop":true,"description":"Build assets","name":"Build assets","sessionUpdate":"async_task_spawned","showInTranscript":true,"taskType":"workflow"}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Bash"},"terminal_info":{"terminal_id":"toolu_bg"}},"content":[{"terminalId":"toolu_bg","type":"terminal"}],"kind":"execute","name":"Bash","sessionUpdate":"tool_call","status":"pending","title":"Terminal","toolCallId":"toolu_bg"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","title":"sleep 100","toolCallId":"toolu_bg"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Bash"},"terminal_info":{"terminal_id":"toolu_bash"}},"content":[{"terminalId":"toolu_bash","type":"terminal"}],"kind":"execute","name":"Bash","sessionUpdate":"tool_call","status":"pending","title":"Terminal","toolCallId":"toolu_bash"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","title":"false","toolCallId":"toolu_bash"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Bash"},"terminal_info":{"terminal_id":"toolu_bash"}},"content":[{"terminalId":"toolu_bash","type":"terminal"}],"kind":"execute","name":"Bash","sessionUpdate":"tool_call","status":"pending","title":"Terminal","toolCallId":"toolu_bash"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","title":"ls -la","toolCallId":"toolu_bash"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"version":1},"version":1}}},"kind":"think","sessionUpdate":"tool_call","status":"in_progress","title":"Compact conversation","toolCallId":"00000000-0000-4000-8000-000000000001"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"error":"Context too small","version":1}}}},"content":[{"content":{"text":"Compaction failed: Context too small","type":"text"},"type":"content"}],"sessionUpdate":"tool_call_update","status":"failed","toolCallId":"00000000-0000-4000-8000-000000000001"}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"version":1},"version":1}}},"kind":"think","sessionUpdate":"tool_call","status":"in_progress","title":"Compact conversation","toolCallId":"00000000-0000-4000-8000-000000000001"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","status":"in_progress","toolCallId":"00000000-0000-4000-8000-000000000001"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"durationMs":7,"postTokens":100,"preTokens":1000,"trigger":"automatic","version":1}}}},"sessionUpdate":"tool_call_update","status":"completed","toolCallId":"00000000-0000-4000-8000-000000000001"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"version":1},"version":1}}},"compactionId":"00000000-0000-4000-8000-000000000001","sessionUpdate":"compaction_update","status":"in_progress"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"compactionId":"00000000-0000-4000-8000-000000000001","content":{"text":"The summary.","type":"text"},"sessionUpdate":"compaction_summary_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"contextCompaction":{"durationMs":7,"postTokens":100,"preTokens":1000,"trigger":"automatic","version":1},"version":1}}},"compactionId":"00000000-0000-4000-8000-000000000001","sessionUpdate":"compaction_update","status":"completed"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Edit"}},"content":[],"kind":"edit","locations":[],"name":"Edit","sessionUpdate":"tool_call","status":"pending","title":"Edit","toolCallId":"toolu_edit"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"locations":[{"path":"<cwd>/src/app.ts"}],"sessionUpdate":"tool_call_update","title":"Edit src/app.ts","toolCallId":"toolu_edit"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Edit"}},"content":[],"kind":"edit","locations":[],"name":"Edit","sessionUpdate":"tool_call","status":"pending","title":"Edit","toolCallId":"toolu_edit"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"locations":[{"path":"<cwd>/src/app.ts"}],"sessionUpdate":"tool_call_update","title":"Edit src/app.ts","toolCallId":"toolu_edit"}}}

View File

@@ -1,11 +1,11 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"ExitPlanMode"}},"content":[],"kind":"switch_mode","name":"ExitPlanMode","sessionUpdate":"tool_call","status":"pending","title":"Approve Plan","toolCallId":"toolu_plan"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"rawInput":{"plan":"# Plan\n1. Do it"},"sessionUpdate":"tool_call_update","toolCallId":"toolu_plan"}}}
{"kind":"requestPermission","payload":{"_meta":{"jetbrains":{"air":{"permission":{"title":"Ready to code?","version":1},"version":1}}},"options":[{"kind":"allow_once","name":"Yes, manually approve edits","optionId":"exit-plan-default"},{"kind":"allow_always","name":"Yes, clear context (0% used) and use auto mode","optionId":"exit-plan-clear-auto"},{"kind":"allow_always","name":"Yes, and use auto mode","optionId":"exit-plan-auto"},{"kind":"allow_always","name":"Yes, and bypass permissions","optionId":"exit-plan-bypass"},{"kind":"reject_once","name":"No, keep planning","optionId":"reject"}],"sessionId":"<session>","toolCall":{"rawInput":{"plan":"# Plan\n1. Do it"},"title":"Approve Plan","toolCallId":"toolu_plan"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"currentModeId":"default","sessionUpdate":"current_mode_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"configOptions":[{"category":"mode","currentValue":"default","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionUpdate":"config_option_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"configOptions":[{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","currentValue":"default","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionUpdate":"config_option_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","status":"completed","title":"Exited Plan Mode","toolCallId":"toolu_plan"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"cost":{"amount":0,"currency":"USD"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"ExitPlanMode"}},"content":[],"kind":"switch_mode","name":"ExitPlanMode","sessionUpdate":"tool_call","status":"pending","title":"Approve Plan","toolCallId":"toolu_plan"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,3 +1,3 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"jetbrains":{"air":{"goal":{"controlMethod":"_session/goal","objective":"Ship the feature","status":"active"},"version":1}}},"sessionUpdate":"session_info_update"}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Grep"}},"content":[],"kind":"search","name":"Grep","sessionUpdate":"tool_call","status":"pending","title":"grep","toolCallId":"toolu_grep"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","title":"grep \"value\"","toolCallId":"toolu_grep"}}}

View File

@@ -1,9 +1,9 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"mcp__docs__search"},"is_mcp_tool_call":true,"jetbrains":{"air":{"mcp":{"server":"docs","tool":"search"},"version":1}}},"content":[],"kind":"other","name":"mcp__docs__search","sessionUpdate":"tool_call","status":"pending","title":"mcp__docs__search","toolCallId":"toolu_mcp"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"mcp__docs__search"},"is_mcp_tool_call":true,"jetbrains":{"air":{"mcp":{"server":"docs","tool":"search"},"version":1}}},"content":[],"kind":"other","name":"mcp__docs__search","sessionUpdate":"tool_call","status":"pending","title":"docs: search","toolCallId":"toolu_mcp"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"rawInput":{"q":"acp"},"sessionUpdate":"tool_call_update","toolCallId":"toolu_mcp"}}}
{"kind":"requestPermission","payload":{"_meta":{"jetbrains":{"air":{"permission":{"title":"mcp__docs__search","version":1},"version":1}}},"options":[{"kind":"allow_once","name":"Yes","optionId":"allow-once"},{"kind":"reject_once","name":"No","optionId":"reject"}],"sessionId":"<session>","toolCall":{"_meta":{"claudeCode":{"mcpServer":{"name":"docs","source":"project"}}},"rawInput":{"q":"acp"},"title":"mcp__docs__search","toolCallId":"toolu_mcp"}}}
{"kind":"requestPermission","payload":{"_meta":{"jetbrains":{"air":{"permission":{"title":"docs: search","version":1},"version":1}}},"options":[{"kind":"allow_once","name":"Yes","optionId":"allow-once"},{"kind":"reject_once","name":"No","optionId":"reject"}],"sessionId":"<session>","toolCall":{"_meta":{"claudeCode":{"mcpServer":{"name":"docs","source":"project"}}},"rawInput":{"q":"acp"},"title":"docs: search","toolCallId":"toolu_mcp"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":[{"content":{"text":"Found 2 documents.","type":"text"},"type":"content"}],"sessionUpdate":"tool_call_update","status":"completed","toolCallId":"toolu_mcp"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"cost":{"amount":0,"currency":"USD"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"memory_recall","toolResponse":{"mode":"select"}}},"kind":"read","locations":[{"path":"/memory/a.md"},{"path":"/memory/b.md"}],"sessionUpdate":"tool_call","status":"completed","title":"Recalled 2 memories","toolCallId":"00000000-0000-4000-8000-000000000001"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"memory_recall","toolResponse":{"mode":"synthesize"}}},"content":[{"content":{"text":"The user prefers tabs.","type":"text"},"type":"content"}],"kind":"read","sessionUpdate":"tool_call","status":"completed","title":"Recalled synthesized memory","toolCallId":"00000000-0000-4000-8000-000000000002"}}}
{"kind":"promptResponse","payload":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"SandboxNetworkAccess"}},"content":[],"kind":"other","name":"SandboxNetworkAccess","rawInput":{"host":"example.com"},"sessionUpdate":"tool_call","status":"pending","title":"SandboxNetworkAccess","toolCallId":"toolu_net"}}}
{"kind":"requestPermission","payload":{"_meta":{"jetbrains":{"air":{"permission":{"description":"Reason: Sandbox blocks network","title":"example.com","version":1},"version":1}}},"options":[{"kind":"allow_once","name":"Yes","optionId":"allow-once"},{"kind":"reject_once","name":"No","optionId":"reject"}],"sessionId":"<session>","toolCall":{"rawInput":{"host":"example.com"},"title":"example.com","toolCallId":"toolu_net"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","status":"completed","toolCallId":"toolu_net"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"NotebookEdit"}},"content":[],"kind":"edit","locations":[],"name":"NotebookEdit","sessionUpdate":"tool_call","status":"pending","title":"Edit notebook","toolCallId":"toolu_nb"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"locations":[{"path":"<cwd>/n.ipynb"}],"sessionUpdate":"tool_call_update","title":"Edit cell in n.ipynb","toolCallId":"toolu_nb"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Bash"},"terminal_info":{"terminal_id":"toolu_denied"}},"content":[{"terminalId":"toolu_denied","type":"terminal"}],"kind":"execute","name":"Bash","sessionUpdate":"tool_call","status":"pending","title":"Terminal","toolCallId":"toolu_denied"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Work","type":"text"},"messageId":"msg_rate","sessionUpdate":"agent_message_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"ing.","type":"text"},"messageId":"msg_rate","sessionUpdate":"agent_message_chunk"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Read"}},"content":[],"kind":"read","locations":[],"name":"Read","sessionUpdate":"tool_call","status":"pending","title":"Read File","toolCallId":"toolu_read"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,4 +1,4 @@
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Fix the bug","type":"text"},"messageId":"00000000-0000-4000-8000-00000000c001","sessionUpdate":"user_message_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Check the file.","type":"text"},"messageId":"msg_r1","sessionUpdate":"agent_thought_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"I will edit it.","type":"text"},"messageId":"msg_r1","sessionUpdate":"agent_message_chunk"}}}
@@ -12,6 +12,6 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>:replay-subagent:toolu_r_task","update":{"_meta":{"claudeCode":{"parentToolUseId":"toolu_r_task"}},"content":{"text":"Subagent text.","type":"text"},"messageId":"msg_r_sub","sessionUpdate":"agent_message_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Fixed.","type":"text"},"messageId":"msg_r2","sessionUpdate":"agent_message_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"subagent_state_update","state":"completed","subagentSessionId":"<session>:replay-subagent:toolu_r_task"}}}
{"kind":"loadSession","payload":{"configOptions":[{"category":"mode","currentValue":"auto","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","id":"default","name":"Manual"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","id":"acceptEdits","name":"Accept edits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","id":"plan","name":"Plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","id":"auto","name":"Auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","id":"bypassPermissions","name":"Bypass permissions"}],"currentModeId":"auto"},"sessionId":"<session>"}}
{"kind":"loadSession","payload":{"configOptions":[{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","currentValue":"auto","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","id":"default","name":"Manual"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","id":"acceptEdits","name":"Accept edits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","id":"plan","name":"Plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","id":"auto","name":"Auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","id":"bypassPermissions","name":"Bypass permissions"}],"currentModeId":"auto"},"sessionId":"<session>"}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>:replay-subagent:toolu_r_task","update":{"configOptions":[{"category":"model","currentValue":"claude-sonnet-4-6","id":"model","name":"Model","options":[{"name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionUpdate":"config_option_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}

View File

@@ -1,3 +1,3 @@
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
{"kind":"newSession","payload":{"configOptions":[{"category":"mode","currentValue":"auto","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","id":"default","name":"Manual"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","id":"acceptEdits","name":"Accept edits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","id":"plan","name":"Plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","id":"auto","name":"Auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","id":"bypassPermissions","name":"Bypass permissions"}],"currentModeId":"auto"},"sessionId":"<session>"}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
{"kind":"newSession","payload":{"configOptions":[{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","currentValue":"auto","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","id":"default","name":"Manual"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","id":"acceptEdits","name":"Accept edits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","id":"plan","name":"Plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","id":"auto","name":"Auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","id":"bypassPermissions","name":"Bypass permissions"}],"currentModeId":"auto"},"sessionId":"<session>"}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Skill"}},"content":[],"kind":"other","name":"Skill","sessionUpdate":"tool_call","status":"pending","title":"Load skill","toolCallId":"toolu_skill"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Background review","prompt":"Review the diff","sessionUpdate":"subagent_spawned","subagentSessionId":"a2","task":"Review the diff"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Check the logs","prompt":"Check logs","sessionUpdate":"subagent_spawned","subagentSessionId":"agent_late","task":"Check logs"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Fix the build","prompt":"Make the build pass","sessionUpdate":"subagent_spawned","subagentSessionId":"agent_n","task":"Make the build pass"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Plan the work","prompt":"Plan it","sessionUpdate":"subagent_spawned","subagentSessionId":"agent_outer","task":"Plan it"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Explore code","prompt":"Find the parser","sessionUpdate":"subagent_spawned","subagentSessionId":"agent_1","task":"Find the parser"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"capabilities":{},"name":"Summarize","prompt":"Summarize the repo","sessionUpdate":"subagent_spawned","subagentSessionId":"agent_t","task":"Summarize the repo"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"entries":[{"content":"Write tests","priority":"medium","status":"pending"}],"sessionUpdate":"plan"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"TaskOutput"}},"content":[],"kind":"other","name":"TaskOutput","sessionUpdate":"tool_call","status":"pending","title":"TaskOutput","toolCallId":"toolu_out"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Let me thin","type":"text"},"messageId":"msg_text","sessionUpdate":"agent_thought_chunk"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"k about it.","type":"text"},"messageId":"msg_text","sessionUpdate":"agent_thought_chunk"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"entries":[{"content":"Writing tests","priority":"medium","status":"in_progress"},{"content":"Ship","priority":"medium","status":"pending"}],"sessionUpdate":"plan"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Bash"},"terminal_info":{"terminal_id":"toolu_slow"}},"content":[{"terminalId":"toolu_slow","type":"terminal"}],"kind":"execute","name":"Bash","sessionUpdate":"tool_call","status":"pending","title":"Terminal","toolCallId":"toolu_slow"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":3}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"WebFetch"}},"content":[],"kind":"fetch","name":"WebFetch","sessionUpdate":"tool_call","status":"pending","title":"Fetch","toolCallId":"toolu_fetch"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"sessionUpdate":"tool_call_update","title":"Fetch https://example.com","toolCallId":"toolu_fetch"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Write"}},"content":[],"kind":"edit","locations":[],"name":"Write","sessionUpdate":"tool_call","status":"pending","title":"Preparing file…","toolCallId":"toolu_write"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"locations":[{"path":"<cwd>/old.ts"}],"sessionUpdate":"tool_call_update","title":"Write old.ts","toolCallId":"toolu_write"}}}

View File

@@ -1,4 +1,4 @@
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"_meta":{"claudeCode":{"toolName":"Write"}},"content":[],"kind":"edit","locations":[],"name":"Write","sessionUpdate":"tool_call","status":"pending","title":"Preparing file…","toolCallId":"toolu_write"}}}
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"locations":[{"path":"<cwd>/new.ts"}],"sessionUpdate":"tool_call_update","title":"Write new.ts","toolCallId":"toolu_write"}}}

View File

@@ -1,5 +1,5 @@
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"acp":{},"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …","type":"text"},"name":"plugin","type":"command"}],"configOptions":[{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 1","type":"text"}],"messageId":"<id-1>","sessionUpdate":"user_message"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-1>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}

View File

@@ -1,5 +1,5 @@
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"acp":{},"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …","type":"text"},"name":"plugin","type":"command"}],"configOptions":[{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 1","type":"text"}],"messageId":"<id-1>","sessionUpdate":"user_message"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-1>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}

View File

@@ -1,5 +1,5 @@
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"acp":{},"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …","type":"text"},"name":"plugin","type":"command"}],"configOptions":[{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 1","type":"text"}],"messageId":"<id-1>","sessionUpdate":"user_message"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-1>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}

View File

@@ -1,5 +1,5 @@
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"acp":{},"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …","type":"text"},"name":"plugin","type":"command"}],"configOptions":[{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 1","type":"text"}],"messageId":"<id-1>","sessionUpdate":"user_message"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-1>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}

View File

@@ -1,5 +1,5 @@
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"response","method":"initialize","payload":{"authMethods":[],"capabilities":{"_meta":{"authStatus":{}},"auth":{"status":{}},"providers":{},"session":{"additionalDirectories":{},"delete":{},"fork":{},"mcp":{"acp":{},"http":{},"stdio":{}},"options":{},"prompt":{"embeddedContext":{},"image":{}},"status":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"info":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"protocolVersion":2}}
{"kind":"response","method":"session/new","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]","type":"text"},"name":"mcp","type":"command"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …","type":"text"},"name":"plugin","type":"command"}],"configOptions":[{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","configId":"mode","currentValue":"auto","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"sessionId":"<session>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 1","type":"text"}],"messageId":"<id-1>","sessionUpdate":"user_message"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-1>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}

Some files were not shown because too many files have changed in this diff Show More