mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-10 03:12:09 +00:00
Compare commits
3 Commits
refactor/l
...
fix-plan-m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fda22f227c | ||
|
|
7643799805 | ||
|
|
ce4ae06993 |
2
.gitattributes
vendored
2
.gitattributes
vendored
@@ -1,2 +0,0 @@
|
||||
src/tests/acp-scenarios/__snapshots__/** linguist-generated=true
|
||||
src/tests/acp-scenarios/origin-main/** linguist-generated=true
|
||||
18
.github/dependabot.yml
vendored
18
.github/dependabot.yml
vendored
@@ -1,18 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
# Check for updates to GitHub Actions every week
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
allow:
|
||||
- dependency-type: "all"
|
||||
groups:
|
||||
minor:
|
||||
update-types:
|
||||
- "minor"
|
||||
- "patch"
|
||||
125
.github/workflows/binaries.yml
vendored
125
.github/workflows/binaries.yml
vendored
@@ -1,125 +0,0 @@
|
||||
# Builds the standalone executables (scripts/build-binary.mjs) and smoke-tests
|
||||
# each one on a runner of its own platform. Each archive holds
|
||||
# `claude-agent-acp` and the Claude CLI (`claude`) it runs from its directory.
|
||||
# CI calls this to check that every target still builds and starts; the
|
||||
# release calls it with `upload: true` and attaches the archives to the GitHub
|
||||
# release.
|
||||
name: Binaries
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
upload:
|
||||
description: Upload each archive as a workflow artifact for the release job.
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Binary (${{ matrix.target }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: bun-linux-x64
|
||||
runner: ubuntu-latest
|
||||
archive: claude-agent-acp-linux-x64.tar.gz
|
||||
- target: bun-linux-arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
archive: claude-agent-acp-linux-arm64.tar.gz
|
||||
# npm skips the musl package on a glibc host, so these are
|
||||
# cross-built and smoke-tested in an Alpine container.
|
||||
- target: bun-linux-x64-musl
|
||||
runner: ubuntu-latest
|
||||
archive: claude-agent-acp-linux-x64-musl.tar.gz
|
||||
musl: true
|
||||
- target: bun-linux-arm64-musl
|
||||
runner: ubuntu-24.04-arm
|
||||
archive: claude-agent-acp-linux-arm64-musl.tar.gz
|
||||
musl: true
|
||||
- target: bun-darwin-x64
|
||||
runner: macos-15-intel
|
||||
archive: claude-agent-acp-darwin-x64.zip
|
||||
- target: bun-darwin-arm64
|
||||
runner: macos-latest
|
||||
archive: claude-agent-acp-darwin-arm64.zip
|
||||
- target: bun-windows-x64
|
||||
runner: windows-latest
|
||||
archive: claude-agent-acp-windows-x64.zip
|
||||
- target: bun-windows-arm64
|
||||
runner: windows-11-arm
|
||||
archive: claude-agent-acp-windows-arm64.zip
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
|
||||
with:
|
||||
node-version: "lts/*"
|
||||
check-latest: true
|
||||
cache: "npm"
|
||||
|
||||
# Unpinned: each build is smoke-tested on its platform before it uploads,
|
||||
# so a Bun release that breaks the executable fails here instead of
|
||||
# shipping. Pin a version if one ever regresses past the smoke test.
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Install the musl Claude CLI package
|
||||
if: ${{ matrix.musl }}
|
||||
run: |
|
||||
version="$(node -p "require('./node_modules/@anthropic-ai/claude-agent-sdk/package.json').version")"
|
||||
npm install --no-save --force "@anthropic-ai/claude-agent-sdk-linux-${RUNNER_ARCH,,}-musl@$version"
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
echo "Built \`${{ matrix.target }}\` with Bun $(bun --version)" >> "$GITHUB_STEP_SUMMARY"
|
||||
node scripts/build-binary.mjs --target ${{ matrix.target }}
|
||||
|
||||
- name: Smoke test
|
||||
if: ${{ !matrix.musl }}
|
||||
run: node scripts/smoke-binary.mjs
|
||||
|
||||
# Claude Code's Alpine requirements: libgcc and libstdc++.
|
||||
- name: Smoke test (Alpine)
|
||||
if: ${{ matrix.musl }}
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/work" -w /work node:lts-alpine \
|
||||
sh -c 'apk add --no-cache libgcc libstdc++ >/dev/null && node scripts/smoke-binary.mjs'
|
||||
|
||||
- name: Archive
|
||||
if: ${{ inputs.upload }}
|
||||
env:
|
||||
ARCHIVE: ${{ matrix.archive }}
|
||||
run: |
|
||||
cd dist-bin
|
||||
if [[ "$ARCHIVE" == *.zip ]]; then
|
||||
if [[ "$RUNNER_OS" == "Windows" ]]; then
|
||||
pwsh -Command "Compress-Archive -Path claude-agent-acp.exe,claude.exe -DestinationPath ../$ARCHIVE"
|
||||
else
|
||||
zip "../$ARCHIVE" claude-agent-acp claude
|
||||
fi
|
||||
else
|
||||
tar czf "../$ARCHIVE" claude-agent-acp claude
|
||||
fi
|
||||
|
||||
- name: Upload
|
||||
if: ${{ inputs.upload }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: ${{ matrix.archive }}
|
||||
path: ${{ matrix.archive }}
|
||||
retention-days: 7
|
||||
if-no-files-found: error
|
||||
11
.github/workflows/ci.yml
vendored
11
.github/workflows/ci.yml
vendored
@@ -21,13 +21,12 @@ jobs:
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
|
||||
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
|
||||
with:
|
||||
node-version: "lts/*"
|
||||
check-latest: true
|
||||
node-version: latest
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
@@ -44,7 +43,3 @@ jobs:
|
||||
|
||||
- name: Run tests
|
||||
run: npm run test:run
|
||||
|
||||
binaries:
|
||||
name: Binaries
|
||||
uses: ./.github/workflows/binaries.yml
|
||||
|
||||
48
.github/workflows/conventional-prs.yml
vendored
48
.github/workflows/conventional-prs.yml
vendored
@@ -1,48 +0,0 @@
|
||||
name: Conventional PRs
|
||||
|
||||
# Squash merges use the PR title as the commit subject, which is what
|
||||
# release-please parses to compute the next version and CHANGELOG entry.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
# labeled/unlabeled so validation re-runs when `dependencies` is applied.
|
||||
types: [opened, reopened, edited, synchronize, labeled, unlabeled]
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: "conventional-prs-${{ github.event.pull_request.number }}"
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate PR title
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
|
||||
steps:
|
||||
# Config reference: https://github.com/amannn/action-semantic-pull-request#configuration
|
||||
- uses: amannn/action-semantic-pull-request@2252a14e810aa9b85c2d560bd7070c802206ecf6 # v6.1.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
# Exactly the types release-please understands. feat/fix/perf/revert/docs
|
||||
# appear in the changelog; the rest are valid but hidden. Any other type
|
||||
# would be dropped silently, so it is rejected here instead.
|
||||
types: |
|
||||
feat
|
||||
fix
|
||||
perf
|
||||
revert
|
||||
docs
|
||||
style
|
||||
chore
|
||||
refactor
|
||||
test
|
||||
build
|
||||
ci
|
||||
# Dependabot titles itself conventionally already; don't block bot PRs.
|
||||
ignoreLabels: |
|
||||
dependencies
|
||||
305
.github/workflows/publish.yml
vendored
305
.github/workflows/publish.yml
vendored
@@ -1,311 +1,36 @@
|
||||
name: Publish and Release
|
||||
name: Publish Package to npmjs
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: Which channel to publish
|
||||
required: true
|
||||
default: stable
|
||||
type: choice
|
||||
options:
|
||||
- stable
|
||||
- preview
|
||||
ref:
|
||||
description: Tag or commit to publish
|
||||
required: true
|
||||
type: string
|
||||
publish_npm:
|
||||
description: Publish the package before updating the registry (stable only)
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
jobs:
|
||||
release-please:
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
runs-on: ubuntu-latest
|
||||
environment: release # Optional: for enhanced security
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 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
|
||||
id: generate-token
|
||||
with:
|
||||
# GitHub App ID secret name
|
||||
app-id: ${{ secrets.RELEASE_PLZ_APP_ID }}
|
||||
# GitHub App private key secret name
|
||||
private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }}
|
||||
- uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7
|
||||
id: release
|
||||
with:
|
||||
token: ${{ steps.generate-token.outputs.token }}
|
||||
# Do not add release-type here. The action ignores config-file whenever
|
||||
# release-type is set, which silently disables the pre-1.0 versioning
|
||||
# rules in release-please-config.json and lets a breaking change jump
|
||||
# straight to 1.0.0. The node release type is declared in that config
|
||||
# instead, so nothing is lost by leaving this out.
|
||||
config-file: release-please-config.json
|
||||
manifest-file: .release-please-manifest.json
|
||||
outputs:
|
||||
release_created: ${{ steps.release.outputs.release_created }}
|
||||
tag_name: ${{ steps.release.outputs.tag_name }}
|
||||
|
||||
publish-npm:
|
||||
name: Publish to npm
|
||||
runs-on: ubuntu-latest
|
||||
needs: [release-please]
|
||||
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && inputs.publish_npm) || needs.release-please.outputs.release_created == 'true') }}
|
||||
environment: release # Optional: for enhanced security
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
outputs:
|
||||
version: ${{ steps.publish.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.ref }}
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
|
||||
# Setup .npmrc file to publish to npm
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
|
||||
with:
|
||||
node-version: "lts/*"
|
||||
check-latest: true
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
- name: Update npm
|
||||
run: npm install -g npm@latest
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- name: Publish
|
||||
id: publish
|
||||
run: |
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
npm publish
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Standalone executables for the GitHub release, stable releases only. They
|
||||
# don't gate the npm publish: a failed build leaves the release without
|
||||
# binaries, and re-running the failed jobs attaches them.
|
||||
build-binaries:
|
||||
name: Build binaries
|
||||
needs: [release-please]
|
||||
if: ${{ needs.release-please.outputs.release_created == 'true' }}
|
||||
# The called workflow only reads the repository; upload-binaries does the write.
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/binaries.yml
|
||||
with:
|
||||
upload: true
|
||||
|
||||
upload-binaries:
|
||||
name: Attach binaries to the release
|
||||
- run: npm publish
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [release-please, build-binaries]
|
||||
needs: [publish-npm]
|
||||
permissions:
|
||||
contents: write
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Upload to the release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAG: ${{ needs.release-please.outputs.tag_name }}
|
||||
run: gh release upload "$TAG" artifacts/* --clobber --repo "$GITHUB_REPOSITORY"
|
||||
|
||||
# Same shape as publish-npm. Tagging is a separate job, so nothing here needs
|
||||
# write access to the repository.
|
||||
publish-npm-preview:
|
||||
name: Publish preview to npm
|
||||
runs-on: ubuntu-latest
|
||||
# Every push to main gets a preview without waiting for CI or release-please,
|
||||
# except release-please's own release merge, which publishes a stable version.
|
||||
# Check the commit author and the generated release subject to avoid publishing
|
||||
# the same tree twice; either match is enough to skip the preview.
|
||||
if: >-
|
||||
${{
|
||||
(github.event_name == 'workflow_dispatch' && inputs.channel == 'preview') ||
|
||||
(github.event_name == 'push'
|
||||
&& github.event.head_commit.author.name != 'acp-release-bot[bot]'
|
||||
&& !startsWith(github.event.head_commit.message, 'chore(main): release '))
|
||||
}}
|
||||
# Same environment as the stable job, so the npm trusted-publisher binding holds.
|
||||
# It carries no required reviewers, so previews never wait for an approval.
|
||||
environment: release
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # npm OIDC trusted publishing
|
||||
timeout-minutes: 15
|
||||
# Serialise previews so two pushes cannot read the same registry state and compute
|
||||
# the same -preview.N. Job-level rather than workflow-level: a workflow-level group
|
||||
# would also serialise release-please, and cancelling a queued release-please run
|
||||
# means a release PR that silently stops updating. The trade-off is that GitHub
|
||||
# keeps only one run pending per group, so a third push landing while one preview
|
||||
# runs and another waits drops the waiting one — that commit gets no preview, but a
|
||||
# version is never reused.
|
||||
concurrency:
|
||||
group: publish-npm-preview
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
# Publish the exact pushed commit, or the explicitly requested manual ref.
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }}
|
||||
# Brings the tags the version calculation reads as its floor. The repo is a
|
||||
# few megabytes packed, so a full fetch is cheap and sidesteps every
|
||||
# shallow-clone tag caveat.
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1
|
||||
with:
|
||||
node-version: "lts/*"
|
||||
check-latest: true
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
# Ahead of the version bump, so this still validates the committed lockfile.
|
||||
- run: npm ci
|
||||
- name: Compute the preview version
|
||||
id: preview
|
||||
run: |
|
||||
version="$(node scripts/next-preview-version.mjs)"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "sha=$sha" >> "$GITHUB_OUTPUT"
|
||||
echo "Preview \`$version\` from \`$sha\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Apply the version to the working tree only
|
||||
# Never committed: package.json and .release-please-manifest.json on main stay
|
||||
# release-please's to own, and this only changes what goes into the tarball.
|
||||
# `npm version` keeps package-lock.json's version fields in step, and
|
||||
# --no-git-tag-version skips every git operation.
|
||||
run: npm version "${{ steps.preview.outputs.version }}" --no-git-tag-version
|
||||
- run: npm run build
|
||||
- name: Publish
|
||||
id: publish
|
||||
# --tag is mandatory: npm publish defaults to `latest` even for a semver
|
||||
# prerelease, which would point every plain `npm install` at a preview.
|
||||
run: |
|
||||
npm publish --tag preview
|
||||
echo "published=true" >> "$GITHUB_OUTPUT"
|
||||
outputs:
|
||||
published: ${{ steps.publish.outputs.published }}
|
||||
version: ${{ steps.preview.outputs.version }}
|
||||
sha: ${{ steps.preview.outputs.sha }}
|
||||
|
||||
publish-tag-preview:
|
||||
name: Tag the published preview
|
||||
runs-on: ubuntu-latest
|
||||
needs: publish-npm-preview
|
||||
if: ${{ needs.publish-npm-preview.outputs.published == 'true' }}
|
||||
environment: release
|
||||
permissions:
|
||||
contents: write # create refs/tags/v<version>
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
# A re-run carries over the outputs of jobs it did not re-run. If that ever stops
|
||||
# holding, fail with the manual recipe rather than tagging the wrong commit.
|
||||
- name: Check the publish handed over a version and a commit
|
||||
env:
|
||||
VERSION: ${{ needs.publish-npm-preview.outputs.version }}
|
||||
SHA: ${{ needs.publish-npm-preview.outputs.sha }}
|
||||
run: |
|
||||
if [ -z "$VERSION" ] || [ -z "$SHA" ]; then
|
||||
echo "::error::publish-npm-preview reported version='$VERSION' sha='$SHA'." \
|
||||
"Tag it by hand — see docs/RELEASES.md, 'A preview published but the" \
|
||||
"commit was not tagged'."
|
||||
exit 1
|
||||
fi
|
||||
- name: Create the tag
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
VERSION: ${{ needs.publish-npm-preview.outputs.version }}
|
||||
SHA: ${{ needs.publish-npm-preview.outputs.sha }}
|
||||
run: |
|
||||
gh api "repos/$GITHUB_REPOSITORY/git/refs" \
|
||||
-f ref="refs/tags/v$VERSION" \
|
||||
-f sha="$SHA"
|
||||
echo "Tagged \`v$VERSION\` at \`$SHA\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
trigger-registry-update:
|
||||
# upload-binaries too, so a stable release's archives are attached before the
|
||||
# registry reads the release: it takes each archive's sha256 from the release
|
||||
# assets when it bumps the version. It only waits; a failed or skipped upload
|
||||
# (every preview) doesn't stop the dispatch.
|
||||
needs: [publish-npm, publish-npm-preview, upload-binaries]
|
||||
# Both channels dispatch this: the registry has its own handling for preview
|
||||
# versions. The two never fire together — a release merge publishes stable and
|
||||
# skips the preview, and every other push does the reverse — so the registry sees
|
||||
# exactly one dispatch per published version. The payload is deliberately
|
||||
# unchanged: it names no version, and the registry resolves what it needs itself.
|
||||
if: >-
|
||||
${{
|
||||
always() && (
|
||||
needs.publish-npm.result == 'success'
|
||||
|| needs.publish-npm-preview.outputs.published == 'true'
|
||||
|| (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.publish_npm)
|
||||
)
|
||||
}}
|
||||
runs-on: ubuntu-latest
|
||||
environment: release
|
||||
permissions: {}
|
||||
# npm metadata is normally visible within about five minutes. Leave 2.5x that
|
||||
# window for propagation, plus enough time to mint the token and dispatch.
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Wait for package to become available
|
||||
if: ${{ needs.publish-npm.result == 'success' || needs.publish-npm-preview.outputs.published == 'true' }}
|
||||
env:
|
||||
PACKAGE: "@agentclientprotocol/claude-agent-acp"
|
||||
VERSION: ${{ needs.publish-npm-preview.outputs.version || needs.publish-npm.outputs.version }}
|
||||
#language=bash
|
||||
run: |
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "::error::The publish job did not report a package version."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
deadline=$((SECONDS + 750))
|
||||
while (( SECONDS < deadline )); do
|
||||
if timeout 10s npm pack "$PACKAGE@$VERSION" \
|
||||
--dry-run \
|
||||
--ignore-scripts \
|
||||
--silent \
|
||||
--registry=https://registry.npmjs.org \
|
||||
--prefer-online \
|
||||
--fetch-retries=0 >/dev/null 2>&1; then
|
||||
echo "$PACKAGE@$VERSION is available from npm."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
remaining=$((deadline - SECONDS))
|
||||
if (( remaining > 0 )); then
|
||||
echo "Waiting for $PACKAGE@$VERSION to become available (${remaining}s remaining)..."
|
||||
sleep 10
|
||||
fi
|
||||
done
|
||||
|
||||
echo "::error::$PACKAGE@$VERSION was not available from npm after 12.5 minutes."
|
||||
exit 1
|
||||
|
||||
- name: Generate token scoped to the registry repo
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
|
||||
id: registry-token
|
||||
with:
|
||||
app-id: ${{ secrets.REGISTRY_UPDATER_APP_ID }}
|
||||
private-key: ${{ secrets.REGISTRY_UPDATER_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: registry
|
||||
|
||||
- name: Dispatch registry version update
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.registry-token.outputs.token }}
|
||||
run: |
|
||||
gh workflow run update-versions.yml \
|
||||
--repo ${{ github.repository_owner }}/registry \
|
||||
--ref main \
|
||||
-f apply=true \
|
||||
-f agents=claude-acp
|
||||
draft: true
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,7 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
.DS_Store
|
||||
.claude/*.local.*
|
||||
CLAUDE.local.md
|
||||
.idea/
|
||||
dist-bin
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
.agent-shell
|
||||
|
||||
.release-please-manifest.json
|
||||
release-please-config.json
|
||||
CHANGELOG.md
|
||||
|
||||
# Recorded ACP traffic, written by src/tests/acp-scenarios.test.ts.
|
||||
src/tests/acp-scenarios/__snapshots__
|
||||
src/tests/acp-scenarios/origin-main
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
".": "0.102.0"
|
||||
}
|
||||
136
AGENTS.md
136
AGENTS.md
@@ -1,136 +0,0 @@
|
||||
# Agent guide
|
||||
|
||||
An ACP-compatible coding agent powered by the Claude Agent SDK. Source in `src/`,
|
||||
TypeScript, ESM, Node >= 22. `src/v1/` holds the v1 agent (`ClaudeAcpAgent` in
|
||||
`src/v1/acp-agent.ts`), `src/v2/` the v2 agent, and the rest of `src/` the modules
|
||||
both share. `src/acp-agent.ts` only re-exports `src/v1/acp-agent.ts` for the
|
||||
published `dist/acp-agent.js` path. ESLint rejects imports between `src/v1/` and
|
||||
`src/v2/`, and from shared modules into either agent. The entry points (`index.ts`, `lib.ts`,
|
||||
`serve.ts`, `binary-entry.ts`, `acp-agent.ts`) are exempt.
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
npm run build # tsc
|
||||
npm run test:run # vitest, single pass
|
||||
npm run check # eslint + prettier --check
|
||||
npm run lint:fix # eslint --fix
|
||||
npm run format # prettier --write
|
||||
```
|
||||
|
||||
CI runs `format:check`, `lint`, `build` and `test:run`. Run `npm run check` before
|
||||
opening a PR.
|
||||
|
||||
## Coding guidelines
|
||||
|
||||
- Keep edits consistent with the surrounding code's formatting, naming and idioms.
|
||||
- Keep comments concise and concrete. Name the actual state, call or failure
|
||||
instead of alluding to it, prefer a short example over an abstract
|
||||
description, and avoid vague phrases like "keeps it honest". A comment or doc
|
||||
must be true on every code path it describes, and a doc that lists what a
|
||||
result omits or rejects must name the actual cases.
|
||||
- When a request can't be served, throw a `RequestError` whose message says what
|
||||
happened and what to do (e.g. "Try again when the turn ends"). Don't drop the
|
||||
request silently.
|
||||
- Don't report success for work you start without awaiting it. If the detached
|
||||
call can still refuse and its `.catch` only logs, check the refusal condition
|
||||
first or report the failure to the client.
|
||||
- A result must not depend on what an earlier call happened to cache. A request
|
||||
right after a restart, with cold caches, must return the same thing as one
|
||||
after a warm-up.
|
||||
- If code relies on an ordering or call sequence that nothing enforces (e.g. an
|
||||
echo arriving before the result), say so in a short comment.
|
||||
|
||||
## Architecture and design fit
|
||||
|
||||
- Before coding, read the code the change plugs into and find the module that
|
||||
owns the state or concept. Build on that module, not beside it.
|
||||
- Don't add new features or components to `src/v1/acp-agent.ts`. If no existing module fits
|
||||
the new code cleanly, create a dedicated one that owns the feature's state and logic,
|
||||
and keep the change in `src/v1/acp-agent.ts` to the calls that wire it in.
|
||||
- Prefer extending an existing mechanism over adding a new one, even if it takes
|
||||
a small refactor (moving a helper, generalizing a function). Add a parallel
|
||||
path, special case or flag only when the existing structure can't support the
|
||||
change.
|
||||
- Before writing new logic, check whether it already exists in a sibling handler
|
||||
of the same flow or in a helper that works with the same data, and reuse it.
|
||||
Paths that handle the same input must apply the same rules through the same
|
||||
code: the live stream and the `session/load` replay, the command list and
|
||||
command dispatch, `prompt` and `steer`. Two copies of one check drift apart.
|
||||
- Put guards, filters and cleanup in the module that owns the state, so every
|
||||
caller gets them. If guards, flags or fallbacks pile up in one place,
|
||||
restructure instead of adding another.
|
||||
- If a result is meant to match another request's output, reuse that request's
|
||||
logic.
|
||||
- The adapter serves ACP v1 and v2. A change that is not meant for one protocol
|
||||
version only must work correctly in both. `ClaudeAcpAgent` serves v1, and
|
||||
`src/v2/` serves v2; they share modules (the SDK mapping, tool call
|
||||
rendering, permissions, config options). Put a change meant for both versions
|
||||
in the shared module, or make it in both cores.
|
||||
- A session runs one turn at a time. On v1, "Claude is working" means
|
||||
`startTurn`'s check (an unsettled turn in `turnQueue`, or `foregroundWork` for
|
||||
the session); on v2, an open turn of the v2 session. Don't write a
|
||||
narrower one. Anything that sends `session/update` must go
|
||||
through the turn queue or be refused while the session is busy, or its output
|
||||
lands inside another turn. Keep the session marked busy across awaited network
|
||||
calls.
|
||||
- Don't branch on a local copy of state that Claude Code or a remote service
|
||||
owns: it goes stale when the other side changes. Have a command set the state
|
||||
the user asks for instead of toggling it.
|
||||
- A command or name the adapter adds must not shadow one that Claude Code or the
|
||||
user's own commands and skills already provide.
|
||||
- New optional request fields and `_meta` keys must not reject requests that
|
||||
were valid before.
|
||||
- If a workaround or new path is unavoidable (e.g. a Claude Code or SDK
|
||||
limitation), say why in a short code comment and in the PR description.
|
||||
|
||||
## Testing guidelines
|
||||
|
||||
- Before adding a test, search `src/tests/` for existing tests of the same API
|
||||
and scenario, and add to their file and `describe` block. Use the helpers in
|
||||
`helpers.ts` and `session-doubles.ts` instead of copying setup.
|
||||
- Don't add cases that take the same code path. Tests that differ only in input
|
||||
and expected output belong in one `it.each`. Don't repeat another test's
|
||||
assertions; assert only what this test is about.
|
||||
- Reach a state the shortest way (e.g. set `session.tornDown = true`) instead of
|
||||
driving a full flow with extra mocks, unless the flow is what you test.
|
||||
- Build test doubles from what the bundled Claude Code CLI really sends,
|
||||
including fields like `origin` it echoes back and fields it omits. A double
|
||||
simpler than the real message hides bugs. If unsure, check against the real
|
||||
CLI (`npm run test:integration`).
|
||||
- Cover both ACP v1 and v2 when a change affects what a client receives
|
||||
(updates, responses, replay). A change to internal logic only does not need
|
||||
its tests duplicated per version.
|
||||
- For each behavior the docs or comments promise, including what is omitted or
|
||||
rejected, have a test that would fail if it broke.
|
||||
|
||||
## Pull requests
|
||||
|
||||
Squash merges use the PR title as the commit subject, and release-please parses it
|
||||
to compute the next version. Titles must be conventional commits using one of:
|
||||
`feat`, `fix`, `perf`, `revert`, `docs`, `style`, `chore`, `refactor`, `test`,
|
||||
`build`, `ci`. `conventional-prs.yml` rejects anything else.
|
||||
|
||||
The title also decides the release: `feat:` bumps the minor, `fix:`/`perf:` the
|
||||
patch, and `chore:`/`ci:`/`test:` and friends do not release at all.
|
||||
|
||||
## Releasing
|
||||
|
||||
Stable releases are fully automated by release-please. There is no manual release
|
||||
workflow, and the version is never chosen by hand — it follows from the commit
|
||||
history.
|
||||
|
||||
```sh
|
||||
npm run release:preflight # verifies it is safe to release, prints the PR and version
|
||||
gh pr merge <pr-number> --squash
|
||||
```
|
||||
|
||||
The preflight is the guard-list as code; if it exits non-zero, follow what it
|
||||
prints rather than merging.
|
||||
|
||||
Every _other_ push to `main` publishes a preview to npm — `0.73.1-preview.4` and
|
||||
so on — under the `preview` dist-tag, tags the commit it came from, and updates
|
||||
the agent registry the same way a release does. Only `latest` is reserved for
|
||||
real releases. So anything merged to `main` is published within minutes; there is
|
||||
no staging branch. Full runbook, including how to recover a stalled release:
|
||||
[`docs/RELEASES.md`](docs/RELEASES.md).
|
||||
1410
CHANGELOG.md
1410
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
61
LICENSE
61
LICENSE
@@ -1,18 +1,42 @@
|
||||
Copyright 2022 - 2025 Zed Industries, Inc.
|
||||
|
||||
Apache License
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
|
||||
1. Definitions.
|
||||
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
@@ -21,23 +45,28 @@
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
@@ -46,6 +75,7 @@
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
@@ -60,10 +90,12 @@
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
@@ -71,6 +103,7 @@
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
@@ -87,23 +120,28 @@
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
@@ -121,6 +159,7 @@
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
@@ -128,6 +167,7 @@
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
@@ -136,11 +176,13 @@
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
@@ -151,6 +193,7 @@
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
@@ -163,6 +206,7 @@
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
@@ -174,18 +218,5 @@
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2025 Zed Industries, Inc. and contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
168
README.md
168
README.md
@@ -1,155 +1,59 @@
|
||||
# ACP adapter for the Claude Agent SDK
|
||||
# ACP adapter for Claude Code
|
||||
|
||||
[](https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp)
|
||||
[](https://www.npmjs.com/package/@zed-industries/claude-code-acp)
|
||||
|
||||
Use [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview#branding-guidelines) from [ACP-compatible](https://agentclientprotocol.com) clients!
|
||||
Use [Claude Code](https://www.anthropic.com/claude-code) from [ACP-compatible](https://agentclientprotocol.com) clients such as [Zed](https://zed.dev)!
|
||||
|
||||
This tool implements an ACP agent by using the official [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), supporting:
|
||||
This tool implements an ACP agent by using the official [Claude Code SDK](https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-overview), supporting:
|
||||
|
||||
- Context @-mentions
|
||||
- Images
|
||||
- Tool calls (with permission requests)
|
||||
- Compact file changes through the negotiated [AIR diff patch extension](docs/air-extensions.md#diff-patch)
|
||||
- Following
|
||||
- Edit review
|
||||
- TODO lists
|
||||
- Nested subagent transcripts
|
||||
- Interactive (and background) terminals
|
||||
- Custom [Slash commands](https://docs.anthropic.com/en/docs/claude-code/slash-commands)
|
||||
- Client MCP servers
|
||||
- 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
|
||||
- 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)
|
||||
- Tool permission presentation, editable choices, and durable effects through the [permission extension](docs/air-extensions.md#permission-presentation)
|
||||
- One fact per field in every tool call report, as the [ACP tool call contract](docs/air-extensions.md#tool-call-contract) defines
|
||||
- All AIR extensions, capabilities, and `_meta` keys: [AIR extensions](docs/air-extensions.md)
|
||||
|
||||
Learn more about the [Agent Client Protocol](https://agentclientprotocol.com/).
|
||||
|
||||
To try changes that have landed on `main` but are not released yet, install from the
|
||||
`preview` channel — every push to `main` publishes one. See
|
||||
[`docs/RELEASES.md`](docs/RELEASES.md#preview-releases).
|
||||
## How to use
|
||||
|
||||
```sh
|
||||
npm install @agentclientprotocol/claude-agent-acp@preview
|
||||
### Zed
|
||||
|
||||
The latest version of Zed can already use this adapter out of the box.
|
||||
|
||||
To use Claude Code, open the Agent Panel and click "New Claude Code Thread" from the `+` button menu in the top-right:
|
||||
|
||||
https://github.com/user-attachments/assets/ddce66c7-79ac-47a3-ad59-4a6a3ca74903
|
||||
|
||||
Read the docs on [External Agent](https://zed.dev/docs/ai/external-agents) support.
|
||||
|
||||
### Other clients
|
||||
|
||||
- Emacs via [agent-shell.el](https://github.com/xenodium/agent-shell)
|
||||
- [marimo notebook](https://github.com/marimo-team/marimo)
|
||||
- Neovim
|
||||
- via [CodeCompanion.nvim](https://codecompanion.olimorris.dev/configuration/adapters#setup-claude-code-via-acp)
|
||||
- via [yetone/avante.nvim](https://github.com/yetone/avante.nvim)
|
||||
|
||||
[Submit a PR](https://github.com/zed-industries/claude-code-acp/pulls) to add yours!
|
||||
|
||||
#### Installation
|
||||
|
||||
Install the adapter from `npm`:
|
||||
|
||||
```bash
|
||||
npm install @zed-industries/claude-code-acp
|
||||
```
|
||||
|
||||
### Standalone executables
|
||||
You can then use `claude-code-acp` as a regular ACP agent:
|
||||
|
||||
Each release attaches archives for Linux (glibc and musl), macOS and Windows, on
|
||||
x64 and arm64, to its [GitHub release](https://github.com/agentclientprotocol/claude-agent-acp/releases).
|
||||
They need no Node.js install. Each holds two files: `claude-agent-acp`, and the
|
||||
Claude CLI (`claude`) it runs. Keep them in the same directory; a symlink to
|
||||
`claude-agent-acp` elsewhere works. To use a Claude CLI you already have
|
||||
instead, set `CLAUDE_CODE_EXECUTABLE`. On Alpine, install `libgcc` and
|
||||
`libstdc++` first.
|
||||
|
||||
To build one for your machine (needs [Bun](https://bun.sh)) and check it:
|
||||
|
||||
```sh
|
||||
npm run build:binary
|
||||
npm run smoke:binary # add `-- --full` to drive a real session; needs a Claude login
|
||||
```
|
||||
ANTHROPIC_API_KEY=sk-... claude-code-acp
|
||||
```
|
||||
|
||||
### Subagent sessions
|
||||
## License
|
||||
|
||||
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.
|
||||
|
||||
`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`, 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.
|
||||
|
||||
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
|
||||
(`_meta.jetbrains.air`) also gets the AIR extensions that ACP v2 does not cover.
|
||||
|
||||
## Contribution Policy
|
||||
|
||||
This project does not require a Contributor License Agreement (CLA). Instead, contributions are accepted under the following terms:
|
||||
|
||||
> By contributing to this project, you agree that your contributions will be licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). You affirm that you have the legal right to submit your work, that you are not including code you do not have rights to, and that you understand contributions are made without requiring a Contributor License Agreement (CLA).
|
||||
Apache-2.0
|
||||
|
||||
255
docs/RELEASES.md
255
docs/RELEASES.md
@@ -1,257 +1,24 @@
|
||||
# Releases
|
||||
## How to publish a new release
|
||||
|
||||
Releases are automated by [release-please](https://github.com/googleapis/release-please)
|
||||
in [`.github/workflows/publish.yml`](../.github/workflows/publish.yml). Every push
|
||||
to `main` re-computes the next version from the conventional commit messages and
|
||||
keeps a single release PR open, titled `chore(main): release X.Y.Z` and labelled
|
||||
`autorelease: pending`.
|
||||
|
||||
Merging that PR is what releases. It tags `vX.Y.Z`, creates the GitHub release,
|
||||
publishes to npm, dispatches a version update to the agent registry, and
|
||||
attaches the [standalone executables](../README.md#standalone-executables) to
|
||||
the GitHub release. Previews get no executables.
|
||||
|
||||
There is no manual release button, and versions are never typed in by hand: the
|
||||
version is an output of the commit history, not an input.
|
||||
|
||||
Every _other_ push to `main` publishes a preview instead — see
|
||||
[Preview releases](#preview-releases). Anything merged to `main` is on npm within
|
||||
minutes; there is no staging branch.
|
||||
|
||||
## Releasing
|
||||
1. Create a new branch prep-vX.X.X
|
||||
|
||||
```sh
|
||||
npm run release:preflight
|
||||
git checkout -b prep-vX.X.X
|
||||
```
|
||||
|
||||
This reports the open release PR, the version it will ship, and checks that the
|
||||
repository is in a state where merging is safe. Nothing has to be remembered —
|
||||
if it exits non-zero, follow what it prints instead of merging.
|
||||
|
||||
Then merge it, using the PR number the preflight printed:
|
||||
2. Bump the version in package.json
|
||||
|
||||
```sh
|
||||
gh pr merge <pr-number> --squash
|
||||
gh run watch "$(gh run list --workflow=publish.yml --limit 1 --json databaseId --jq '.[0].databaseId')"
|
||||
npm version vX.X.X
|
||||
```
|
||||
|
||||
The run is looked up rather than picked interactively, so this is safe to script.
|
||||
If the workflow has already finished, `gh run list --workflow=publish.yml` shows
|
||||
the outcome instead.
|
||||
|
||||
Merging main requires no review, so a green preflight and `Build` are the only
|
||||
gates. Once the workflow finishes, confirm both outputs landed:
|
||||
3. Add a new entry in CHANGELOG.md
|
||||
4. Create a PR for `prev-vX.X.X` & merge it
|
||||
5. Create tag and push it
|
||||
|
||||
```sh
|
||||
gh release view "v<version>"
|
||||
npm view "@agentclientprotocol/claude-agent-acp@<version>"
|
||||
git tag vX.X.X
|
||||
git push origin vX.X.X
|
||||
```
|
||||
|
||||
The release should list 8 `claude-agent-acp-*` archives. They are attached a
|
||||
few minutes after the release is created, once every platform has built.
|
||||
|
||||
## Preview releases
|
||||
|
||||
Every push to `main` that is not a release merge publishes a preview from the
|
||||
same workflow. There is no GitHub release — only an npm publish under the
|
||||
`preview` dist-tag, a `v<version>` tag on the commit it came from, and the same
|
||||
agent registry update a stable release dispatches, since the registry has its own
|
||||
handling for preview versions.
|
||||
|
||||
Those are three jobs, in that order: `publish-npm-preview` mirrors `publish-npm`
|
||||
and does nothing but publish; `publish-tag-preview` creates the tag; and
|
||||
`trigger-registry-update` is shared with the stable path. Before dispatching,
|
||||
the registry job polls npm for the exact published version for up to 12.5 minutes,
|
||||
including downloading its tarball, so the registry never checks while npm is
|
||||
still propagating the package. The tag is a separate job so that a tag failure
|
||||
can be retried on its own with **Re-run failed jobs** — re-running the publish is
|
||||
not an option, because npm versions are immutable and publishing the same one
|
||||
twice fails outright.
|
||||
|
||||
Both downstream jobs are gated on a `published` output that the publish step
|
||||
sets only after `npm publish --tag preview` succeeds. This ensures tagging runs
|
||||
only after publication and the registry update runs only after that exact version
|
||||
can also be downloaded from npm.
|
||||
|
||||
A stable and a preview dispatch can never collide — a release merge publishes
|
||||
stable and skips the preview, every other push does the reverse — so the registry
|
||||
sees exactly one dispatch per published version.
|
||||
|
||||
```sh
|
||||
npm install @agentclientprotocol/claude-agent-acp@preview
|
||||
npm view @agentclientprotocol/claude-agent-acp dist-tags
|
||||
git ls-remote --tags origin 'refs/tags/*preview*'
|
||||
```
|
||||
|
||||
The version is the `package.json` version with the patch incremented, plus
|
||||
`-preview.N`: with `main` at 0.73.0 the previews are `0.73.1-preview.1`,
|
||||
`0.73.1-preview.2`, and so on. `N` restarts at 1 whenever release-please moves
|
||||
`package.json`, which keeps the sequence monotonic whichever way the next release
|
||||
goes — a patch release makes the next base 0.73.2, a minor makes it 0.74.1, and
|
||||
both sort above every `0.73.1-preview.*`.
|
||||
|
||||
`0.73.1-preview.4` is **not** a promise that 0.73.1 will ship. The base is a
|
||||
patch bump because that is the only choice depending solely on `package.json`,
|
||||
which release-please only ever increases. Using release-please's predicted next
|
||||
version would read better but that prediction moves mid-flight: a `fix:` opens a
|
||||
0.73.1 release PR, a later `feat:` moves it to 0.74.0, and `N` would reset under
|
||||
previews that were already published.
|
||||
|
||||
`N` comes from [`scripts/next-preview-version.mjs`](../scripts/next-preview-version.mjs),
|
||||
which takes the larger of two sources. The npm registry says what is taken — npm
|
||||
versions are immutable and stay reserved even after `npm unpublish`, so reusing
|
||||
one is a hard failure — but it is CDN-served and can lag a publish by minutes.
|
||||
The git tags this job writes are strongly consistent and cover that window. The
|
||||
job publishes before it tags, so a version can exist on npm without a tag but
|
||||
never the reverse; that is why a registry read failure aborts the run rather than
|
||||
falling back to the tags alone.
|
||||
|
||||
Two pushes landing together cannot collide, because the job takes a concurrency
|
||||
group. GitHub keeps only one run pending per group, so a third push arriving
|
||||
while one preview runs and another waits drops the waiting one — that commit
|
||||
simply gets no preview.
|
||||
|
||||
`latest` stays put because the job passes `npm publish --tag preview`. Without
|
||||
it npm would move `latest` onto the preview: `--tag` defaults to `latest` even
|
||||
for a semver prerelease. Right after a release the `preview` dist-tag can name a
|
||||
version _below_ `latest` until the next push lands; that is cosmetic.
|
||||
|
||||
Release merges are excluded by checking the head commit's author and the subject
|
||||
release-please generates. Both are checked, either is enough, and the cost of a
|
||||
miss is one wasted version number plus a `preview` tag briefly pointing at
|
||||
already-released code — `latest` is untouched. Previews start directly on pushes
|
||||
to `main`, without waiting for CI or the `release-please` job. The commit checks
|
||||
let previews run independently of release-please's outputs.
|
||||
|
||||
To publish a preview by hand from any commit:
|
||||
|
||||
```sh
|
||||
gh workflow run publish.yml --ref main \
|
||||
-f channel=preview -f ref=<commit-or-branch> -f publish_npm=false
|
||||
```
|
||||
|
||||
`--ref main` is required: the `release` environment only accepts protected
|
||||
branches, so a dispatch from anywhere else is rejected before the job starts.
|
||||
|
||||
## How the version is chosen
|
||||
|
||||
Squash merges use the PR title as the commit subject, so the PR title decides the
|
||||
next version. [`conventional-prs.yml`](../.github/workflows/conventional-prs.yml)
|
||||
rejects titles release-please would not understand.
|
||||
|
||||
| PR title prefix | Effect |
|
||||
| --------------------------------------------------------- | --------------------------- |
|
||||
| `fix:`, `perf:`, `revert:`, `docs:` | patch, e.g. 0.66.0 → 0.66.1 |
|
||||
| `feat:` | minor, e.g. 0.66.0 → 0.67.0 |
|
||||
| any of the above with `!`, or BREAKING CHANGE | minor while below 1.0.0 |
|
||||
| `chore:`, `ci:`, `build:`, `test:`, `refactor:`, `style:` | no release on their own |
|
||||
|
||||
Breaking changes bump the minor rather than the major because
|
||||
`bump-minor-pre-major` is set in
|
||||
[`release-please-config.json`](../release-please-config.json) and the package is
|
||||
still below 1.0.0. That is deliberate: it keeps a single `!` in a PR title from
|
||||
shipping 1.0.0 by accident.
|
||||
|
||||
Note that `config-file` only takes effect while the workflow does **not** pass a
|
||||
`release-type` input to the action — with `release-type` set, the action ignores
|
||||
the config entirely. The release type is declared inside the config instead.
|
||||
|
||||
`release-type` also switches release-please from `Manifest.fromManifest` to
|
||||
`Manifest.fromConfig`, which is a second and sharper reason never to set it. On
|
||||
the manifest path the previous release is found by an exact string match against
|
||||
the version in [`.release-please-manifest.json`](../.release-please-manifest.json),
|
||||
which is why the `v<x>-preview.<n>` tags are invisible to it. On the config path
|
||||
release-please instead sorts every candidate tag and release descending and takes
|
||||
the highest — and there the preview tags _would_ be candidates.
|
||||
|
||||
Because the config is what is read, it also has to say
|
||||
`"include-component-in-tag": false`. Left at its default, release-please derives a
|
||||
component from the package name and tags `claude-agent-acp-vX.Y.Z` instead of
|
||||
`vX.Y.Z`. That renames the tag every step here looks up, and because no tag under
|
||||
the new scheme exists, it also walks the entire commit history into the changelog
|
||||
rather than just what landed since the last release. The preflight checks the tag
|
||||
release-please is going to use, so this cannot reach a published release.
|
||||
|
||||
Releasing 1.0.0 is therefore an explicit act: add `"release-as": "1.0.0"` to
|
||||
`release-please-config.json` in its own PR, release, then remove it again.
|
||||
|
||||
## Recovering a stalled release
|
||||
|
||||
### The release PR merged but nothing was tagged
|
||||
|
||||
The preflight fails with `release-please is jammed`. While a merged release PR
|
||||
still carries `autorelease: pending`, release-please refuses to open any new
|
||||
release PR at all, so every later release stalls silently until this is cleared.
|
||||
|
||||
Take the release notes release-please already wrote into the changelog, create
|
||||
the missing release, then move the label the way release-please would have:
|
||||
|
||||
```sh
|
||||
awk '/^## \[<version>\]/{f=1;print;next} /^## \[/{f=0} f' CHANGELOG.md > notes.md
|
||||
gh release create "v<version>" --target <merge-commit-sha> --notes-file notes.md
|
||||
gh pr edit <pr-number> --remove-label "autorelease: pending" \
|
||||
--add-label "autorelease: tagged"
|
||||
```
|
||||
|
||||
Then publish the tag as described below.
|
||||
|
||||
### The tag exists but npm or the registry is missing
|
||||
|
||||
npm publishes through OIDC from inside the workflow, so this cannot be done from
|
||||
a laptop. Re-run the publish workflow against the existing tag:
|
||||
|
||||
```sh
|
||||
gh workflow run publish.yml -f ref="v<version>" -f publish_npm=true
|
||||
```
|
||||
|
||||
npm versions are immutable. If the package already published and only the
|
||||
registry update failed, pass `-f publish_npm=false` so the run skips publishing
|
||||
and only re-dispatches the registry update.
|
||||
|
||||
### The release has no executables
|
||||
|
||||
`build-binaries` and `upload-binaries` don't gate npm, so a failed build only
|
||||
leaves the release without archives. Re-run the failed jobs of that publish run
|
||||
(`gh run rerun <run-id> --failed`); the upload uses `--clobber`, so archives
|
||||
already attached are replaced rather than duplicated.
|
||||
|
||||
### A preview published but the commit was not tagged
|
||||
|
||||
Only the publish is irreversible, so re-run just the tag job:
|
||||
|
||||
```sh
|
||||
gh run rerun <run-id> --failed
|
||||
```
|
||||
|
||||
Or **Re-run failed jobs** on the run in the web or mobile UI. This re-runs
|
||||
`publish-tag-preview` alone and leaves the successful publish untouched, which
|
||||
matters because re-publishing an immutable npm version would fail.
|
||||
|
||||
If the re-run reports that it received no version or commit, the run's carried
|
||||
over job outputs are gone and it cannot tag anything safely. Do it by hand
|
||||
instead, taking the version from the publish job's log:
|
||||
|
||||
```sh
|
||||
gh api "repos/$(gh repo view --json nameWithOwner --jq .nameWithOwner)/git/refs" \
|
||||
-f ref="refs/tags/v<version>" -f sha="<commit-sha>"
|
||||
```
|
||||
|
||||
Either way nothing is broken in the meantime: the next preview still picks the
|
||||
right `N` once the registry CDN catches up. The tag is how that number is known
|
||||
immediately.
|
||||
|
||||
## Credentials
|
||||
|
||||
| Secret | Used for |
|
||||
| ------------------------------------------------------------- | ----------------------------------------------------------------- |
|
||||
| `RELEASE_PLZ_APP_ID`, `RELEASE_PLZ_APP_PRIVATE_KEY` | App token for release PRs and tags, so they can trigger workflows |
|
||||
| `REGISTRY_UPDATER_APP_ID`, `REGISTRY_UPDATER_APP_PRIVATE_KEY` | App token scoped to the `registry` repository |
|
||||
|
||||
Publishing to npm uses OIDC trusted publishing, so there is no npm token. All
|
||||
release jobs run in the `release` environment.
|
||||
|
||||
npm binds a trusted publisher to one repository, one **workflow filename** and
|
||||
one environment, and a package may only have one such binding. That is why
|
||||
preview publishing is another job inside `publish.yml` rather than a workflow of
|
||||
its own: a separate file would fail to authenticate, and registering it would
|
||||
cost the stable path its publisher.
|
||||
6. Paste CHANGELOG into release notes and publish the version on GitHub
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,67 +0,0 @@
|
||||
# Model Configuration
|
||||
|
||||
When using claude-agent-acp with alternative providers (e.g. AWS Bedrock), model IDs differ from the direct Anthropic API. The `CLAUDE_MODEL_CONFIG` environment variable lets you configure model overrides and availability at the deployment level.
|
||||
|
||||
## `CLAUDE_MODEL_CONFIG`
|
||||
|
||||
A JSON string with two optional fields:
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------- |
|
||||
| `modelOverrides` | `Record<string, string>` | Maps Anthropic model IDs to provider-specific model IDs (e.g. Bedrock model IDs or ARNs) |
|
||||
| `availableModels` | `string[]` | Restricts which models are offered to users. Accepts aliases (`"opus"`), prefixes (`"opus-4-5"`), or full IDs |
|
||||
|
||||
### Examples
|
||||
|
||||
**Bedrock model overrides:**
|
||||
|
||||
```bash
|
||||
CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1","claude-sonnet-4-5":"us.anthropic.claude-sonnet-4-5-v1"}}'
|
||||
```
|
||||
|
||||
**Restrict available models:**
|
||||
|
||||
```bash
|
||||
CLAUDE_MODEL_CONFIG='{"availableModels":["opus","sonnet"]}'
|
||||
```
|
||||
|
||||
**Both together:**
|
||||
|
||||
```bash
|
||||
CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1","claude-sonnet-4-5":"us.anthropic.claude-sonnet-4-5-v1"},"availableModels":["opus","sonnet"]}'
|
||||
```
|
||||
|
||||
**Full Bedrock example:**
|
||||
|
||||
```bash
|
||||
CLAUDE_CODE_USE_BEDROCK=1 \
|
||||
AWS_REGION=us-west-2 \
|
||||
CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1"}}' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
## Precedence
|
||||
|
||||
An ACP caller can provide `settings` via `_meta.claudeCode.options.settings` in `session/new` or `session/load`, as an object or a path to a settings file. The adapter merges `CLAUDE_MODEL_CONFIG` into those settings, so a caller that only adds hooks keeps the model settings. When both set the same key, the caller wins; the merge is shallow, so a caller's `modelOverrides` replaces the env var's map.
|
||||
|
||||
| Source | Priority |
|
||||
| -------------------------------------------- | ---------------------------------------------- |
|
||||
| `_meta.claudeCode.options.settings` (caller) | Highest — wins for each key it sets |
|
||||
| `CLAUDE_MODEL_CONFIG` (env var) | Used for the keys that the caller does not set |
|
||||
|
||||
## Format details
|
||||
|
||||
- The value must be valid JSON. Invalid JSON will cause session creation to fail with a parse error.
|
||||
- Only `modelOverrides` and `availableModels` keys are read; other keys in the JSON are ignored.
|
||||
- Both fields map directly to the Claude Agent SDK's `Settings` type.
|
||||
|
||||
## Models of a `providers/set` gateway
|
||||
|
||||
When an ACP client routes the agent through a gateway with `providers/set`, the adapter lists the gateway's models before `providers/set` returns, with the provider headers:
|
||||
|
||||
- `anthropic`: `GET {baseUrl}/v1/models`, paginated by `has_more`/`last_id`.
|
||||
- `bedrock`: `GET {baseUrl}/foundation-models` (Bedrock `ListFoundationModels`, `modelSummaries[].modelId`). Only `anthropic.` ids count. The cross-region prefix `global` when listed, else that of the first listed id with one (`eu` for `eu.anthropic.claude-sonnet-5`), becomes the session's `ANTHROPIC_BEDROCK_REGION_PREFIX`, and ids with other prefixes, or without one, are dropped.
|
||||
|
||||
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.
|
||||
@@ -4,23 +4,6 @@ import tsparser from "@typescript-eslint/parser";
|
||||
import prettierConfig from "eslint-config-prettier";
|
||||
import globals from "globals";
|
||||
|
||||
/**
|
||||
* Rules that reject a module specifier matching `regex` in static imports and
|
||||
* re-exports (type-only ones too), `import()` calls and `import("...")` types.
|
||||
*/
|
||||
function protocolBoundary(regex, message) {
|
||||
// esquery regex literals end at the first `/`, so spell it `\x2F`.
|
||||
const literal = `/${regex.replaceAll("/", "\\x2F")}/`;
|
||||
return {
|
||||
"no-restricted-imports": ["error", { patterns: [{ regex, message }] }],
|
||||
"no-restricted-syntax": [
|
||||
"error",
|
||||
{ selector: `ImportExpression[source.value=${literal}]`, message },
|
||||
{ selector: `TSImportType[argument.literal.value=${literal}]`, message },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: ["node_modules/", "dist/", "coverage/", "*.min.js", "*.config.js", ".github/"],
|
||||
@@ -57,43 +40,9 @@ export default [
|
||||
"default-case": "error",
|
||||
"prefer-const": "error",
|
||||
"no-var": "error",
|
||||
eqeqeq: ["error", "smart"],
|
||||
eqeqeq: ["error", "always"],
|
||||
curly: ["error", "all"],
|
||||
},
|
||||
},
|
||||
// `src/v2/` must not import the v1 agent (`src/v1/`, or `src/acp-agent.ts`, which re-exports it).
|
||||
{
|
||||
files: ["src/v2/**/*.ts"],
|
||||
rules: protocolBoundary(
|
||||
"^(\\.\\./)+(v1/|acp-agent\\.js$)",
|
||||
"src/v2/ must not import the v1 agent. Move what both versions need into a shared module in src/.",
|
||||
),
|
||||
},
|
||||
// `src/v1/` must not import the v2 agent.
|
||||
{
|
||||
files: ["src/v1/**/*.ts"],
|
||||
rules: protocolBoundary(
|
||||
"^(\\.\\./)+v2/",
|
||||
"src/v1/ must not import the v2 agent. Move what both versions need into a shared module in src/.",
|
||||
),
|
||||
},
|
||||
// Shared modules must not import either agent. The entry points wire the agents up.
|
||||
{
|
||||
files: ["src/**/*.ts"],
|
||||
ignores: [
|
||||
"src/v1/**",
|
||||
"src/v2/**",
|
||||
"src/tests/**",
|
||||
"src/index.ts",
|
||||
"src/lib.ts",
|
||||
"src/serve.ts",
|
||||
"src/binary-entry.ts",
|
||||
"src/acp-agent.ts",
|
||||
],
|
||||
rules: protocolBoundary(
|
||||
"^(\\./|(\\.\\./)+)(v1/|v2/|acp-agent\\.js$)",
|
||||
"Shared modules must not import src/v1/, src/v2/ or src/acp-agent.ts. Move the code into the shared module, or pass it in from the agent.",
|
||||
),
|
||||
},
|
||||
prettierConfig,
|
||||
];
|
||||
|
||||
@@ -1,706 +0,0 @@
|
||||
/**
|
||||
* Example: a dead-simple interactive ACP client for this agent.
|
||||
*
|
||||
* This is the "no editor required" way to exercise the agent: it launches
|
||||
* `dist/index.js` as a subprocess, speaks ACP over its stdio using the SDK, and
|
||||
* prints every JSON-RPC message that crosses the wire in both directions. Each
|
||||
* line you type becomes a `session/prompt`; the agent's answer streams back as
|
||||
* `session/update` notifications.
|
||||
*
|
||||
* Every message is preceded by a header line naming its direction:
|
||||
*
|
||||
* [agent] ◂ inbound — everything the agent sends us
|
||||
* [user] ▸ outbound — everything we send the agent, including our own
|
||||
* permission answers and `session/cancel`
|
||||
*
|
||||
* The label and the arrow carry the direction, so it survives NO_COLOR and
|
||||
* redirection to a file (`2> wire.log`). The JSON itself is printed in full,
|
||||
* flush left and undecorated — select it and you have valid JSON on the
|
||||
* clipboard. This exists to show you the protocol, not to summarize it.
|
||||
*
|
||||
* There are four ways for a client to get a message to this agent, and all four
|
||||
* are reachable from the prompt so you can watch what each one looks like on
|
||||
* the wire. Plain text is the first; the rest are `!`-prefixed commands, chosen
|
||||
* so they cannot be confused with the agent's own slash commands (`/compact`
|
||||
* and friends are ordinary prompt text here). `!!` escapes a literal `!`.
|
||||
*
|
||||
* <text> `session/prompt`. Typed mid-turn it is *buffered* by this
|
||||
* client and sent once the running turn responds.
|
||||
* !steer <text> `_session/steering` — injected into the turn that is
|
||||
* already running, so it can change course between tool
|
||||
* calls. Answers "injected", or "startedNewTurn" if the turn
|
||||
* beat us to the finish. An injected reply streams as
|
||||
* `session/update` notifications inside that turn, whose
|
||||
* `stopReason` waits for it. "startedNewTurn" output belongs
|
||||
* to a detached turn no `session/prompt` of ours tracks.
|
||||
* See ./steering.ts.
|
||||
* !queue <text> `session/prompt` sent mid-turn anyway. The agent advertises
|
||||
* `promptQueueing`, so it takes the backlog instead of us —
|
||||
* same ordering, different owner.
|
||||
* !cancel `session/cancel` for the running turn, as Ctrl-C does.
|
||||
*
|
||||
* Run (build the agent first so `dist/index.js` exists):
|
||||
*
|
||||
* npm run build
|
||||
* node examples/simple-client.ts
|
||||
*
|
||||
* or, equivalently, `npm run example:simple-client`.
|
||||
*
|
||||
* To debug the agent itself, pass a port. The agent is then rebuilt with source
|
||||
* maps and started under `--inspect-brk=<port>`, i.e. paused before its first
|
||||
* line, so you can attach (IntelliJ: Run → Attach to Node.js/Chrome; VS Code:
|
||||
* "Attach to Node Process"), set breakpoints in `src/*.ts`, and resume:
|
||||
*
|
||||
* node examples/simple-client.ts --debug-port=9229
|
||||
*
|
||||
* The client will sit waiting for `initialize` until you attach and resume —
|
||||
* that is expected, ACP has no request timeout.
|
||||
*
|
||||
* (Node < 22.18 needs `node --experimental-strip-types examples/simple-client.ts`.)
|
||||
*
|
||||
* Keys: Enter sends (or buffers), Ctrl-C cancels the running turn (again to
|
||||
* quit), Ctrl-D drains anything buffered and exits. `!help` lists the commands.
|
||||
*
|
||||
* Flags: --debug-port=<port>, --no-build, --help.
|
||||
* Env: AGENT_ENTRY (default dist/index.js), CWD (default process.cwd()).
|
||||
*
|
||||
* Requires the agent to be authenticated, since it talks to the real model.
|
||||
*
|
||||
* Note: this client does not advertise the `elicitation` capability, so the
|
||||
* agent disables its AskUserQuestion tool instead of asking us to render a
|
||||
* form. That is the one intentional behaviour difference from a full client.
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
PROTOCOL_VERSION,
|
||||
client as acpClient,
|
||||
methods,
|
||||
ndJsonStream,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
// Type-only: Node's type stripping does not elide value imports, and these two
|
||||
// exist only in the .d.ts — importing them normally is a runtime SyntaxError.
|
||||
import type { AnyMessage, Stream } from "@agentclientprotocol/sdk/unstable";
|
||||
|
||||
// ---------------------------------------------------------------- steering
|
||||
|
||||
/**
|
||||
* The steering extension (../steering_protocol.md, and ./steering.ts for a
|
||||
* scripted walkthrough). It is not part of ACP proper, so it has no entry in
|
||||
* `methods` and is sent as a raw method name with hand-written types.
|
||||
*/
|
||||
const STEERING_METHOD = "_session/steering";
|
||||
|
||||
type SteeringRequest = {
|
||||
sessionId: string;
|
||||
prompt: Array<{ type: "text"; text: string }>;
|
||||
};
|
||||
|
||||
/** Both outcomes are successes; they say where the message landed, not whether
|
||||
* it worked. "startedNewTurn" means the turn finished before we got there. */
|
||||
type SteeringResponse = {
|
||||
outcome: "injected" | "startedNewTurn";
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- arguments
|
||||
|
||||
const ARGV = process.argv.slice(2);
|
||||
|
||||
/** Reads `--name=value` or `--name value`; returns "" for a valueless flag. */
|
||||
function flag(name: string): string | undefined {
|
||||
const index = ARGV.findIndex((arg) => arg === `--${name}` || arg.startsWith(`--${name}=`));
|
||||
if (index === -1) return undefined;
|
||||
const [, ...rest] = ARGV[index].split("=");
|
||||
return rest.length > 0 ? rest.join("=") : (ARGV[index + 1] ?? "");
|
||||
}
|
||||
|
||||
if (ARGV.includes("--help") || ARGV.includes("-h")) {
|
||||
process.stdout.write(
|
||||
[
|
||||
"Usage: node examples/simple-client.ts [--debug-port=<port>] [--no-build]",
|
||||
"",
|
||||
" --debug-port=<port> rebuild with source maps and start the agent under",
|
||||
" --inspect-brk=<port>, paused until a debugger attaches",
|
||||
" --no-build skip the tsc rebuild and use dist/ as-is",
|
||||
"",
|
||||
"Env: AGENT_ENTRY (default dist/index.js), CWD (default process.cwd()).",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// The built agent entry. Rebuilt below unless --no-build is passed.
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const AGENT_ENTRY = process.env.AGENT_ENTRY ?? path.join(repoRoot, "dist", "index.js");
|
||||
const CWD = process.env.CWD ?? process.cwd();
|
||||
const BUILD = !ARGV.includes("--no-build");
|
||||
|
||||
const debugPortArg = flag("debug-port");
|
||||
const DEBUG_PORT = debugPortArg === undefined ? undefined : Number(debugPortArg);
|
||||
if (
|
||||
DEBUG_PORT !== undefined &&
|
||||
(!Number.isInteger(DEBUG_PORT) || DEBUG_PORT < 1 || DEBUG_PORT > 65535)
|
||||
) {
|
||||
process.stderr.write(`--debug-port expects a port between 1 and 65535, got "${debugPortArg}"\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** Shown by `!help`, and once at startup. */
|
||||
const HELP = [
|
||||
"<text> send it — as a new turn, or buffered until this turn ends",
|
||||
"!steer <text> inject into the running turn (_session/steering)",
|
||||
"!queue <text> send session/prompt now and let the agent queue it",
|
||||
"!cancel session/cancel the running turn (same as Ctrl-C)",
|
||||
"!help this list; !! sends a line that really starts with '!'",
|
||||
];
|
||||
|
||||
// How long to wait for a cancelled turn to settle, and for the agent to exit
|
||||
// after we close its stdin, before escalating during shutdown.
|
||||
const CANCEL_TIMEOUT_MS = 5_000;
|
||||
const EXIT_TIMEOUT_MS = 5_000;
|
||||
|
||||
// ---------------------------------------------------------------- output
|
||||
|
||||
const COLOR = process.stderr.isTTY === true && !process.env.NO_COLOR;
|
||||
const paint = (code: string, text: string) => (COLOR ? `\x1b[${code}m${text}\x1b[0m` : text);
|
||||
const dim = (text: string) => paint("2", text);
|
||||
|
||||
const TTY = process.stdin.isTTY === true && process.stderr.isTTY === true;
|
||||
const startedAt = Date.now();
|
||||
|
||||
let rl: readline.Interface | null = null;
|
||||
let shuttingDown = false;
|
||||
let queue: string[] = [];
|
||||
// How many `session/prompt` requests are awaiting a response. Usually 0 or 1;
|
||||
// `!queue` deliberately drives it higher to exercise the agent's own queueing.
|
||||
let inFlight = 0;
|
||||
const turnRunning = () => inFlight > 0;
|
||||
let cancelRequested = false;
|
||||
let lastUpdateKind = "";
|
||||
// False until `initialize` returns — an agent still paused under --inspect-brk
|
||||
// will never act on stdin EOF, so shutdown skips straight to signalling it.
|
||||
let agentReady = false;
|
||||
|
||||
/**
|
||||
* The single writer for everything this process prints. It wipes the half-typed
|
||||
* input line, writes the block, then asks readline to redraw its prompt with the
|
||||
* buffer intact — without this, streamed output and typing shred each other.
|
||||
* (One caveat: a soft-wrapped input line leaves a stale fragment behind, since
|
||||
* clearLine only clears the row the cursor is on.)
|
||||
*/
|
||||
function writeBlock(text: string) {
|
||||
if (TTY) {
|
||||
readline.cursorTo(process.stderr, 0);
|
||||
readline.clearLine(process.stderr, 0);
|
||||
}
|
||||
process.stderr.write(text.endsWith("\n") ? text : `${text}\n`);
|
||||
if (TTY) rl?.prompt(true);
|
||||
}
|
||||
|
||||
function log(message: string) {
|
||||
writeBlock(`${dim("[client]")} ${message}`);
|
||||
}
|
||||
|
||||
function refreshPrompt() {
|
||||
if (!rl) return;
|
||||
const queued = queue.length > 0 ? `[${queue.length} queued] ` : "";
|
||||
const running = inFlight > 1 ? `[${inFlight} turns] ` : "";
|
||||
const busy = turnRunning() ? dim(`⋯ ${lastUpdateKind} `) : "";
|
||||
rl.setPrompt(`${busy}${running}${queued}› `);
|
||||
if (TTY) rl.prompt(true);
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
// ---------------------------------------------------------------- wire log
|
||||
|
||||
/** A permissive view of the JSON-RPC union, purely for the summary line. */
|
||||
type WireMessage = {
|
||||
id?: string | number | null;
|
||||
method?: string;
|
||||
params?: { update?: { sessionUpdate?: string } };
|
||||
result?: { stopReason?: string };
|
||||
error?: { code: number; message: string };
|
||||
};
|
||||
|
||||
/** One-line summary: method (plus session update kind), or which reply this is. */
|
||||
function describe(message: AnyMessage): string {
|
||||
const wire = message as WireMessage;
|
||||
const id = wire.id === undefined || wire.id === null ? "" : ` #${wire.id}`;
|
||||
if (wire.method !== undefined) {
|
||||
const kind = wire.params?.update?.sessionUpdate;
|
||||
return `${wire.method}${kind ? ` · ${kind}` : ""}${id}`;
|
||||
}
|
||||
if (wire.error !== undefined) {
|
||||
return `error${id} · ${wire.error.code} ${wire.error.message}`;
|
||||
}
|
||||
const stopReason = wire.result?.stopReason;
|
||||
return `result${id}${stopReason ? ` · ${stopReason}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints one JSON-RPC message. The SDK exposes no logging hook, so this is
|
||||
* called from a stream tap (see `tapStream`) that sits between the SDK and the
|
||||
* transport — what you see is exactly what is written to / read from the pipe.
|
||||
*/
|
||||
function logMessage(direction: "agent" | "user", message: AnyMessage) {
|
||||
const inbound = direction === "agent";
|
||||
const color = inbound ? "36" : "35";
|
||||
const elapsed = ((Date.now() - startedAt) / 1000).toFixed(3);
|
||||
const header = [
|
||||
dim(`+${elapsed}s`),
|
||||
paint(`1;${color}`, inbound ? "[agent]" : "[user] "),
|
||||
paint(color, inbound ? "◂" : "▸"),
|
||||
dim(describe(message)),
|
||||
].join(" ");
|
||||
// The body is printed flush left and unadorned so that selecting it in the
|
||||
// terminal yields valid JSON you can paste straight into a tool.
|
||||
writeBlock(`${header}\n${JSON.stringify(message, null, 2)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a transport stream so every message is logged post-parse/pre-stringify.
|
||||
* A TransformStream per direction is the only complete interposition point: the
|
||||
* SDK reads inbound with a single reader and takes a fresh writer per outbound
|
||||
* message, and both survive being handed a transform.
|
||||
*/
|
||||
function tapStream(inner: Stream): Stream {
|
||||
const inbound = new TransformStream<AnyMessage, AnyMessage>({
|
||||
transform(message, controller) {
|
||||
logMessage("agent", message);
|
||||
controller.enqueue(message);
|
||||
},
|
||||
});
|
||||
const outbound = new TransformStream<AnyMessage, AnyMessage>({
|
||||
transform(message, controller) {
|
||||
logMessage("user", message);
|
||||
controller.enqueue(message);
|
||||
},
|
||||
});
|
||||
// The SDK never closes its writable, so this pipe only settles on failure —
|
||||
// typically the agent died and its stdin is gone. Teardown handles the rest;
|
||||
// without the catch this would be an unhandled rejection.
|
||||
outbound.readable.pipeTo(inner.writable).catch((err) => {
|
||||
if (!shuttingDown) log(`transport write failed: ${err}`);
|
||||
});
|
||||
return { readable: inner.readable.pipeThrough(inbound), writable: outbound.writable };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- build
|
||||
|
||||
/** Runs the repo's tsc, sending its diagnostics to our stderr. */
|
||||
async function build(sourceMaps: boolean) {
|
||||
const localTsc = path.join(repoRoot, "node_modules", "typescript", "bin", "tsc");
|
||||
const useLocal = existsSync(localTsc);
|
||||
const args = sourceMaps ? ["--sourceMap"] : [];
|
||||
log(`building agent (tsc${sourceMaps ? " --sourceMap" : ""}) …`);
|
||||
|
||||
const child = useLocal
|
||||
? spawn(process.execPath, [localTsc, ...args], { cwd: repoRoot, stdio: ["ignore", 2, 2] })
|
||||
: spawn(process.platform === "win32" ? "npx.cmd" : "npx", ["tsc", ...args], {
|
||||
cwd: repoRoot,
|
||||
stdio: ["ignore", 2, 2],
|
||||
});
|
||||
|
||||
const [code] = (await once(child, "exit")) as [number | null];
|
||||
if (code !== 0) {
|
||||
log(`build failed (tsc exit ${code}) — fix the errors above, or pass --no-build`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- main
|
||||
|
||||
async function main() {
|
||||
if (BUILD) {
|
||||
await build(DEBUG_PORT !== undefined);
|
||||
} else if (!existsSync(AGENT_ENTRY)) {
|
||||
log(`${AGENT_ENTRY} not found — run \`npm run build\` first, or unset --no-build`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// An ACP client launches the agent as a subprocess and speaks JSON-RPC over
|
||||
// its stdin/stdout. Its stderr is piped rather than inherited so that agent
|
||||
// logs go through writeBlock() and don't corrupt the readline input line.
|
||||
const nodeArgs =
|
||||
DEBUG_PORT === undefined ? [AGENT_ENTRY] : [`--inspect-brk=${DEBUG_PORT}`, AGENT_ENTRY];
|
||||
const child = spawn(process.execPath, nodeArgs, {
|
||||
cwd: repoRoot,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
log(`failed to spawn agent (${AGENT_ENTRY}): ${err}`);
|
||||
process.exit(1);
|
||||
});
|
||||
// A write racing the agent's exit surfaces as an unhandled 'error' event that
|
||||
// would take this client down with it.
|
||||
child.stdin?.on("error", (err: NodeJS.ErrnoException) => {
|
||||
if (err.code !== "EPIPE") log(`agent stdin error: ${err}`);
|
||||
});
|
||||
child.stdout?.on("error", () => {});
|
||||
process.stderr.on("error", () => {});
|
||||
|
||||
pumpAgentStderr(child);
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (!shuttingDown) log(`agent exited (code ${code}, signal ${signal})`);
|
||||
});
|
||||
|
||||
const stream = tapStream(
|
||||
ndJsonStream(
|
||||
Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>,
|
||||
Readable.toWeb(child.stdout!) as unknown as ReadableStream<Uint8Array>,
|
||||
),
|
||||
);
|
||||
|
||||
const connection = acpClient({ name: "simple-client" })
|
||||
// The tap already prints every update; this handler exists so the prompt line
|
||||
// can show what the agent is currently doing.
|
||||
.onNotification(methods.client.session.update, (ctx) => {
|
||||
lastUpdateKind = ctx.params.update.sessionUpdate;
|
||||
})
|
||||
// Auto-approve, chosen by `kind` and never by a hard-coded optionId: for
|
||||
// ExitPlanMode this agent uses permission-*mode* names as option ids
|
||||
// (auto / acceptEdits / default / plan / bypassPermissions).
|
||||
.onRequest(methods.client.session.requestPermission, (ctx) => {
|
||||
const options = ctx.params.options;
|
||||
const option = options.find((o) => o.kind === "allow_once") ?? options[0];
|
||||
if (!option) return { outcome: { outcome: "cancelled" } };
|
||||
log(`auto-approving permission: ${option.name} (${option.kind}/${option.optionId})`);
|
||||
return { outcome: { outcome: "selected", optionId: option.optionId } };
|
||||
})
|
||||
// Minimal file-system stubs. This agent performs its own file I/O inside the
|
||||
// Claude Agent SDK subprocess and never calls these today.
|
||||
.onRequest(methods.client.fs.readTextFile, () => ({ content: "" }))
|
||||
.onRequest(methods.client.fs.writeTextFile, () => ({}))
|
||||
.connect(stream);
|
||||
|
||||
const agent = connection.agent;
|
||||
|
||||
// Signals are wired up *before* the first request. Under --inspect-brk the
|
||||
// wait below is unbounded, and a client that dies without running shutdown()
|
||||
// orphans a paused agent still holding the debug port.
|
||||
const onInterrupt = () => {
|
||||
if (turnRunning() && !cancelRequested) {
|
||||
cancelRequested = true;
|
||||
const dropped = queue.length;
|
||||
queue = [];
|
||||
// A notification, not a request: every turn in flight settles through its
|
||||
// own session/prompt response, normally with stopReason "cancelled".
|
||||
void agent.notify(methods.agent.session.cancel, { sessionId });
|
||||
log(`sent session/cancel${dropped > 0 ? `, dropped ${dropped} queued line(s)` : ""}`);
|
||||
refreshPrompt();
|
||||
return;
|
||||
}
|
||||
void shutdown(turnRunning() ? "^C while cancelling" : "^C");
|
||||
};
|
||||
// In terminal mode readline puts stdin in raw mode and owns ^C, so this only
|
||||
// ever fires for an explicit `kill -INT`; with piped stdin it is the ^C path.
|
||||
process.on("SIGINT", onInterrupt);
|
||||
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
||||
|
||||
// 1. Initialize. Under --inspect-brk the agent is paused before it reads a
|
||||
// single byte, so this request stays unanswered until a debugger attaches
|
||||
// and resumes it. ACP has no request timeout, so waiting is safe; the
|
||||
// interval below just keeps the terminal from looking dead.
|
||||
let nudge: NodeJS.Timeout | undefined;
|
||||
if (DEBUG_PORT !== undefined) {
|
||||
log(`agent is PAUSED before its first line (--inspect-brk=${DEBUG_PORT})`);
|
||||
log(`attach a debugger to port ${DEBUG_PORT} and resume it — breakpoints go in src/*.ts`);
|
||||
nudge = setInterval(
|
||||
() => log(`still waiting for a debugger on port ${DEBUG_PORT} … (Ctrl-C to give up)`),
|
||||
10_000,
|
||||
);
|
||||
}
|
||||
let init;
|
||||
try {
|
||||
init = await agent.request(methods.agent.initialize, {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: true, writeTextFile: true },
|
||||
terminal: false,
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
if (nudge) clearInterval(nudge);
|
||||
}
|
||||
agentReady = true;
|
||||
log(`connected to ${init.agentInfo?.name ?? "agent"} ${init.agentInfo?.version ?? ""}`.trim());
|
||||
|
||||
// Steering is advertised at the TOP-LEVEL `_meta` of the initialize result —
|
||||
// a sibling of `agentCapabilities`, not nested inside it. Prompt queueing is
|
||||
// a Claude-specific capability flag and does live inside.
|
||||
const initMeta = init._meta as { steering?: { supported?: boolean } } | null | undefined;
|
||||
const steeringSupported = initMeta?.steering?.supported === true;
|
||||
const queueMeta = init.agentCapabilities?._meta as
|
||||
{ claudeCode?: { promptQueueing?: boolean } } | null | undefined;
|
||||
log(
|
||||
`agent supports: steering=${steeringSupported} ` +
|
||||
`promptQueueing=${queueMeta?.claudeCode?.promptQueueing === true}`,
|
||||
);
|
||||
|
||||
// 2. Open a session.
|
||||
let sessionId: string;
|
||||
try {
|
||||
const session = await agent.request(methods.agent.session.new, { cwd: CWD, mcpServers: [] });
|
||||
sessionId = session.sessionId;
|
||||
} catch (err) {
|
||||
log(`session/new failed: ${err}`);
|
||||
log("if this is an auth error, log in first: node dist/index.js --cli auth login");
|
||||
await shutdown("session/new failed", 1);
|
||||
return;
|
||||
}
|
||||
log(`session ${sessionId} in ${CWD}`);
|
||||
|
||||
// 3. Turns. There are four ways to get a message to the agent, and the client
|
||||
// can drive all of them (see `handleCommand`); plain text uses the first.
|
||||
//
|
||||
// session/prompt a new turn, or — for text typed mid-turn — one
|
||||
// buffered here and sent when the turn responds
|
||||
// session/prompt sent mid-turn anyway, so the *agent* queues it
|
||||
// (!queue) (it advertises `_meta.claudeCode.promptQueueing`)
|
||||
// _session/steering injected into the turn that is already running
|
||||
// (!steer)
|
||||
// session/cancel abandon the running turn
|
||||
// (!cancel, ^C)
|
||||
let draining = false;
|
||||
|
||||
/** One `session/prompt` round-trip. Several may be in flight at once when
|
||||
* `!queue` is used; the agent runs them in order. */
|
||||
async function sendPrompt(text: string) {
|
||||
inFlight += 1;
|
||||
cancelRequested = false;
|
||||
refreshPrompt();
|
||||
try {
|
||||
const result = await agent.request(methods.agent.session.prompt, {
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text }],
|
||||
});
|
||||
log(`turn ended: ${result.stopReason}`);
|
||||
} catch (err) {
|
||||
// The error response itself was already printed by the tap; this is
|
||||
// the human-readable "your prompt did not run".
|
||||
log(`prompt failed: ${err}`);
|
||||
if (connection.signal.aborted) queue = [];
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
refreshPrompt();
|
||||
exitWhenIdle();
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends the buffered lines one turn at a time, oldest first. */
|
||||
async function drain() {
|
||||
if (draining) return;
|
||||
draining = true;
|
||||
try {
|
||||
while (queue.length > 0 && !shuttingDown) {
|
||||
await sendPrompt(queue.shift()!);
|
||||
if (connection.signal.aborted) break;
|
||||
}
|
||||
} finally {
|
||||
draining = false;
|
||||
refreshPrompt();
|
||||
exitWhenIdle();
|
||||
}
|
||||
}
|
||||
|
||||
/** A piped stdin ends; exiting has to wait for the work already handed out. */
|
||||
function exitWhenIdle() {
|
||||
if (inputClosed && !draining && queue.length === 0 && inFlight === 0) {
|
||||
void shutdown("input closed, queue drained");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side commands, prefixed with `!` so they cannot collide with the
|
||||
* agent's own slash commands (`/compact` and friends, which are just prompt
|
||||
* text as far as this client is concerned). `!!` escapes a literal `!`.
|
||||
*/
|
||||
function handleCommand(line: string) {
|
||||
const word = line.split(/\s+/)[0];
|
||||
const text = line.slice(word.length).trim();
|
||||
switch (word) {
|
||||
case "!steer":
|
||||
if (text.length === 0) {
|
||||
log("usage: !steer <message> — injects into the turn that is running");
|
||||
break;
|
||||
}
|
||||
if (!steeringSupported) log("agent did not advertise steering; trying anyway");
|
||||
void steer(text);
|
||||
break;
|
||||
case "!queue":
|
||||
if (text.length === 0) {
|
||||
log("usage: !queue <message> — sends session/prompt now, agent queues it");
|
||||
break;
|
||||
}
|
||||
void sendPrompt(text);
|
||||
break;
|
||||
case "!cancel":
|
||||
if (!turnRunning()) {
|
||||
log("nothing to cancel");
|
||||
break;
|
||||
}
|
||||
onInterrupt();
|
||||
break;
|
||||
case "!help":
|
||||
for (const entry of HELP) log(entry);
|
||||
break;
|
||||
default:
|
||||
log(`unknown command ${word} — try !help`);
|
||||
break;
|
||||
}
|
||||
refreshPrompt();
|
||||
}
|
||||
|
||||
/** `_session/steering`: deliver a message to the turn already in progress. */
|
||||
async function steer(text: string) {
|
||||
const params: SteeringRequest = { sessionId, prompt: [{ type: "text", text }] };
|
||||
try {
|
||||
const result = await agent.request<SteeringResponse>(STEERING_METHOD, params);
|
||||
// Either way the steered message's own output arrives as `session/update`
|
||||
// notifications, not in this response. When injected, it lands inside the
|
||||
// turn we steered, whose `stopReason` waits for it.
|
||||
log(
|
||||
result.outcome === "injected"
|
||||
? "steer outcome: injected into the running turn"
|
||||
: "steer outcome: startedNewTurn — the turn had already finished, so the " +
|
||||
"agent began a new one that no session/prompt of ours is tracking",
|
||||
);
|
||||
} catch (err) {
|
||||
log(`steer rejected: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
let inputClosed = false;
|
||||
let steerHinted = false;
|
||||
|
||||
rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stderr,
|
||||
terminal: TTY,
|
||||
crlfDelay: Infinity,
|
||||
historySize: 200,
|
||||
});
|
||||
|
||||
rl.on("line", (raw) => {
|
||||
const line = raw.trim();
|
||||
if (line.length === 0 || shuttingDown) {
|
||||
refreshPrompt();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith("!") && !line.startsWith("!!")) {
|
||||
handleCommand(line);
|
||||
return;
|
||||
}
|
||||
// "!!steer …" is how you send text that begins with the command prefix.
|
||||
queue.push(line.startsWith("!!") ? line.slice(1) : line);
|
||||
if (turnRunning()) {
|
||||
log(`buffered — will send when this turn ends (${queue.length} queued)`);
|
||||
if (!steerHinted) {
|
||||
steerHinted = true;
|
||||
log("…or use !steer <text> to inject into the running turn instead");
|
||||
}
|
||||
}
|
||||
refreshPrompt();
|
||||
void drain();
|
||||
});
|
||||
|
||||
rl.on("SIGINT", onInterrupt);
|
||||
|
||||
rl.on("close", () => {
|
||||
inputClosed = true;
|
||||
exitWhenIdle();
|
||||
});
|
||||
|
||||
void connection.closed.then(() => {
|
||||
if (!shuttingDown) void shutdown("connection closed");
|
||||
});
|
||||
|
||||
for (const entry of HELP) log(entry);
|
||||
log("Enter sends, Ctrl-C cancels a turn, Ctrl-D exits");
|
||||
refreshPrompt();
|
||||
|
||||
/**
|
||||
* Order matters here. The agent exits cleanly on stdin EOF (src/index.ts wires
|
||||
* `connection.closed` to `agent.dispose()`), whereas killing it skips disposal
|
||||
* and can orphan the Claude Agent SDK subprocess. Closing our connection first
|
||||
* would cancel the reader on the agent's stdout and make it die of EPIPE
|
||||
* mid-write, so that comes last.
|
||||
*/
|
||||
async function shutdown(reason: string, exitCode = 0) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
log(`shutting down (${reason})`);
|
||||
queue = [];
|
||||
rl?.removeAllListeners("close");
|
||||
rl?.close();
|
||||
|
||||
if (turnRunning()) {
|
||||
if (!cancelRequested) {
|
||||
try {
|
||||
await agent.notify(methods.agent.session.cancel, { sessionId });
|
||||
} catch {
|
||||
// The connection may already be gone; teardown continues regardless.
|
||||
}
|
||||
}
|
||||
const deadline = Date.now() + CANCEL_TIMEOUT_MS;
|
||||
while (turnRunning() && Date.now() < deadline) await delay(50);
|
||||
}
|
||||
|
||||
child.stdin?.end();
|
||||
const exited = await Promise.race([
|
||||
once(child, "exit").then(() => true),
|
||||
delay(agentReady ? EXIT_TIMEOUT_MS : 250).then(() => false),
|
||||
]);
|
||||
if (!exited) {
|
||||
log("agent did not exit on stdin EOF; sending SIGTERM");
|
||||
child.kill("SIGTERM");
|
||||
const stopped = await Promise.race([
|
||||
once(child, "exit").then(() => true),
|
||||
delay(2_000).then(() => false),
|
||||
]);
|
||||
if (!stopped) child.kill("SIGKILL");
|
||||
}
|
||||
|
||||
connection.close();
|
||||
process.exit(exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
/** Streams the agent's stderr through writeBlock, flagging inspector messages. */
|
||||
function pumpAgentStderr(child: ReturnType<typeof spawn>) {
|
||||
let buffered = "";
|
||||
child.stderr?.setEncoding("utf8");
|
||||
child.stderr?.on("data", (chunk: string) => {
|
||||
buffered += chunk;
|
||||
const lines = buffered.split("\n");
|
||||
buffered = lines.pop() ?? "";
|
||||
for (const line of lines) {
|
||||
if (line.length === 0) continue;
|
||||
if (line.includes("Debugger listening on")) {
|
||||
writeBlock(paint("1;33", `[agent] ${line.trim()}`));
|
||||
} else if (line.includes("address already in use")) {
|
||||
writeBlock(paint("1;31", `[agent] ${line.trim()}`));
|
||||
log("that inspector port is taken — pass a different --debug-port");
|
||||
} else {
|
||||
writeBlock(dim(`[agent:stderr] ${line}`));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
// Tearing down rejects whatever request main() is awaiting; that is the
|
||||
// teardown finishing its job, not a failure, and shutdown() owns the exit.
|
||||
if (shuttingDown) return;
|
||||
log(`fatal: ${err?.stack ?? err}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,221 +0,0 @@
|
||||
/**
|
||||
* Example: mid-turn steering over ACP with the `_session/steering` extension.
|
||||
*
|
||||
* "Steering" lets a client deliver a follow-up message to a turn that is still
|
||||
* running, instead of waiting for it to finish and sending a fresh
|
||||
* `session/prompt`. This is what powers "the user typed something while the
|
||||
* agent was still working" — the new message joins the in-flight turn so the
|
||||
* agent can adapt immediately (it shines in multi-step / tool-using turns,
|
||||
* where the message slots in between tool calls).
|
||||
*
|
||||
* The wire protocol has three moving parts:
|
||||
*
|
||||
* 1. The agent advertises support in its `initialize` response, at the
|
||||
* top-level `_meta.steering` (a sibling of `agentCapabilities`).
|
||||
* 2. The client calls the `_session/steering` request with `{ sessionId,
|
||||
* prompt }` while a turn is running.
|
||||
* 3. The agent replies with an `outcome`:
|
||||
* - "injected" the message joined the running turn;
|
||||
* - "startedNewTurn" the turn had already finished and the legacy
|
||||
* detached fallback was used;
|
||||
* - "promptRequired" the turn had already finished, but this request
|
||||
* explicitly opted into Host-owned prompt delivery.
|
||||
*
|
||||
* This example launches the agent as a subprocess, starts a deliberately
|
||||
* long-running prompt, and — as soon as the agent begins streaming — injects a
|
||||
* steering message and prints the outcome. All agent output is streamed to
|
||||
* stdout so you can watch the turn change course.
|
||||
*
|
||||
* Run (build the agent first so `dist/index.js` exists):
|
||||
*
|
||||
* npm run build
|
||||
* node examples/steering.ts
|
||||
*
|
||||
* (Node < 22.18 needs `node --experimental-strip-types examples/steering.ts`.)
|
||||
*
|
||||
* Override the prompts with the PROMPT / STEER env vars. Requires the agent to
|
||||
* be authenticated, since it talks to the real model.
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import {
|
||||
client as acpClient,
|
||||
methods,
|
||||
ndJsonStream,
|
||||
type PromptRequest,
|
||||
type PromptResponse,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
|
||||
/** The steering extension method, per the ACP steering wire protocol. */
|
||||
const STEERING_METHOD = "_session/steering";
|
||||
|
||||
/** Params for a `_session/steering` request — the same shape as the relevant
|
||||
* subset of a `session/prompt`. */
|
||||
type SteeringRequest = {
|
||||
sessionId: string;
|
||||
prompt: Array<{ type: "text"; text: string }>;
|
||||
_meta?: { steering?: { idleBehavior?: "promptRequired" } };
|
||||
};
|
||||
|
||||
/** Result of a `_session/steering` request. `injected` means the message joined
|
||||
* the running turn; `promptRequired` means the turn had already settled, so the
|
||||
* message was NOT consumed and must be (re)sent through a normal
|
||||
* `session/prompt`. Both are successes. */
|
||||
type SteeringResponse =
|
||||
| { outcome: "injected" }
|
||||
| { outcome: "startedNewTurn" }
|
||||
| { outcome: "promptRequired"; reason: "noRunningTurn" };
|
||||
|
||||
/** The existing steering capability advertised at the top-level `_meta.steering`
|
||||
* of the `initialize` result. The idle behavior is selected per request. */
|
||||
type SteeringCapability = {
|
||||
supported?: boolean;
|
||||
};
|
||||
|
||||
// The built agent entry. Run `npm run build` first so this exists.
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const AGENT_ENTRY = process.env.AGENT_ENTRY ?? path.join(repoRoot, "dist", "index.js");
|
||||
const CWD = process.env.CWD ?? process.cwd();
|
||||
|
||||
// A deliberately long-running first prompt, and the follow-up injected while it
|
||||
// is still streaming. Override either via env vars to experiment.
|
||||
const PROMPT =
|
||||
process.env.PROMPT ??
|
||||
"Count slowly from 1 to 30, one number per line, with a short sentence of " +
|
||||
"commentary after each. Do not stop early.";
|
||||
const STEER =
|
||||
process.env.STEER ?? "Actually stop counting and instead reply with exactly one line: STEERED-OK";
|
||||
|
||||
function log(msg: string) {
|
||||
process.stderr.write(`\x1b[2m[client]\x1b[0m ${msg}\n`);
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function main() {
|
||||
// An ACP client launches the agent as a subprocess and speaks JSON-RPC over
|
||||
// its stdin/stdout. stderr is inherited so the agent's own logs stay visible.
|
||||
const child = spawn(process.execPath, [AGENT_ENTRY], {
|
||||
stdio: ["pipe", "pipe", "inherit"],
|
||||
env: process.env,
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
log(`failed to spawn agent (${AGENT_ENTRY}): ${err}`);
|
||||
});
|
||||
|
||||
try {
|
||||
const stream = ndJsonStream(
|
||||
Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>,
|
||||
Readable.toWeb(child.stdout!) as unknown as ReadableStream<Uint8Array>,
|
||||
);
|
||||
|
||||
// Resolves the first time the agent streams assistant text — our signal that
|
||||
// the turn is genuinely underway and therefore steerable.
|
||||
let signalFirstOutput = () => {};
|
||||
const firstOutput = new Promise<void>((resolve) => (signalFirstOutput = resolve));
|
||||
|
||||
const connection = acpClient({ name: "steering-example" })
|
||||
.onNotification(methods.client.session.update, (ctx) => {
|
||||
const update = ctx.params.update;
|
||||
if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
|
||||
process.stdout.write(update.content.text);
|
||||
signalFirstOutput();
|
||||
}
|
||||
})
|
||||
// Auto-approve permission prompts so the turn is never blocked on us.
|
||||
.onRequest(methods.client.session.requestPermission, (ctx) => {
|
||||
const options = ctx.params.options;
|
||||
const option = options.find((o) => o.kind === "allow_once") ?? options[0];
|
||||
return { outcome: { outcome: "selected", optionId: option.optionId } };
|
||||
})
|
||||
// Minimal file-system stubs; the example prompts don't touch files.
|
||||
.onRequest(methods.client.fs.readTextFile, () => ({ content: "" }))
|
||||
.onRequest(methods.client.fs.writeTextFile, () => ({}))
|
||||
.connect(stream);
|
||||
|
||||
try {
|
||||
const agent = connection.agent;
|
||||
|
||||
// 1. Initialize and confirm the agent advertises steering. Per the wire
|
||||
// protocol the capability lives at the TOP-LEVEL `_meta` of the initialize
|
||||
// result — a sibling of `agentCapabilities`, not nested inside it.
|
||||
const init = await agent.request(methods.agent.initialize, {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
|
||||
});
|
||||
const steering = (init._meta as { steering?: SteeringCapability } | null | undefined)
|
||||
?.steering;
|
||||
if (steering?.supported !== true) {
|
||||
throw new Error("agent does not advertise steering support");
|
||||
}
|
||||
log("agent advertises steering support");
|
||||
|
||||
// 2. Open a session.
|
||||
const { sessionId } = await agent.request(methods.agent.session.new, {
|
||||
cwd: CWD,
|
||||
mcpServers: [],
|
||||
});
|
||||
log(`session: ${sessionId}`);
|
||||
|
||||
// 3. Start a long turn, but DON'T await it yet — we need it in flight so we
|
||||
// can steer it. Its output streams through the notification handler above.
|
||||
log(`prompt: ${PROMPT}`);
|
||||
process.stdout.write("\n----- agent output -----\n");
|
||||
const turn = agent.request(methods.agent.session.prompt, {
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text: PROMPT }],
|
||||
});
|
||||
|
||||
// 4. Once the turn is producing output, inject the follow-up. Wait for the
|
||||
// first streamed chunk (with a fallback) plus a beat, so the steer clearly
|
||||
// lands mid-turn.
|
||||
await Promise.race([firstOutput, delay(5000)]);
|
||||
await delay(1000);
|
||||
|
||||
process.stdout.write("\n");
|
||||
log(`steer: ${STEER}`);
|
||||
const steerRequest: SteeringRequest = {
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text: STEER }],
|
||||
// Opt into the host-owned idle fallback. Without this request metadata,
|
||||
// the Adapter preserves its legacy `startedNewTurn` behavior.
|
||||
_meta: { steering: { idleBehavior: "promptRequired" } },
|
||||
};
|
||||
const result = await agent.request<SteeringResponse>(STEERING_METHOD, steerRequest);
|
||||
log(`steer outcome: ${result.outcome}`);
|
||||
|
||||
if (result.outcome === "promptRequired") {
|
||||
// The target turn already settled, so steering did not consume the message.
|
||||
// Start a normal session/prompt on the same session to deliver it — that
|
||||
// request owns the continuation's updates and terminal response.
|
||||
log(`steer fallback: ${result.reason}; starting a normal session/prompt`);
|
||||
const continuationRequest: PromptRequest = {
|
||||
sessionId: steerRequest.sessionId,
|
||||
prompt: steerRequest.prompt,
|
||||
};
|
||||
const continuation = await agent.request<PromptResponse, PromptRequest>(
|
||||
methods.agent.session.prompt,
|
||||
continuationRequest,
|
||||
);
|
||||
log(`continuation stopReason: ${continuation.stopReason}`);
|
||||
}
|
||||
|
||||
// 5. Await the original turn. With outcome "injected" the steer already
|
||||
// reshaped the output above; the promptRequired branch owns its own turn.
|
||||
const response = await turn;
|
||||
log(`original turn stopReason: ${response.stopReason}`);
|
||||
process.stdout.write("\n----- end of agent output -----\n");
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
log(`fatal: ${err?.stack ?? err}`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
3602
package-lock.json
generated
3602
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
62
package.json
62
package.json
@@ -1,44 +1,30 @@
|
||||
{
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"name": "@zed-industries/claude-code-acp",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "0.102.0",
|
||||
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
|
||||
"version": "0.12.3",
|
||||
"description": "An ACP-compatible coding agent powered by the Claude Code SDK (TypeScript)",
|
||||
"main": "dist/lib.js",
|
||||
"types": "dist/lib.d.ts",
|
||||
"bin": {
|
||||
"claude-agent-acp": "dist/index.js"
|
||||
"claude-code-acp": "./dist/index.js"
|
||||
},
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/lib.d.ts",
|
||||
"import": "./dist/lib.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"files": [
|
||||
"dist/",
|
||||
"!dist/tests/",
|
||||
"!dist/binary-entry.*",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"package.json"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"build:binary": "node scripts/build-binary.mjs",
|
||||
"smoke:binary": "node scripts/smoke-binary.mjs",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "npm run build && npm run start",
|
||||
"example:simple-client": "node --experimental-strip-types --disable-warning=ExperimentalWarning examples/simple-client.ts",
|
||||
"lint": "eslint src --ext .ts",
|
||||
"lint:fix": "eslint src --ext .ts --fix",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"check": "npm run lint && npm run format:check",
|
||||
"release:preflight": "bash scripts/release-preflight.sh",
|
||||
"test": "vitest",
|
||||
"test:integration": "RUN_INTEGRATION_TESTS=true vitest run",
|
||||
"test:run": "vitest run",
|
||||
@@ -54,39 +40,33 @@
|
||||
"sdk",
|
||||
"code"
|
||||
],
|
||||
"homepage": "https://github.com/agentclientprotocol/claude-agent-acp#readme",
|
||||
"homepage": "https://github.com/zed-industries/claude-code-acp#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/agentclientprotocol/claude-agent-acp/issues"
|
||||
"url": "https://github.com/zed-industries/claude-code-acp/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/agentclientprotocol/claude-agent-acp.git"
|
||||
"url": "git+https://github.com/zed-industries/claude-code-acp.git"
|
||||
},
|
||||
"author": "Zed Industries",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.5.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.321",
|
||||
"diff": "9.0.0",
|
||||
"zod": "4.6.7"
|
||||
"@agentclientprotocol/sdk": "0.8.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.1.61",
|
||||
"@modelcontextprotocol/sdk": "1.24.3",
|
||||
"diff": "8.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@anthropic-ai/sdk": "1.7.0",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@tsconfig/node22": "22.0.6",
|
||||
"@types/node": "26.6.6",
|
||||
"@typescript-eslint/eslint-plugin": "8.72.2",
|
||||
"@typescript-eslint/parser": "8.72.2",
|
||||
"ajv": "8.20.0",
|
||||
"ajv-formats": "3.0.1",
|
||||
"eslint": "10.14.0",
|
||||
"@anthropic-ai/sdk": "0.71.2",
|
||||
"@types/node": "24.10.1",
|
||||
"@typescript-eslint/eslint-plugin": "8.48.1",
|
||||
"@typescript-eslint/parser": "8.48.1",
|
||||
"eslint": "9.39.1",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"globals": "17.14.0",
|
||||
"prettier": "3.9.10",
|
||||
"typescript": "6.0.3",
|
||||
"vitest": "5.1.0"
|
||||
"globals": "16.5.0",
|
||||
"prettier": "3.7.4",
|
||||
"ts-node": "10.9.2",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "4.0.15"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"bump-minor-pre-major": true,
|
||||
"include-component-in-tag": false,
|
||||
"packages": {
|
||||
".": {
|
||||
"changelog-path": "CHANGELOG.md",
|
||||
"release-type": "node",
|
||||
"bump-minor-pre-major": true,
|
||||
"include-component-in-tag": false
|
||||
}
|
||||
},
|
||||
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json"
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds an executable of the agent with `bun build --compile` and copies the
|
||||
// target platform's Claude CLI next to it. Both files go in the release
|
||||
// archive: the executable runs the CLI from its own directory.
|
||||
//
|
||||
// node scripts/build-binary.mjs [--target bun-linux-x64-musl] [--outfile path]
|
||||
//
|
||||
// --target defaults to the host. Cross-compiling needs the target's SDK
|
||||
// platform package installed; the script prints the install command when it
|
||||
// is missing.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { chmodSync, copyFileSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
function hostTarget() {
|
||||
const os = process.platform === "win32" ? "windows" : process.platform;
|
||||
// Node linked against glibc reports its version; musl builds don't.
|
||||
const musl =
|
||||
process.platform === "linux" && !process.report.getReport().header.glibcVersionRuntime;
|
||||
return `bun-${os}-${process.arch}${musl ? "-musl" : ""}`;
|
||||
}
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
target: { type: "string", default: hostTarget() },
|
||||
outfile: { type: "string" },
|
||||
},
|
||||
});
|
||||
const target = values.target;
|
||||
|
||||
// Bun targets look like `bun-<os>-<arch>` with optional `-musl`, `-baseline` or
|
||||
// `-modern` suffixes; the SDK names its packages `<platform>-<arch>[-musl]`.
|
||||
const match = /^bun-(linux|darwin|windows)-(x64|arm64|aarch64)(?:-.+)?$/.exec(target);
|
||||
if (!match) {
|
||||
console.error(
|
||||
`Unsupported target "${target}". Expected e.g. bun-linux-x64, bun-darwin-arm64, bun-windows-x64.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const [, os, rawArch] = match;
|
||||
const platform = os === "windows" ? "win32" : os;
|
||||
const arch = rawArch === "aarch64" ? "arm64" : rawArch;
|
||||
const musl = target.split("-").includes("musl");
|
||||
const exe = os === "windows" ? ".exe" : "";
|
||||
const cliPackage = `@anthropic-ai/claude-agent-sdk-${platform}-${arch}${musl ? "-musl" : ""}`;
|
||||
const cliSpecifier = `${cliPackage}/claude${exe}`;
|
||||
const outfile = resolve(values.outfile ?? join(repoRoot, "dist-bin", `claude-agent-acp${exe}`));
|
||||
|
||||
// Resolve from the SDK, the way claudeCliPath() does at runtime, so a nested
|
||||
// install is checked rather than only a hoisted one.
|
||||
const sdkRequire = createRequire(
|
||||
createRequire(join(repoRoot, "package.json")).resolve("@anthropic-ai/claude-agent-sdk"),
|
||||
);
|
||||
let cliPath;
|
||||
try {
|
||||
cliPath = sdkRequire.resolve(cliSpecifier);
|
||||
} catch {
|
||||
const sdkVersion = JSON.parse(
|
||||
readFileSync(
|
||||
join(dirname(sdkRequire.resolve("@anthropic-ai/claude-agent-sdk")), "package.json"),
|
||||
"utf8",
|
||||
),
|
||||
).version;
|
||||
console.error(
|
||||
`${cliSpecifier} is not installed. npm only installs the host's platform package; for ${target} run:\n\n` +
|
||||
` npm install --no-save --force ${cliPackage}@${sdkVersion}\n`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const bun = spawnSync(
|
||||
"bun",
|
||||
["build", "src/binary-entry.ts", "--compile", "--target", target, "--outfile", outfile],
|
||||
{ cwd: repoRoot, stdio: "inherit", shell: process.platform === "win32" },
|
||||
);
|
||||
if (bun.error) {
|
||||
console.error(`Could not run bun: ${bun.error.message}. Install it from https://bun.sh.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (bun.status !== 0) process.exit(bun.status ?? 1);
|
||||
|
||||
// The executable runs the CLI from its own directory (src/binary-entry.ts).
|
||||
const cliOutfile = join(dirname(outfile), `claude${exe}`);
|
||||
copyFileSync(cliPath, cliOutfile);
|
||||
chmodSync(cliOutfile, 0o755);
|
||||
console.log(`Copied ${cliSpecifier} to ${cliOutfile}`);
|
||||
@@ -1,202 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
//
|
||||
// Prints the next preview version for this package, e.g. `0.73.1-preview.4`.
|
||||
//
|
||||
// The base is package.json's version with the patch incremented, so a preview always
|
||||
// sorts above the last release and below whatever release follows it. `-preview.N`
|
||||
// counts from 1 per base and restarts whenever release-please moves package.json on.
|
||||
//
|
||||
// Basing the preview on release-please's *predicted* next version would be more
|
||||
// truthful — it would give `0.74.0-preview.N` when a `feat:` is queued — but the
|
||||
// prediction moves mid-flight: a `fix:` opens a 0.73.1 release PR, a later `feat:`
|
||||
// moves it to 0.74.0, and N resets under previews that were already published. If the
|
||||
// prediction ever moved down, the next preview would sort below the previous one.
|
||||
// package.json only ever increases, so patch+1 is monotonic in every case:
|
||||
// 0.73.1-preview.9 < 0.73.2-preview.1 and < 0.74.1-preview.1, whichever way the next
|
||||
// release goes. The cost is that `0.73.1-preview.4` is not a promise that 0.73.1 will
|
||||
// ship.
|
||||
//
|
||||
// N has to be a number nobody has used, and two sources are consulted because either
|
||||
// alone is unsafe:
|
||||
//
|
||||
// * the npm registry, authoritative for what is taken — npm versions are immutable
|
||||
// and stay reserved even after `npm unpublish`, so a taken N is a hard E403 at
|
||||
// publish time — but served from a CDN, so it can lag a publish by minutes;
|
||||
// * git tags, written by the workflow after each publish and strongly consistent,
|
||||
// which cover that window and any unpublish.
|
||||
//
|
||||
// The workflow publishes before it tags, so a version can exist on npm without a tag
|
||||
// but never the other way round. That asymmetry is why the registry is the authority
|
||||
// and the tags are only a floor, and why a registry read failure is fatal here rather
|
||||
// than falling back to the tags alone.
|
||||
//
|
||||
// See docs/RELEASES.md.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
||||
const PREVIEW_ID = "preview";
|
||||
const FETCH_ATTEMPTS = 3;
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
const BACKOFF_MS = 500;
|
||||
|
||||
/** X.Y.Z: no prerelease, no build metadata, no leading zeros. */
|
||||
const RELEASE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
||||
|
||||
/** The base a preview anticipates: package.json's version with the patch bumped. */
|
||||
export function bumpPatch(version) {
|
||||
const match = RELEASE_VERSION.exec(String(version ?? "").trim());
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`expected a plain X.Y.Z release version, got ${JSON.stringify(version)}. ` +
|
||||
`release-please owns package.json's version; a prerelease or a range here means ` +
|
||||
`something else has edited it.`,
|
||||
);
|
||||
}
|
||||
const [, major, minor, patch] = match;
|
||||
return `${major}.${minor}.${Number(patch) + 1}`;
|
||||
}
|
||||
|
||||
function escapeRegExp(literal) {
|
||||
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Matcher for `<base>-preview.<n>`. `0731-preview.1` would match a base of `0.73.1`. `n`
|
||||
* is a semver-legal numeric identifier, so leading zeros are rejected; npm would never
|
||||
* have accepted `preview.01` in the first place.
|
||||
*/
|
||||
export function previewPattern(base) {
|
||||
return new RegExp(`^${escapeRegExp(base)}-${PREVIEW_ID}\\.(0|[1-9]\\d*)$`);
|
||||
}
|
||||
|
||||
/** The N in `<base>-preview.N`, or null for anything else. */
|
||||
export function previewNumber(candidate, base) {
|
||||
const match = previewPattern(base).exec(String(candidate ?? "").trim());
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
/** `refs/tags/v1.2.3`, `v1.2.3` and `1.2.3` all become `1.2.3`. */
|
||||
export function versionFromTag(tag) {
|
||||
return String(tag ?? "")
|
||||
.trim()
|
||||
.replace(/^refs\/tags\//, "")
|
||||
.replace(/^v/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Highest N among the candidates, or 0 when none match.
|
||||
*/
|
||||
export function highestPreviewNumber(candidates, base) {
|
||||
let highest = 0;
|
||||
for (const candidate of candidates) {
|
||||
const n = previewNumber(candidate, base);
|
||||
if (n !== null && n > highest) {
|
||||
highest = n;
|
||||
}
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
|
||||
export function nextPreviewVersion({ base, registryVersions = [], tags = [] }) {
|
||||
const taken = Math.max(
|
||||
highestPreviewNumber(registryVersions, base),
|
||||
highestPreviewNumber(tags.map(versionFromTag), base),
|
||||
);
|
||||
return `${base}-${PREVIEW_ID}.${taken + 1}`;
|
||||
}
|
||||
|
||||
/** Every version this package has ever published, per the registry. */
|
||||
export async function fetchPublishedVersions(name, options = {}) {
|
||||
const {
|
||||
registry = DEFAULT_REGISTRY,
|
||||
fetchImpl = fetch,
|
||||
attempts = FETCH_ATTEMPTS,
|
||||
backoffMs = BACKOFF_MS,
|
||||
} = options;
|
||||
const url = `${registry}/${name.replace("/", "%2f")}`;
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
const response = await fetchImpl(url, {
|
||||
// The abbreviated packument is a fraction of the full one — tens of kilobytes
|
||||
// rather than megabytes — and still carries every version key.
|
||||
headers: { accept: "application/vnd.npm.install-v1+json" },
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (response.status === 404) {
|
||||
// Never published. A definite answer, not a failure.
|
||||
return [];
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`${url} answered ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const packument = await response.json();
|
||||
// `versions` on a packument is always an object keyed by version, so there is
|
||||
// none of the "a single version comes back as a bare string" shape that
|
||||
// `npm view <pkg> versions --json` has.
|
||||
return Object.keys(packument.versions ?? {});
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < attempts) {
|
||||
await new Promise((resolve) => setTimeout(resolve, backoffMs * 2 ** (attempt - 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`could not read published versions for ${name} after ${attempts} attempts: ${lastError}. ` +
|
||||
`Refusing to guess a preview number: the registry is the only record of versions ` +
|
||||
`that were published and then unpublished, and those can never be reused.`,
|
||||
{ cause: lastError },
|
||||
);
|
||||
}
|
||||
|
||||
function localPreviewTags(base) {
|
||||
try {
|
||||
return execFileSync("git", ["tag", "--list", `v${base}-${PREVIEW_ID}.*`], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
})
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
} catch {
|
||||
// No git, no repository, or a clone without tags. Tags are only a floor under the
|
||||
// registry, so carry on rather than fail.
|
||||
process.stderr.write("warning: could not list git tags; using the registry alone\n");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function readFlag(argv, name) {
|
||||
const index = argv.indexOf(name);
|
||||
return index === -1 ? undefined : argv[index + 1];
|
||||
}
|
||||
|
||||
async function main(argv) {
|
||||
const packageJsonPath = readFlag(argv, "--package-json") ?? "package.json";
|
||||
const manifest = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
||||
const base = bumpPatch(manifest.version);
|
||||
const registryVersions = await fetchPublishedVersions(manifest.name, {
|
||||
registry: readFlag(argv, "--registry") ?? DEFAULT_REGISTRY,
|
||||
});
|
||||
const tags = argv.includes("--no-git-tags") ? [] : localPreviewTags(base);
|
||||
|
||||
// Diagnostics on stderr so stdout stays a single machine-readable line.
|
||||
process.stderr.write(
|
||||
`${manifest.name} ${manifest.version} -> base ${base}; registry high-water ` +
|
||||
`${highestPreviewNumber(registryVersions, base)}, tag high-water ` +
|
||||
`${highestPreviewNumber(tags.map(versionFromTag), base)}\n`,
|
||||
);
|
||||
process.stdout.write(`${nextPreviewVersion({ base, registryVersions, tags })}\n`);
|
||||
}
|
||||
|
||||
// Only when invoked as a program, so the helpers above can be imported by the test
|
||||
// without doing any I/O.
|
||||
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
||||
main(process.argv.slice(2)).catch((error) => {
|
||||
process.stderr.write(`${error.message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import {
|
||||
bumpPatch,
|
||||
previewNumber,
|
||||
versionFromTag,
|
||||
highestPreviewNumber,
|
||||
nextPreviewVersion,
|
||||
fetchPublishedVersions,
|
||||
} from "./next-preview-version.mjs";
|
||||
|
||||
const PACKAGE = "@agentclientprotocol/claude-agent-acp";
|
||||
|
||||
/** A packument response, abbreviated the way the registry returns it. */
|
||||
function packument(versions) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
json: async () => ({ name: PACKAGE, versions }),
|
||||
};
|
||||
}
|
||||
|
||||
function failure(status, statusText = "Internal Server Error") {
|
||||
return { ok: false, status, statusText, json: async () => ({}) };
|
||||
}
|
||||
|
||||
describe("bumpPatch", () => {
|
||||
it("increments the patch", () => {
|
||||
expect(bumpPatch("0.73.0")).toBe("0.73.1");
|
||||
expect(bumpPatch("1.0.0")).toBe("1.0.1");
|
||||
expect(bumpPatch("0.0.0")).toBe("0.0.1");
|
||||
});
|
||||
|
||||
it("increments numerically rather than by concatenation", () => {
|
||||
expect(bumpPatch("0.73.9")).toBe("0.73.10");
|
||||
expect(bumpPatch("0.73.19")).toBe("0.73.20");
|
||||
});
|
||||
|
||||
it("trims surrounding whitespace", () => {
|
||||
expect(bumpPatch(" 0.73.0 ")).toBe("0.73.1");
|
||||
});
|
||||
|
||||
// release-please owns package.json's version, so anything that is not a plain
|
||||
// release means something else has edited it. Failing loudly beats guessing.
|
||||
it.each([
|
||||
["a two-part version", "0.73"],
|
||||
["a four-part version", "0.73.0.1"],
|
||||
["a prerelease", "0.73.0-preview.1"],
|
||||
["build metadata", "0.73.0+build.1"],
|
||||
["a v prefix", "v0.73.0"],
|
||||
["a range", "^0.73.0"],
|
||||
["leading zeros", "01.2.3"],
|
||||
["the empty string", ""],
|
||||
["undefined", undefined],
|
||||
])("throws on %s", (_label, version) => {
|
||||
expect(() => bumpPatch(version)).toThrow(/plain X\.Y\.Z release version/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("previewNumber", () => {
|
||||
it("reads N out of a matching version", () => {
|
||||
expect(previewNumber("0.73.1-preview.1", "0.73.1")).toBe(1);
|
||||
expect(previewNumber("0.73.1-preview.10", "0.73.1")).toBe(10);
|
||||
});
|
||||
|
||||
it("treats zero as a number rather than as no match", () => {
|
||||
expect(previewNumber("0.73.1-preview.0", "0.73.1")).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a plain release", "0.73.1"],
|
||||
["a different base", "0.73.2-preview.1"],
|
||||
["a missing number", "0.73.1-preview"],
|
||||
["leading zeros in N", "0.73.1-preview.01"],
|
||||
["a dotted N", "0.73.1-preview.1.2"],
|
||||
["build metadata", "0.73.1-preview.1+build.5"],
|
||||
["another prerelease id", "0.73.1-alpha.1"],
|
||||
// Proves the base's dots are escaped rather than matching any character.
|
||||
["a base whose dots are elided", "0731-preview.1"],
|
||||
// Proves the pattern is anchored at the start.
|
||||
["a base with a numeric prefix", "10.73.1-preview.1"],
|
||||
])("returns null for %s", (_label, candidate) => {
|
||||
expect(previewNumber(candidate, "0.73.1")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("versionFromTag", () => {
|
||||
it("strips a refs/tags/ prefix and a v", () => {
|
||||
expect(versionFromTag("refs/tags/v0.73.1-preview.3")).toBe("0.73.1-preview.3");
|
||||
expect(versionFromTag("v0.73.1")).toBe("0.73.1");
|
||||
expect(versionFromTag("0.73.1")).toBe("0.73.1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("highestPreviewNumber", () => {
|
||||
it("is 0 when nothing matches", () => {
|
||||
expect(highestPreviewNumber([], "0.73.1")).toBe(0);
|
||||
expect(highestPreviewNumber(["0.73.1", "0.72.1-preview.4"], "0.73.1")).toBe(0);
|
||||
});
|
||||
|
||||
// Sorted as strings, `preview.9` would beat `preview.10`.
|
||||
it("compares numerically, not lexicographically", () => {
|
||||
expect(highestPreviewNumber(["0.73.1-preview.9", "0.73.1-preview.10"], "0.73.1")).toBe(10);
|
||||
expect(highestPreviewNumber(["0.73.1-preview.10", "0.73.1-preview.9"], "0.73.1")).toBe(10);
|
||||
});
|
||||
|
||||
it("ignores order and duplicates", () => {
|
||||
const candidates = [
|
||||
"0.73.1-preview.2",
|
||||
"0.73.1-preview.7",
|
||||
"0.73.1-preview.2",
|
||||
"0.73.1-preview.5",
|
||||
];
|
||||
expect(highestPreviewNumber(candidates, "0.73.1")).toBe(7);
|
||||
});
|
||||
|
||||
it("counts only the requested base", () => {
|
||||
const candidates = ["0.72.1-preview.99", "0.73.1-preview.3", "0.74.1-preview.42"];
|
||||
expect(highestPreviewNumber(candidates, "0.73.1")).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextPreviewVersion", () => {
|
||||
it("starts at 1 with no history", () => {
|
||||
expect(nextPreviewVersion({ base: "0.73.1" })).toBe("0.73.1-preview.1");
|
||||
});
|
||||
|
||||
it("continues from the registry", () => {
|
||||
const registryVersions = ["0.73.0", "0.73.1-preview.1", "0.73.1-preview.2", "0.73.1-preview.3"];
|
||||
expect(nextPreviewVersion({ base: "0.73.1", registryVersions })).toBe("0.73.1-preview.4");
|
||||
});
|
||||
|
||||
// The registry is CDN-served and can lag a publish by minutes; the tag the previous
|
||||
// run wrote is what closes that window.
|
||||
it("uses the tags as a floor when the registry is behind", () => {
|
||||
const next = nextPreviewVersion({
|
||||
base: "0.73.1",
|
||||
registryVersions: ["0.73.1-preview.1"],
|
||||
tags: ["refs/tags/v0.73.1-preview.3"],
|
||||
});
|
||||
expect(next).toBe("0.73.1-preview.4");
|
||||
});
|
||||
|
||||
// The converse: publish succeeded but the tag step did not, so the registry is
|
||||
// ahead. It stays authoritative.
|
||||
it("keeps the registry authoritative when the tags are behind", () => {
|
||||
const next = nextPreviewVersion({
|
||||
base: "0.73.1",
|
||||
registryVersions: ["0.73.1-preview.1", "0.73.1-preview.2", "0.73.1-preview.3"],
|
||||
tags: ["v0.73.1-preview.1"],
|
||||
});
|
||||
expect(next).toBe("0.73.1-preview.4");
|
||||
});
|
||||
|
||||
it("restarts at 1 once a release moves the base", () => {
|
||||
const next = nextPreviewVersion({
|
||||
base: "0.73.1",
|
||||
registryVersions: ["0.72.1-preview.7", "0.73.0"],
|
||||
tags: ["v0.72.1-preview.7"],
|
||||
});
|
||||
expect(next).toBe("0.73.1-preview.1");
|
||||
});
|
||||
|
||||
it("composes with bumpPatch", () => {
|
||||
const next = nextPreviewVersion({
|
||||
base: bumpPatch("0.73.0"),
|
||||
registryVersions: ["0.73.0"],
|
||||
tags: ["v0.73.0"],
|
||||
});
|
||||
expect(next).toBe("0.73.1-preview.1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchPublishedVersions", () => {
|
||||
const options = (fetchImpl) => ({ fetchImpl, backoffMs: 0 });
|
||||
|
||||
it("returns the version keys of the packument", async () => {
|
||||
const fetchImpl = vi.fn(async () => packument({ "0.73.0": {}, "0.73.1-preview.1": {} }));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).resolves.toEqual([
|
||||
"0.73.0",
|
||||
"0.73.1-preview.1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("requests the abbreviated packument at the scope-encoded URL", async () => {
|
||||
const fetchImpl = vi.fn(async () => packument({}));
|
||||
await fetchPublishedVersions(PACKAGE, options(fetchImpl));
|
||||
const [url, init] = fetchImpl.mock.calls[0];
|
||||
expect(url).toBe("https://registry.npmjs.org/@agentclientprotocol%2fclaude-agent-acp");
|
||||
expect(init.headers.accept).toBe("application/vnd.npm.install-v1+json");
|
||||
});
|
||||
|
||||
it("honours a custom registry", async () => {
|
||||
const fetchImpl = vi.fn(async () => packument({}));
|
||||
await fetchPublishedVersions(PACKAGE, {
|
||||
...options(fetchImpl),
|
||||
registry: "http://127.0.0.1:4873",
|
||||
});
|
||||
expect(fetchImpl.mock.calls[0][0]).toBe(
|
||||
"http://127.0.0.1:4873/@agentclientprotocol%2fclaude-agent-acp",
|
||||
);
|
||||
});
|
||||
|
||||
it("tolerates a packument with no versions", async () => {
|
||||
const fetchImpl = vi.fn(async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
json: async () => ({ name: PACKAGE }),
|
||||
}));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
// A 404 is a definite answer — the package has never been published — so it must not
|
||||
// be retried or turned into a failure.
|
||||
it("treats 404 as an empty history without retrying", async () => {
|
||||
const fetchImpl = vi.fn(async () => failure(404, "Not Found"));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).resolves.toEqual([]);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retries a server error and resolves", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(failure(500))
|
||||
.mockResolvedValueOnce(packument({ "0.73.0": {} }));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).resolves.toEqual(["0.73.0"]);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries a network failure and resolves", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new TypeError("fetch failed"))
|
||||
.mockResolvedValueOnce(packument({ "0.73.0": {} }));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).resolves.toEqual(["0.73.0"]);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Guessing N after a failed read risks reusing a version that was published and then
|
||||
// unpublished, which npm reserves forever.
|
||||
it("gives up rather than guessing when every attempt fails", async () => {
|
||||
const fetchImpl = vi.fn(async () => failure(500));
|
||||
await expect(fetchPublishedVersions(PACKAGE, options(fetchImpl))).rejects.toThrow(
|
||||
/could not read published versions for @agentclientprotocol\/claude-agent-acp after 3 attempts/,
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Preflight checks for a release.
|
||||
#
|
||||
# release-please decides what the next version is; this script only verifies the
|
||||
# repository is in a state where merging the open release PR produces a correct
|
||||
# release. Merging main needs no review, so these checks are the only thing
|
||||
# standing between a mistake and a published package — keep them as code rather
|
||||
# than as a list someone has to remember. See docs/RELEASES.md.
|
||||
#
|
||||
# Requires an authenticated GitHub CLI. Nothing else: gh has a jq engine builtin.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PENDING_LABEL="autorelease: pending"
|
||||
|
||||
fail() {
|
||||
printf 'FAIL %s\n' "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
pass() {
|
||||
printf 'ok %s\n' "$1"
|
||||
}
|
||||
|
||||
command -v gh >/dev/null 2>&1 ||
|
||||
fail "GitHub CLI (gh) is not installed."
|
||||
gh auth status >/dev/null 2>&1 ||
|
||||
fail "GitHub CLI is not authenticated. Run 'gh auth login'."
|
||||
|
||||
repo=$(gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null) ||
|
||||
fail "cannot work out which GitHub repository this is. Run from a checkout."
|
||||
|
||||
# A merged release PR that still carries the pending label means release-please
|
||||
# never tagged it. In that state it refuses to open any new release PR at all,
|
||||
# so every later release stalls silently until it is recovered by hand.
|
||||
stuck=$(gh pr list --repo "$repo" --state merged --label "$PENDING_LABEL" \
|
||||
--json number --jq 'map("#\(.number)") | join(", ")')
|
||||
[ -z "$stuck" ] ||
|
||||
fail "merged release PR still labelled '$PENDING_LABEL': $stuck.
|
||||
release-please is jammed and will not open new release PRs.
|
||||
See docs/RELEASES.md, 'Recovering a stalled release'."
|
||||
pass "no untagged merged release PR"
|
||||
|
||||
rows=$(gh pr list --repo "$repo" --state open --label "$PENDING_LABEL" \
|
||||
--json number,title,headRefName --jq '.[] | [.number, .headRefName, .title] | @tsv')
|
||||
count=$(printf '%s\n' "$rows" | grep -c . || true)
|
||||
|
||||
if [ "$count" -eq 0 ]; then
|
||||
fail "no open release PR.
|
||||
Nothing has landed since the last tag that release-please puts in a
|
||||
changelog, so there is nothing to release. Land a feat/fix/perf/revert/docs
|
||||
change first, or check that the Publish and Release workflow is running."
|
||||
fi
|
||||
if [ "$count" -gt 1 ]; then
|
||||
fail "$count open release PRs, expected exactly one:
|
||||
$rows"
|
||||
fi
|
||||
IFS=$(printf '\t') read -r pr_number head_ref pr_title <<EOF
|
||||
$rows
|
||||
EOF
|
||||
pass "one open release PR: #$pr_number ($pr_title)"
|
||||
|
||||
# release-please reads the version to tag from the PR title, while npm publishes
|
||||
# whatever package.json says. If those disagree the tag and the published package
|
||||
# describe different releases, so check all three sources against each other.
|
||||
# The version is the last field, not everything after 'release': release-please
|
||||
# writes the component into the title as 'release <component> X.Y.Z' whenever it
|
||||
# is configured to tag with one.
|
||||
title_version=${pr_title##* }
|
||||
case $title_version in
|
||||
[0-9]*.[0-9]*.[0-9]*) ;;
|
||||
*) fail "cannot read a version from PR title '$pr_title'." ;;
|
||||
esac
|
||||
pkg_version=$(gh api "repos/$repo/contents/package.json?ref=$head_ref" \
|
||||
-H "Accept: application/vnd.github.raw" --jq .version)
|
||||
manifest_version=$(gh api "repos/$repo/contents/.release-please-manifest.json?ref=$head_ref" \
|
||||
-H "Accept: application/vnd.github.raw" --jq '."."')
|
||||
|
||||
if [ "$title_version" != "$pkg_version" ] || [ "$title_version" != "$manifest_version" ]; then
|
||||
fail "version mismatch on #$pr_number:
|
||||
PR title $title_version
|
||||
package.json $pkg_version
|
||||
.release-please-manifest.json $manifest_version"
|
||||
fi
|
||||
pass "version agrees across PR title, package.json and manifest: $title_version"
|
||||
|
||||
# The tag comes from the config, not from the PR title. With
|
||||
# include-component-in-tag left on, release-please tags <component>-vX.Y.Z, which
|
||||
# breaks the vX.Y.Z scheme the rest of this script and docs/RELEASES.md rely on,
|
||||
# and makes it rewrite the whole history into the changelog because no tag under
|
||||
# that scheme exists yet. The compare link it writes into the PR body names the
|
||||
# tags it is going to use, so check those rather than trusting the config.
|
||||
compare_tag=$(gh pr view "$pr_number" --repo "$repo" --json body --jq '
|
||||
.body | capture("/compare/[^)]*[.][.][.](?<to>[^)\\s]+)").to // ""' 2>/dev/null || true)
|
||||
case $compare_tag in
|
||||
"" | "v$title_version") ;;
|
||||
*) fail "release-please is going to tag '$compare_tag', not 'v$title_version'.
|
||||
Every previous release is tagged vX.Y.Z, and the changelog for #$pr_number
|
||||
covers the whole history rather than just this release, because no tag
|
||||
under that scheme exists. Set 'include-component-in-tag': false in
|
||||
release-please-config.json, then let it rewrite the release PR." ;;
|
||||
esac
|
||||
|
||||
if gh release view "v$title_version" --repo "$repo" >/dev/null 2>&1; then
|
||||
fail "tag v$title_version already exists. Merging would try to release it twice."
|
||||
fi
|
||||
pass "tag v$title_version does not exist yet"
|
||||
|
||||
build=$(gh pr view "$pr_number" --repo "$repo" --json statusCheckRollup --jq '
|
||||
[.statusCheckRollup[]? | select(.name == "Build")]
|
||||
| if length == 0 then "MISSING" else (.[0].conclusion // .[0].status // "PENDING") end')
|
||||
[ "$build" = "SUCCESS" ] ||
|
||||
fail "required check 'Build' is $build on #$pr_number, expected SUCCESS."
|
||||
pass "required check 'Build' passed"
|
||||
|
||||
cat <<EOF
|
||||
|
||||
Ready to release $title_version.
|
||||
|
||||
gh pr merge $pr_number --squash
|
||||
|
||||
Merging tags v$title_version, publishes to npm and updates the agent registry.
|
||||
EOF
|
||||
@@ -1,470 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Smoke-tests a built agent over ACP. Defaults to the executable from
|
||||
// scripts/build-binary.mjs, with `claude` next to it. Pass another command
|
||||
// after `--` to compare, e.g.
|
||||
// `node scripts/smoke-binary.mjs --full -- node "$PWD/dist/index.js"` (the full
|
||||
// run starts the agent in a scratch directory, so paths must be absolute).
|
||||
//
|
||||
// node scripts/smoke-binary.mjs # no login needed
|
||||
// node scripts/smoke-binary.mjs --full # talks to the model; needs a logged-in Claude
|
||||
//
|
||||
// SMOKE_DEBUG=1 prints every tool call the full run saw.
|
||||
//
|
||||
// The basic run checks `--version`, `--cli --version`, `initialize` (v1 and
|
||||
// v2) and the `terminal-auth` login command. The
|
||||
// full run also has Claude use Bash, Read (text and image), Edit and a
|
||||
// subagent in a scratch directory, then cancels a turn, lists the session,
|
||||
// loads it in a fresh agent process, and forks and deletes it.
|
||||
//
|
||||
// Claude Code's native builds have no Grep or Glob tool: its Bash shell wraps
|
||||
// `grep` and `find` in functions that run the ugrep and bfs built into the
|
||||
// Claude binary at `$CLAUDE_CODE_EXECPATH`. The full run checks that those
|
||||
// run, since they are the helpers a packaged build could fail to reach.
|
||||
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import readline from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const { values, positionals } = parseArgs({
|
||||
options: { full: { type: "boolean", default: false } },
|
||||
allowPositionals: true,
|
||||
});
|
||||
const exe = process.platform === "win32" ? ".exe" : "";
|
||||
const [command, ...commandArgs] =
|
||||
positionals.length > 0 ? positionals : [join(repoRoot, "dist-bin", `claude-agent-acp${exe}`)];
|
||||
|
||||
let failures = 0;
|
||||
function check(ok, label, detail) {
|
||||
console.log(
|
||||
`${ok ? "ok " : "FAIL"} ${label}${!ok && detail !== undefined ? `: ${detail}` : ""}`,
|
||||
);
|
||||
if (!ok) failures++;
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- basic
|
||||
|
||||
function runSync(args, [cmd, ...cmdArgs] = [command, ...commandArgs]) {
|
||||
const result = spawnSync(cmd, [...cmdArgs, ...args], {
|
||||
encoding: "utf8",
|
||||
timeout: 60_000,
|
||||
});
|
||||
return { stdout: (result.stdout ?? "").trim(), error: result.error ?? result.stderr };
|
||||
}
|
||||
|
||||
const version = JSON.parse(readFileSync(join(repoRoot, "package.json"), "utf8")).version;
|
||||
const own = runSync(["--version"]);
|
||||
check(own.stdout === version, `--version prints ${version}`, own.stdout || own.error);
|
||||
const cli = runSync(["--cli", "--version"]);
|
||||
check(
|
||||
/\(Claude Code\)$/.test(cli.stdout),
|
||||
"--cli --version runs the bundled Claude CLI",
|
||||
cli.stdout || cli.error,
|
||||
);
|
||||
|
||||
// The release archive's layout: the executable finds `claude` in the directory
|
||||
// of its real path. Only for the default executable; a `--` command has no
|
||||
// such layout.
|
||||
if (positionals.length === 0) {
|
||||
const scratch = mkdtempSync(join(tmpdir(), "acp-layout-"));
|
||||
try {
|
||||
if (process.platform !== "win32") {
|
||||
const link = join(scratch, "claude-agent-acp");
|
||||
symlinkSync(command, link);
|
||||
const linked = runSync(["--cli", "--version"], [link]);
|
||||
check(
|
||||
/\(Claude Code\)$/.test(linked.stdout),
|
||||
"a symlink to the executable finds the bundled CLI",
|
||||
linked.stdout || linked.error,
|
||||
);
|
||||
rmSync(link);
|
||||
}
|
||||
const alone = join(scratch, `claude-agent-acp${exe}`);
|
||||
copyFileSync(command, alone);
|
||||
const missing = runSync(["--cli", "--version"], [alone]);
|
||||
check(
|
||||
String(missing.error).includes("The Claude CLI is missing"),
|
||||
"without claude next to it, says the CLI is missing",
|
||||
missing.stdout || missing.error,
|
||||
);
|
||||
} finally {
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the agent and speaks newline-delimited JSON-RPC to it. */
|
||||
function startAgent(cwd, onNotification) {
|
||||
const child = spawn(command, commandArgs, { cwd, stdio: ["pipe", "pipe", "pipe"] });
|
||||
const stderr = [];
|
||||
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
||||
let nextId = 0;
|
||||
const pending = new Map();
|
||||
const write = (message) =>
|
||||
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
|
||||
readline.createInterface({ input: child.stdout }).on("line", (line) => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(line);
|
||||
} catch {
|
||||
check(false, "stdout carries only JSON-RPC", line.slice(0, 200));
|
||||
return;
|
||||
}
|
||||
if (message.method === undefined && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
} else if (message.method === "session/request_permission") {
|
||||
const allow =
|
||||
message.params.options.find((o) => o.kind === "allow_once") ?? message.params.options[0];
|
||||
write({
|
||||
id: message.id,
|
||||
result: { outcome: { outcome: "selected", optionId: allow.optionId } },
|
||||
});
|
||||
} else if (message.id !== undefined && message.method !== undefined) {
|
||||
write({
|
||||
id: message.id,
|
||||
error: { code: -32601, message: `smoke client does not handle ${message.method}` },
|
||||
});
|
||||
} else {
|
||||
onNotification?.(message);
|
||||
}
|
||||
});
|
||||
const exited = new Promise((resolve) => child.on("exit", resolve));
|
||||
// Answer anything still pending if the agent dies, instead of hanging.
|
||||
let exitError;
|
||||
exited.then((code) => {
|
||||
exitError = { message: `agent exited with ${code}: ${Buffer.concat(stderr)}` };
|
||||
for (const resolve of pending.values()) resolve({ error: exitError });
|
||||
pending.clear();
|
||||
});
|
||||
return {
|
||||
request(method, params) {
|
||||
const id = ++nextId;
|
||||
return new Promise((resolve) => {
|
||||
if (exitError) return resolve({ error: exitError });
|
||||
pending.set(id, resolve);
|
||||
write({ id, method, params });
|
||||
});
|
||||
},
|
||||
notify: (method, params) => write({ method, params }),
|
||||
async stop() {
|
||||
child.stdin.end();
|
||||
const code = await Promise.race([
|
||||
exited,
|
||||
new Promise((r) => setTimeout(() => r("timeout"), 10_000)),
|
||||
]);
|
||||
if (code === "timeout") child.kill();
|
||||
return { code, stderr: Buffer.concat(stderr).toString() };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const initializeParams = { protocolVersion: 1, clientCapabilities: {} };
|
||||
{
|
||||
const agent = startAgent(process.cwd());
|
||||
const init = await agent.request("initialize", initializeParams);
|
||||
check(
|
||||
init.result?.agentInfo?.version === version,
|
||||
"initialize answers",
|
||||
JSON.stringify(init.error),
|
||||
);
|
||||
const { code } = await agent.stop();
|
||||
check(code === 0, "exits 0 when stdin closes", code);
|
||||
}
|
||||
{
|
||||
// The `terminal-auth` login command reruns the agent; run it with
|
||||
// `--version` in place of `auth login --console` instead of logging in.
|
||||
// `--version` wins over a stray argument, so also check that no path inside
|
||||
// a compiled executable leaked into the arguments.
|
||||
const agent = startAgent(process.cwd());
|
||||
const init = await agent.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { _meta: { "terminal-auth": true } },
|
||||
});
|
||||
await agent.stop();
|
||||
const login = init.result?.authMethods?.find((m) => m.id === "console-login")?._meta?.[
|
||||
"terminal-auth"
|
||||
];
|
||||
const cliArgs = login?.args?.slice(0, login.args.indexOf("--cli") + 1);
|
||||
const rerun = login
|
||||
? runSync([...cliArgs, "--version"], [login.command])
|
||||
: { stdout: "", error: "no terminal-auth console-login method" };
|
||||
check(
|
||||
/\(Claude Code\)$/.test(rerun.stdout) &&
|
||||
!login.args.some((arg) => arg.includes("$bunfs") || arg.includes("~BUN")),
|
||||
"the terminal-auth login command reruns the agent",
|
||||
`${JSON.stringify(login)} -> ${rerun.stdout || rerun.error}`,
|
||||
);
|
||||
}
|
||||
{
|
||||
const agent = startAgent(process.cwd());
|
||||
const init = await agent.request("initialize", {
|
||||
protocolVersion: 2,
|
||||
info: { name: "smoke-binary", version },
|
||||
capabilities: {},
|
||||
});
|
||||
check(
|
||||
init.result?.protocolVersion === 2,
|
||||
"initialize answers ACP v2",
|
||||
JSON.stringify(init.error),
|
||||
);
|
||||
await agent.stop();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- full
|
||||
|
||||
if (values.full) {
|
||||
const work = mkdtempSync(join(tmpdir(), "acp-smoke-"));
|
||||
try {
|
||||
await fullSmoke(work);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** A solid red 16x16 PNG, so the model has something to name. */
|
||||
function redPng() {
|
||||
const crcTable = Array.from({ length: 256 }, (_, n) => {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
return c >>> 0;
|
||||
});
|
||||
const crc = (buf) => {
|
||||
let c = 0xffffffff;
|
||||
for (const byte of buf) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
};
|
||||
const chunk = (type, data) => {
|
||||
const body = Buffer.concat([Buffer.from(type), data]);
|
||||
const out = Buffer.alloc(body.length + 8);
|
||||
out.writeUInt32BE(data.length, 0);
|
||||
body.copy(out, 4);
|
||||
out.writeUInt32BE(crc(body), body.length + 4);
|
||||
return out;
|
||||
};
|
||||
const size = 16;
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(size, 0);
|
||||
header.writeUInt32BE(size, 4);
|
||||
header[8] = 8; // bit depth
|
||||
header[9] = 2; // RGB
|
||||
const row = Buffer.concat([Buffer.from([0]), Buffer.alloc(size * 3, Buffer.from([255, 0, 0]))]);
|
||||
return Buffer.concat([
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
|
||||
chunk("IHDR", header),
|
||||
chunk("IDAT", deflateSync(Buffer.concat(Array(size).fill(row)))),
|
||||
chunk("IEND", Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Writes its results to files so the checks don't depend on the model's reply. */
|
||||
function searchCommand(token) {
|
||||
return [
|
||||
`grep -rl "${token}" . > grep.out`,
|
||||
'find . -name "*.md" > find.out',
|
||||
'{ echo "$CLAUDE_CODE_EXECPATH"; grep --version | head -1; find --version | head -1; } > tools.out',
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
function searchResults(work) {
|
||||
const read = (name) => {
|
||||
try {
|
||||
return readFileSync(join(work, name), "utf8");
|
||||
} catch (error) {
|
||||
return String(error);
|
||||
}
|
||||
};
|
||||
const [execPath = "", grepVersion = "", findVersion = ""] = read("tools.out").split("\n");
|
||||
return { grep: read("grep.out"), find: read("find.out"), execPath, grepVersion, findVersion };
|
||||
}
|
||||
|
||||
async function fullSmoke(work) {
|
||||
const token = `SMOKE_TOKEN_${process.pid}`;
|
||||
mkdirSync(join(work, "notes"));
|
||||
mkdirSync(join(work, "src"));
|
||||
writeFileSync(join(work, "notes", "alpha.md"), `# Alpha\n\nThe token is ${token}.\n`);
|
||||
writeFileSync(join(work, "notes", "beta.md"), "# Beta\n\nNothing here.\n");
|
||||
writeFileSync(join(work, "src", "gamma.ts"), `export const value = "${token}";\n`);
|
||||
writeFileSync(join(work, "pixel.png"), redPng());
|
||||
|
||||
const toolCalls = new Map();
|
||||
let text = "";
|
||||
const onNotification = (message) => {
|
||||
if (message.method !== "session/update") return;
|
||||
const update = message.params.update;
|
||||
if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
|
||||
text += update.content.text;
|
||||
} else if (
|
||||
update.sessionUpdate === "tool_call" ||
|
||||
update.sessionUpdate === "tool_call_update"
|
||||
) {
|
||||
const call = toolCalls.get(update.toolCallId) ?? {};
|
||||
toolCalls.set(update.toolCallId, {
|
||||
...call,
|
||||
name: update._meta?.claudeCode?.toolName ?? call.name,
|
||||
status: update.status ?? call.status,
|
||||
title: update.title ?? call.title,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const agent = startAgent(work, onNotification);
|
||||
await agent.request("initialize", initializeParams);
|
||||
const created = await agent.request("session/new", { cwd: work, mcpServers: [] });
|
||||
if (!check(created.result?.sessionId, "session/new", JSON.stringify(created.error))) {
|
||||
console.error((await agent.stop()).stderr);
|
||||
return;
|
||||
}
|
||||
const sessionId = created.result.sessionId;
|
||||
|
||||
const started = Date.now();
|
||||
const prompt = await agent.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: [
|
||||
"This is an automated smoke test of your tools. Do each step with the named tool, in order, one tool call per step:",
|
||||
`1. Bash: run exactly \`${searchCommand(token)}\``,
|
||||
"2. Read: read notes/alpha.md.",
|
||||
"3. Read: read pixel.png and note its color.",
|
||||
`4. Edit: in notes/alpha.md replace "${token}" with "EDITED".`,
|
||||
"5. Bash: run `cat notes/alpha.md`.",
|
||||
'6. Agent: launch a subagent (subagent_type "Explore") that counts the .ts files under src/ and reports the number.',
|
||||
"Then reply with one line: SMOKE-DONE color=<the color of pixel.png> tsfiles=<the subagent's count>.",
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
check(
|
||||
prompt.result?.stopReason === "end_turn",
|
||||
"prompt ends with end_turn",
|
||||
JSON.stringify(prompt.result ?? prompt.error),
|
||||
);
|
||||
console.log(` (turn took ${Math.round((Date.now() - started) / 1000)}s)`);
|
||||
|
||||
const calls = [...toolCalls.values()];
|
||||
if (process.env.SMOKE_DEBUG) console.log(JSON.stringify(calls, null, 1));
|
||||
const searched = searchResults(work);
|
||||
check(
|
||||
searched.grep.includes("alpha.md") && searched.grep.includes("gamma.ts"),
|
||||
"grep found the token",
|
||||
searched.grep,
|
||||
);
|
||||
check(
|
||||
searched.find.includes("alpha.md") && searched.find.includes("beta.md"),
|
||||
"find listed the .md files",
|
||||
searched.find,
|
||||
);
|
||||
check(
|
||||
/^ugrep /.test(searched.grepVersion),
|
||||
"grep ran Claude's embedded ugrep",
|
||||
searched.grepVersion,
|
||||
);
|
||||
check(/^bfs /.test(searched.findVersion), "find ran Claude's embedded bfs", searched.findVersion);
|
||||
console.log(` (CLAUDE_CODE_EXECPATH=${searched.execPath})`);
|
||||
for (const name of ["Read", "Edit", "Bash"]) {
|
||||
const used = calls.filter((c) => c.name === name);
|
||||
check(
|
||||
used.length > 0 && used.every((c) => c.status === "completed"),
|
||||
`${name} ran and completed`,
|
||||
JSON.stringify(used),
|
||||
);
|
||||
}
|
||||
const subagent = calls.filter((c) => c.name === "Agent" || c.name === "Task");
|
||||
check(
|
||||
subagent.some((c) => c.status === "completed"),
|
||||
"subagent ran and completed",
|
||||
JSON.stringify(subagent),
|
||||
);
|
||||
const failed = calls.filter((c) => c.status === "failed");
|
||||
check(failed.length === 0, "no tool call failed", JSON.stringify(failed));
|
||||
check(
|
||||
readFileSync(join(work, "notes", "alpha.md"), "utf8").includes("EDITED"),
|
||||
"Edit changed the file on disk",
|
||||
);
|
||||
check(
|
||||
/SMOKE-DONE/.test(text) && /color=\W*red/i.test(text),
|
||||
"image read as red",
|
||||
text.slice(-300),
|
||||
);
|
||||
check(/tsfiles=\W*1\b/.test(text), "subagent counted 1 .ts file", text.slice(-300));
|
||||
|
||||
// A cancel interrupts a running Bash command and ends the turn as cancelled.
|
||||
const cancelled = agent.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{ type: "text", text: "Use the Bash tool to run `sleep 60`. Do not run anything else." },
|
||||
],
|
||||
});
|
||||
const deadline = Date.now() + 60_000;
|
||||
const bashRunning = () =>
|
||||
[...toolCalls.values()].some((c) => c.name === "Bash" && c.status !== "completed");
|
||||
while (!bashRunning() && Date.now() < deadline) {
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
}
|
||||
agent.notify("session/cancel", { sessionId });
|
||||
const cancelResult = await cancelled;
|
||||
check(
|
||||
cancelResult.result?.stopReason === "cancelled",
|
||||
"session/cancel ends the turn as cancelled",
|
||||
JSON.stringify(cancelResult.result ?? cancelResult.error),
|
||||
);
|
||||
|
||||
const listed = await agent.request("session/list", { cwd: work });
|
||||
check(
|
||||
listed.result?.sessions?.some((s) => s.sessionId === sessionId),
|
||||
"session/list finds the session",
|
||||
JSON.stringify(listed.result ?? listed.error),
|
||||
);
|
||||
const { code, stderr } = await agent.stop();
|
||||
check(code === 0, "exits 0 when stdin closes", code);
|
||||
if (failures > 0) console.error(stderr);
|
||||
|
||||
// A fresh process, so the replay comes from the transcript on disk.
|
||||
let replayed = "";
|
||||
const reloaded = startAgent(work, (message) => {
|
||||
const update = message.params?.update;
|
||||
if (update?.sessionUpdate === "user_message_chunk" && update.content.type === "text")
|
||||
replayed += update.content.text;
|
||||
});
|
||||
await reloaded.request("initialize", initializeParams);
|
||||
const loaded = await reloaded.request("session/load", { sessionId, cwd: work, mcpServers: [] });
|
||||
check(!loaded.error, "session/load in a new process", JSON.stringify(loaded.error));
|
||||
check(replayed.includes(token), "session/load replays the first prompt", replayed.slice(0, 200));
|
||||
|
||||
// Fork and delete go through the SDK's transcript helpers, not the CLI.
|
||||
const forked = await reloaded.request("session/fork", { sessionId, cwd: work, mcpServers: [] });
|
||||
const forkId = forked.result?.sessionId;
|
||||
check(
|
||||
forkId && forkId !== sessionId,
|
||||
"session/fork",
|
||||
JSON.stringify(forked.result ?? forked.error),
|
||||
);
|
||||
if (forkId) {
|
||||
const deleted = await reloaded.request("session/delete", { sessionId: forkId });
|
||||
const after = await reloaded.request("session/list", { cwd: work });
|
||||
check(
|
||||
!deleted.error && !after.result?.sessions?.some((s) => s.sessionId === forkId),
|
||||
"session/delete removes the fork",
|
||||
JSON.stringify(deleted.error ?? after.result),
|
||||
);
|
||||
}
|
||||
await reloaded.stop();
|
||||
}
|
||||
|
||||
console.log(failures === 0 ? "\nsmoke test passed" : `\n${failures} check(s) failed`);
|
||||
process.exit(failures === 0 ? 0 : 1);
|
||||
1154
src/acp-agent.ts
1154
src/acp-agent.ts
File diff suppressed because it is too large
Load Diff
@@ -1,43 +0,0 @@
|
||||
import type {
|
||||
CompleteElicitationNotification,
|
||||
CreateElicitationRequest,
|
||||
CreateElicitationResponse,
|
||||
ReadTextFileRequest,
|
||||
ReadTextFileResponse,
|
||||
RequestPermissionResponse,
|
||||
WriteTextFileRequest,
|
||||
WriteTextFileResponse,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { AcpSessionNotification } from "./acp-subagents.js";
|
||||
import type { AcpPermissionRequest } from "./permissions/presentation.js";
|
||||
|
||||
/**
|
||||
* Client-facing surface the agent calls back into. This is the subset of ACP
|
||||
* client methods the agent actually uses, expressed as a narrow interface so
|
||||
* tests can supply lightweight mocks. In the v1 agent it is backed by
|
||||
* `ClientConnection` (`v1/acp-agent.ts`) over the SDK's typed `AgentContext`.
|
||||
* The v2 session output passes one that only takes `sessionUpdate`
|
||||
* (`v2/stream.ts`).
|
||||
*/
|
||||
export interface AcpClient {
|
||||
sessionUpdate(params: AcpSessionNotification): Promise<void>;
|
||||
/** `signal`, when aborted, sends `$/cancel_request` for the in-flight
|
||||
* permission request so the client can dismiss its prompt, and rejects the
|
||||
* call at once: a client that ignores the cancel never answers. */
|
||||
requestPermission(
|
||||
params: AcpPermissionRequest,
|
||||
signal?: AbortSignal,
|
||||
): Promise<RequestPermissionResponse>;
|
||||
readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse>;
|
||||
writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse>;
|
||||
/** `signal`, when aborted, sends `$/cancel_request` for the in-flight
|
||||
* elicitation so the client can dismiss its prompt, and rejects the call
|
||||
* at once, as {@link requestPermission} does. */
|
||||
createElicitation(
|
||||
params: CreateElicitationRequest,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CreateElicitationResponse>;
|
||||
completeElicitation(params: CompleteElicitationNotification): Promise<void>;
|
||||
/** Send a custom (extension) notification, e.g. `_claude/sdkMessage`. */
|
||||
extNotification(method: string, params: Record<string, unknown>): Promise<void>;
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
import type {
|
||||
ClientCapabilities,
|
||||
SessionCapabilities,
|
||||
SessionNotification,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY,
|
||||
clientSupportsAirCapability,
|
||||
isAirClient,
|
||||
} from "./air-extension.js";
|
||||
|
||||
export { AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY } from "./air-extension.js";
|
||||
|
||||
/**
|
||||
* How a client gets native subagent sessions.
|
||||
*
|
||||
* - `rfd`: the subagents RFD (agentclientprotocol/agent-client-protocol#1992,
|
||||
* as revised): `subagent_update` and `session_message`, which the SDK types.
|
||||
* A client that declares `clientCapabilities.subagents` and is not AIR gets
|
||||
* it.
|
||||
* - `air`: the earlier draft of that RFD, which AIR implements:
|
||||
* `subagent_spawned` and `subagent_state_update`, typed below. AIR gets it,
|
||||
* whichever capability it declares (`docs/air-extensions.md`).
|
||||
*/
|
||||
export type SubagentForm = "rfd" | "air";
|
||||
|
||||
/** 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;
|
||||
return isAirClient(capabilities) ? "air" : "rfd";
|
||||
}
|
||||
|
||||
/**
|
||||
* The earlier draft of the subagents RFD, which AIR implements and the SDK
|
||||
* does not type.
|
||||
*/
|
||||
export type SubagentSessionCapabilities = {
|
||||
cancel?: boolean;
|
||||
close?: boolean;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type SubagentSpawnedUpdate = {
|
||||
sessionUpdate: "subagent_spawned";
|
||||
subagentSessionId: string;
|
||||
name: string;
|
||||
task: string;
|
||||
/**
|
||||
* Adapter extension: the exact prompt of the subagent. A client can show it
|
||||
* as the first user message of the subagent session. It is absent when the
|
||||
* adapter does not know the prompt.
|
||||
*/
|
||||
prompt?: string;
|
||||
capabilities: SubagentSessionCapabilities;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type SubagentState = "completed" | "failed" | "cancelled" | "disconnected";
|
||||
|
||||
export type SubagentStateUpdate = {
|
||||
sessionUpdate: "subagent_state_update";
|
||||
subagentSessionId: string;
|
||||
state: SubagentState;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type AsyncTaskState = "running" | "paused" | "completed" | "failed" | "stopped";
|
||||
|
||||
export type AsyncTaskSpawnedUpdate = {
|
||||
sessionUpdate: "async_task_spawned";
|
||||
asyncTaskId: string;
|
||||
name: string;
|
||||
taskType: string;
|
||||
description: string;
|
||||
showInTranscript: boolean;
|
||||
canStop: boolean;
|
||||
outputFilePath?: string;
|
||||
toolCallId?: string;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type AsyncTaskProgressUpdate = {
|
||||
sessionUpdate: "async_task_progress";
|
||||
asyncTaskId: string;
|
||||
description?: string;
|
||||
summary?: string;
|
||||
lastToolName?: string;
|
||||
usage?: { totalTokens: number; toolUses: number; durationMs: number };
|
||||
/** Latest durable task log path. May arrive after spawn. */
|
||||
outputFilePath?: string;
|
||||
/** Originating tool call, when correlation becomes known after spawn. */
|
||||
toolCallId?: string;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type AsyncTaskStateUpdate = {
|
||||
sessionUpdate: "async_task_state_update";
|
||||
asyncTaskId: string;
|
||||
state: AsyncTaskState;
|
||||
summary?: string;
|
||||
/** Latest durable task log path, including terminal-only SDK reports. */
|
||||
outputFilePath?: string;
|
||||
/** Originating tool call, including terminal-only late correlation. */
|
||||
toolCallId?: string;
|
||||
_meta?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export type AcpSessionUpdate =
|
||||
| SessionNotification["update"]
|
||||
| SubagentSpawnedUpdate
|
||||
| SubagentStateUpdate
|
||||
| AsyncTaskSpawnedUpdate
|
||||
| AsyncTaskProgressUpdate
|
||||
| AsyncTaskStateUpdate;
|
||||
|
||||
export type AcpSessionNotification = Omit<SessionNotification, "update"> & {
|
||||
update: AcpSessionUpdate;
|
||||
};
|
||||
|
||||
export type SubagentAwareSessionCapabilities = SessionCapabilities & {
|
||||
subagents?: Record<string, never>;
|
||||
};
|
||||
|
||||
export function clientSupportsSubagents(capabilities?: ClientCapabilities | null): boolean {
|
||||
const subagents = (
|
||||
capabilities as (ClientCapabilities & { subagents?: unknown }) | null | undefined
|
||||
)?.subagents;
|
||||
if (typeof subagents === "object" && subagents !== null && !Array.isArray(subagents)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return clientSupportsAirCapability(capabilities, AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY);
|
||||
}
|
||||
|
||||
/** The cast that AIR's draft updates and the async task updates need. */
|
||||
export function asSdkSessionNotification(
|
||||
notification: AcpSessionNotification,
|
||||
): SessionNotification {
|
||||
return notification as SessionNotification;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* The command that starts this agent again with the flags it was started with,
|
||||
* for a client to run in a terminal (e.g. `terminal-auth` login).
|
||||
*
|
||||
* Under Node, `process.argv` is `[node, script, ...flags]`, so the command is
|
||||
* `node script ...flags`. In a `bun build --compile` executable it is
|
||||
* `["bun", "/$bunfs/root/<name>", ...flags]` (`B:\~BUN\root\<name>` on
|
||||
* Windows): `process.execPath` is the executable itself and `argv[1]` names a
|
||||
* file inside it, which must not be passed back as an argument.
|
||||
*/
|
||||
export function agentCommand(argv: readonly string[] = process.argv): {
|
||||
command: string;
|
||||
args: string[];
|
||||
} {
|
||||
const [, script, ...flags] = argv;
|
||||
if (script === undefined) return { command: process.execPath, args: [] };
|
||||
const compiled = script.includes("$bunfs") || script.includes("~BUN");
|
||||
return { command: process.execPath, args: compiled ? flags : [script, ...flags] };
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
export const AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY = "nativeSubagentSessions";
|
||||
export const AIR_ASYNC_TASKS_CAPABILITY = "asyncTasks";
|
||||
/**
|
||||
* A prompt turn ends at its result also while its background subagents run.
|
||||
* The subagent updates and requests then go out after the prompt response.
|
||||
*/
|
||||
export const AIR_BACKGROUND_SUBAGENTS_CAPABILITY = "backgroundSubagents";
|
||||
export const AIR_SESSION_FAILURE_CAPABILITY = "sessionFailure";
|
||||
export const AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY = "recommendedValue";
|
||||
export const AIR_CUSTOM_INSTRUCTIONS_CAPABILITY = "customInstructions";
|
||||
export const AIR_DIFF_PATCH_CAPABILITY = "diffPatch";
|
||||
/** AIR renders `rawInput` itself and needs no display copy of the input. */
|
||||
export const AIR_RAW_INPUT_RENDERING_CAPABILITY = "rawInputRendering";
|
||||
/**
|
||||
* The plan of an ExitPlanMode is a file. `rawInput.planFilePath` names the
|
||||
* file, and AIR reads the plan from it.
|
||||
*/
|
||||
export const AIR_PLAN_FILE_CAPABILITY = "planFile";
|
||||
/**
|
||||
* The session index: a bounded, ordered `session/list` with row metadata, and
|
||||
* `_session/rename`, `_session/archive`, `_session/unarchive` and the list
|
||||
* subscription. Advertised only to a client that declares it.
|
||||
*/
|
||||
export const AIR_SESSION_INDEX_CAPABILITY = "sessionIndex";
|
||||
/** Metadata lookup of known ids with `_session/batch_get`. Advertised
|
||||
* exactly when {@link AIR_SESSION_INDEX_CAPABILITY} is negotiated. */
|
||||
export const AIR_SESSION_BATCH_GET_CAPABILITY = "sessionBatchGet";
|
||||
/**
|
||||
* The agent supports `_session/archive` and `_session/unarchive`. Advertised
|
||||
* exactly when {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not
|
||||
* declare it.
|
||||
*/
|
||||
export const AIR_SESSION_ARCHIVE_CAPABILITY = "sessionArchive";
|
||||
/**
|
||||
* The agent supports `_session/rename`. Advertised exactly when
|
||||
* {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not declare it.
|
||||
*/
|
||||
export const AIR_SESSION_RENAME_CAPABILITY = "sessionRename";
|
||||
/**
|
||||
* The agent supports `_session/list/subscribe`, `_session/list/unsubscribe`
|
||||
* and `_session/list/changes`. Advertised exactly when
|
||||
* {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not declare it.
|
||||
*/
|
||||
export const AIR_SESSION_LIST_SUBSCRIBE_CAPABILITY = "sessionListSubscribe";
|
||||
/**
|
||||
* Session index rows carry `agentWorktree: true` when the session runs in a
|
||||
* linked git worktree that Claude Code made for it. Advertised exactly when
|
||||
* {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not declare it.
|
||||
*/
|
||||
export const AIR_SESSION_WORKTREES_CAPABILITY = "sessionWorktrees";
|
||||
/**
|
||||
* The client wants to know when the history replay of a loaded session is
|
||||
* whole. After the last replayed update, the agent sends one
|
||||
* `session_info_update` with `_meta.jetbrains.air.loadReplayEnd: true` (see
|
||||
* {@link AIR_LOAD_REPLAY_END_KEY}). The client declares it; the agent does not
|
||||
* advertise it.
|
||||
*/
|
||||
export const AIR_LOAD_REPLAY_END_CAPABILITY = "loadReplayEnd";
|
||||
|
||||
/** The `_meta.jetbrains.air` keys that the ACP tool call contract defines. */
|
||||
export const AIR_COMMAND_TITLE_KEY = "commandTitle";
|
||||
export const AIR_SUBAGENT_KEY = "subagent";
|
||||
export const AIR_SKILL_KEY = "skill";
|
||||
export const AIR_MCP_KEY = "mcp";
|
||||
export const AIR_CONTEXT_COMPACTION_KEY = "contextCompaction";
|
||||
export const AIR_GOAL_KEY = "goal";
|
||||
export const AIR_KIND_KEY = "kind";
|
||||
/** The absolute path of the `SKILL.md` of a skill command in `available_commands_update`. */
|
||||
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 the update that ends a whole history replay. */
|
||||
export const AIR_LOAD_REPLAY_END_KEY = "loadReplayEnd";
|
||||
/**
|
||||
* The root `_meta` spelling of {@link AIR_CUSTOM_ANSWER_KEY} that released
|
||||
* AIR versions read. Remove it when the ACP registry no longer serves AIR
|
||||
* versions that read only this spelling.
|
||||
*/
|
||||
export const LEGACY_AIR_CUSTOM_ANSWER_KEY = "_askUserQuestionCustomAnswer";
|
||||
|
||||
const JETBRAINS_META_KEY = "jetbrains";
|
||||
const AIR_META_KEY = "air";
|
||||
const AIR_EXTENSION_VERSION_KEY = "version";
|
||||
const AIR_EXTENSION_CAPABILITIES_KEY = "capabilities";
|
||||
const AIR_EXTENSION_VERSION = 1;
|
||||
|
||||
/** The capability list this side advertises, as its own `_meta` object. */
|
||||
export function airCapabilityMeta(...capabilities: string[]) {
|
||||
return withAirMeta(undefined, AIR_EXTENSION_CAPABILITIES_KEY, capabilities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges one AIR extension payload into an existing `_meta`.
|
||||
*
|
||||
* Every other namespace is preserved: an update can carry both agent-native
|
||||
* `claudeCode` metadata and an AIR payload, and two AIR payloads can share the
|
||||
* same `air` object. Pass `undefined` to build a fresh `_meta`.
|
||||
*/
|
||||
export function withAirMeta(
|
||||
meta: Record<string, unknown> | null | undefined,
|
||||
capability: string,
|
||||
payload: unknown,
|
||||
): Record<string, unknown> {
|
||||
const jetbrains = asRecord(meta?.[JETBRAINS_META_KEY]);
|
||||
const air = asRecord(jetbrains[AIR_META_KEY]);
|
||||
return {
|
||||
...meta,
|
||||
[JETBRAINS_META_KEY]: {
|
||||
...jetbrains,
|
||||
[AIR_META_KEY]: {
|
||||
...air,
|
||||
[AIR_EXTENSION_VERSION_KEY]: AIR_EXTENSION_VERSION,
|
||||
[capability]: payload,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the client is JetBrains AIR: it declared `_meta.jetbrains.air` in
|
||||
* its capabilities.
|
||||
*
|
||||
* Only AIR gets the AIR extensions of `docs/air-extensions.md`. Every other
|
||||
* client, Zed too, gets the fields and the upstream `_meta` keys of the
|
||||
* upstream adapter, and no key that exists only for AIR.
|
||||
*/
|
||||
export function isAirClient(capabilities: unknown): boolean {
|
||||
return airExtensionMeta(asRecord(capabilities)._meta) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `_meta` of an AIR client with one more AIR payload, or undefined for
|
||||
* every other client: a client that is not AIR gets no AIR key.
|
||||
*/
|
||||
export function airOnlyMeta(
|
||||
airClient: boolean,
|
||||
capability: string,
|
||||
payload: unknown,
|
||||
meta?: Record<string, unknown> | null,
|
||||
): Record<string, unknown> | undefined {
|
||||
return airClient ? withAirMeta(meta, capability, payload) : (meta ?? undefined);
|
||||
}
|
||||
|
||||
/** The `air` object inside a `_meta`, or undefined when the peer sent no AIR extension. */
|
||||
export function airExtensionMeta(meta: unknown): Record<string, unknown> | undefined {
|
||||
const air = asRecord(asRecord(meta)[JETBRAINS_META_KEY])[AIR_META_KEY];
|
||||
return air && typeof air === "object" && !Array.isArray(air)
|
||||
? (air as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the peer advertised `capability`.
|
||||
*
|
||||
* Takes `unknown` because every caller is reading wire data: an ACP
|
||||
* `ClientCapabilities`, or a bag whose `_meta` was never validated.
|
||||
*/
|
||||
export function clientSupportsAirCapability(capabilities: unknown, capability: string): boolean {
|
||||
const air = airExtensionMeta(asRecord(capabilities)._meta);
|
||||
const version = air?.[AIR_EXTENSION_VERSION_KEY];
|
||||
const advertised = air?.[AIR_EXTENSION_CAPABILITIES_KEY];
|
||||
return (
|
||||
typeof version === "number" &&
|
||||
Number.isFinite(version) &&
|
||||
Number.isInteger(version) &&
|
||||
version >= AIR_EXTENSION_VERSION &&
|
||||
Array.isArray(advertised) &&
|
||||
advertised.includes(capability)
|
||||
);
|
||||
}
|
||||
|
||||
/** Read custom instructions from `session/new` metadata. */
|
||||
export function airCustomInstructions(meta: unknown): string | undefined {
|
||||
const air = airExtensionMeta(meta);
|
||||
const instructions = air?.[AIR_CUSTOM_INSTRUCTIONS_CAPABILITY];
|
||||
return typeof instructions === "string" ? instructions : undefined;
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
1152
src/async-tasks.ts
1152
src/async-tasks.ts
File diff suppressed because it is too large
Load Diff
@@ -1,88 +0,0 @@
|
||||
import type { AuthMethod } from "@agentclientprotocol/sdk/unstable";
|
||||
import { agentCommand } from "./agent-command.js";
|
||||
import { shouldHideClaudeAuth } from "./hide-claude-auth.js";
|
||||
|
||||
/**
|
||||
* The terminal login methods the agent advertises, in v1 form.
|
||||
*
|
||||
* - `terminal`: the client runs `args` against the agent's own command
|
||||
* (`auth.terminal` in v1, an `auth.terminal` object in v2).
|
||||
* - `metaTerminal`: the client reads `_meta["terminal-auth"]`, which names
|
||||
* the command too.
|
||||
*
|
||||
* Without either, the client cannot run a login, and the list is empty. On a
|
||||
* remote machine (SSH, `NO_BROWSER`, `CLAUDE_CODE_REMOTE`, as the SDK's own
|
||||
* isRemote check) the OAuth redirect to localhost cannot reach a browser, and
|
||||
* `claude auth login` falls back to a manual flow that does not work over ACP,
|
||||
* so the one method runs the TUI's `claude /login` instead. The Claude
|
||||
* subscription method is left out when `shouldHideClaudeAuth()` says so.
|
||||
*/
|
||||
export function terminalAuthMethods({
|
||||
terminal,
|
||||
metaTerminal,
|
||||
}: {
|
||||
terminal: boolean;
|
||||
metaTerminal: boolean;
|
||||
}): AuthMethod[] {
|
||||
if (!terminal && !metaTerminal) return [];
|
||||
const withMeta = (method: AuthMethod & { args: string[] }, label: string): AuthMethod => {
|
||||
if (!metaTerminal) return method;
|
||||
const agent = agentCommand();
|
||||
return {
|
||||
...method,
|
||||
_meta: {
|
||||
"terminal-auth": { command: agent.command, args: [...agent.args, ...method.args], label },
|
||||
},
|
||||
};
|
||||
};
|
||||
const isRemote = !!(
|
||||
process.env.NO_BROWSER ||
|
||||
process.env.SSH_CONNECTION ||
|
||||
process.env.SSH_CLIENT ||
|
||||
process.env.SSH_TTY ||
|
||||
process.env.CLAUDE_CODE_REMOTE
|
||||
);
|
||||
if (isRemote) {
|
||||
if (shouldHideClaudeAuth()) return [];
|
||||
return [
|
||||
withMeta(
|
||||
{
|
||||
description: "Run `claude /login` in the terminal",
|
||||
name: "Log in with Claude",
|
||||
id: "claude-login",
|
||||
type: "terminal",
|
||||
args: ["--cli"],
|
||||
},
|
||||
"Claude Login",
|
||||
),
|
||||
];
|
||||
}
|
||||
const methods: AuthMethod[] = [];
|
||||
if (!shouldHideClaudeAuth()) {
|
||||
methods.push(
|
||||
withMeta(
|
||||
{
|
||||
description: "Use Claude subscription ",
|
||||
name: "Claude Subscription",
|
||||
id: "claude-ai-login",
|
||||
type: "terminal",
|
||||
args: ["--cli", "auth", "login", "--claudeai"],
|
||||
},
|
||||
"Claude Login",
|
||||
),
|
||||
);
|
||||
}
|
||||
methods.push(
|
||||
withMeta(
|
||||
{
|
||||
description: "Use Anthropic Console (API usage billing)",
|
||||
name: "Anthropic Console",
|
||||
id: "console-login",
|
||||
type: "terminal",
|
||||
args: ["--cli", "auth", "login", "--console"],
|
||||
},
|
||||
"Anthropic Console Login",
|
||||
),
|
||||
);
|
||||
return methods;
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
/**
|
||||
* The connection's `authStatus` state, shared by the v1 core and the v2
|
||||
* core: the last identity it reported, the `claude auth status --json` probe,
|
||||
* and the `_auth/status_update` pushes (see `auth-status.ts` for when each
|
||||
* core reads the identity).
|
||||
*/
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
type AccountInfo,
|
||||
filterEscalatingDefaultMode,
|
||||
type Options,
|
||||
resolveSettings,
|
||||
type Settings,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
AUTH_STATUS_PROBE_TIMEOUT_MS,
|
||||
type AuthStatus,
|
||||
type AuthStatusKind,
|
||||
fromAccountInfo,
|
||||
fromCliStatus,
|
||||
mergeAuthStatus,
|
||||
sameAuthStatus,
|
||||
} from "./auth-status.js";
|
||||
import { claudeCliPath } from "./claude-cli.js";
|
||||
import type { SettingsManager } from "./settings.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
type ReporterLogger = { log: (...args: any[]) => void; error: (...args: any[]) => void };
|
||||
|
||||
/** The settings a probe runs under: a session's cwd, its key helper, and its launch env. */
|
||||
export type AuthStatusSettings = Pick<SettingsManager, "getCwd" | "getApiKeyHelper">;
|
||||
|
||||
export interface AuthStatusReporterOptions {
|
||||
/** Sends `_auth/status_update`. */
|
||||
push: (status: AuthStatus) => Promise<void>;
|
||||
logger: ReporterLogger;
|
||||
/** An ACP gateway login is active: the gateway, not the CLI store, is the identity. */
|
||||
gatewayLogin: () => boolean;
|
||||
/** A `providers/set` override is active: a session account describes its route. */
|
||||
providerOverride: () => boolean;
|
||||
/** A completed probe read `kind`. */
|
||||
onProbe?: (kind: AuthStatusKind) => void;
|
||||
}
|
||||
|
||||
export class AuthStatusReporter {
|
||||
/** Last identity reported to the client. Undefined means "not determined yet". */
|
||||
current?: AuthStatus;
|
||||
/**
|
||||
* Counts auth-affecting events (a login, a logout, a new settings context).
|
||||
* A probe records it at start and publishes only if it has not moved, so a
|
||||
* slow read can never overwrite a newer login or logout.
|
||||
*/
|
||||
epoch = 0;
|
||||
private settings?: {
|
||||
manager: AuthStatusSettings;
|
||||
override?: Settings;
|
||||
env?: Options["env"];
|
||||
};
|
||||
private helper?: string;
|
||||
/** In-flight `claude auth status --json` probe, shared by every caller so
|
||||
* a concurrent `initialize` and start-of-prompt read never spawn two CLI
|
||||
* processes. */
|
||||
private probing: Promise<AuthStatus | undefined> | null = null;
|
||||
/** Keeps the "session account told us nothing" note to one line per process
|
||||
* instead of one per session. */
|
||||
private loggedUninformativeAccount = false;
|
||||
/** Same, for the "client provider override active" note. */
|
||||
private loggedOverriddenAccount = false;
|
||||
/** Same, for the "the CLI probe timed out" warning: a wedged CLI stays wedged
|
||||
* and would otherwise warn once per probe, i.e. once per user prompt. */
|
||||
private loggedProbeTimeout = false;
|
||||
|
||||
constructor(private readonly options: AuthStatusReporterOptions) {}
|
||||
|
||||
/**
|
||||
* Stores `next` and pushes it to the client.
|
||||
*
|
||||
* A push goes out only when the payload changed. The identity is read on many
|
||||
* occasions — each session create, each guarded turn, the start of each user
|
||||
* prompt — and almost all of them see the same login. Clients replace their
|
||||
* whole state on each update and tolerate duplicates, so a repeat is
|
||||
* harmless, but it is also pure noise; {@link sameAuthStatus} drops it.
|
||||
*
|
||||
* What the agent owes is truth — a stale or uninformative source must not
|
||||
* reach here at all (see the epoch check in the probe and the guards at
|
||||
* session create).
|
||||
*/
|
||||
set(next: AuthStatus | undefined): void {
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
if (sameAuthStatus(this.current, next)) {
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/** A login or a logout: any probe already running read the world before it. */
|
||||
changed(): void {
|
||||
this.epoch += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes run under these settings from now on. A new context (cwd, key
|
||||
* helper, or launch env) starts a fresh probe in it.
|
||||
*/
|
||||
useSettings(
|
||||
manager: AuthStatusSettings,
|
||||
settingsOverride?: Settings,
|
||||
launchEnv?: Options["env"],
|
||||
) {
|
||||
const helper = manager.getApiKeyHelper(settingsOverride);
|
||||
const changed =
|
||||
manager.getCwd() !== (this.settings?.manager.getCwd() ?? process.cwd()) ||
|
||||
helper !== this.helper ||
|
||||
JSON.stringify(launchEnv) !== JSON.stringify(this.settings?.env);
|
||||
this.settings = { manager, override: settingsOverride, env: launchEnv };
|
||||
this.helper = helper;
|
||||
if (changed) {
|
||||
// The epoch bump discards any probe that read the old context, and the
|
||||
// session account may carry no identity signal (an apiKeyHelper), so
|
||||
// only a probe in the new context can classify it.
|
||||
this.epoch += 1;
|
||||
void this.probe({ fresh: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report the identity behind a session's `AccountInfo`.
|
||||
*
|
||||
* `AccountInfo` is richer than the CLI probe (it is what the live query
|
||||
* actually authenticates with). The v1 core calls it before the
|
||||
* `--hide-claude-auth` guard may refuse the session or the turn: that flag
|
||||
* blocks the *use* of a subscription, it does not make the state secret, and
|
||||
* a refusal is when the client most needs to know the account it was
|
||||
* refused for.
|
||||
*
|
||||
* Two cases skip it:
|
||||
*
|
||||
* - ACP gateway *authentication*: the gateway, not this account, is the
|
||||
* agent-owned identity — already reported as `kind: "gateway"` by the login.
|
||||
* - A client-driven provider override (`providers/set`): the session then
|
||||
* routes through the client's endpoint and `AccountInfo` describes that
|
||||
* route (e.g. `apiProvider: "gateway"`), which is NOT agent-owned state.
|
||||
* `authStatus` reports the agent's own login only, so the CLI probe —
|
||||
* which reads the credential store the override never touches — stays
|
||||
* authoritative.
|
||||
*
|
||||
* An account with no identity signal (e.g. `{apiProvider: "firstParty"}`
|
||||
* under an apiKeyHelper) means "nothing to add", not "logged out" — keep
|
||||
* what the CLI probe already established instead of overwriting it.
|
||||
*/
|
||||
publishSessionAccount(account: AccountInfo | undefined, apiKeyHelper?: string): void {
|
||||
if (this.options.providerOverride()) {
|
||||
if (!this.loggedOverriddenAccount) {
|
||||
this.loggedOverriddenAccount = true;
|
||||
this.options.logger.log(
|
||||
"[authStatus] client provider override active; keeping agent-owned probe state",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.options.gatewayLogin()) {
|
||||
return;
|
||||
}
|
||||
const fromSession = fromAccountInfo(account, apiKeyHelper);
|
||||
if (fromSession) {
|
||||
this.set(fromSession);
|
||||
} else if (!this.loggedUninformativeAccount) {
|
||||
this.loggedUninformativeAccount = true;
|
||||
this.options.logger.log(
|
||||
"[authStatus] session account carries no identity signal; keeping probe",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Shares one in-flight `claude auth status --json` run between callers. The
|
||||
* promise is released once settled so a later call re-probes instead of
|
||||
* replaying a stale verdict. `fresh` forces a new run even when one is in
|
||||
* flight — `logout` needs a read that started after the credentials were
|
||||
* cleared. */
|
||||
probe(options?: { fresh?: boolean }): Promise<AuthStatus | undefined> {
|
||||
if (!options?.fresh && this.probing) {
|
||||
return this.probing;
|
||||
}
|
||||
const probe = this.runProbe();
|
||||
this.probing = probe;
|
||||
void probe.finally(() => {
|
||||
if (this.probing === probe) {
|
||||
this.probing = null;
|
||||
}
|
||||
});
|
||||
return probe;
|
||||
}
|
||||
|
||||
/** Never rejects: an unavailable CLI means "not reported", not an error. */
|
||||
private async runProbe(): Promise<AuthStatus | undefined> {
|
||||
const { logger } = this.options;
|
||||
// Monotonicity: a read that started before the connection's latest
|
||||
// auth-affecting event describes a world that no longer exists. Remember
|
||||
// which one this read belongs to and drop the answer if it moved on.
|
||||
const epoch = this.epoch;
|
||||
const context = this.settings;
|
||||
const apiKeyHelper = context?.manager.getApiKeyHelper(context.override);
|
||||
// ACP gateway auth bypasses the CLI credential store entirely, so the
|
||||
// probe would report an identity that is not the one being used. A mere
|
||||
// client provider override (`providers/set`) does NOT skip the probe: it
|
||||
// reroutes traffic without touching the credential store, and the store is
|
||||
// exactly the agent-owned login `authStatus` reports.
|
||||
if (this.options.gatewayLogin()) {
|
||||
return this.current;
|
||||
}
|
||||
let stdout: string;
|
||||
try {
|
||||
const cliPath = await claudeCliPath();
|
||||
const args = ["auth", "status", "--json"];
|
||||
// `--settings` is a global CLI option: after the `auth status` subcommand the CLI rejects
|
||||
// it with "unknown option '--settings'", so it has to come first.
|
||||
if (context?.override) args.unshift("--settings", JSON.stringify(context.override));
|
||||
({ stdout } = await execFileAsync(cliPath, args, {
|
||||
timeout: AUTH_STATUS_PROBE_TIMEOUT_MS,
|
||||
cwd: context?.manager.getCwd() ?? process.cwd(),
|
||||
env: context?.env ? { ...process.env, ...context.env } : process.env,
|
||||
}));
|
||||
} catch (error) {
|
||||
const failed = error as { stdout?: unknown; killed?: boolean; signal?: unknown } | null;
|
||||
// Node killed the child on the timeout. Whatever it printed so far is a
|
||||
// truncated fragment, never valid JSON: report nothing and keep the last
|
||||
// known state, so nothing regresses and no push goes out.
|
||||
if (failed?.killed === true && failed.signal) {
|
||||
if (!this.loggedProbeTimeout) {
|
||||
this.loggedProbeTimeout = true;
|
||||
logger.error(
|
||||
"claude auth status did not answer within 5 s; the identity is not refreshed",
|
||||
);
|
||||
}
|
||||
return this.current;
|
||||
}
|
||||
// The logged-out case exits 1 while still printing valid JSON, so the
|
||||
// stdout of a failed exec is parsed just like a successful one.
|
||||
if (typeof failed?.stdout !== "string" || failed.stdout.trim().length === 0) {
|
||||
logger.error(
|
||||
"claude auth status failed:",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
stdout = failed.stdout;
|
||||
}
|
||||
let status = fromCliStatus(stdout, 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);
|
||||
} 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.
|
||||
logger.log("[authStatus] discarding a probe that predates the latest auth change");
|
||||
return this.current;
|
||||
}
|
||||
// The CLI probe can be poorer than the session `AccountInfo` for the very
|
||||
// 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);
|
||||
this.set(merged);
|
||||
this.options.onProbe?.(status.kind);
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `claude auth logout`. The Claude and Console logins keep their
|
||||
* credentials in the CLI's store (keychain or config dir), which only the
|
||||
* binary can clear. The command is non-interactive and idempotent. Throws an
|
||||
* `internal_error` with the CLI's stderr when it fails.
|
||||
*/
|
||||
export async function cliLogout(): Promise<void> {
|
||||
try {
|
||||
const cliPath = await claudeCliPath();
|
||||
await execFileAsync(cliPath, ["auth", "logout"]);
|
||||
} catch (error) {
|
||||
const stderr =
|
||||
typeof error === "object" && error && "stderr" in error
|
||||
? String((error as { stderr: unknown }).stderr).trim()
|
||||
: undefined;
|
||||
throw RequestError.internalError(
|
||||
{ stderr: stderr || undefined },
|
||||
`claude auth logout failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,367 +0,0 @@
|
||||
/**
|
||||
* `authStatus` — interim `_meta`-based ACP extension that reports which auth
|
||||
* identity the agent process itself uses (Claude subscription, API key,
|
||||
* gateway, external cloud credentials, or nothing).
|
||||
*
|
||||
* Push only. One carrier, connection-scoped (never per session): the
|
||||
* notification `_auth/status_update` → `{authStatus}`. The client never asks;
|
||||
* there is no request method. The empty `agentCapabilities._meta.authStatus`
|
||||
* marker means "this agent pushes its identity", nothing more.
|
||||
*
|
||||
* The agent reads the identity at these moments:
|
||||
* - `initialize`, with an asynchronous CLI probe. Nothing waits for it, and its
|
||||
* result is the first push of the connection;
|
||||
* - a completed `authenticate` or a `logout`;
|
||||
* - each `createSession`, from the session account. A refused session reports
|
||||
* too: the client must know which account was refused;
|
||||
* - each turn the `--hide-claude-auth` guard checks. The guard reads the
|
||||
* account anyway, so this costs nothing;
|
||||
* - the START of each user prompt, with an asynchronous CLI probe. This finds a
|
||||
* login or a logout done in another terminal, including the sign-in a client
|
||||
* performs after a refusal, because the retried prompt is a new prompt.
|
||||
* Nothing waits for it and the push goes out mid-turn if that is when the
|
||||
* read lands.
|
||||
*
|
||||
* A probe whose kind differs from a live session's account marks that session
|
||||
* for recreation under `--hide-claude-auth`. The mark is a flag, consumed at
|
||||
* the next turn boundary: a running turn is never interrupted. The probe judges
|
||||
* nothing itself — the next turn runs a new `initialize`, and the creation
|
||||
* guard decides on the account it reports.
|
||||
*
|
||||
* A read does not always cause a push. The agent sends `_auth/status_update`
|
||||
* only when the payload is different from the last one it sent.
|
||||
*
|
||||
* "Cannot determine" is expressed by silence: an agent that cannot read its own
|
||||
* identity pushes nothing, and the client shows "not reported". A known
|
||||
* logged-out state is a payload of its own (`kind: "none"`), which is what
|
||||
* distinguishes the two.
|
||||
*
|
||||
* Reporting only — there is no write path in v1. When the upstream RFD lands,
|
||||
* the same payload moves from `_meta` to first-class fields and this module
|
||||
* is retired.
|
||||
*/
|
||||
|
||||
import type { AccountInfo } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/** Change notification, agent → client. Fire and forget: clients that do not
|
||||
* know the method drop it silently, so it is sent unconditionally. */
|
||||
export const AUTH_STATUS_UPDATE_METHOD = "_auth/status_update";
|
||||
|
||||
/** Upper bound on one `claude auth status --json` run, so a hung CLI cannot
|
||||
* wedge every later probe that joins it. */
|
||||
export const AUTH_STATUS_PROBE_TIMEOUT_MS = 5000;
|
||||
|
||||
export type AuthStatusKind = "account" | "api_key" | "gateway" | "external" | "none";
|
||||
|
||||
export type AuthStatusAccount = {
|
||||
email?: string;
|
||||
organization?: string;
|
||||
/** Vendor plan/license string, not normalized. */
|
||||
plan?: string;
|
||||
};
|
||||
|
||||
export type AuthStatus = {
|
||||
kind: AuthStatusKind;
|
||||
/** Human-readable and usable as a UI string on its own. The "type" line:
|
||||
* "Claude Max", "Anthropic API key", "AWS Bedrock". */
|
||||
label: string;
|
||||
/** Optional second line carrying the specifics (key source, gateway host, …).
|
||||
* Clients render it under `label`, falling back to `account.email`. */
|
||||
detail?: string;
|
||||
account?: AuthStatusAccount;
|
||||
/** Vendor-namespaced extras, e.g. `{claudeCode: {...}}`. */
|
||||
vendor?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type AuthStatusUpdateNotification = { authStatus: AuthStatus };
|
||||
|
||||
/** Advertisement carried in `agentCapabilities._meta.authStatus`, never a
|
||||
* status payload: its mere presence means "this agent pushes its identity",
|
||||
* and it stays empty. Informational — a client that never saw it still
|
||||
* accepts `_auth/status_update`, because there is nothing to ask for. */
|
||||
export type AuthStatusCapability = Record<string, never>;
|
||||
|
||||
export function authStatusCapability(): AuthStatusCapability {
|
||||
return {};
|
||||
}
|
||||
|
||||
/** Shape of `claude auth status --json`. Absent fields are omitted, not null,
|
||||
* and the logged-out case exits 1 while still printing valid JSON. */
|
||||
export type CliAuthStatus = {
|
||||
loggedIn?: boolean;
|
||||
authMethod?: string;
|
||||
apiProvider?: string;
|
||||
apiKeySource?: string;
|
||||
email?: string;
|
||||
orgId?: string;
|
||||
orgName?: string;
|
||||
subscriptionType?: string;
|
||||
};
|
||||
|
||||
const NOT_LOGGED_IN: AuthStatus = {
|
||||
kind: "none",
|
||||
label: "Not logged in",
|
||||
};
|
||||
|
||||
const API_KEY_SOURCE_DETAILS = new Map([
|
||||
["apiKeyHelper", "API key helper"],
|
||||
["env", "env"],
|
||||
["ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY"],
|
||||
["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN"],
|
||||
]);
|
||||
|
||||
/** Display names for the non-firstParty backends, where auth lives outside the
|
||||
* agent (AWS credentials, gcloud ADC, …). */
|
||||
const EXTERNAL_PROVIDER_LABELS: Record<string, string> = {
|
||||
bedrock: "AWS Bedrock",
|
||||
vertex: "Google Vertex AI",
|
||||
foundry: "Azure AI Foundry",
|
||||
anthropicAws: "Anthropic on AWS",
|
||||
anthropicGoogleCloud: "Anthropic on Google Cloud",
|
||||
mantle: "Mantle",
|
||||
};
|
||||
|
||||
export function notLoggedInAuthStatus(): AuthStatus {
|
||||
return { ...NOT_LOGGED_IN };
|
||||
}
|
||||
|
||||
/** ACP-level gateway auth (`authenticate` with `gateway`/`gateway-bedrock`).
|
||||
* The gateway owns the credentials, so it wins over anything the CLI reports. */
|
||||
export function gatewayAuthStatus(baseUrl?: string): AuthStatus {
|
||||
let host: string | undefined;
|
||||
if (baseUrl) {
|
||||
try {
|
||||
host = new URL(baseUrl).host;
|
||||
} catch {
|
||||
host = baseUrl;
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: "gateway",
|
||||
label: "Custom model gateway",
|
||||
...(host ? { detail: host } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this `AccountInfo` say anything about the identity?
|
||||
*
|
||||
* The SDK always fills `apiProvider`, but the identity fields come from the
|
||||
* claude.ai profile: with an `apiKeyHelper` and no subscription login the
|
||||
* session reports `{apiProvider: "firstParty"}` and nothing else. That is "no
|
||||
* information", not "logged out" — an empty read must never be mapped to
|
||||
* `none`, or it destroys what the CLI probe already established.
|
||||
*
|
||||
* `tokenSource` is deliberately not a signal: the CLI sets it to the OAuth
|
||||
* token's origin (`CLAUDE_CODE_OAUTH_TOKEN`,
|
||||
* `CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`, …), never to a key source, so it
|
||||
* cannot attribute a key and carries no plan of its own.
|
||||
*/
|
||||
export function accountInfoHasIdentitySignal(account: AccountInfo | undefined): boolean {
|
||||
if (!account) return false;
|
||||
return Boolean(
|
||||
account.apiKeySource ||
|
||||
account.subscriptionType ||
|
||||
(account.apiProvider && account.apiProvider !== "firstParty"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Session-time mapping from the SDK's `AccountInfo`, the richest source when
|
||||
* it is populated. Returns `undefined` when the account carries no identity
|
||||
* signal, so callers keep the status they already know. */
|
||||
export function fromAccountInfo(
|
||||
account: AccountInfo | undefined,
|
||||
apiKeyHelper?: string,
|
||||
): AuthStatus | undefined {
|
||||
if (!account || !accountInfoHasIdentitySignal(account)) {
|
||||
return undefined;
|
||||
}
|
||||
return mapAuthFields({
|
||||
apiProvider: account.apiProvider,
|
||||
subscriptionType: account.subscriptionType,
|
||||
apiKeySource: account.apiKeySource,
|
||||
email: account.email,
|
||||
organization: account.organization,
|
||||
apiKeyHelper,
|
||||
});
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(stdout);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
const status = parsed as CliAuthStatus;
|
||||
if (typeof status.loggedIn !== "boolean") {
|
||||
return undefined;
|
||||
}
|
||||
// `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.
|
||||
const externalBackend = Boolean(status.apiProvider && status.apiProvider !== "firstParty");
|
||||
if (!externalBackend && !status.loggedIn && !status.apiKeySource) {
|
||||
return notLoggedInAuthStatus();
|
||||
}
|
||||
if (
|
||||
status.loggedIn &&
|
||||
status.authMethod === "oauth_token" &&
|
||||
status.apiProvider === "firstParty" &&
|
||||
!status.apiKeySource &&
|
||||
!status.subscriptionType
|
||||
) {
|
||||
return { kind: "account", label: "Claude subscription", detail: "OAuth token" };
|
||||
}
|
||||
return mapAuthFields({
|
||||
apiProvider: status.apiProvider,
|
||||
subscriptionType: status.subscriptionType,
|
||||
apiKeySource: status.apiKeySource,
|
||||
email: status.email,
|
||||
organization: status.orgName,
|
||||
apiKeyHelper,
|
||||
});
|
||||
}
|
||||
|
||||
/** Single mapping table shared by both sources; see the `kind`/`label` table in
|
||||
* `extension-authstatus-meta.md`. Order matters: a 3P backend or a gateway
|
||||
* decides the kind before any firstParty identity fields are considered, and
|
||||
* an API key outranks a stored subscription login.
|
||||
*
|
||||
* Both can be reported at once — an `apiKeyHelper` in settings.json next to a
|
||||
* claude.ai OAuth login yields `apiKeySource` AND `subscriptionType`. Claude
|
||||
* Code's authentication precedence puts `apiKeyHelper` above the `/login`
|
||||
* subscription, so the key is what actually pays for the turn and is what we
|
||||
* report. */
|
||||
function mapAuthFields(fields: {
|
||||
apiProvider?: string;
|
||||
subscriptionType?: string;
|
||||
apiKeySource?: string;
|
||||
email?: string;
|
||||
organization?: string;
|
||||
apiKeyHelper?: string;
|
||||
}): AuthStatus {
|
||||
const { apiProvider, subscriptionType, apiKeySource, email, organization } = fields;
|
||||
|
||||
if (apiProvider === "gateway") {
|
||||
return gatewayAuthStatus();
|
||||
}
|
||||
if (apiProvider && apiProvider !== "firstParty") {
|
||||
return {
|
||||
kind: "external",
|
||||
label: EXTERNAL_PROVIDER_LABELS[apiProvider] ?? apiProvider,
|
||||
};
|
||||
}
|
||||
if (apiKeySource) {
|
||||
if (
|
||||
apiKeySource === "apiKeyHelper" &&
|
||||
typeof fields.apiKeyHelper === "string" &&
|
||||
/\bcentral\b/i.test(fields.apiKeyHelper) &&
|
||||
/\bproxy\s+start\b/i.test(fields.apiKeyHelper)
|
||||
) {
|
||||
return { kind: "gateway", label: "JetBrains Air Gateway" };
|
||||
}
|
||||
const detail = API_KEY_SOURCE_DETAILS.get(apiKeySource);
|
||||
return {
|
||||
kind: "api_key",
|
||||
label: "Anthropic API key",
|
||||
...(detail ? { detail } : {}),
|
||||
};
|
||||
}
|
||||
if (subscriptionType) {
|
||||
// `account.plan` keeps the raw vendor string; only the label is titled.
|
||||
const account: AuthStatusAccount = { plan: subscriptionType };
|
||||
if (email) account.email = email;
|
||||
if (organization) account.organization = organization;
|
||||
return {
|
||||
kind: "account",
|
||||
label: planLabel(subscriptionType),
|
||||
// No detail: the client falls back to `account.email` for line 2.
|
||||
account,
|
||||
};
|
||||
}
|
||||
return notLoggedInAuthStatus();
|
||||
}
|
||||
|
||||
/** Names the plan with exactly one "Claude". A newer CLI already reports
|
||||
* "Claude Max", an older one reports "max", and both must read "Claude Max".
|
||||
* Each word is title-cased; a word that already carries capitals is kept. */
|
||||
function planLabel(plan: string): string {
|
||||
const titled = plan.replace(/\S+/g, (word) => word.charAt(0).toUpperCase() + word.slice(1));
|
||||
return /^claude(\s|$)/i.test(plan) ? titled : `Claude ${titled}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do two payloads describe the same login? Compared on the field that
|
||||
* identifies each kind — the key source for `api_key`, the email for
|
||||
* `account`, the kind alone for the rest, which carry no per-identity key.
|
||||
*/
|
||||
export function sameIdentity(a: AuthStatus, b: AuthStatus): boolean {
|
||||
if (a.kind !== b.kind) {
|
||||
return false;
|
||||
}
|
||||
switch (a.kind) {
|
||||
case "api_key":
|
||||
return a.detail === b.detail;
|
||||
case "account":
|
||||
return (a.account?.email ?? "") === (b.account?.email ?? "");
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a fresh read into what is already known. Sources differ in richness for
|
||||
* the very same login: the SDK's session `AccountInfo` can carry an
|
||||
* organization the CLI probe omits. So when the read describes the same
|
||||
* identity, its values win field by field but the fields it lacks are kept;
|
||||
* when it describes a different identity, it replaces the old one wholesale.
|
||||
*/
|
||||
export function mergeAuthStatus(previous: AuthStatus | undefined, next: AuthStatus): AuthStatus {
|
||||
if (!previous || !sameIdentity(previous, next)) {
|
||||
return next;
|
||||
}
|
||||
const merged: AuthStatus = { ...next };
|
||||
if (merged.detail === undefined && previous.detail !== undefined) {
|
||||
merged.detail = previous.detail;
|
||||
}
|
||||
if (previous.account || next.account) {
|
||||
merged.account = { ...previous.account, ...next.account };
|
||||
}
|
||||
if (merged.vendor === undefined && previous.vendor !== undefined) {
|
||||
merged.vendor = previous.vendor;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do two payloads carry the same information? Unlike {@link sameIdentity},
|
||||
* which asks "is this the same login", this compares every rendered field, so
|
||||
* a richer read of one login is NOT the same. Callers use it to suppress a
|
||||
* push that would tell the client nothing new.
|
||||
*
|
||||
* `a` undefined means "nothing reported yet", which never equals a payload.
|
||||
*/
|
||||
export function sameAuthStatus(a: AuthStatus | undefined, b: AuthStatus): boolean {
|
||||
if (!a) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
a.kind === b.kind &&
|
||||
a.label === b.label &&
|
||||
a.detail === b.detail &&
|
||||
a.account?.email === b.account?.email &&
|
||||
a.account?.organization === b.account?.organization &&
|
||||
a.account?.plan === b.account?.plan &&
|
||||
// Vendor extras are an open bag, so compare them structurally. Both sides
|
||||
// are built by this module from the same key order, so a string compare is
|
||||
// enough and costs nothing on the usual `undefined`/`undefined` pair.
|
||||
JSON.stringify(a.vendor) === JSON.stringify(b.vendor)
|
||||
);
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* The output of a command that went to the background, read from the file
|
||||
* that Claude Code writes it to. Claude Code streams no output of such a
|
||||
* command, so its display terminal would show only the placeholder of the
|
||||
* Bash result ("Command running in background with ID …") until the command
|
||||
* exits. ACP v2 asks an Agent to keep a listed terminal's output current
|
||||
* whenever it can read it (the v2 prompt lifecycle, "Background work").
|
||||
*
|
||||
* The file is polled: watching a file is not reliable on every platform, and
|
||||
* a missing file only means that nothing was written yet.
|
||||
*/
|
||||
import { open } from "node:fs/promises";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
|
||||
/** How often a running command's output file is read. */
|
||||
export const BACKGROUND_OUTPUT_POLL_MS = 500;
|
||||
|
||||
/** The most bytes one read takes, so a burst of output does not block the loop. */
|
||||
export const BACKGROUND_OUTPUT_READ_BYTES = 256 * 1024;
|
||||
|
||||
/**
|
||||
* The most unread bytes that are still sent. A command that writes faster
|
||||
* than the polls read falls behind. Past this, the reads skip to the file's
|
||||
* last bytes, as a snapshot: a terminal shows the latest output, and a
|
||||
* client keeps a bounded amount of it anyway.
|
||||
*/
|
||||
export const BACKGROUND_OUTPUT_MAX_BACKLOG_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Text that the file adds. A snapshot replaces the terminal's output so far:
|
||||
* the first one replaces the placeholder of the Bash result, and a later one
|
||||
* follows a skip or a file that shrank. Other text appends to it.
|
||||
*/
|
||||
export type BackgroundOutput = { text: string; replaces: boolean };
|
||||
|
||||
/**
|
||||
* Follows the output file `path` of one background command and hands each
|
||||
* piece of new text to `publish`, in order. Reads never overlap. A read that
|
||||
* fails, for example because the file does not exist yet, is tried again at
|
||||
* the next poll. `publish` must not reject: the next read waits for it.
|
||||
*/
|
||||
export class BackgroundOutputTail {
|
||||
private offset = 0;
|
||||
private decoder = new StringDecoder("utf8");
|
||||
/** Whether the next text replaces the terminal's output. */
|
||||
private replaces = true;
|
||||
private stopped = false;
|
||||
private reading: Promise<void> = Promise.resolve();
|
||||
private readonly timer: ReturnType<typeof setInterval>;
|
||||
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
private readonly publish: (output: BackgroundOutput) => Promise<void>,
|
||||
) {
|
||||
this.timer = setInterval(() => void this.read(false), BACKGROUND_OUTPUT_POLL_MS);
|
||||
// A command that runs on must not keep the agent process alive.
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the rest of the file and stops. The command ended, so what the file
|
||||
* holds is its whole output, and it goes out before the terminal's exit.
|
||||
*/
|
||||
async finish(): Promise<void> {
|
||||
clearInterval(this.timer);
|
||||
await this.read(true);
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
/** Stops without reading more: the session ended. */
|
||||
stop(): void {
|
||||
clearInterval(this.timer);
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads what the file adds, one read of at most
|
||||
* {@link BACKGROUND_OUTPUT_READ_BYTES} at a time, and publishes each read's
|
||||
* text before the next. `toEnd` reads until the end of the file, and ends a
|
||||
* character that the command cut off with a replacement character.
|
||||
*/
|
||||
private read(toEnd: boolean): Promise<void> {
|
||||
this.reading = this.reading.then(async () => {
|
||||
if (this.stopped) return;
|
||||
let file;
|
||||
try {
|
||||
file = await open(this.path, "r");
|
||||
} catch {
|
||||
// Nothing written yet, or the file is gone: try again at the next
|
||||
// poll. At the end, the terminal keeps the output it has.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
// A file that shrank is a new one: its output starts over. Past the
|
||||
// backlog, the reads skip to the file's last bytes.
|
||||
const start = size < this.offset ? 0 : this.offset;
|
||||
const skipTo = Math.max(start, size - BACKGROUND_OUTPUT_MAX_BACKLOG_BYTES);
|
||||
if (skipTo !== this.offset) {
|
||||
this.offset = skipTo;
|
||||
this.decoder = new StringDecoder("utf8");
|
||||
this.replaces = true;
|
||||
}
|
||||
const buffer = Buffer.alloc(BACKGROUND_OUTPUT_READ_BYTES);
|
||||
let bytesRead: number;
|
||||
do {
|
||||
({ bytesRead } = await file.read(buffer, 0, buffer.length, this.offset));
|
||||
this.offset += bytesRead;
|
||||
const text = this.decoder.write(buffer.subarray(0, bytesRead));
|
||||
if (text !== "") await this.send(text);
|
||||
} while (toEnd && bytesRead > 0);
|
||||
if (toEnd) {
|
||||
const rest = this.decoder.end();
|
||||
// A command that wrote nothing still replaces the placeholder.
|
||||
if (rest !== "" || this.replaces) await this.send(rest);
|
||||
}
|
||||
} catch {
|
||||
// The read failed: try again at the next poll.
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
});
|
||||
return this.reading;
|
||||
}
|
||||
|
||||
private async send(text: string): Promise<void> {
|
||||
const replaces = this.replaces;
|
||||
this.replaces = false;
|
||||
await this.publish({ text, replaces });
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Entry of the release executable (`scripts/build-binary.mjs`). It registers the
|
||||
// Claude CLI shipped next to the executable before importing the agent:
|
||||
// index.ts starts serving (or, with --cli, spawns the CLI) while it evaluates,
|
||||
// and a static import would evaluate it before this module's body runs.
|
||||
import { realpathSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { useBundledClaudeCli } from "./claude-cli.js";
|
||||
|
||||
// realpath, so a symlink to the executable (e.g. in /usr/local/bin) still finds
|
||||
// the CLI next to the real file.
|
||||
useBundledClaudeCli(dirname(realpathSync(process.execPath)));
|
||||
await import("./index.js");
|
||||
@@ -1,125 +0,0 @@
|
||||
/**
|
||||
* Embedded `resource` prompt blocks whose resource is a base64 `blob`, and the
|
||||
* Claude content each supported MIME type becomes.
|
||||
*/
|
||||
import type { BlobResourceContents } from "@agentclientprotocol/sdk/unstable";
|
||||
|
||||
/** Image types the Messages API accepts as a base64 `image` block. */
|
||||
const IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"] as const;
|
||||
type ImageMimeType = (typeof IMAGE_MIME_TYPES)[number];
|
||||
|
||||
/** Non-`text/*` types whose bytes are text, e.g. a `.json` or `.ts` file. */
|
||||
const TEXT_APPLICATION_MIME_TYPES = new Set([
|
||||
"application/json",
|
||||
"application/xml",
|
||||
"application/javascript",
|
||||
"application/typescript",
|
||||
"application/x-yaml",
|
||||
"application/yaml",
|
||||
"application/toml",
|
||||
"application/x-sh",
|
||||
"application/sql",
|
||||
"application/graphql",
|
||||
]);
|
||||
|
||||
export type BlobResourceContent =
|
||||
| {
|
||||
kind: "image";
|
||||
block: {
|
||||
type: "image";
|
||||
source: { type: "base64"; media_type: ImageMimeType; data: string };
|
||||
};
|
||||
}
|
||||
| {
|
||||
kind: "document";
|
||||
block: {
|
||||
type: "document";
|
||||
source: { type: "base64"; media_type: "application/pdf"; data: string };
|
||||
};
|
||||
}
|
||||
/** The decoded text, to send like a text resource. */
|
||||
| { kind: "text"; text: string };
|
||||
|
||||
/**
|
||||
* The MIME type without parameters or case, e.g. `text/plain; charset=utf-8` ->
|
||||
* `text/plain`. `image/jpg`, which some clients send, becomes `image/jpeg`.
|
||||
*/
|
||||
function baseMimeType(mimeType: string | null | undefined): string | undefined {
|
||||
const base = mimeType?.split(";")[0].trim().toLowerCase();
|
||||
if (base === "image/jpg") return "image/jpeg";
|
||||
return base || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a text blob with the `charset` parameter of its MIME type, e.g.
|
||||
* `text/csv; charset=iso-8859-1`, and UTF-8 when there is none or the label is
|
||||
* unknown. A leading byte order mark is dropped.
|
||||
*/
|
||||
function decodeText(blob: string, mimeType: string | null | undefined): string {
|
||||
const charset = /;\s*charset\s*=\s*"?([^";\s]+)/i.exec(mimeType ?? "")?.[1];
|
||||
let decoder: TextDecoder;
|
||||
try {
|
||||
decoder = new TextDecoder(charset ?? "utf-8");
|
||||
} catch {
|
||||
decoder = new TextDecoder("utf-8");
|
||||
}
|
||||
return decoder.decode(Buffer.from(blob, "base64"));
|
||||
}
|
||||
|
||||
function isImageMimeType(mimeType: string): mimeType is ImageMimeType {
|
||||
return (IMAGE_MIME_TYPES as readonly string[]).includes(mimeType);
|
||||
}
|
||||
|
||||
function isTextMimeType(mimeType: string): boolean {
|
||||
return (
|
||||
mimeType.startsWith("text/") ||
|
||||
TEXT_APPLICATION_MIME_TYPES.has(mimeType) ||
|
||||
mimeType.endsWith("+json") ||
|
||||
mimeType.endsWith("+xml")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@link blobResourceToClaude} can send a blob of this MIME type. A blob
|
||||
* without a MIME type is not supported: its bytes could be anything.
|
||||
*/
|
||||
export function isSupportedBlobMimeType(mimeType: string | null | undefined): boolean {
|
||||
const base = baseMimeType(mimeType);
|
||||
if (!base) return false;
|
||||
return isImageMimeType(base) || base === "application/pdf" || isTextMimeType(base);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Claude content for a blob resource: an `image` block for PNG, JPEG, GIF
|
||||
* and WebP, a `document` block for PDF, and the decoded text for text
|
||||
* types such as `text/markdown` or `application/json`. Returns `undefined` for
|
||||
* any other type, e.g. `application/zip`.
|
||||
*/
|
||||
export function blobResourceToClaude(
|
||||
resource: BlobResourceContents,
|
||||
): BlobResourceContent | undefined {
|
||||
const mimeType = baseMimeType(resource.mimeType);
|
||||
if (!mimeType) return undefined;
|
||||
if (isImageMimeType(mimeType)) {
|
||||
return {
|
||||
kind: "image",
|
||||
block: {
|
||||
type: "image",
|
||||
source: { type: "base64", media_type: mimeType, data: resource.blob },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (mimeType === "application/pdf") {
|
||||
return {
|
||||
kind: "document",
|
||||
block: {
|
||||
type: "document",
|
||||
source: { type: "base64", media_type: "application/pdf", data: resource.blob },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (isTextMimeType(mimeType)) {
|
||||
return { kind: "text", text: decodeText(resource.blob, resource.mimeType) };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const CLI_FILE_NAME = process.platform === "win32" ? "claude.exe" : "claude";
|
||||
|
||||
let bundledCliDirectory: string | undefined;
|
||||
|
||||
/**
|
||||
* Called by the executable's entry (`src/binary-entry.ts`) before the agent
|
||||
* starts. A `bun build --compile` executable has no `node_modules` to resolve
|
||||
* the SDK's platform package from, so the release archive ships the Claude CLI
|
||||
* next to it. The CLI isn't embedded: a child process can't run a file inside
|
||||
* Bun's `$bunfs`, so an embedded copy would have to be extracted to disk first.
|
||||
*/
|
||||
export function useBundledClaudeCli(directory: string): void {
|
||||
bundledCliDirectory = directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Claude CLI binary to spawn: `CLAUDE_CODE_EXECUTABLE` if set, then the CLI
|
||||
* shipped next to the executable, then the SDK's platform-specific package.
|
||||
*/
|
||||
export async function claudeCliPath(): Promise<string> {
|
||||
if (process.env.CLAUDE_CODE_EXECUTABLE) {
|
||||
return process.env.CLAUDE_CODE_EXECUTABLE;
|
||||
}
|
||||
if (bundledCliDirectory !== undefined) {
|
||||
return bundledClaudeCliPath(bundledCliDirectory);
|
||||
}
|
||||
return installedClaudeCliPath();
|
||||
}
|
||||
|
||||
function bundledClaudeCliPath(directory: string): string {
|
||||
const path = join(directory, CLI_FILE_NAME);
|
||||
// Without this check, spawning a missing CLI fails with a bare ENOENT.
|
||||
if (!existsSync(path)) {
|
||||
throw new Error(
|
||||
`The Claude CLI is missing: expected ${path}. Keep ${CLI_FILE_NAME} from the release archive ` +
|
||||
"in the same directory as claude-agent-acp, or set CLAUDE_CODE_EXECUTABLE to a Claude CLI binary.",
|
||||
);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
async function installedClaudeCliPath(): Promise<string> {
|
||||
// The SDK's CLI is a native binary shipped as a platform-specific optional
|
||||
// dependency of @anthropic-ai/claude-agent-sdk. Resolve via a require bound
|
||||
// to the SDK so nested installs are found even when npm doesn't hoist.
|
||||
const { createRequire } = await import("node:module");
|
||||
const req = createRequire(import.meta.resolve("@anthropic-ai/claude-agent-sdk"));
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
// On linux, both glibc and musl variants may be installed side-by-side
|
||||
// (e.g. bunx hydrates every optional dep), so picking one by trial is
|
||||
// unreliable: the wrong binary segfaults at runtime instead of failing to
|
||||
// spawn. Detect the runtime libc and prefer the matching variant, falling
|
||||
// back to the other only if the preferred one isn't installed.
|
||||
const candidates =
|
||||
process.platform === "linux"
|
||||
? isMuslLibc()
|
||||
? [
|
||||
`@anthropic-ai/claude-agent-sdk-linux-${process.arch}-musl/claude${ext}`,
|
||||
`@anthropic-ai/claude-agent-sdk-linux-${process.arch}/claude${ext}`,
|
||||
]
|
||||
: [
|
||||
`@anthropic-ai/claude-agent-sdk-linux-${process.arch}/claude${ext}`,
|
||||
`@anthropic-ai/claude-agent-sdk-linux-${process.arch}-musl/claude${ext}`,
|
||||
]
|
||||
: [`@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}/claude${ext}`];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
return req.resolve(candidate);
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`Claude native binary not found for ${process.platform}-${process.arch}. ` +
|
||||
`Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set CLAUDE_CODE_EXECUTABLE.`,
|
||||
);
|
||||
}
|
||||
|
||||
function isMuslLibc(): boolean {
|
||||
// process.report.getReport().header.glibcVersionRuntime is populated when
|
||||
// Node is dynamically linked against glibc, and absent on musl.
|
||||
const report = process.report?.getReport() as
|
||||
{ header?: { glibcVersionRuntime?: string } } | undefined;
|
||||
return !report?.header?.glibcVersionRuntime;
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
import type { NewSessionRequest, SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
EffortLevel,
|
||||
Options,
|
||||
PermissionMode,
|
||||
SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { DEFAULT_AGENT_ID, DEFAULT_MODEL_ID } from "./session-config-ids.js";
|
||||
|
||||
export type ClearContextReset = {
|
||||
toolUseId: string;
|
||||
plan: string;
|
||||
mode: PermissionMode;
|
||||
};
|
||||
|
||||
type Usage = {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
cachedReadTokens: number;
|
||||
cachedWriteTokens: number;
|
||||
};
|
||||
|
||||
export type ClearContextTurn = {
|
||||
settled: boolean;
|
||||
promptUuid: string;
|
||||
carriedUsage?: Usage;
|
||||
carriedModelUsage?: Record<string, Usage>;
|
||||
};
|
||||
|
||||
/** The session state needed to replace Claude's private conversation without
|
||||
* replacing the public ACP turn. Keeping this projection here makes the
|
||||
* restart workflow independent from the agent's much larger Session record. */
|
||||
export type ClearContextSession<Turn extends ClearContextTurn = ClearContextTurn> = {
|
||||
cwd: string;
|
||||
creationParams?: NewSessionRequest;
|
||||
accumulatedUsage: Usage;
|
||||
accumulatedModelUsage?: Record<string, Usage>;
|
||||
models: { currentModelId: string };
|
||||
configOptions: SessionConfigOption[];
|
||||
currentAgent: string;
|
||||
fastModeEnabled: boolean;
|
||||
ultracodeEnabled: boolean;
|
||||
effortPinnedLevel?: string;
|
||||
activeTurn?: Turn | null;
|
||||
turnQueue?: Turn[];
|
||||
pendingExitPlanContextReset?: ClearContextReset;
|
||||
contextUsedTokens?: number;
|
||||
contextWindowSize: number;
|
||||
sentUserUuids?: Set<string>;
|
||||
input: { push(message: SDKUserMessage): unknown };
|
||||
};
|
||||
|
||||
export type ClearContextCoordinatorHost<
|
||||
Session extends ClearContextSession<Turn>,
|
||||
Turn extends ClearContextTurn,
|
||||
> = {
|
||||
currentSession(sessionId: string): Session | undefined;
|
||||
closeQueryStream(session: Session): void;
|
||||
restartSession(
|
||||
params: NewSessionRequest,
|
||||
options: { publicSessionId: string; permissionMode: PermissionMode },
|
||||
): Promise<Session>;
|
||||
applyFastMode(session: Session, enabled: boolean): Promise<void>;
|
||||
applyUltracode(session: Session, enabled: boolean): Promise<void>;
|
||||
/** Publishes the fresh context's mode, config options, and usage: the
|
||||
* context starts empty in a window of `contextWindowSize` tokens. */
|
||||
publishSessionState(
|
||||
sessionId: string,
|
||||
mode: PermissionMode,
|
||||
configOptions: SessionConfigOption[],
|
||||
contextWindowSize: number,
|
||||
): Promise<void>;
|
||||
continuationMessage(sessionId: string, plan: string, promptUuid: string): SDKUserMessage;
|
||||
ensureConsumer(session: Session, sessionId: string): void;
|
||||
logError(message: string, error: unknown): void;
|
||||
};
|
||||
|
||||
function restartParams<Session extends ClearContextSession>(session: Session): NewSessionRequest {
|
||||
const originalParams = session.creationParams ?? { cwd: session.cwd, mcpServers: [] };
|
||||
const originalMeta = originalParams._meta as
|
||||
({ claudeCode?: { options?: Options } } & Record<string, unknown>) | undefined;
|
||||
const originalOptions = originalMeta?.claudeCode?.options;
|
||||
const unmanagedOptions = { ...(originalOptions ?? {}) };
|
||||
delete unmanagedOptions.model;
|
||||
delete unmanagedOptions.agent;
|
||||
delete unmanagedOptions.effort;
|
||||
|
||||
return {
|
||||
...originalParams,
|
||||
_meta: {
|
||||
...(originalMeta ?? {}),
|
||||
claudeCode: {
|
||||
...(originalMeta?.claudeCode ?? {}),
|
||||
options: {
|
||||
...unmanagedOptions,
|
||||
...(session.models.currentModelId !== DEFAULT_MODEL_ID
|
||||
? { model: session.models.currentModelId }
|
||||
: {}),
|
||||
...(session.currentAgent !== DEFAULT_AGENT_ID ? { agent: session.currentAgent } : {}),
|
||||
...(session.effortPinnedLevel !== undefined
|
||||
? { effort: session.effortPinnedLevel as EffortLevel }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace Claude's private conversation and attach the still-pending ACP turn
|
||||
* to it. The host owns provider-specific creation and stream mechanics; this
|
||||
* coordinator owns the ordering and state transfer invariants. */
|
||||
export async function continuePlanInFreshContext<
|
||||
Turn extends ClearContextTurn,
|
||||
Session extends ClearContextSession<Turn>,
|
||||
>(
|
||||
sessionId: string,
|
||||
oldSession: Session,
|
||||
reset: ClearContextReset,
|
||||
host: ClearContextCoordinatorHost<Session, Turn>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const assertRestartActive = (session?: Session): void => {
|
||||
if (signal?.aborted || (session && host.currentSession(sessionId) !== session)) {
|
||||
throw new Error("Clear-context restart aborted");
|
||||
}
|
||||
};
|
||||
assertRestartActive();
|
||||
const turn = oldSession.activeTurn;
|
||||
if (!turn || turn.settled || host.currentSession(sessionId) !== oldSession) {
|
||||
throw new Error("Cannot clear context without an active ACP turn");
|
||||
}
|
||||
|
||||
const params = restartParams(oldSession);
|
||||
host.closeQueryStream(oldSession);
|
||||
|
||||
const freshSession = await host.restartSession(params, {
|
||||
publicSessionId: sessionId,
|
||||
permissionMode: reset.mode,
|
||||
});
|
||||
assertRestartActive(freshSession);
|
||||
|
||||
// Do not consume the reset or mutate the turn until a replacement exists.
|
||||
// A failed restart must remain distinguishable from a lost query transport.
|
||||
turn.carriedUsage = { ...oldSession.accumulatedUsage };
|
||||
turn.carriedModelUsage = { ...oldSession.accumulatedModelUsage };
|
||||
oldSession.pendingExitPlanContextReset = undefined;
|
||||
if (oldSession.fastModeEnabled !== freshSession.fastModeEnabled) {
|
||||
try {
|
||||
await host.applyFastMode(freshSession, oldSession.fastModeEnabled);
|
||||
} catch (error) {
|
||||
host.logError("Failed to restore Fast mode after clearing context:", error);
|
||||
}
|
||||
assertRestartActive(freshSession);
|
||||
}
|
||||
// The fresh query seeds ultracode from settings only, so a toggle made
|
||||
// during the old session would otherwise be lost.
|
||||
if (oldSession.ultracodeEnabled !== freshSession.ultracodeEnabled) {
|
||||
try {
|
||||
await host.applyUltracode(freshSession, oldSession.ultracodeEnabled);
|
||||
} catch (error) {
|
||||
host.logError("Failed to restore ultracode after clearing context:", error);
|
||||
}
|
||||
assertRestartActive(freshSession);
|
||||
}
|
||||
|
||||
oldSession.activeTurn = null;
|
||||
oldSession.turnQueue = [];
|
||||
freshSession.turnQueue = [turn];
|
||||
freshSession.contextUsedTokens = 0;
|
||||
|
||||
try {
|
||||
await host.publishSessionState(
|
||||
sessionId,
|
||||
reset.mode,
|
||||
freshSession.configOptions,
|
||||
freshSession.contextWindowSize,
|
||||
);
|
||||
} catch (error) {
|
||||
host.logError("Failed to publish clear-context session state:", error);
|
||||
}
|
||||
assertRestartActive(freshSession);
|
||||
|
||||
(freshSession.sentUserUuids ??= new Set()).add(turn.promptUuid);
|
||||
freshSession.input.push(host.continuationMessage(sessionId, reset.plan, turn.promptUuid));
|
||||
assertRestartActive(freshSession);
|
||||
host.ensureConsumer(freshSession, sessionId);
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* The client-provided system prompt of the unstable `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
|
||||
* SDK's `{ type: "preset", preset: "claude_code", append }`.
|
||||
* - `override` replaces the Claude Code preset with the text, the SDK's custom
|
||||
* string prompt. Tools, MCP servers, permissions, and settings (including the
|
||||
* CLAUDE.md files that `settingSources` loads) are unchanged.
|
||||
*
|
||||
* 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
|
||||
* deferral.
|
||||
*/
|
||||
import type { Options } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
RequestError,
|
||||
type SessionCapabilities,
|
||||
type SystemPrompt,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
|
||||
/** The `sessionCapabilities.systemPrompt` the agent advertises: both modes. */
|
||||
export const SYSTEM_PROMPT_CAPABILITY = {
|
||||
mode: { override: {} },
|
||||
} satisfies NonNullable<SessionCapabilities["systemPrompt"]>;
|
||||
|
||||
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.
|
||||
*/
|
||||
export function clientSystemPrompt(
|
||||
systemPrompt: SystemPrompt | null | undefined,
|
||||
): ClientSystemPrompt | undefined {
|
||||
if (systemPrompt == null) return undefined;
|
||||
const { mode, content } = systemPrompt;
|
||||
if (mode !== "append" && mode !== "override") {
|
||||
throw RequestError.invalidParams(
|
||||
{ systemPrompt: { mode } },
|
||||
`Unsupported systemPrompt mode: ${mode}`,
|
||||
);
|
||||
}
|
||||
const text: string[] = [];
|
||||
for (const block of content) {
|
||||
if (block.type !== "text") {
|
||||
throw RequestError.invalidParams(
|
||||
{ systemPrompt: { content: { type: block.type } } },
|
||||
`systemPrompt content must be text, but received a ${block.type} block`,
|
||||
);
|
||||
}
|
||||
text.push(block.text);
|
||||
}
|
||||
return { mode, text: text.join("\n\n") };
|
||||
}
|
||||
|
||||
/**
|
||||
* The SDK `systemPrompt` option for a client system prompt. `customInstructions`
|
||||
* (AIR's `customInstructions` on `session/new` metadata) still follows the
|
||||
* client text in both modes.
|
||||
*/
|
||||
export function sdkSystemPrompt(
|
||||
prompt: ClientSystemPrompt,
|
||||
customInstructions: string | undefined,
|
||||
): NonNullable<Options["systemPrompt"]> {
|
||||
const text = [prompt.text, customInstructions].filter((part) => part).join("\n\n");
|
||||
if (prompt.mode === "override") return text;
|
||||
return text
|
||||
? { type: "preset", preset: "claude_code", append: text }
|
||||
: { type: "preset", preset: "claude_code" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The SDK `systemPrompt` of a session: the spec's `systemPrompt`
|
||||
* (`clientPrompt`), else the `_meta.systemPrompt` extension (`metaPrompt`), a
|
||||
* string that replaces the preset or an object of preset options, else the
|
||||
* Claude Code preset. `customInstructions` are appended to the preset.
|
||||
*/
|
||||
export function sessionSystemPrompt(
|
||||
clientPrompt: ClientSystemPrompt | undefined,
|
||||
metaPrompt: unknown,
|
||||
customInstructions?: string,
|
||||
): NonNullable<Options["systemPrompt"]> {
|
||||
if (clientPrompt) return sdkSystemPrompt(clientPrompt, customInstructions);
|
||||
if (typeof metaPrompt === "string" && metaPrompt) return metaPrompt;
|
||||
if (typeof metaPrompt === "object" && metaPrompt !== null && !Array.isArray(metaPrompt)) {
|
||||
// Forward all preset options (append, excludeDynamicSections, and
|
||||
// anything the SDK adds later) while locking type/preset.
|
||||
return {
|
||||
...(metaPrompt as object),
|
||||
type: "preset",
|
||||
preset: "claude_code",
|
||||
} as NonNullable<Options["systemPrompt"]>;
|
||||
}
|
||||
return customInstructions === undefined
|
||||
? { type: "preset", preset: "claude_code" }
|
||||
: { type: "preset", preset: "claude_code", append: customInstructions };
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { AIR_CONTEXT_COMPACTION_KEY, withAirMeta } from "./air-extension.js";
|
||||
|
||||
export const CONTEXT_COMPACTION_META_VERSION = 1;
|
||||
|
||||
export type ContextCompactionTrigger = "manual" | "automatic" | "idle";
|
||||
|
||||
export interface ContextCompactionMetadata {
|
||||
version: typeof CONTEXT_COMPACTION_META_VERSION;
|
||||
trigger?: ContextCompactionTrigger;
|
||||
preTokens?: number;
|
||||
postTokens?: number;
|
||||
durationMs?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `_meta` of a context compaction report:
|
||||
* `_meta.jetbrains.air.contextCompaction`, as `docs/air-extensions.md`
|
||||
* defines. The standard toolCallId and status fields own lifecycle identity
|
||||
* and phase; this extension carries only compaction-specific facts. Only AIR
|
||||
* gets it.
|
||||
*/
|
||||
export function createContextCompactionMeta(
|
||||
metadata: Omit<ContextCompactionMetadata, "version"> = {},
|
||||
): Record<string, unknown> {
|
||||
return withAirMeta(undefined, AIR_CONTEXT_COMPACTION_KEY, {
|
||||
version: CONTEXT_COMPACTION_META_VERSION,
|
||||
...metadata,
|
||||
} satisfies ContextCompactionMetadata);
|
||||
}
|
||||
@@ -1,474 +0,0 @@
|
||||
import { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
ContextCompactionMetadata,
|
||||
ContextCompactionTrigger,
|
||||
createContextCompactionMeta,
|
||||
} from "./context-compaction-meta.js";
|
||||
import { assistantMessageText } from "./session-failure-extension.js";
|
||||
import { compactionToolCall } from "./tool-calls/reporters/compaction.js";
|
||||
|
||||
type CompactionStatus = "completed" | "failed";
|
||||
type TerminalStatus = CompactionStatus | "cancelled";
|
||||
|
||||
/**
|
||||
* How compaction reaches the client.
|
||||
*
|
||||
* - `compaction_update`: the ACP session-compaction contract (ID-addressed
|
||||
* `compaction_update` / `compaction_summary_chunk`), used when the v1 client
|
||||
* advertises `clientCapabilities.session.compaction`.
|
||||
* - `tool_call`: the legacy synthetic "Compact conversation" tool call, kept
|
||||
* for clients that do not advertise the capability.
|
||||
*/
|
||||
export type CompactionPresentation = "tool_call" | "compaction_update";
|
||||
|
||||
type CompactionState = {
|
||||
/** Doubles as the toolCallId under the legacy presentation. */
|
||||
compactionId: string;
|
||||
terminalStatus?: TerminalStatus;
|
||||
heartbeatSent: boolean;
|
||||
/** The summary text that went out as chunks. */
|
||||
streamedSummary?: string;
|
||||
/** User-displayable summary reported by the PostCompact hook. While the
|
||||
* compaction is in progress it awaits the terminal update; on a `completed`
|
||||
* state it has been sent. */
|
||||
summary?: string;
|
||||
};
|
||||
|
||||
type SendUpdate = (notification: SessionNotification) => Promise<void>;
|
||||
|
||||
export type ContextCompactionLifecycleOptions = {
|
||||
sessionId: string;
|
||||
presentation?: CompactionPresentation;
|
||||
/** Receives failures of the send that must not propagate: the turn-boundary
|
||||
* `cancelled` terminal. */
|
||||
logError?: (message: string, error: unknown) => void;
|
||||
/** The client is AIR. Only AIR gets the compaction facts, under `_meta.jetbrains.air`. */
|
||||
airClient?: boolean;
|
||||
};
|
||||
|
||||
export function clientSupportsCompactionUpdates(capabilities?: ClientCapabilities | null): boolean {
|
||||
const compaction = capabilities?.session?.compaction;
|
||||
return typeof compaction === "object" && compaction !== null && !Array.isArray(compaction);
|
||||
}
|
||||
|
||||
/** Tags on their own line, as the model emits them; a summary that merely
|
||||
* quotes `<summary>` mid-sentence must not be truncated at the mention. */
|
||||
const SUMMARY_OPEN_LINE = /^[ \t]*<summary>[ \t]*\r?\n/gim;
|
||||
const SUMMARY_CLOSE_LINE = /^[ \t]*<\/summary>[ \t]*$/gim;
|
||||
/** The model's private reasoning block that precedes the summary; stripped
|
||||
* first so a `<summary>` it merely mentions cannot anchor the summary span,
|
||||
* and even when the summary tags themselves are missing. Own-line tags
|
||||
* anywhere; inline tags only as a leading block, since a summary body may
|
||||
* quote both tag names. */
|
||||
const ANALYSIS_BLOCKS = [
|
||||
/^[ \t]*<analysis>[ \t]*\r?\n[\s\S]*?\n[ \t]*<\/analysis>[ \t]*$/gim,
|
||||
/^\s*<analysis>[\s\S]*?<\/analysis>/i,
|
||||
];
|
||||
/** The framing Claude Code wraps around the retained summary when it persists
|
||||
* it as the post-compaction user message. */
|
||||
const CONTINUATION_PREAMBLE = /^\s*This session is being continued from a previous conversation/i;
|
||||
const PERSISTED_PREAMBLE =
|
||||
/^\s*This session is being continued from a previous conversation[^\n]*\n(?:[\s\S]*?\n)?Summary:[ \t]*\r?\n/;
|
||||
const PERSISTED_TRAILERS = [
|
||||
/\n+If you need specific details from before compaction[\s\S]*$/,
|
||||
/\n+(?:Please )?[Cc]ontinue the conversation from where it left (?:it )?off[\s\S]*$/,
|
||||
];
|
||||
|
||||
/**
|
||||
* Reduce Claude's compaction output to the user-displayable summary.
|
||||
*
|
||||
* The PostCompact hook reports the model's raw output, which wraps the
|
||||
* summary in `<summary>` tags (often preceded by an `<analysis>` block). The
|
||||
* persisted transcript instead frames the same summary with continuation
|
||||
* instructions for the model. Neither framing belongs in the ACP `summary`,
|
||||
* and a continuation prompt whose framing is not recognized yields no summary
|
||||
* at all rather than model-facing instructions.
|
||||
*/
|
||||
export function compactionSummaryText(raw: string): string | undefined {
|
||||
let text = raw;
|
||||
for (const block of ANALYSIS_BLOCKS) {
|
||||
text = text.replace(block, "");
|
||||
}
|
||||
const tagged = taggedSummary(text);
|
||||
if (tagged !== undefined) {
|
||||
text = tagged;
|
||||
} else if (CONTINUATION_PREAMBLE.test(text)) {
|
||||
const body = text.replace(PERSISTED_PREAMBLE, "");
|
||||
if (body === text) return undefined;
|
||||
text = body;
|
||||
for (const trailer of PERSISTED_TRAILERS) {
|
||||
text = text.replace(trailer, "");
|
||||
}
|
||||
}
|
||||
text = text.trim();
|
||||
return text.length > 0 ? text : undefined;
|
||||
}
|
||||
|
||||
function taggedSummary(raw: string): string | undefined {
|
||||
const close = [...raw.matchAll(SUMMARY_CLOSE_LINE)].at(-1);
|
||||
if (close?.index !== undefined) {
|
||||
const open = [...raw.slice(0, close.index).matchAll(SUMMARY_OPEN_LINE)].at(-1);
|
||||
if (open?.index !== undefined) {
|
||||
return raw.slice(open.index + open[0].length, close.index);
|
||||
}
|
||||
}
|
||||
// Inline tags: the widest span, so a quoted `</summary>` inside the body
|
||||
// does not end it early. Plain index scans keep an unterminated tag linear.
|
||||
const openInline = raw.search(/<summary>/i);
|
||||
const closeInline = raw.toLowerCase().lastIndexOf("</summary>");
|
||||
if (openInline >= 0 && closeInline > openInline) {
|
||||
return raw.slice(openInline + "<summary>".length, closeInline);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** True for the post-compaction user message Claude Code persists (and
|
||||
* `getSessionMessages` returns) with the summary of the dropped history. */
|
||||
export function isCompactSummaryMessage(message: unknown): boolean {
|
||||
return (
|
||||
typeof message === "object" &&
|
||||
message !== null &&
|
||||
(message as { type?: unknown }).type === "user" &&
|
||||
(message as { isCompactSummary?: unknown }).isCompactSummary === true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the compact summary message `message` (see
|
||||
* {@link isCompactSummaryMessage}) of the root conversation as one completed
|
||||
* `compaction_update` at its transcript position, keyed by the message's
|
||||
* uuid. Returns false, and sends nothing, for any other message.
|
||||
*
|
||||
* The boundary's own system record comes back from `getSessionMessages`
|
||||
* without its metadata, so the summary message is the one durable marker.
|
||||
* Its uuid differs from the live id (the `compacting` status uuid): replay
|
||||
* is terminal-first by the RFD, and no client merges a replay into a live
|
||||
* entity store. A summary whose framing is unrecognized is still this
|
||||
* compaction, without summary text.
|
||||
*/
|
||||
export async function replayCompactSummary(
|
||||
message: { uuid?: unknown; message?: unknown },
|
||||
sendUpdate: SendUpdate,
|
||||
options: { sessionId: string; airClient?: boolean },
|
||||
): Promise<boolean> {
|
||||
if (!isCompactSummaryMessage(message) || typeof message.uuid !== "string" || !message.uuid) {
|
||||
return false;
|
||||
}
|
||||
const replayed = new ContextCompactionLifecycle(sendUpdate, {
|
||||
...options,
|
||||
presentation: "compaction_update",
|
||||
});
|
||||
replayed.recordSummary(assistantMessageText(message.message));
|
||||
await replayed.finish(message.uuid, "completed");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates Claude's compaction signals into one idempotent ACP lifecycle.
|
||||
*
|
||||
* The SDK can duplicate terminal compact_result messages and can omit the
|
||||
* opening status on replay. State therefore lives until the owning turn's
|
||||
* result (or abort), while a new compacting status after a terminal outcome
|
||||
* starts a fresh lifecycle.
|
||||
*/
|
||||
export class ContextCompactionLifecycle {
|
||||
private activeCompaction: CompactionState | undefined;
|
||||
private outputDelivered = false;
|
||||
private duplicateErrorOutput: string | undefined;
|
||||
/** After interruption, uncorrelated terminal frames and hooks may still
|
||||
* arrive from the abandoned work, including an opening we never consumed.
|
||||
* Wait for a known new turn before accepting them again. */
|
||||
private interrupted = false;
|
||||
/** Summary reported by PostCompact before the opening status was consumed.
|
||||
* Deliberately survives `reset()`: the CLI awaits the hook before emitting
|
||||
* the compaction's terminal frames, so a pending summary always belongs to
|
||||
* a compaction whose frames are still ahead of the consumer — possibly
|
||||
* queued behind a previous turn's result. */
|
||||
private pendingSummary: string | undefined;
|
||||
private readonly sessionId: string;
|
||||
readonly presentation: CompactionPresentation;
|
||||
private readonly logError: (message: string, error: unknown) => void;
|
||||
private readonly airClient: boolean;
|
||||
|
||||
constructor(
|
||||
private readonly sendUpdate: SendUpdate,
|
||||
options: ContextCompactionLifecycleOptions,
|
||||
) {
|
||||
this.sessionId = options.sessionId;
|
||||
this.presentation = options.presentation ?? "tool_call";
|
||||
this.logError = options.logError ?? (() => {});
|
||||
this.airClient = options.airClient ?? false;
|
||||
}
|
||||
|
||||
get hasDeliveredOutput(): boolean {
|
||||
return this.outputDelivered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the lifecycle at a turn boundary (result, cancel, idle-abandon).
|
||||
*
|
||||
* A `compaction_update` entity still `in_progress` here never received its
|
||||
* terminal signal from the runtime and gets its one terminal status,
|
||||
* `cancelled`. The legacy tool call is deliberately left as it was (an
|
||||
* `in_progress` call): ACP `ToolCallStatus` has no cancelled state and that
|
||||
* presentation's behavior predates this lifecycle. Never throws — a failed
|
||||
* send is logged, so callers can settle the turn unconditionally.
|
||||
*/
|
||||
async reset(): Promise<void> {
|
||||
const state = this.activeCompaction;
|
||||
this.activeCompaction = undefined;
|
||||
this.outputDelivered = false;
|
||||
this.duplicateErrorOutput = undefined;
|
||||
if (!state || state.terminalStatus || this.presentation !== "compaction_update") return;
|
||||
state.terminalStatus = "cancelled";
|
||||
await this.sendQuietly(
|
||||
{
|
||||
sessionUpdate: "compaction_update",
|
||||
compactionId: state.compactionId,
|
||||
status: "cancelled",
|
||||
},
|
||||
"cancelled compaction",
|
||||
);
|
||||
}
|
||||
|
||||
/** Abandon the current work before settling its prompt or tearing down the
|
||||
* stream. Unlike a normal result boundary, its pending hooks are not safe
|
||||
* to carry into the next compaction. A hook has no command ID, so even an
|
||||
* early hook for the next compaction must be omitted until the stream gives
|
||||
* us a new live turn boundary. Idempotent and best-effort. */
|
||||
async interrupt(): Promise<void> {
|
||||
if (this.presentation === "compaction_update") {
|
||||
this.interrupted = true;
|
||||
this.pendingSummary = undefined;
|
||||
}
|
||||
await this.reset();
|
||||
}
|
||||
|
||||
/** A live command's dispatch/echo proves the interrupted command's tail
|
||||
* has drained in the SDK's FIFO stream. Do not reset normal lifecycle
|
||||
* state: compaction may already have started before the user echo. */
|
||||
resume(): void {
|
||||
this.interrupted = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude also emits a failed manual compaction's error as local-command
|
||||
* stdout. Consume that one duplicate after the lifecycle carried it,
|
||||
* without hiding unrelated command output.
|
||||
*/
|
||||
consumeDuplicateErrorOutput(content: string): boolean {
|
||||
if (
|
||||
this.duplicateErrorOutput === undefined ||
|
||||
content.trim() !== this.duplicateErrorOutput.trim()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
this.duplicateErrorOutput = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
async start(compactionId: string): Promise<void> {
|
||||
if (this.interrupted) return;
|
||||
if (this.activeCompaction && !this.activeCompaction.terminalStatus) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.open(compactionId);
|
||||
if (this.presentation === "compaction_update") {
|
||||
await this.send({
|
||||
sessionUpdate: "compaction_update",
|
||||
compactionId,
|
||||
status: "in_progress",
|
||||
...(this.airClient ? { _meta: createContextCompactionMeta() } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.send(compactionToolCall.started(compactionId, this.airClient));
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming progress from the API's compaction content block.
|
||||
*
|
||||
* Under `compaction_update` the block's text is the retained summary and
|
||||
* streams as `compaction_summary_chunk`s — but only into an entity the CLI
|
||||
* announced with its `compacting` status. The block alone carries no
|
||||
* terminal signal, so opening an entity from it would leave nothing but the
|
||||
* turn-boundary `cancelled` to close a compaction that succeeded. The legacy
|
||||
* tool call keeps its historical behavior: open on first sight, re-assert
|
||||
* `in_progress` once.
|
||||
*/
|
||||
async heartbeat(fallbackId: string, summaryChunk?: string): Promise<void> {
|
||||
if (this.presentation === "compaction_update") {
|
||||
const state = this.activeCompaction;
|
||||
if (!state || state.terminalStatus || !summaryChunk) return;
|
||||
state.streamedSummary = (state.streamedSummary ?? "") + summaryChunk;
|
||||
await this.send({
|
||||
sessionUpdate: "compaction_summary_chunk",
|
||||
compactionId: state.compactionId,
|
||||
content: { type: "text", text: summaryChunk },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.activeCompaction) await this.start(fallbackId);
|
||||
const state = this.activeCompaction;
|
||||
if (!state || state.terminalStatus || state.heartbeatSent) return;
|
||||
state.heartbeatSent = true;
|
||||
await this.send(compactionToolCall.inProgress(state.compactionId, this.airClient));
|
||||
}
|
||||
|
||||
/**
|
||||
* The PostCompact hook's summary. The CLI awaits the hook before emitting
|
||||
* the compaction's terminal frames, so the summary lands while its
|
||||
* compaction is `in_progress` and rides on the terminal update. Anything
|
||||
* else — no entity yet, or the entity is a previous, already-terminal
|
||||
* compaction of the same turn whose status frame the consumer is still
|
||||
* catching up to — belongs to the compaction whose frames are ahead of the
|
||||
* consumer, and waits for it. Only the `compaction_update` presentation
|
||||
* carries the summary; the legacy tool call never exposed it. Never throws:
|
||||
* it runs detached from a hook callback. Returns whether a summary was
|
||||
* retained.
|
||||
*/
|
||||
recordSummary(rawSummary: unknown): boolean {
|
||||
if (this.interrupted) return false;
|
||||
if (this.presentation !== "compaction_update" || typeof rawSummary !== "string") return false;
|
||||
const summary = compactionSummaryText(rawSummary);
|
||||
if (!summary) return false;
|
||||
|
||||
const state = this.activeCompaction;
|
||||
if (state && !state.terminalStatus) {
|
||||
state.summary = summary;
|
||||
} else {
|
||||
this.pendingSummary = summary;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async finish(
|
||||
compactionId: string,
|
||||
status: CompactionStatus,
|
||||
metadata: Omit<ContextCompactionMetadata, "version"> = {},
|
||||
enrichTerminal = false,
|
||||
): Promise<void> {
|
||||
if (this.interrupted) return;
|
||||
// The opening status can be missed (replay, or a terminal-only runtime):
|
||||
// the first update for the ID is then already terminal.
|
||||
const opened = this.activeCompaction === undefined;
|
||||
const firstTerminal = !this.activeCompaction?.terminalStatus;
|
||||
const state = this.activeCompaction ?? this.open(compactionId, status);
|
||||
if (firstTerminal) {
|
||||
state.terminalStatus = status;
|
||||
} else if (!enrichTerminal) {
|
||||
return;
|
||||
}
|
||||
if (status === "failed" && metadata.error) {
|
||||
this.duplicateErrorOutput = metadata.error;
|
||||
}
|
||||
const terminalStatus = state.terminalStatus ?? status;
|
||||
const hasMetadata = Object.keys(metadata).length > 0;
|
||||
|
||||
if (this.presentation === "compaction_update") {
|
||||
// A summary that went out as chunks is not sent again in full. The
|
||||
// chunks are the raw API text and the summary is the cleaned hook text,
|
||||
// so the summary is left out only when both hold the same text.
|
||||
const summaryStreamed = state.streamedSummary === state.summary;
|
||||
const summary =
|
||||
firstTerminal && terminalStatus === "completed" && !summaryStreamed
|
||||
? state.summary
|
||||
: undefined;
|
||||
await this.send({
|
||||
sessionUpdate: "compaction_update",
|
||||
compactionId: state.compactionId,
|
||||
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.
|
||||
// The standard `error` field carries the error, so `_meta` does not.
|
||||
// Only AIR gets the compaction facts.
|
||||
...(this.airClient && (firstTerminal || hasMetadata)
|
||||
? { _meta: createContextCompactionMeta(withoutError(metadata)) }
|
||||
: {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await this.send(
|
||||
compactionToolCall.finished(
|
||||
state.compactionId,
|
||||
opened || firstTerminal ? status : undefined,
|
||||
metadata,
|
||||
opened,
|
||||
this.airClient,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Make `compactionId` the active entity, moving a pending hook summary onto
|
||||
* it, and mark compaction output as delivered for the owning turn. */
|
||||
private open(compactionId: string, terminalStatus?: TerminalStatus): CompactionState {
|
||||
const state: CompactionState = {
|
||||
compactionId,
|
||||
heartbeatSent: false,
|
||||
...(terminalStatus ? { terminalStatus } : {}),
|
||||
...(this.pendingSummary !== undefined ? { summary: this.pendingSummary } : {}),
|
||||
};
|
||||
this.pendingSummary = undefined;
|
||||
this.activeCompaction = state;
|
||||
this.outputDelivered = true;
|
||||
return state;
|
||||
}
|
||||
|
||||
private send(update: SessionNotification["update"]): Promise<void> {
|
||||
return this.sendUpdate({ sessionId: this.sessionId, update });
|
||||
}
|
||||
|
||||
private async sendQuietly(update: SessionNotification["update"], what: string): Promise<void> {
|
||||
try {
|
||||
await this.send(update);
|
||||
} catch (error) {
|
||||
this.logError(`Failed to send the ${what} update for session ${this.sessionId}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function withoutError({
|
||||
error: _error,
|
||||
...facts
|
||||
}: Omit<ContextCompactionMetadata, "version">): Omit<ContextCompactionMetadata, "version"> {
|
||||
return facts;
|
||||
}
|
||||
|
||||
function compactionTrigger(
|
||||
cliTrigger: "manual" | "auto",
|
||||
sentByAdapter: boolean,
|
||||
): ContextCompactionTrigger {
|
||||
// The CLI's own automatic compaction stays automatic, even inside the adapter's /compact turn.
|
||||
if (cliTrigger === "auto") return "automatic";
|
||||
// The CLI reports every /compact as manual; only the adapter knows it sent this one itself.
|
||||
if (sentByAdapter) return "idle";
|
||||
return "manual";
|
||||
}
|
||||
|
||||
/** `idleCompaction` marks a `/compact` that the adapter sent itself (see `IdleCompaction`). */
|
||||
export function contextCompactionMetadataFromBoundary(
|
||||
compactMetadata: {
|
||||
trigger: "manual" | "auto";
|
||||
pre_tokens: number;
|
||||
post_tokens?: number;
|
||||
duration_ms?: number;
|
||||
},
|
||||
{ idleCompaction = false }: { idleCompaction?: boolean } = {},
|
||||
): Omit<ContextCompactionMetadata, "version"> {
|
||||
return {
|
||||
trigger: compactionTrigger(compactMetadata.trigger, idleCompaction),
|
||||
preTokens: compactMetadata.pre_tokens,
|
||||
...(compactMetadata.post_tokens !== undefined
|
||||
? { postTokens: compactMetadata.post_tokens }
|
||||
: {}),
|
||||
...(compactMetadata.duration_ms !== undefined
|
||||
? { durationMs: compactMetadata.duration_ms }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
/**
|
||||
* The context window of a session's model, as both the v1 core and the
|
||||
* v2 core report it in `usage_update.size`: seeded without IPC when the
|
||||
* session starts or switches models, refined by a background
|
||||
* `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";
|
||||
|
||||
/** Cross-session cache of authoritative context windows, keyed by
|
||||
* `${providerCacheKey}\0${modelId}` (see {@link contextWindowCacheKey}).
|
||||
* The window is a property of (model id, backend): the same resolved model id
|
||||
* (e.g. "claude-sonnet-5[1m]", the spelling of the `result.modelUsage` keys)
|
||||
* can name different context lanes behind different base URLs, routing
|
||||
* headers, or credentials, so the key carries both. Caching it module-level
|
||||
* lets a later session/new or switch that resolves to the same (backend,
|
||||
* model) — in this session or any other, within the adapter's lifetime — seed
|
||||
* the correct window synchronously with no IPC. Keying on the resolved id
|
||||
* (rather than the picker value) means aliases that resolve to the same
|
||||
* concrete model share one entry; the result handler additionally writes the
|
||||
* bare assistant-message spelling so seed-time reads that fall back to a
|
||||
* verbatim live id (rows without `resolvedModel`) can hit too.
|
||||
*
|
||||
* Populated authoritatively by each `result.modelUsage` a turn confirms (see
|
||||
* the consumer's result handler). We deliberately never populate it from
|
||||
* `getContextUsage`: its `model` spelling and `rawMaxTokens` can differ from
|
||||
* the `result.modelUsage` key and window (e.g. 967000 vs 1000000 for sonnet),
|
||||
* so it only refines the live session (`refreshContextWindowInBackground`).
|
||||
* Cleared on `logout`: 1M-context entitlement can differ per account/tier, so
|
||||
* windows learned under one login must not seed sessions under the next. */
|
||||
const contextWindowCache = new Map<string, number>();
|
||||
|
||||
/** The env vars that determine which LLM backend — and which context lane on
|
||||
* it — a query's API traffic reaches: endpoint selection (base URLs and the
|
||||
* Bedrock/Vertex switches with their project/region), routing/beta headers
|
||||
* (an `anthropic-beta: context-1m-…` header flips the same model id at the
|
||||
* same endpoint between context lanes), and credential identity (extended
|
||||
* context is entitlement-gated per account). Used to derive the
|
||||
* provider-cache key from the exact env a query is created with, so
|
||||
* `providers/set` config, per-session `_meta` env overrides, and ambient
|
||||
* process env are all distinguished exactly as the CLI will see them. */
|
||||
const PROVIDER_ROUTING_ENV_VARS = [
|
||||
"ANTHROPIC_BASE_URL",
|
||||
"ANTHROPIC_BEDROCK_BASE_URL",
|
||||
"ANTHROPIC_VERTEX_BASE_URL",
|
||||
"CLAUDE_CODE_USE_BEDROCK",
|
||||
"CLAUDE_CODE_USE_VERTEX",
|
||||
"ANTHROPIC_VERTEX_PROJECT_ID",
|
||||
"CLOUD_ML_REGION",
|
||||
"AWS_REGION",
|
||||
"ANTHROPIC_CUSTOM_HEADERS",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"ANTHROPIC_AUTH_TOKEN",
|
||||
"CLAUDE_CODE_OAUTH_TOKEN",
|
||||
] as const;
|
||||
|
||||
/** Stable identifier for the LLM backend a session's query is created against,
|
||||
* used to scope {@link contextWindowCache} per backend. Positional `\0`-join
|
||||
* of {@link PROVIDER_ROUTING_ENV_VARS} values, so no segment can masquerade
|
||||
* as another and unset vars everywhere yield one stable "default" bucket.
|
||||
* 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. */
|
||||
export function providerCacheKeyFor(env: Record<string, string | undefined>): string {
|
||||
return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
|
||||
}
|
||||
|
||||
/** Compose the `contextWindowCache` key from a session's provider key and a
|
||||
* model id. `\0`-joined so the model segment can't collide with a provider
|
||||
* segment. */
|
||||
export function contextWindowCacheKey(providerCacheKey: string, modelId: string): string {
|
||||
return `${providerCacheKey}\0${modelId}`;
|
||||
}
|
||||
|
||||
function cacheContextWindow(modelKey: string, window: number): void {
|
||||
if (window > 0) {
|
||||
contextWindowCache.set(modelKey, window);
|
||||
}
|
||||
}
|
||||
|
||||
/** Caches the window that a result's `modelUsage` reported, keyed on (the
|
||||
* session's provider, the resolved model id — the `modelUsage` key, e.g.
|
||||
* "claude-sonnet-5[1m]") so a later session/new or switch on the same
|
||||
* provider that resolves to this model seeds the correct window
|
||||
* synchronously, with no getContextUsage IPC.
|
||||
*
|
||||
* Also caches it under the assistant message's own (bare) spelling. Seed-time
|
||||
* reads fall back to a picker value / verbatim live id when a row carries no
|
||||
* resolvedModel (the synthesized out-of-allowlist resume row sets it
|
||||
* undefined on purpose), and those spellings match `.model` from the
|
||||
* assistant message, not the decorated modelUsage key — without this entry
|
||||
* such rows could never hit the cache. A non-positive window is not cached. */
|
||||
export function cacheResultContextWindow(
|
||||
providerCacheKey: string,
|
||||
modelUsageKey: string,
|
||||
assistantModel: string | null | undefined,
|
||||
window: number,
|
||||
): void {
|
||||
cacheContextWindow(contextWindowCacheKey(providerCacheKey, modelUsageKey), window);
|
||||
if (assistantModel && assistantModel !== modelUsageKey) {
|
||||
cacheContextWindow(contextWindowCacheKey(providerCacheKey, assistantModel), window);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
export function immediateContextWindow(
|
||||
providerCacheKey: string,
|
||||
modelId: string,
|
||||
modelInfo?: Pick<ModelInfo, "resolvedModel" | "displayName" | "description">,
|
||||
): { 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,
|
||||
};
|
||||
}
|
||||
|
||||
/** Forgets the learned windows, as a logout asks: 1M-context entitlement is
|
||||
* gated per org/tier, and an OAuth re-login is invisible to the env-derived
|
||||
* provider cache key, so windows learned under the old login must not seed
|
||||
* sessions under the next. */
|
||||
export function clearContextWindowCache(): void {
|
||||
contextWindowCache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the window of the query's current model with
|
||||
* `getContextUsage().rawMaxTokens`. Undefined when Claude Code reports none.
|
||||
*
|
||||
* Requests the `summary` detail instead of the default `full` breakdown,
|
||||
* which issues one `messages/count_tokens` call per category (~18 for a bare
|
||||
* session) and hit rate limits on every model switch; `summary` answers
|
||||
* locally with the same `rawMaxTokens`. Callers never await it on the setup
|
||||
* or switch path: SDK control requests are serialized, so awaiting would
|
||||
* delay session/new or a model switch (~15s on older CLIs, issues
|
||||
* #886/#880; ~0.5s on 2.1.283).
|
||||
*
|
||||
* The result does not go into the cross-session cache: its `rawMaxTokens` can
|
||||
* differ from the `result.modelUsage` window (e.g. 967000 vs 1000000 for
|
||||
* sonnet), so it only refines the live session.
|
||||
*/
|
||||
export async function readContextWindow(
|
||||
query: Pick<Query, "getContextUsage">,
|
||||
): Promise<number | undefined> {
|
||||
const usage = await query.getContextUsage({ detail: "summary" });
|
||||
return usage.rawMaxTokens > 0 ? usage.rawMaxTokens : undefined;
|
||||
}
|
||||
748
src/diff.ts
748
src/diff.ts
@@ -1,748 +0,0 @@
|
||||
import { ToolCallContent, ToolCallLocation } from "@agentclientprotocol/sdk/unstable";
|
||||
import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
|
||||
import { structuredPatch } from "diff";
|
||||
import { constants } from "node:fs";
|
||||
import { type FileHandle, open } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { AIR_DIFF_PATCH_CAPABILITY, withAirMeta } from "./air-extension.js";
|
||||
import { normalizeWriteInput } from "./tool-calls/reporters/file-edit.js";
|
||||
|
||||
/**
|
||||
* The largest file, in bytes, that the adapter turns into a git patch.
|
||||
*
|
||||
* A larger file, a larger new text, or an Edit whose result can be larger
|
||||
* gets no patch. The tool call then keeps its standard ACP content. The limit
|
||||
* bounds the file read, the replacement, and the line diff that run while
|
||||
* Claude waits for an approval.
|
||||
*/
|
||||
export const MAX_PATCH_FILE_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The wall-clock budget, in milliseconds, of one line diff for a patch.
|
||||
*
|
||||
* The diff runs synchronously, so the budget is also the longest block of the
|
||||
* event loop.
|
||||
*/
|
||||
const PATCH_DIFF_TIMEOUT_MS = 100;
|
||||
|
||||
/** The number of context lines around a change in a hunk. */
|
||||
const PATCH_CONTEXT_LINES = 3;
|
||||
|
||||
/** Git reads this many leading bytes to decide that a file is binary. */
|
||||
const BINARY_SNIFF_BYTES = 8000;
|
||||
|
||||
const NO_NEWLINE_MARKER = "\\ No newline at end of file";
|
||||
|
||||
/**
|
||||
* One unified-diff hunk in the `diff` package convention.
|
||||
*
|
||||
* A side with zero lines stores the number of the line after the change as its
|
||||
* start. {@link hunkHeader} converts that start to the git convention.
|
||||
*/
|
||||
interface PatchHunk {
|
||||
oldStart: number;
|
||||
oldLines: number;
|
||||
newStart: number;
|
||||
newLines: number;
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
interface DiffToolResponse {
|
||||
filePath?: string;
|
||||
structuredPatch?: PatchHunk[];
|
||||
/** FileWriteOutput only (FileEditOutput carries no `type`): whether the
|
||||
* write created the file or overwrote an existing one. */
|
||||
type?: "create" | "update";
|
||||
/** FileWriteOutput only: the content that was written. */
|
||||
content?: string;
|
||||
/** The pre-change content. It is null on a Write create, or on a Write
|
||||
* update whose previous content was too large to include. An Edit that
|
||||
* creates a file reports an empty string, as for an existing empty file. */
|
||||
originalFile?: string | null;
|
||||
/** FileEditOutput only: the text that the Edit replaced. It is empty when
|
||||
* the Edit created the file or filled an existing empty file. */
|
||||
oldString?: string;
|
||||
}
|
||||
|
||||
interface EditPreviewInput {
|
||||
file_path?: unknown;
|
||||
old_string?: unknown;
|
||||
new_string?: unknown;
|
||||
replace_all?: unknown;
|
||||
}
|
||||
|
||||
/** The kind of file change that a git patch describes. */
|
||||
type FileChange = "create" | "update";
|
||||
|
||||
/** A file change and the hunks of its git patch. */
|
||||
interface FilePatch {
|
||||
change: FileChange;
|
||||
hunks: PatchHunk[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The diff that carries an exact patch: AIR's `diffPatch` extension of a v1
|
||||
* diff, or an ACP v2 diff.
|
||||
*/
|
||||
export type PatchForm = "air" | "v2";
|
||||
|
||||
/**
|
||||
* How a git patch names its file. `git` is git's own form: the leading slash
|
||||
* dropped and the `a/` and `b/` prefixes added. `absolute` is the form of an
|
||||
* ACP v2 `git_patch`, whose paths must be absolute: the native path itself.
|
||||
*/
|
||||
type GitPatchPaths = "git" | "absolute";
|
||||
|
||||
/** An ACP v2 diff, as tool call content. */
|
||||
type V2DiffContent = v2.Diff & { type: "diff" };
|
||||
|
||||
/**
|
||||
* Builds the exact patch shown before Claude runs an Edit or Write tool.
|
||||
*
|
||||
* Returns undefined when the adapter cannot predict the file change exactly.
|
||||
* The caller then keeps the standard tool-call content. The adapter declines
|
||||
* a file that is missing for an Edit, too large, binary, or that has CR line
|
||||
* endings. Claude converts the line endings of an edited file, so an in-memory
|
||||
* replacement would not match the bytes that Claude writes. It also declines
|
||||
* an `old_string` that does not match exactly once, because Claude then
|
||||
* normalizes quotes or fails.
|
||||
*
|
||||
* A Write always gets content that shows the change: the patch, the standard
|
||||
* diff (in v2, the change alone) of a text that cannot have an exact patch, or
|
||||
* a notice that the Write overwrites a file that the adapter cannot show.
|
||||
*
|
||||
* The preview uses the tool input as it is. Claude can still remove the
|
||||
* trailing whitespace of a line before it writes. The PostToolUse hook then
|
||||
* sends the patch of the written file.
|
||||
*/
|
||||
export async function previewPatchContent(
|
||||
toolName: string,
|
||||
input: Record<string, unknown>,
|
||||
cwd?: string,
|
||||
form: PatchForm = "air",
|
||||
): Promise<ToolCallContent[] | undefined> {
|
||||
if (toolName === "Edit") {
|
||||
const edit = input as EditPreviewInput;
|
||||
if (
|
||||
typeof edit.file_path !== "string" ||
|
||||
typeof edit.old_string !== "string" ||
|
||||
typeof edit.new_string !== "string"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const oldString = edit.old_string;
|
||||
const filePath = resolveToolPath(edit.file_path, cwd);
|
||||
const oldText = await readPatchSource(filePath);
|
||||
if (oldText === undefined) return undefined;
|
||||
const newString = edit.new_string;
|
||||
if (oldString === newString || !isPatchableText(newString)) return undefined;
|
||||
if (oldString.length === 0) {
|
||||
// An empty old_string creates the file, or fills an existing file that
|
||||
// holds only whitespace. `trim` also removes a byte order mark, whose
|
||||
// handling the adapter does not predict, so such a file is declined.
|
||||
if (oldText !== null && (oldText.trim() !== "" || oldText.includes("\uFEFF"))) {
|
||||
return undefined;
|
||||
}
|
||||
return exactPatch(filePath, oldText, newString, form);
|
||||
}
|
||||
if (oldText === null) return undefined;
|
||||
const occurrences = oldText.split(oldString).length - 1;
|
||||
if (occurrences === 0 || (edit.replace_all !== true && occurrences !== 1)) return undefined;
|
||||
if (replacedTextBytesBound(oldText, oldString, newString, occurrences) > MAX_PATCH_FILE_BYTES) {
|
||||
return undefined;
|
||||
}
|
||||
const newText = replacedText(oldText, oldString, newString, edit.replace_all === true);
|
||||
return exactPatch(filePath, oldText, newText, form);
|
||||
}
|
||||
|
||||
if (toolName === "Write") {
|
||||
const write = normalizeWriteInput(input);
|
||||
if (typeof write?.file_path !== "string" || typeof write.content !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
// The Write tool call shows no diff, so the approval is the only place that
|
||||
// shows what the Write changes.
|
||||
const content = write.content;
|
||||
const filePath = resolveToolPath(write.file_path, cwd);
|
||||
const oldText = await readPatchSource(filePath);
|
||||
if (oldText === undefined) {
|
||||
return [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: `Overwrites the existing file \`${write.file_path}\`. The adapter cannot show its current content.`,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
if (oldText === content) return undefined;
|
||||
const standard: ToolCallContent[] = [
|
||||
form === "v2"
|
||||
? v2DiffContent(filePath, oldText === null ? "create" : "update")
|
||||
: { type: "diff", path: write.file_path, oldText, newText: content },
|
||||
];
|
||||
if (!isPatchableText(content)) return standard;
|
||||
// A dense change can exceed the diff budget. The approval then shows the standard diff.
|
||||
return exactPatch(filePath, oldText, content, form) ?? standard;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* An upper bound of the UTF-8 size, in bytes, of {@link replacedText}.
|
||||
*
|
||||
* The caller checks the bound before it builds the text. A `replace_all` of
|
||||
* many short matches with a long `newString` can otherwise build a text of
|
||||
* gigabytes before the timed line diff starts.
|
||||
*/
|
||||
function replacedTextBytesBound(
|
||||
fileText: string,
|
||||
oldString: string,
|
||||
newString: string,
|
||||
occurrences: number,
|
||||
): number {
|
||||
const growth = Buffer.byteLength(newString, "utf8") - Buffer.byteLength(oldString, "utf8");
|
||||
return Buffer.byteLength(fileText, "utf8") + occurrences * Math.max(0, growth);
|
||||
}
|
||||
|
||||
/**
|
||||
* The file text after Claude replaces `oldString` with `newString`.
|
||||
*
|
||||
* An empty `newString` deletes a line: when `oldString` does not end with a
|
||||
* line break and the file holds `oldString` and a line break, Claude also
|
||||
* removes that line break. With `replaceAll`, it then replaces only the
|
||||
* occurrences that a line break follows.
|
||||
*/
|
||||
function replacedText(
|
||||
fileText: string,
|
||||
oldString: string,
|
||||
newString: string,
|
||||
replaceAll: boolean,
|
||||
): string {
|
||||
const target =
|
||||
newString === "" && !oldString.endsWith("\n") && fileText.includes(`${oldString}\n`)
|
||||
? `${oldString}\n`
|
||||
: oldString;
|
||||
return replaceAll
|
||||
? fileText.split(target).join(newString)
|
||||
: fileText.replace(target, () => newString);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the git patch for a finished Edit or Write from the file on disk.
|
||||
*
|
||||
* The Claude SDK `structuredPatch` is display data: Claude converts leading
|
||||
* tabs to spaces and CRLF line endings to LF before it computes the hunks. A
|
||||
* patch built from those hunks does not match the file. This function diffs
|
||||
* `originalFile` against the written file instead. It returns undefined when
|
||||
* it cannot build an exact patch, and the caller then sends the standard diff.
|
||||
* A written file that contains a CR or a byte order mark is declined, because
|
||||
* Claude removed those bytes from `originalFile`.
|
||||
*/
|
||||
export async function patchUpdateFromDiffToolResponse(
|
||||
toolResponse: unknown,
|
||||
form: PatchForm = "air",
|
||||
): Promise<{ content: ToolCallContent[]; locations: ToolCallLocation[] } | undefined> {
|
||||
if (!toolResponse || typeof toolResponse !== "object") return undefined;
|
||||
const response = toolResponse as DiffToolResponse;
|
||||
if (typeof response.filePath !== "string") return undefined;
|
||||
// An Edit with an empty old_string reports "" as the original of a created
|
||||
// file and of an existing empty file. The response does not tell the two
|
||||
// apart, so the caller keeps the standard diff.
|
||||
if (response.type === undefined && response.oldString === "" && response.originalFile === "") {
|
||||
return undefined;
|
||||
}
|
||||
// A Write whose content is the previous text changed nothing. The file on
|
||||
// disk can hold a later change, and that change is not the change of this Write.
|
||||
if (
|
||||
response.type === "update" &&
|
||||
typeof response.content === "string" &&
|
||||
response.originalFile === response.content
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const oldText =
|
||||
response.type === "create"
|
||||
? null
|
||||
: typeof response.originalFile === "string"
|
||||
? response.originalFile
|
||||
: undefined;
|
||||
if (oldText === undefined) return undefined;
|
||||
// The same size limit as the new side: a larger text gets the standard diff.
|
||||
if (oldText !== null && Buffer.byteLength(oldText, "utf8") > MAX_PATCH_FILE_BYTES)
|
||||
return undefined;
|
||||
const newText = await readPatchSource(response.filePath);
|
||||
if (typeof newText !== "string" || newText.startsWith("\uFEFF")) return undefined;
|
||||
if (response.type === "create" && newText !== response.content) return undefined;
|
||||
const patch = filePatch(oldText, newText);
|
||||
if (!patch) return undefined;
|
||||
return {
|
||||
content: [patchContent(response.filePath, patch, form)],
|
||||
// A created file keeps the location of its Write tool call.
|
||||
locations:
|
||||
oldText === null
|
||||
? [{ path: response.filePath }]
|
||||
: patch.hunks.map(({ newStart }) => ({ path: response.filePath!, line: newStart })),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds standard ACP diff content from the structured toolResponse provided
|
||||
* by the PostToolUse hook for diff-producing tools (Edit, Write). Unlike
|
||||
* parsing the plain unified diff string, this uses the pre-parsed
|
||||
* structuredPatch which supports multiple replacement sites (replaceAll) and
|
||||
* always includes context lines for better readability.
|
||||
*/
|
||||
export function toolUpdateFromDiffToolResponse(toolResponse: unknown): {
|
||||
content?: ToolCallContent[];
|
||||
locations?: ToolCallLocation[];
|
||||
} {
|
||||
if (!toolResponse || typeof toolResponse !== "object") return {};
|
||||
const response = toolResponse as DiffToolResponse;
|
||||
if (!response.filePath || !Array.isArray(response.structuredPatch)) return {};
|
||||
|
||||
const content: ToolCallContent[] = [];
|
||||
const locations: ToolCallLocation[] = [];
|
||||
for (const { lines, newStart } of response.structuredPatch) {
|
||||
const oldText: string[] = [];
|
||||
const newText: string[] = [];
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("-")) {
|
||||
oldText.push(line.slice(1));
|
||||
} else if (line.startsWith("+")) {
|
||||
newText.push(line.slice(1));
|
||||
} else if (line === NO_NEWLINE_MARKER) {
|
||||
continue;
|
||||
} else {
|
||||
oldText.push(line.slice(1));
|
||||
newText.push(line.slice(1));
|
||||
}
|
||||
}
|
||||
if (oldText.length > 0 || newText.length > 0) {
|
||||
locations.push({ path: response.filePath, line: newStart });
|
||||
content.push({
|
||||
type: "diff",
|
||||
path: response.filePath,
|
||||
oldText: oldText.join("\n") || null,
|
||||
newText: newText.join("\n"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// A Write `update` can arrive with an empty structuredPatch — nothing
|
||||
// changed, the diff timed out, or the previous content was too large to
|
||||
// diff (originalFile null; SDK 0.3.252 documents the lane). Returning `{}`
|
||||
// would leave Write's optimistic tool_use-time content standing, and that
|
||||
// was built with `oldText: null` — "creation" semantics — so an overwrite
|
||||
// of a large existing file would render as creating it. Emit a truthful
|
||||
// replacement instead. Gated on `type` so Edit (whose output carries no
|
||||
// `type` and whose optimistic old/new diff is already truthful) keeps the
|
||||
// empty-return behavior. A `create` needs nothing here: the
|
||||
// tool_use-time diff shows the created file, and a client with diffPatch
|
||||
// gets it from the Write reporter.
|
||||
if (content.length === 0 && response.type === "update" && typeof response.content === "string") {
|
||||
locations.push({ path: response.filePath });
|
||||
content.push(
|
||||
typeof response.originalFile === "string"
|
||||
? {
|
||||
type: "diff",
|
||||
path: response.filePath,
|
||||
oldText: response.originalFile,
|
||||
newText: response.content,
|
||||
}
|
||||
: {
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: `Updated \`${response.filePath}\` (previous content too large to diff)`,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const result: { content?: ToolCallContent[]; locations?: ToolCallLocation[] } = {};
|
||||
if (content.length > 0) result.content = content;
|
||||
if (locations.length > 0) result.locations = locations;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ACP v2 diff of a finished Edit or Write: the exact patch of
|
||||
* {@link patchUpdateFromDiffToolResponse} when it can be built, else the
|
||||
* change with a patch from what the toolResponse holds.
|
||||
*
|
||||
* The fallback patch of an update comes from the `structuredPatch`, which is
|
||||
* display data (see {@link patchUpdateFromDiffToolResponse}). That is enough
|
||||
* for a v2 patch, which is renderable text, not a patch to apply. An update
|
||||
* without hunks, such as one whose previous content was too large to diff,
|
||||
* gets the change alone. An Edit with an empty `old_string` reports the same
|
||||
* response for a created file and a filled empty one, so it gets no diff.
|
||||
*/
|
||||
export async function v2UpdateFromDiffToolResponse(toolResponse: unknown): Promise<{
|
||||
content?: ToolCallContent[];
|
||||
locations?: ToolCallLocation[];
|
||||
}> {
|
||||
const exact = await patchUpdateFromDiffToolResponse(toolResponse, "v2");
|
||||
if (exact) return exact;
|
||||
if (!toolResponse || typeof toolResponse !== "object") return {};
|
||||
const response = toolResponse as DiffToolResponse;
|
||||
const filePath = response.filePath;
|
||||
if (typeof filePath !== "string") return {};
|
||||
if (response.type === "create") {
|
||||
const hunk =
|
||||
typeof response.content === "string" && isPatchableText(response.content)
|
||||
? wholeFileHunk(response.content)
|
||||
: undefined;
|
||||
return {
|
||||
content: [v2DiffContent(filePath, "create", hunk && [hunk])],
|
||||
locations: [{ path: filePath }],
|
||||
};
|
||||
}
|
||||
if (response.type === undefined && response.oldString === "" && response.originalFile === "") {
|
||||
return {};
|
||||
}
|
||||
// A Write whose content is the previous text changed nothing.
|
||||
if (response.type === "update" && response.content === response.originalFile) return {};
|
||||
const hunks =
|
||||
Array.isArray(response.structuredPatch) && response.structuredPatch.length > 0
|
||||
? response.structuredPatch
|
||||
: undefined;
|
||||
return {
|
||||
content: [v2DiffContent(filePath, "update", hunks)],
|
||||
locations: hunks
|
||||
? hunks.map(({ newStart }) => ({ path: filePath, line: newStart }))
|
||||
: [{ path: filePath }],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of one git patch for `filePath`.
|
||||
*
|
||||
* The headers follow `git diff`: the path is quoted when git would quote it,
|
||||
* and a created file gets its mode line and a `/dev/null` side. With `git`
|
||||
* paths, the path loses its leading slash and gets the `a/` and `b/` prefixes.
|
||||
*/
|
||||
export function gitPatchText(
|
||||
filePath: string,
|
||||
change: FileChange,
|
||||
hunks: PatchHunk[],
|
||||
paths: GitPatchPaths = "git",
|
||||
): string {
|
||||
return [
|
||||
...gitPatchHeader(filePath, change, paths),
|
||||
...hunks.flatMap((hunk) => [hunkHeader(hunk), ...hunk.lines]),
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function gitPatchHeader(filePath: string, change: FileChange, paths: GitPatchPaths): string[] {
|
||||
// git's form uses forward slashes, so the header names the same file on
|
||||
// every platform, and drops one leading slash of an absolute path. An ACP v2
|
||||
// patch keeps the native path so that, once unquoted, it equals the `changes`
|
||||
// entry: `C:\work\App.ts` is written `"C:\\work\\App.ts"`.
|
||||
const name = paths === "git" ? filePath.replaceAll("\\", "/").replace(/^\/+/u, "") : filePath;
|
||||
const oldName = quoteGitPath(paths === "git" ? "a/" : "", name);
|
||||
const newName = quoteGitPath(paths === "git" ? "b/" : "", name);
|
||||
// git ends a ---/+++ name that contains a space with a tab, for GNU patch.
|
||||
const tab = name.includes(" ") ? "\t" : "";
|
||||
return [
|
||||
`diff --git ${oldName} ${newName}`,
|
||||
...(change === "create" ? ["new file mode 100644"] : []),
|
||||
`--- ${change === "create" ? "/dev/null" : `${oldName}${tab}`}`,
|
||||
`+++ ${newName}${tab}`,
|
||||
];
|
||||
}
|
||||
|
||||
const GIT_PATH_ESCAPES: Record<number, string> = {
|
||||
0x07: "a",
|
||||
0x08: "b",
|
||||
0x09: "t",
|
||||
0x0a: "n",
|
||||
0x0b: "v",
|
||||
0x0c: "f",
|
||||
0x0d: "r",
|
||||
0x22: '"',
|
||||
0x5c: "\\",
|
||||
};
|
||||
|
||||
/**
|
||||
* Quotes `prefix + name` like git with the default `core.quotePath`.
|
||||
*
|
||||
* A double quote, a backslash, a control byte, or a non-ASCII byte makes git
|
||||
* put the whole name in double quotes. git then writes a C escape or a
|
||||
* three-digit octal escape for each such UTF-8 byte.
|
||||
*/
|
||||
function quoteGitPath(prefix: string, name: string): string {
|
||||
const full = `${prefix}${name}`;
|
||||
let quoted = "";
|
||||
let needsQuotes = false;
|
||||
for (const byte of Buffer.from(full, "utf8")) {
|
||||
const escape = GIT_PATH_ESCAPES[byte];
|
||||
if (escape !== undefined) {
|
||||
quoted += `\\${escape}`;
|
||||
needsQuotes = true;
|
||||
} else if (byte < 0x20 || byte >= 0x7f) {
|
||||
quoted += `\\${byte.toString(8).padStart(3, "0")}`;
|
||||
needsQuotes = true;
|
||||
} else {
|
||||
quoted += String.fromCharCode(byte);
|
||||
}
|
||||
}
|
||||
return needsQuotes ? `"${quoted}"` : full;
|
||||
}
|
||||
|
||||
function hunkHeader({ oldStart, oldLines, newStart, newLines }: PatchHunk): string {
|
||||
return `@@ -${hunkRange(oldStart, oldLines)} +${hunkRange(newStart, newLines)} @@`;
|
||||
}
|
||||
|
||||
/** A git hunk range. A side with zero lines names the line before the change. */
|
||||
function hunkRange(start: number, count: number): string {
|
||||
if (count === 0) return `${Math.max(0, start - 1)},0`;
|
||||
return count === 1 ? String(start) : `${start},${count}`;
|
||||
}
|
||||
|
||||
/** The hunk that adds every line of `text` to an empty file. */
|
||||
function wholeFileHunk(text: string): PatchHunk | undefined {
|
||||
if (text.length === 0) return undefined;
|
||||
const terminated = text.endsWith("\n");
|
||||
const lines = (terminated ? text.slice(0, -1) : text).split("\n");
|
||||
return {
|
||||
oldStart: 1,
|
||||
oldLines: 0,
|
||||
newStart: 1,
|
||||
newLines: lines.length,
|
||||
lines: [...lines.map((line) => `+${line}`), ...(terminated ? [] : [NO_NEWLINE_MARKER])],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The line-diff hunks between two texts. Returns undefined when the diff runs
|
||||
* out of its time budget.
|
||||
*/
|
||||
function diffHunks(oldText: string | null, newText: string): PatchHunk[] | undefined {
|
||||
if (oldText === null) {
|
||||
const hunk = wholeFileHunk(newText);
|
||||
return hunk ? [hunk] : [];
|
||||
}
|
||||
const oldLines = textLines(oldText);
|
||||
const newLines = textLines(newText);
|
||||
// The diff gets only the changed middle and its context lines. An edit
|
||||
// usually changes a small part of a large file.
|
||||
const common = Math.min(oldLines.length, newLines.length);
|
||||
let prefix = 0;
|
||||
while (prefix < common && oldLines[prefix] === newLines[prefix]) prefix++;
|
||||
let suffix = 0;
|
||||
while (
|
||||
suffix < common - prefix &&
|
||||
oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]
|
||||
) {
|
||||
suffix++;
|
||||
}
|
||||
const skipped = Math.max(0, prefix - PATCH_CONTEXT_LINES);
|
||||
const skippedEnd = Math.max(0, suffix - PATCH_CONTEXT_LINES);
|
||||
const patch = structuredPatch(
|
||||
"",
|
||||
"",
|
||||
oldLines.slice(skipped, oldLines.length - skippedEnd).join(""),
|
||||
newLines.slice(skipped, newLines.length - skippedEnd).join(""),
|
||||
"",
|
||||
"",
|
||||
{ context: PATCH_CONTEXT_LINES, timeout: PATCH_DIFF_TIMEOUT_MS },
|
||||
);
|
||||
return patch?.hunks.map((hunk) => ({
|
||||
...hunk,
|
||||
oldStart: hunk.oldStart + skipped,
|
||||
newStart: hunk.newStart + skipped,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The lines of a text, each with its line break. The last line can have none. */
|
||||
function textLines(text: string): string[] {
|
||||
return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The patch of a change from `oldText`, null for a missing file, to
|
||||
* `newText`. Returns undefined when nothing changed or the diff runs out of
|
||||
* its time budget.
|
||||
*/
|
||||
function filePatch(oldText: string | null, newText: string): FilePatch | undefined {
|
||||
const hunks = memoizedDiffHunks(oldText, newText);
|
||||
if (!hunks || hunks.length === 0) return undefined;
|
||||
return { change: oldText === null ? "create" : "update", hunks };
|
||||
}
|
||||
|
||||
/** The number of recent line diffs that {@link memoizedDiffHunks} keeps. */
|
||||
const DIFF_MEMO_SIZE = 4;
|
||||
|
||||
/** Recent line diffs not read again yet, the most recent last. A text of at
|
||||
* most {@link MAX_PATCH_FILE_BYTES} is held until it is read again or later
|
||||
* diffs push it out. */
|
||||
const diffMemo: { oldText: string | null; newText: string; hunks: PatchHunk[] }[] = [];
|
||||
|
||||
/**
|
||||
* {@link diffHunks} of a recent pair of texts again, without a second diff.
|
||||
*
|
||||
* The approval of an Edit or Write diffs the file against the predicted text,
|
||||
* and the PostToolUse hook diffs the same texts once Claude wrote them. On a
|
||||
* large file each diff can block the event loop for its whole time budget.
|
||||
* Only a diff that completed is remembered: one that ran out of its budget
|
||||
* says nothing about the texts, so a later call diffs them again. The hunks
|
||||
* are shared, and no caller changes them.
|
||||
*/
|
||||
function memoizedDiffHunks(oldText: string | null, newText: string): PatchHunk[] | undefined {
|
||||
const index = diffMemo.findIndex(
|
||||
(entry) => entry.oldText === oldText && entry.newText === newText,
|
||||
);
|
||||
if (index >= 0) {
|
||||
// The hook is normally the last reader of a pair, so the entry goes: the
|
||||
// memo does not hold two large texts longer than needed.
|
||||
const [entry] = diffMemo.splice(index, 1);
|
||||
return entry.hunks;
|
||||
}
|
||||
const hunks = diffHunks(oldText, newText);
|
||||
if (hunks) {
|
||||
diffMemo.push({ oldText, newText, hunks });
|
||||
if (diffMemo.length > DIFF_MEMO_SIZE) diffMemo.shift();
|
||||
}
|
||||
return hunks;
|
||||
}
|
||||
|
||||
/** Forget the remembered line diffs. For tests. */
|
||||
export function clearDiffMemo(): void {
|
||||
diffMemo.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a file as patch input.
|
||||
*
|
||||
* Returns null when the file does not exist. Returns undefined when the file
|
||||
* cannot be read, is not a regular file, is larger than
|
||||
* {@link MAX_PATCH_FILE_BYTES}, is binary, is not valid UTF-8, or contains a
|
||||
* CR.
|
||||
*/
|
||||
async function readPatchSource(filePath: string): Promise<string | null | undefined> {
|
||||
let handle: FileHandle;
|
||||
try {
|
||||
// O_NONBLOCK keeps the open of a FIFO from waiting for a writer. It does not change a regular file.
|
||||
handle = await open(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
|
||||
} catch (error) {
|
||||
return isMissingFileError(error) ? null : undefined;
|
||||
}
|
||||
try {
|
||||
// The checks and the read use one open file, so a swap of the path between them has no effect.
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isFile() || stats.size > MAX_PATCH_FILE_BYTES) return undefined;
|
||||
// One byte more than the checked size shows a file that grew after the check.
|
||||
const buffer = Buffer.alloc(stats.size + 1);
|
||||
let length = 0;
|
||||
while (length < buffer.length) {
|
||||
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
|
||||
if (bytesRead === 0) break;
|
||||
length += bytesRead;
|
||||
}
|
||||
if (length > stats.size) return undefined;
|
||||
const text = decodeFileText(buffer.subarray(0, length));
|
||||
return text?.includes("\r") ? undefined : text;
|
||||
} catch {
|
||||
return undefined;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The text of a file of at most {@link MAX_PATCH_FILE_BYTES} that is not binary and is valid UTF-8. */
|
||||
function decodeFileText(bytes: Uint8Array): string | undefined {
|
||||
if (bytes.length > MAX_PATCH_FILE_BYTES) return undefined;
|
||||
if (bytes.subarray(0, BINARY_SNIFF_BYTES).includes(0)) return undefined;
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a tool input text can be the new side of an exact patch. */
|
||||
function isPatchableText(text: string): boolean {
|
||||
return (
|
||||
Buffer.byteLength(text, "utf8") <= MAX_PATCH_FILE_BYTES &&
|
||||
!text.includes("\0") &&
|
||||
!text.includes("\r")
|
||||
);
|
||||
}
|
||||
|
||||
/** The exact patch content of a change, or undefined when it has no patch. */
|
||||
function exactPatch(
|
||||
filePath: string,
|
||||
oldText: string | null,
|
||||
newText: string,
|
||||
form: PatchForm,
|
||||
): ToolCallContent[] | undefined {
|
||||
const patch = filePatch(oldText, newText);
|
||||
return patch && [patchContent(filePath, patch, form)];
|
||||
}
|
||||
|
||||
/** The content that carries a patch, in the given form. */
|
||||
function patchContent(filePath: string, patch: FilePatch, form: PatchForm): ToolCallContent {
|
||||
return form === "v2"
|
||||
? v2DiffContent(filePath, patch.change, patch.hunks)
|
||||
: airPatchContent(filePath, patch);
|
||||
}
|
||||
|
||||
/**
|
||||
* A diff block in the AIR patch form.
|
||||
*
|
||||
* `oldText: null` and `newText: ""` only satisfy the ACP schema. The adapter
|
||||
* sends this form only to a client that advertised `diffPatch`.
|
||||
*/
|
||||
function airPatchContent(filePath: string, { change, hunks }: FilePatch): ToolCallContent {
|
||||
return {
|
||||
type: "diff",
|
||||
path: filePath,
|
||||
oldText: null,
|
||||
newText: "",
|
||||
_meta: withAirMeta(undefined, AIR_DIFF_PATCH_CAPABILITY, {
|
||||
version: 1,
|
||||
format: "git_patch",
|
||||
text: gitPatchText(filePath, change, hunks),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The ACP v2 diff of a change to the text file `filePath`: the change and,
|
||||
* given hunks, its git patch.
|
||||
*
|
||||
* The agent builds tool call content in v1 types, and v1 cannot express a v2
|
||||
* diff, so the diff travels as v1 content. Nothing in the agent reads inside a
|
||||
* diff, and only a v2 client gets one: the v2 core sends it as it is
|
||||
* (`src/v2/tool-call.ts`).
|
||||
*/
|
||||
export function v2DiffContent(
|
||||
filePath: string,
|
||||
change: FileChange,
|
||||
hunks?: PatchHunk[],
|
||||
): ToolCallContent {
|
||||
const fileChange: v2.DiffChange =
|
||||
change === "create"
|
||||
? { operation: "add", path: filePath, fileType: "text" }
|
||||
: { operation: "modify", path: filePath, fileType: "text" };
|
||||
const diff: V2DiffContent = {
|
||||
type: "diff",
|
||||
changes: [fileChange],
|
||||
...(hunks?.length
|
||||
? { patch: { format: "git_patch", text: gitPatchText(filePath, change, hunks, "absolute") } }
|
||||
: {}),
|
||||
};
|
||||
return diff as unknown as ToolCallContent;
|
||||
}
|
||||
|
||||
function resolveToolPath(filePath: string, cwd?: string): string {
|
||||
return path.isAbsolute(filePath) ? filePath : path.resolve(cwd ?? process.cwd(), filePath);
|
||||
}
|
||||
|
||||
function isMissingFileError(error: unknown): boolean {
|
||||
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
||||
}
|
||||
@@ -1,673 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type {
|
||||
CreateElicitationRequest,
|
||||
CreateElicitationResponse,
|
||||
ElicitationPropertySchema,
|
||||
ElicitationSchema,
|
||||
EnumOption,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
ElicitationRequest,
|
||||
ElicitationResult,
|
||||
PermissionResult,
|
||||
UserDialogRequest,
|
||||
UserDialogResult,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import type {
|
||||
AskUserQuestionInput,
|
||||
AskUserQuestionOutput,
|
||||
} from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
|
||||
import {
|
||||
AIR_CUSTOM_ANSWER_KEY,
|
||||
LEGACY_AIR_CUSTOM_ANSWER_KEY,
|
||||
withAirMeta,
|
||||
} from "./air-extension.js";
|
||||
|
||||
/**
|
||||
* Bridges between the Claude Agent SDK's elicitation/dialog callbacks and ACP's
|
||||
* (unstable) elicitation protocol.
|
||||
*
|
||||
* Two distinct SDK surfaces flow through here:
|
||||
*
|
||||
* 1. `onElicitation` — fired when an MCP server requests user input. These map
|
||||
* directly onto ACP `session/create_elicitation` (form or url mode).
|
||||
* 2. The built-in AskUserQuestion tool — when a `canUseTool` callback is
|
||||
* registered the SDK routes its permission check through `canUseTool`
|
||||
* (not the interactive `permission_ask_user_question` dialog). We render
|
||||
* its questions as an ACP form elicitation and feed the user's selections
|
||||
* back as the tool's `updatedInput`, which the tool's own `call()` reads.
|
||||
*/
|
||||
|
||||
/** Modes the connected client advertised support for. */
|
||||
export type ElicitationSupport = {
|
||||
form: boolean;
|
||||
url: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert an MCP elicitation request (from the SDK's `onElicitation` callback)
|
||||
* into an ACP `CreateElicitationRequest`. Returns `null` when the request can't
|
||||
* be represented (e.g. a url-mode request with no url).
|
||||
*/
|
||||
export function mcpElicitationToCreateRequest(
|
||||
request: ElicitationRequest,
|
||||
sessionId: string,
|
||||
): CreateElicitationRequest | null {
|
||||
if (request.mode === "url") {
|
||||
if (!request.url) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
mode: "url",
|
||||
sessionId,
|
||||
message: request.message,
|
||||
url: request.url,
|
||||
// URL elicitations need a stable id so the client can correlate the
|
||||
// later `session/complete_elicitation` notification. MCP servers usually
|
||||
// provide one; fall back to a generated id if not.
|
||||
elicitationId: request.elicitationId ?? randomUUID(),
|
||||
};
|
||||
}
|
||||
|
||||
// Form mode (the default). The MCP `requestedSchema` is already a JSON Schema
|
||||
// with primitive-typed properties, which is structurally what ACP expects.
|
||||
return {
|
||||
mode: "form",
|
||||
sessionId,
|
||||
message: request.message,
|
||||
requestedSchema: normalizeElicitationSchema(request.requestedSchema),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Content of an accepted elicitation response, or `{}` when the response is
|
||||
* no accept or its `content` is no JSON object.
|
||||
*
|
||||
* The values are not checked. v1 allows a string, number, boolean, or string
|
||||
* array; v2 also allows any other JSON value, such as an object. An MCP
|
||||
* server checks the content against its own `requestedSchema`, so it gets the
|
||||
* content as the client sent it: before, an accept whose content held an
|
||||
* object reached the server as `{ action: "accept", content: {} }`. Callers
|
||||
* that read a field must check its type.
|
||||
*/
|
||||
function acceptedElicitationContent(response: CreateElicitationResponse): Record<string, unknown> {
|
||||
if (response.action !== "accept") return {};
|
||||
const content: unknown = (response as { content?: unknown }).content;
|
||||
return content !== null && typeof content === "object" && !Array.isArray(content)
|
||||
? (content as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an ACP elicitation response back to the MCP `ElicitResult` the SDK expects
|
||||
* to hand back to the requesting server.
|
||||
*/
|
||||
export function createElicitationResponseToElicitResult(
|
||||
response: CreateElicitationResponse,
|
||||
): ElicitationResult {
|
||||
switch (response.action) {
|
||||
case "accept":
|
||||
// `ElicitResult` types the values as v1 does. The MCP server checks them.
|
||||
return {
|
||||
action: "accept",
|
||||
content: acceptedElicitationContent(response) as ElicitationResult["content"],
|
||||
};
|
||||
case "decline":
|
||||
return { action: "decline" };
|
||||
case "cancel":
|
||||
default:
|
||||
return { action: "cancel" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A single question as supplied by the AskUserQuestion tool. Derived from the
|
||||
* SDK's input type so the shape stays in sync; the SDK validates the model's
|
||||
* tool call against this schema before it reaches us.
|
||||
*/
|
||||
export type AskUserQuestion = AskUserQuestionInput["questions"][number];
|
||||
|
||||
/**
|
||||
* Pull the well-formed questions out of an AskUserQuestion tool input. Returns
|
||||
* `null` when there are no usable questions — including the case where every
|
||||
* entry is malformed and filtering leaves an empty list — so callers can treat
|
||||
* "nothing to ask" uniformly.
|
||||
*/
|
||||
export function extractAskUserQuestions(input: Record<string, unknown>): AskUserQuestion[] | null {
|
||||
const questions = (input as { questions?: unknown }).questions;
|
||||
if (!Array.isArray(questions)) {
|
||||
return null;
|
||||
}
|
||||
const valid = questions.filter(
|
||||
(q): q is AskUserQuestion =>
|
||||
!!q && typeof q.question === "string" && Array.isArray(q.options) && q.options.length > 0,
|
||||
);
|
||||
return valid.length > 0 ? valid : null;
|
||||
}
|
||||
|
||||
/** Stable form-field key for the question at the given index. */
|
||||
function questionFieldKey(index: number): string {
|
||||
return `question_${index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form-field key for the per-question free-text "custom answer" field that sits
|
||||
* alongside `question_<n>`. Mirrors the first-party clients, where every
|
||||
* question carries its own "Other" box rather than one form-level field.
|
||||
*/
|
||||
function questionCustomFieldKey(index: number): string {
|
||||
return `question_${index}_custom`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `_meta` key under which a bridged enum option carries its `preview`, the one
|
||||
* option field ACP's `EnumOption` still has no slot for (descriptions are
|
||||
* first-class as of schema 1.19). Namespaced like the agent's other `_meta`
|
||||
* extensions (`_claude/...`).
|
||||
*/
|
||||
const OPTION_META_KEY = "_claude/askUserQuestionOption";
|
||||
|
||||
/**
|
||||
* Render the AskUserQuestion tool's questions as an ACP form elicitation.
|
||||
*
|
||||
* Fields are keyed by a short stable id (`question_<n>`) rather than the full
|
||||
* question text, so the question text appears in exactly one place per field.
|
||||
* Single-select questions use a titled `oneOf` enum; multi-select questions use
|
||||
* an array with a titled `anyOf` item enum. The enum `const` is always the
|
||||
* option label, since that is what the tool records as the answer; an option's
|
||||
* secondary text travels in the enum option's own `description` field.
|
||||
*
|
||||
* Each question is followed by its own optional free-text "custom answer" field
|
||||
* (`question_<n>_custom`), mirroring the CLI's per-question "Other" box: the
|
||||
* user can type their own answer instead of picking an option, add it to a
|
||||
* multi-select's picks, or attach it as a note to a single-select's pick (see
|
||||
* `applyAskElicitationResponse`), scoped to that specific question. Nothing is
|
||||
* marked required, so the user can also just skip — matching the built-in tool,
|
||||
* which always offers Skip + a free-text box.
|
||||
*/
|
||||
export function askUserQuestionsToCreateRequest(
|
||||
questions: AskUserQuestion[],
|
||||
sessionId: string,
|
||||
toolCallId: string | undefined,
|
||||
airClient = false,
|
||||
): CreateElicitationRequest {
|
||||
const single = questions.length === 1;
|
||||
const properties: Record<string, ElicitationPropertySchema> = {};
|
||||
|
||||
questions.forEach((question, index) => {
|
||||
const options: EnumOption[] = question.options.map((option) => {
|
||||
const enumOption: EnumOption = {
|
||||
const: option.label,
|
||||
title: option.label,
|
||||
};
|
||||
if (option.description) {
|
||||
enumOption.description = option.description;
|
||||
}
|
||||
// The SDK option's `preview` (mockups, code snippets, comparisons shown
|
||||
// on focus) still has no structural slot in `EnumOption`, so forward it
|
||||
// under ACP's reserved `_meta` extension point for clients that render it.
|
||||
if (option.preview) {
|
||||
enumOption._meta = { [OPTION_META_KEY]: { preview: option.preview } };
|
||||
}
|
||||
return enumOption;
|
||||
});
|
||||
|
||||
// For a single question the prompt is carried by `message`, so we don't
|
||||
// repeat it in the field description. With multiple questions each field
|
||||
// needs its own question text.
|
||||
const description = single ? undefined : question.question;
|
||||
const title = question.header || undefined;
|
||||
|
||||
properties[questionFieldKey(index)] = question.multiSelect
|
||||
? { type: "array", title, description, items: { anyOf: options } }
|
||||
: { type: "string", title, description, oneOf: options };
|
||||
|
||||
const customAnswer = { questionId: questionFieldKey(index), isCustomAnswer: true };
|
||||
properties[questionCustomFieldKey(index)] = {
|
||||
type: "string",
|
||||
title: "Other",
|
||||
description: question.multiSelect
|
||||
? "Type your own answer to add to your selection above (optional)."
|
||||
: "Type your own answer, or add a note to the option you chose above (optional).",
|
||||
// Marks the field as the custom answer companion of a select question,
|
||||
// under `_meta.jetbrains.air.customAnswer` and under the root key that
|
||||
// released AIR versions read. Only AIR gets the marker.
|
||||
...(airClient
|
||||
? {
|
||||
_meta: withAirMeta(
|
||||
{ [LEGACY_AIR_CUSTOM_ANSWER_KEY]: customAnswer },
|
||||
AIR_CUSTOM_ANSWER_KEY,
|
||||
customAnswer,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const requestedSchema: ElicitationSchema = {
|
||||
type: "object",
|
||||
properties,
|
||||
};
|
||||
|
||||
const message = single ? questions[0].question : "Please answer the following questions.";
|
||||
|
||||
return {
|
||||
mode: "form",
|
||||
sessionId,
|
||||
...(toolCallId ? { toolCallId } : {}),
|
||||
message,
|
||||
requestedSchema,
|
||||
};
|
||||
}
|
||||
|
||||
/** Outcome of an AskUserQuestion elicitation, decoupled from any transport. */
|
||||
export type AskUserQuestionOutcome =
|
||||
{ action: "answered"; updatedInput: Record<string, unknown> } | { action: "cancel" };
|
||||
|
||||
/**
|
||||
* Serialize a multi-select answer the way the CLI's own AskUserQuestion UI
|
||||
* does: comma-joined, with any item that itself contains the separator (or a
|
||||
* double quote) JSON-quoted. The tool's `call()` splits the string back on the
|
||||
* same rule, so a free-text answer like `Redis, not Memcached` stays one item
|
||||
* instead of reading as two more picks.
|
||||
*/
|
||||
function joinMultiSelectAnswer(items: string[]): string {
|
||||
return items
|
||||
.map((item) => (item.includes(", ") || item.includes('"') ? JSON.stringify(item) : item))
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold an ACP elicitation response into the AskUserQuestion tool's input.
|
||||
*
|
||||
* Selected labels are read back from the indexed form fields and written into
|
||||
* `answers` as a `{ [questionText]: label }` map — the key shape the tool's own
|
||||
* `call()` reads — with multi-selects comma-joined in the CLI's own quoted form
|
||||
* (see `joinMultiSelectAnswer`). A non-empty per-question custom-answer field
|
||||
* (`question_<n>_custom`) joins the selection of a multi-select question, where
|
||||
* the two fields are independent and filling both means both. For a
|
||||
* single-select question it is the answer when nothing was picked (the user
|
||||
* typed their own instead), and otherwise travels beside the pick as the
|
||||
* tool's own per-question `annotations[question].notes` — the slot the CLI
|
||||
* uses for free text attached to a selection and renders to the model as
|
||||
* `"Q"="A" notes: ...` — so a client that presents the box as a notes field
|
||||
* cannot make the selection disappear. Decline yields empty answers (the model
|
||||
* is told the user skipped rather than the turn aborting); cancel — and any
|
||||
* custom/future action we don't understand — aborts the tool call.
|
||||
*
|
||||
* With `reportUnanswered` set (the session's `system/init` listed
|
||||
* `ask_user_question_unanswered_v1`), each question left without an answer
|
||||
* also gets `annotations[question].unanswered`: `"dismissed"` for every
|
||||
* question when the user declined the form, `"skipped"` for a question left
|
||||
* blank in an accepted form. The model does not see this field; the tool
|
||||
* result carries it for clients and transcripts. A CLI without the capability
|
||||
* can refuse the whole answer over it, so it is left out there.
|
||||
*/
|
||||
export function applyAskElicitationResponse(
|
||||
response: CreateElicitationResponse,
|
||||
toolInput: Record<string, unknown>,
|
||||
questions: AskUserQuestion[],
|
||||
options: { reportUnanswered?: boolean } = {},
|
||||
): AskUserQuestionOutcome {
|
||||
// Typed against the output schema: as of SDK 0.3.319 only it lists
|
||||
// `unanswered`, though the tool reads the same annotations from its input.
|
||||
const annotations: NonNullable<AskUserQuestionOutput["annotations"]> = {};
|
||||
const withAnnotations = (answers: AskUserQuestionOutput["answers"]) => ({
|
||||
...toolInput,
|
||||
answers,
|
||||
...(Object.keys(annotations).length > 0 ? { annotations } : {}),
|
||||
});
|
||||
|
||||
if (response.action === "decline") {
|
||||
if (options.reportUnanswered) {
|
||||
for (const question of questions) {
|
||||
annotations[question.question] = { unanswered: "dismissed" };
|
||||
}
|
||||
}
|
||||
return { action: "answered", updatedInput: withAnnotations({}) };
|
||||
}
|
||||
|
||||
if (response.action !== "accept") {
|
||||
return { action: "cancel" };
|
||||
}
|
||||
|
||||
const content = acceptedElicitationContent(response);
|
||||
// Typed against the tool's own output schema so the answer/response shapes
|
||||
// stay in sync with what the built-in tool's call() expects to read back.
|
||||
const answers: AskUserQuestionOutput["answers"] = {};
|
||||
questions.forEach((question, index) => {
|
||||
const custom = content[questionCustomFieldKey(index)];
|
||||
const customText = typeof custom === "string" ? custom.trim() : "";
|
||||
|
||||
// A pick is a string, number, or boolean. Other values, such as an object
|
||||
// that a v2 client may send, are dropped instead of read as "[object Object]".
|
||||
const value = content[questionFieldKey(index)];
|
||||
const picks: string[] = (Array.isArray(value) ? value : [value])
|
||||
.filter(isElicitationScalar)
|
||||
.map(String)
|
||||
.filter((item) => item !== "");
|
||||
|
||||
// A multi-select is additive, and the form offers the selection and the
|
||||
// custom box as independent fields — a user who fills both means both, so
|
||||
// the typed answer joins the checked options.
|
||||
if (question.multiSelect) {
|
||||
const text = joinMultiSelectAnswer(customText === "" ? picks : [...picks, customText]);
|
||||
if (text !== "") {
|
||||
answers[question.question] = text;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// A single-select question is answered by exactly one thing. With no option
|
||||
// picked, the typed text is that answer (the CLI's "Other"). With an option
|
||||
// picked as well, the pick stays the answer and the text rides along as the
|
||||
// tool's per-question `notes` annotation, so neither is lost. A single-select
|
||||
// normally holds one item; the plain join only matters if a client hands
|
||||
// back an array for it, and then mirrors the old behavior.
|
||||
const picked = picks.join(", ");
|
||||
if (picked === "") {
|
||||
if (customText !== "") {
|
||||
answers[question.question] = customText;
|
||||
}
|
||||
return;
|
||||
}
|
||||
answers[question.question] = picked;
|
||||
if (customText !== "") {
|
||||
annotations[question.question] = { notes: customText };
|
||||
}
|
||||
});
|
||||
|
||||
if (options.reportUnanswered) {
|
||||
for (const question of questions) {
|
||||
if (answers[question.question] === undefined) {
|
||||
annotations[question.question] = { unanswered: "skipped" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { action: "answered", updatedInput: withAnnotations(answers) };
|
||||
}
|
||||
|
||||
function isElicitationScalar(value: unknown): value is string | number | boolean {
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce an arbitrary MCP `requestedSchema` into an ACP `ElicitationSchema`.
|
||||
* The two are structurally compatible JSON Schemas; we just guarantee the
|
||||
* `type: "object"` discriminator and a `properties` map are present. The v2
|
||||
* schema requires both, so a client on SDK 2.2.0 or later rejects an MCP
|
||||
* schema such as `{ type: "object" }` that has no `properties`.
|
||||
*/
|
||||
function normalizeElicitationSchema(
|
||||
schema: Record<string, unknown> | undefined,
|
||||
): ElicitationSchema {
|
||||
if (!schema || typeof schema !== "object") {
|
||||
return { type: "object", properties: {} };
|
||||
}
|
||||
const { properties } = schema as Partial<ElicitationSchema>;
|
||||
return { ...(schema as ElicitationSchema), type: "object", properties: properties ?? {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* The `request_user_dialog` kind the CLI emits when a model refusal has a
|
||||
* fallback available but needs user consent before retrying (e.g. Claude Fable
|
||||
* declining a request with Opus available as the fallback). Declaring this
|
||||
* kind in `supportedDialogKinds` is the opt-in: the CLI fails closed and never
|
||||
* emits an undeclared kind — the flow degrades to the classic refusal error
|
||||
* ending the turn.
|
||||
*/
|
||||
export const REFUSAL_FALLBACK_DIALOG_KIND = "refusal_fallback_prompt";
|
||||
|
||||
/**
|
||||
* Payload of the `refusal_fallback_prompt` dialog. The dialog protocol
|
||||
* transports payloads opaquely, so this shape is recovered from the CLI's own
|
||||
* schema (v2.1.177): `originalModel`/`fallbackModel` are required strings;
|
||||
* `apiRefusalCategory` (nullable), `guidanceText`, and
|
||||
* `retractedMessageUuids` are optional. We ignore `retractedMessageUuids` —
|
||||
* ACP has no way to retract already-streamed chunks.
|
||||
*/
|
||||
export type RefusalFallbackPrompt = {
|
||||
originalModel: string;
|
||||
fallbackModel: string;
|
||||
apiRefusalCategory: string | null;
|
||||
guidanceText?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the opaque dialog payload into a {@link RefusalFallbackPrompt}.
|
||||
* Returns `null` when the required fields are missing or mistyped (a newer CLI
|
||||
* may reshape the payload), so the caller can cancel the dialog and let the
|
||||
* CLI apply its default behavior instead of rendering something misleading.
|
||||
*/
|
||||
export function extractRefusalFallbackPrompt(
|
||||
payload: Record<string, unknown>,
|
||||
): RefusalFallbackPrompt | null {
|
||||
const { originalModel, fallbackModel, apiRefusalCategory, guidanceText } = payload;
|
||||
if (typeof originalModel !== "string" || typeof fallbackModel !== "string") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
originalModel,
|
||||
fallbackModel,
|
||||
apiRefusalCategory: typeof apiRefusalCategory === "string" ? apiRefusalCategory : null,
|
||||
...(typeof guidanceText === "string" && guidanceText ? { guidanceText } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Form-field key carrying the user's choice in the refusal-fallback form. */
|
||||
const REFUSAL_FALLBACK_CHOICE_KEY = "choice";
|
||||
|
||||
/** Wire values of the dialog's result enum (CLI schema). `edit_prompt` is
|
||||
* deliberately not offered: in the CLI it prefills the composer with the
|
||||
* refused prompt for edit-and-retry, and ACP has no composer-prefill surface
|
||||
* — the user can simply edit and resend on their own. */
|
||||
const RETRY_FALLBACK_RESULT = "retry_fallback";
|
||||
const KEEP_REFUSAL_RESULT = "cancelled";
|
||||
|
||||
/**
|
||||
* Render the refusal-fallback consent prompt as an ACP form elicitation: a
|
||||
* single-select between retrying on the fallback model and keeping the
|
||||
* refusal. The enum `const`s are the dialog's wire result values, so the
|
||||
* response maps back without a translation table.
|
||||
*/
|
||||
export function refusalFallbackToCreateRequest(
|
||||
prompt: RefusalFallbackPrompt,
|
||||
sessionId: string,
|
||||
): CreateElicitationRequest {
|
||||
const category = prompt.apiRefusalCategory ? ` (${prompt.apiRefusalCategory})` : "";
|
||||
const guidance = prompt.guidanceText ? `\n\n${prompt.guidanceText}` : "";
|
||||
return {
|
||||
mode: "form",
|
||||
sessionId,
|
||||
message:
|
||||
`${prompt.originalModel} declined this request${category}. ` +
|
||||
`Retry with ${prompt.fallbackModel}?` +
|
||||
guidance,
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
[REFUSAL_FALLBACK_CHOICE_KEY]: {
|
||||
type: "string",
|
||||
oneOf: [
|
||||
{
|
||||
const: RETRY_FALLBACK_RESULT,
|
||||
title: `Retry with ${prompt.fallbackModel}`,
|
||||
description: `The session continues on ${prompt.fallbackModel}.`,
|
||||
},
|
||||
{
|
||||
const: KEEP_REFUSAL_RESULT,
|
||||
title: "Keep the refusal",
|
||||
description: "You can send a new message.",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Map the elicitation response back to the dialog's result enum. Only an
|
||||
* explicit accept-with-retry resolves to `retry_fallback`; decline, cancel, a
|
||||
* skipped field, or an unrecognized value all keep the refusal — the dialog's
|
||||
* own default — so a dismissed or half-filled form can never trigger a model
|
||||
* switch the user didn't ask for.
|
||||
*/
|
||||
export function refusalFallbackResultFromResponse(response: CreateElicitationResponse): string {
|
||||
const choice = acceptedElicitationContent(response)[REFUSAL_FALLBACK_CHOICE_KEY];
|
||||
return choice === RETRY_FALLBACK_RESULT ? RETRY_FALLBACK_RESULT : KEEP_REFUSAL_RESULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* What became of an elicitation: the client's response, or `withdrawn` when
|
||||
* its signal aborted first (Claude Code withdrew the request, or a cancel or
|
||||
* close of the session did). A response that comes after the abort counts as
|
||||
* withdrawn too.
|
||||
*/
|
||||
export type ElicitationOutcome = { response: CreateElicitationResponse } | { withdrawn: true };
|
||||
|
||||
/**
|
||||
* Sends an elicitation with `send` and reads what became of it. A rejection
|
||||
* while `signal` is not aborted, such as the client's -32602 for a form it
|
||||
* cannot render, is rethrown.
|
||||
*/
|
||||
export async function elicitUnlessWithdrawn(
|
||||
signal: AbortSignal,
|
||||
send: (signal: AbortSignal) => Promise<CreateElicitationResponse>,
|
||||
): Promise<ElicitationOutcome> {
|
||||
try {
|
||||
const response = await send(signal);
|
||||
return signal.aborted ? { withdrawn: true } : { response };
|
||||
} catch (error) {
|
||||
if (signal.aborted) return { withdrawn: true };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends a built elicitation to the client (see {@link elicitUnlessWithdrawn}). */
|
||||
export type Elicit = (request: CreateElicitationRequest) => Promise<ElicitationOutcome>;
|
||||
|
||||
type ElicitationLogger = { error: (...args: unknown[]) => void };
|
||||
|
||||
/**
|
||||
* Answers an MCP server's elicitation (the SDK's `onElicitation`) through
|
||||
* `elicit`. Only the user's own decline reaches the MCP server as `decline`.
|
||||
* A request the user never saw, because the client did not advertise its
|
||||
* mode, it cannot be represented, the client answered with an error, or it
|
||||
* was withdrawn, is a `cancel`.
|
||||
*/
|
||||
export async function answerMcpElicitation(
|
||||
request: ElicitationRequest,
|
||||
{
|
||||
sessionId,
|
||||
support,
|
||||
elicit,
|
||||
logger,
|
||||
}: { sessionId: string; support: ElicitationSupport; elicit: Elicit; logger: ElicitationLogger },
|
||||
): Promise<ElicitationResult> {
|
||||
const isUrl = request.mode === "url";
|
||||
if ((isUrl && !support.url) || (!isUrl && !support.form)) {
|
||||
return { action: "cancel" };
|
||||
}
|
||||
const createRequest = mcpElicitationToCreateRequest(request, sessionId);
|
||||
if (!createRequest) {
|
||||
return { action: "cancel" };
|
||||
}
|
||||
try {
|
||||
const outcome = await elicit(createRequest);
|
||||
if ("withdrawn" in outcome) return { action: "cancel" };
|
||||
return createElicitationResponseToElicitResult(outcome.response);
|
||||
} catch (error) {
|
||||
// The client answered with an error, e.g. -32602 for a form it cannot
|
||||
// render, so the user never saw the request. MCP's `decline` means the
|
||||
// user refused; `cancel` means they made no explicit choice.
|
||||
logger.error(`Failed to forward MCP elicitation: ${error}`);
|
||||
return { action: "cancel" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents the AskUserQuestion tool's questions as a form elicitation of
|
||||
* `sessionId` through `elicit`, and returns the answers as the tool's
|
||||
* `updatedInput`. A withdrawn question, or one the user cancelled, aborts the
|
||||
* tool use. `reportUnanswered` is read once the answer is in (see
|
||||
* {@link applyAskElicitationResponse}).
|
||||
*/
|
||||
export async function answerAskUserQuestion(
|
||||
toolInput: Record<string, unknown>,
|
||||
{
|
||||
sessionId,
|
||||
toolUseID,
|
||||
airClient = false,
|
||||
reportUnanswered,
|
||||
elicit,
|
||||
logger,
|
||||
}: {
|
||||
sessionId: string;
|
||||
toolUseID: string;
|
||||
airClient?: boolean;
|
||||
reportUnanswered: () => boolean;
|
||||
elicit: Elicit;
|
||||
logger: ElicitationLogger;
|
||||
},
|
||||
): Promise<PermissionResult> {
|
||||
const questions = extractAskUserQuestions(toolInput);
|
||||
if (!questions) {
|
||||
return { behavior: "deny", message: "AskUserQuestion called with no valid questions." };
|
||||
}
|
||||
const createRequest = askUserQuestionsToCreateRequest(questions, sessionId, toolUseID, airClient);
|
||||
let outcome: ElicitationOutcome;
|
||||
try {
|
||||
outcome = await elicit(createRequest);
|
||||
} catch (error) {
|
||||
logger.error(`Failed to present AskUserQuestion elicitation: ${error}`);
|
||||
return { behavior: "deny", message: "Could not present the question to the user." };
|
||||
}
|
||||
if ("withdrawn" in outcome) {
|
||||
throw new Error("Tool use aborted");
|
||||
}
|
||||
const answer = applyAskElicitationResponse(outcome.response, toolInput, questions, {
|
||||
reportUnanswered: reportUnanswered(),
|
||||
});
|
||||
if (answer.action === "cancel") {
|
||||
throw new Error("Tool use aborted");
|
||||
}
|
||||
return { behavior: "allow", updatedInput: answer.updatedInput };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a `request_user_dialog` of Claude Code (the SDK's `onUserDialog`).
|
||||
* Only kinds declared in `supportedDialogKinds` are ever emitted; everything
|
||||
* unexpected is answered `cancelled` (the required answer for unrecognized
|
||||
* kinds), which applies the dialog's default behavior CLI-side. The only
|
||||
* declared kind is the refusal-fallback consent prompt, rendered as a form
|
||||
* elicitation. A failed or withdrawn elicitation is `cancelled` too: the CLI
|
||||
* then keeps the refusal rather than switching models without consent.
|
||||
*/
|
||||
export async function answerUserDialog(
|
||||
request: UserDialogRequest,
|
||||
{ sessionId, elicit, logger }: { sessionId: string; elicit: Elicit; logger: ElicitationLogger },
|
||||
): Promise<UserDialogResult> {
|
||||
if (request.dialogKind !== REFUSAL_FALLBACK_DIALOG_KIND) {
|
||||
return { behavior: "cancelled" };
|
||||
}
|
||||
const prompt = extractRefusalFallbackPrompt(request.payload);
|
||||
if (!prompt) {
|
||||
logger.error(
|
||||
`refusal_fallback_prompt payload had an unexpected shape; cancelling the dialog: ${JSON.stringify(request.payload)}`,
|
||||
);
|
||||
return { behavior: "cancelled" };
|
||||
}
|
||||
let outcome: ElicitationOutcome;
|
||||
try {
|
||||
outcome = await elicit(refusalFallbackToCreateRequest(prompt, sessionId));
|
||||
} catch (error) {
|
||||
logger.error(`Failed to present refusal fallback elicitation: ${error}`);
|
||||
return { behavior: "cancelled" };
|
||||
}
|
||||
if ("withdrawn" in outcome) {
|
||||
return { behavior: "cancelled" };
|
||||
}
|
||||
return { behavior: "completed", result: refusalFallbackResultFromResponse(outcome.response) };
|
||||
}
|
||||
292
src/exit-plan.ts
292
src/exit-plan.ts
@@ -1,292 +0,0 @@
|
||||
import type { SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { SDKResultMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
type ClearContextCoordinatorHost,
|
||||
type ClearContextReset,
|
||||
type ClearContextSession,
|
||||
type ClearContextTurn,
|
||||
continuePlanInFreshContext,
|
||||
} from "./clear-context-coordinator.js";
|
||||
import { parseToolResultMeta } from "./tool-result-meta.js";
|
||||
|
||||
export function acceptedPlanToolResult(
|
||||
notification: SessionNotification,
|
||||
toolUseId: string | undefined,
|
||||
): SessionNotification {
|
||||
const update = notification.update;
|
||||
if (
|
||||
!toolUseId ||
|
||||
update.sessionUpdate !== "tool_call_update" ||
|
||||
update.toolCallId !== toolUseId
|
||||
) {
|
||||
return notification;
|
||||
}
|
||||
const completed = { ...update };
|
||||
delete completed.rawOutput;
|
||||
delete completed.content;
|
||||
return { ...notification, update: { ...completed, status: "completed" } };
|
||||
}
|
||||
|
||||
function containsToolResultFor(content: unknown, toolUseId: string): boolean {
|
||||
return (
|
||||
Array.isArray(content) &&
|
||||
content.some(
|
||||
(block) =>
|
||||
typeof block === "object" &&
|
||||
block !== null &&
|
||||
(block as { type?: unknown }).type === "tool_result" &&
|
||||
(block as { tool_use_id?: unknown }).tool_use_id === toolUseId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
type ExitPlanState = {
|
||||
toolUseCache: Record<string, { name: string } | undefined>;
|
||||
pendingExitPlanModeInterruption?: { toolUseId: string; toolResultSeen: boolean };
|
||||
pendingExitPlanContextReset?: ClearContextReset;
|
||||
};
|
||||
|
||||
function rejectedExitPlanToolUseId(
|
||||
content: unknown,
|
||||
toolUseCache: ExitPlanState["toolUseCache"],
|
||||
rawToolResultMeta: unknown,
|
||||
): string | undefined {
|
||||
if (!Array.isArray(content)) return undefined;
|
||||
const toolResultMeta = parseToolResultMeta(rawToolResultMeta);
|
||||
if (!toolResultMeta) return undefined;
|
||||
for (const block of content) {
|
||||
if (typeof block !== "object" || block === null) continue;
|
||||
const { type, tool_use_id: toolUseId, is_error: isError } = block as Record<string, unknown>;
|
||||
if (
|
||||
type === "tool_result" &&
|
||||
typeof toolUseId === "string" &&
|
||||
isError === true &&
|
||||
toolResultMeta.get(toolUseId)?.nonExecutionKind === "user-rejected" &&
|
||||
toolUseCache[toolUseId]?.name === "ExitPlanMode"
|
||||
) {
|
||||
return toolUseId;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Reconcile an SDK user message with the two pending ExitPlanMode lanes and
|
||||
* return the accepted plan tool id whose rendered update must be completed. */
|
||||
export function observeExitPlanToolResults(
|
||||
message: { type: string; tool_result_meta?: unknown },
|
||||
content: unknown,
|
||||
state: ExitPlanState,
|
||||
): string | undefined {
|
||||
if (message.type !== "user") return undefined;
|
||||
|
||||
const rejectedToolUseId = rejectedExitPlanToolUseId(
|
||||
content,
|
||||
state.toolUseCache,
|
||||
message.tool_result_meta,
|
||||
);
|
||||
if (rejectedToolUseId) {
|
||||
// The stream is authoritative: resumed queries can lose the short-lived
|
||||
// marker installed by canUseTool, while metadata preserves correlation.
|
||||
state.pendingExitPlanModeInterruption = {
|
||||
toolUseId: rejectedToolUseId,
|
||||
toolResultSeen: true,
|
||||
};
|
||||
}
|
||||
|
||||
const pendingInterruption = state.pendingExitPlanModeInterruption;
|
||||
if (pendingInterruption && containsToolResultFor(content, pendingInterruption.toolUseId)) {
|
||||
pendingInterruption.toolResultSeen = true;
|
||||
}
|
||||
|
||||
const pendingReset = state.pendingExitPlanContextReset;
|
||||
return pendingReset && containsToolResultFor(content, pendingReset.toolUseId)
|
||||
? pendingReset.toolUseId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function executionDiagnostic(message: SDKResultMessage): string | undefined {
|
||||
if (message.subtype === "success") {
|
||||
return message.result.startsWith("[ede_diagnostic]") ? message.result : undefined;
|
||||
}
|
||||
return message.errors.find((error) => error.startsWith("[ede_diagnostic]"));
|
||||
}
|
||||
|
||||
/** Whether `message` is the error-shaped diagnostic Claude emits for the cycle
|
||||
* a recorded ExitPlanMode `interrupt: true` answer stopped. */
|
||||
export function isExitPlanInterruptionResult(
|
||||
message: SDKResultMessage,
|
||||
pending: ExitPlanState["pendingExitPlanModeInterruption"],
|
||||
): boolean {
|
||||
if (!pending?.toolResultSeen || !message.is_error) return false;
|
||||
const diagnostic = executionDiagnostic(message);
|
||||
return (
|
||||
!!diagnostic &&
|
||||
/(?:^|\s)result_type=user(?:\s|$)/.test(diagnostic) &&
|
||||
/(?:^|\s)stop_reason=tool_use(?:\s|$)/.test(diagnostic)
|
||||
);
|
||||
}
|
||||
|
||||
/** The base ID of an approved plan. AIR appends the review ID to keep each
|
||||
* approval in the transcript. Other clients replace one plan per session.
|
||||
* The TodoWrite checklist is a separate plan. */
|
||||
export const PLAN_MODE_PLAN_ID = "plan-mode";
|
||||
|
||||
/** The plan, trimmed, that a successful ExitPlanMode result approved: the plan
|
||||
* of the structured `output`, which includes the user's edits, else the plan
|
||||
* that Claude Code adds to the tool's `input`. Replay has only the input: the
|
||||
* SDK's `getSessionMessages` drops the structured output that the transcript
|
||||
* keeps. Undefined for a subagent's plan, one that waits for its team lead
|
||||
* (both only known from the output), and an empty plan. */
|
||||
export function approvedPlan(input: unknown, output: unknown): string | undefined {
|
||||
const result = output as
|
||||
{ plan?: unknown; isAgent?: unknown; awaitingLeaderApproval?: unknown } | undefined;
|
||||
if (result?.isAgent === true || result?.awaitingLeaderApproval === true) return undefined;
|
||||
const plan =
|
||||
typeof result?.plan === "string"
|
||||
? result.plan
|
||||
: (input as { plan?: unknown } | undefined)?.plan;
|
||||
return typeof plan === "string" && plan.trim() !== "" ? plan.trim() : undefined;
|
||||
}
|
||||
|
||||
/** The update that shows an approved plan to a client that supports plan
|
||||
* operations (the `plan` client capability, which every v2 client has).
|
||||
* For AIR, pass the review ID to join the plan to its approval card. */
|
||||
export function planModeUpdate(
|
||||
plan: string,
|
||||
reviewToolCallId?: string,
|
||||
): SessionNotification["update"] {
|
||||
return {
|
||||
sessionUpdate: "plan_update",
|
||||
plan: {
|
||||
type: "markdown",
|
||||
planId: reviewToolCallId ? `${PLAN_MODE_PLAN_ID}:${reviewToolCallId}` : PLAN_MODE_PLAN_ID,
|
||||
content: plan,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Claude wraps a rejected ExitPlanMode explanation in a Markdown code fence.
|
||||
* Strip exactly one complete outer fence for that tool only. */
|
||||
export function exitPlanModeRawOutput(toolName: string, content: unknown): unknown {
|
||||
if (toolName !== "ExitPlanMode" || typeof content !== "string") {
|
||||
return content;
|
||||
}
|
||||
const fenced = /^\s*```[^\r\n]*\r?\n([\s\S]*?)\r?\n```\s*$/.exec(content);
|
||||
return fenced?.[1] ?? content;
|
||||
}
|
||||
|
||||
export type ExitPlanRestartHost<
|
||||
Session extends ClearContextSession<Turn>,
|
||||
Turn extends ClearContextTurn,
|
||||
> = Omit<
|
||||
ClearContextCoordinatorHost<Session, Turn>,
|
||||
"publishSessionState" | "continuationMessage"
|
||||
> & {
|
||||
sessionUpdate(notification: SessionNotification): Promise<void>;
|
||||
/** Whether the client takes plan operations (see planModeUpdate). */
|
||||
supportsPlanOperations(): boolean;
|
||||
isAirClient(): boolean;
|
||||
destroyReplacement(sessionId: string, session: Session): void;
|
||||
settleCancelledTurn(oldSession: Session, turnSession: Session, turn: Turn): void;
|
||||
settleFailedTurn(turnSession: Session, turn: Turn, error: unknown): void;
|
||||
};
|
||||
|
||||
/** Owns the lifetime of accepted-plan context replacements. In particular, a
|
||||
* session cancellation invalidates an in-progress async restart so a late
|
||||
* restartSession result cannot recreate a closed public session. */
|
||||
export class ExitPlanCoordinator<
|
||||
Session extends ClearContextSession<Turn>,
|
||||
Turn extends ClearContextTurn,
|
||||
> {
|
||||
private readonly restarts = new Map<string, AbortController>();
|
||||
|
||||
constructor(private readonly host: ExitPlanRestartHost<Session, Turn>) {}
|
||||
|
||||
cancel(sessionId: string): void {
|
||||
this.restarts.get(sessionId)?.abort();
|
||||
}
|
||||
|
||||
async restart(sessionId: string, oldSession: Session, reset: ClearContextReset): Promise<void> {
|
||||
this.cancel(sessionId);
|
||||
const controller = new AbortController();
|
||||
this.restarts.set(sessionId, controller);
|
||||
try {
|
||||
const clearContextHost: ClearContextCoordinatorHost<Session, Turn> = {
|
||||
...this.host,
|
||||
publishSessionState: async (id, mode, configOptions, contextWindowSize) => {
|
||||
await this.host.sessionUpdate({
|
||||
sessionId: id,
|
||||
update: { sessionUpdate: "current_mode_update", currentModeId: mode },
|
||||
});
|
||||
await this.host.sessionUpdate({
|
||||
sessionId: id,
|
||||
update: { sessionUpdate: "config_option_update", configOptions },
|
||||
});
|
||||
// Otherwise the client shows the old context's usage until the fresh
|
||||
// context first reports its own.
|
||||
await this.host.sessionUpdate({
|
||||
sessionId: id,
|
||||
update: { sessionUpdate: "usage_update", used: 0, size: contextWindowSize },
|
||||
});
|
||||
// The approved plan becomes the session's plan once the fresh
|
||||
// context that carries it out exists. Its ExitPlanMode ended with
|
||||
// an error result, so toAcpNotifications did not publish it.
|
||||
if (this.host.supportsPlanOperations()) {
|
||||
await this.host.sessionUpdate({
|
||||
sessionId: id,
|
||||
update: planModeUpdate(
|
||||
reset.plan,
|
||||
this.host.isAirClient() ? reset.toolUseId : undefined,
|
||||
),
|
||||
});
|
||||
}
|
||||
},
|
||||
continuationMessage: (id, plan, promptUuid) => ({
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "text", text: `Implement the following plan:\n\n${plan}` }],
|
||||
},
|
||||
session_id: id,
|
||||
parent_tool_use_id: null,
|
||||
origin: { kind: "human" },
|
||||
uuid: promptUuid as `${string}-${string}-${string}-${string}-${string}`,
|
||||
}),
|
||||
};
|
||||
await continuePlanInFreshContext(
|
||||
sessionId,
|
||||
oldSession,
|
||||
reset,
|
||||
clearContextHost,
|
||||
controller.signal,
|
||||
);
|
||||
} catch (error) {
|
||||
const currentSession = this.host.currentSession(sessionId);
|
||||
const replacement = currentSession !== oldSession ? currentSession : undefined;
|
||||
if (replacement) this.host.destroyReplacement(sessionId, replacement);
|
||||
|
||||
const turn = replacement?.activeTurn ?? oldSession.activeTurn;
|
||||
if (turn && !turn.settled) {
|
||||
const turnSession = replacement?.activeTurn === turn ? replacement : oldSession;
|
||||
if (controller.signal.aborted) {
|
||||
this.host.settleCancelledTurn(oldSession, turnSession, turn);
|
||||
} else {
|
||||
// A provider/session-creation failure is turn-scoped. Settling it
|
||||
// here keeps it out of the query consumer's transport-loss catch.
|
||||
this.host.settleFailedTurn(turnSession, turn, error);
|
||||
}
|
||||
oldSession.activeTurn = null;
|
||||
oldSession.turnQueue = (oldSession.turnQueue ?? []).filter((queued) => queued !== turn);
|
||||
if (replacement) {
|
||||
replacement.activeTurn = null;
|
||||
replacement.turnQueue = (replacement.turnQueue ?? []).filter((queued) => queued !== turn);
|
||||
}
|
||||
}
|
||||
oldSession.pendingExitPlanContextReset = undefined;
|
||||
} finally {
|
||||
if (this.restarts.get(sessionId) === controller) {
|
||||
this.restarts.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
import type { Query, RewindFilesResult } from "@anthropic-ai/claude-agent-sdk";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { airExtensionMeta, clientSupportsAirCapability, withAirMeta } from "./air-extension.js";
|
||||
|
||||
export const AGENT_FILE_CHANGE_REPORT_CAPABILITY = "agentFileChangeReport";
|
||||
|
||||
const MAX_REPORTED_PATHS = 1024;
|
||||
const MAX_REPORTED_PATH_LENGTH = 4096;
|
||||
export const AGENT_FILE_CHANGE_REPORT_MAX_BYTES = 256 * 1024;
|
||||
export const AGENT_FILE_CHANGE_REPORT_TIMEOUT_MS = 2_000;
|
||||
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
|
||||
|
||||
export type FileChangeReportTurnState = {
|
||||
requestId: string;
|
||||
phase: "requested" | "collecting" | "finished";
|
||||
};
|
||||
|
||||
export type NativeFileChangeReportTurn = {
|
||||
promptUuid: string;
|
||||
fileChangeReport?: FileChangeReportTurnState;
|
||||
/** Raw `file_path`/`notebook_path` values of the file-tool edits that
|
||||
* subagents of this turn completed. Checkpoints do not track files that
|
||||
* only a subagent edited. */
|
||||
editedPaths?: Set<string>;
|
||||
};
|
||||
|
||||
export type FileChangeReportWorkspace = {
|
||||
cwd: string;
|
||||
additionalDirectories: string[];
|
||||
};
|
||||
|
||||
export type AgentFileChangeReportResult = {
|
||||
version: 1;
|
||||
requestId: string;
|
||||
} & (
|
||||
| {
|
||||
status: "reported";
|
||||
paths: string[];
|
||||
declaredComplete: boolean;
|
||||
truncated: boolean;
|
||||
}
|
||||
| {
|
||||
status: "unavailable";
|
||||
reason: FileChangeReportUnavailableReason;
|
||||
}
|
||||
);
|
||||
|
||||
export type FileChangeReportUnavailableReason =
|
||||
"cancelled" | "timeout" | "invalidOutput" | "notReported" | "providerError";
|
||||
|
||||
type NativeFileChangeReporterOptions = {
|
||||
cwd: string;
|
||||
additionalDirectories: string[];
|
||||
publish: (result: AgentFileChangeReportResult) => Promise<void>;
|
||||
logError: (message: string) => void;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
export type NativeFileChangeReporter = {
|
||||
request(meta: unknown): FileChangeReportTurnState | undefined;
|
||||
report(
|
||||
turn: NativeFileChangeReportTurn | null | undefined,
|
||||
query: Pick<Query, "rewindFiles">,
|
||||
): Promise<void>;
|
||||
finish(
|
||||
state: FileChangeReportTurnState | undefined,
|
||||
reason: FileChangeReportUnavailableReason,
|
||||
): void;
|
||||
};
|
||||
|
||||
export function agentFileChangeReportRequestId(meta: unknown): string | undefined {
|
||||
const air = airExtensionMeta(meta);
|
||||
const request = air?.agentFileChangeReportRequest;
|
||||
if (!request || typeof request !== "object" || Array.isArray(request)) return undefined;
|
||||
const requestRecord = request as Record<string, unknown>;
|
||||
const requestKeys = Object.keys(requestRecord);
|
||||
if (
|
||||
requestKeys.length !== 2 ||
|
||||
!requestKeys.includes("version") ||
|
||||
!requestKeys.includes("requestId") ||
|
||||
requestRecord.version !== 1
|
||||
)
|
||||
return undefined;
|
||||
const requestId = requestRecord.requestId;
|
||||
return typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)
|
||||
? requestId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function supportsAgentFileChangeReport(capabilities: unknown): boolean {
|
||||
return clientSupportsAirCapability(capabilities, AGENT_FILE_CHANGE_REPORT_CAPABILITY);
|
||||
}
|
||||
|
||||
export function agentFileChangeReportMeta(
|
||||
result: AgentFileChangeReportResult,
|
||||
): Record<string, unknown> {
|
||||
return withAirMeta(undefined, AGENT_FILE_CHANGE_REPORT_CAPABILITY, result);
|
||||
}
|
||||
|
||||
const FILE_EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
||||
|
||||
/**
|
||||
* Adds to `turn.editedPaths` the `file_path` (`notebook_path` for NotebookEdit)
|
||||
* of each successful file-tool edit among the tool results of a subagent
|
||||
* message. Root-agent messages (`parentToolUseId === null`) are skipped: the
|
||||
* checkpoint already tracks their files. A turn that v1 marked `settled`
|
||||
* records nothing. Must run before `toAcpNotifications` drops the tool use
|
||||
* cache entries.
|
||||
*/
|
||||
export function recordSubagentFileEdits(
|
||||
turn: (NativeFileChangeReportTurn & { settled?: boolean }) | null | undefined,
|
||||
parentToolUseId: string | null,
|
||||
content: unknown,
|
||||
toolUses: Record<string, { name: string; input: unknown } | undefined>,
|
||||
): void {
|
||||
if (parentToolUseId === null || !turn || turn.settled || !turn.fileChangeReport) return;
|
||||
if (!Array.isArray(content)) return;
|
||||
for (const block of content) {
|
||||
if (
|
||||
block?.type !== "tool_result" ||
|
||||
block.is_error === true ||
|
||||
typeof block.tool_use_id !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const toolUse = toolUses[block.tool_use_id];
|
||||
if (!toolUse || !FILE_EDIT_TOOLS.has(toolUse.name)) continue;
|
||||
const input = toolUse.input as Record<string, unknown> | undefined;
|
||||
const editedPath = toolUse.name === "NotebookEdit" ? input?.notebook_path : input?.file_path;
|
||||
if (typeof editedPath === "string" && editedPath.length > 0) {
|
||||
(turn.editedPaths ??= new Set()).add(editedPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createNativeFileChangeReporter(
|
||||
options: NativeFileChangeReporterOptions,
|
||||
): NativeFileChangeReporter {
|
||||
const workspace = normalizeWorkspace(options.cwd, options.additionalDirectories);
|
||||
const timeoutMs = options.timeoutMs ?? AGENT_FILE_CHANGE_REPORT_TIMEOUT_MS;
|
||||
const requestIds = new Set<string>();
|
||||
|
||||
async function publish(state: FileChangeReportTurnState, result: AgentFileChangeReportResult) {
|
||||
if (state.phase === "finished") return;
|
||||
state.phase = "finished";
|
||||
try {
|
||||
await options.publish(result);
|
||||
} catch (error) {
|
||||
options.logError(`Failed to publish file-change report ${state.requestId}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function finishUnavailable(
|
||||
state: FileChangeReportTurnState,
|
||||
reason: FileChangeReportUnavailableReason,
|
||||
) {
|
||||
await publish(state, {
|
||||
version: 1,
|
||||
requestId: state.requestId,
|
||||
status: "unavailable",
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
async function publishReported(state: FileChangeReportTurnState, reportedPaths: string[]) {
|
||||
const normalized = normalizeReportedPaths(reportedPaths, workspace);
|
||||
await publish(
|
||||
state,
|
||||
fitReportedAgentFileChangeReport({
|
||||
version: 1,
|
||||
requestId: state.requestId,
|
||||
status: "reported",
|
||||
paths: normalized.paths,
|
||||
// Checkpoints miss Bash mutations. Subagent file-tool edits are added
|
||||
// from the message stream, but the list is still not exhaustive.
|
||||
declaredComplete: false,
|
||||
truncated: normalized.truncated,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Used when the checkpoint preview fails: the subagent edits seen in the
|
||||
// stream are still worth reporting.
|
||||
async function finishWithoutPreview(
|
||||
state: FileChangeReportTurnState,
|
||||
editedPaths: Set<string> | undefined,
|
||||
reason: FileChangeReportUnavailableReason,
|
||||
) {
|
||||
if (editedPaths && editedPaths.size > 0) {
|
||||
await publishReported(state, [...editedPaths]);
|
||||
} else {
|
||||
await finishUnavailable(state, reason);
|
||||
}
|
||||
}
|
||||
|
||||
async function report(
|
||||
turn: NativeFileChangeReportTurn | null | undefined,
|
||||
query: Pick<Query, "rewindFiles">,
|
||||
) {
|
||||
const state = turn?.fileChangeReport;
|
||||
if (!state || state.phase !== "requested") return;
|
||||
state.phase = "collecting";
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const previewPromise = query.rewindFiles(turn.promptUuid, { dryRun: true });
|
||||
// A timed-out control request may still settle later. Observe it so a late
|
||||
// rejection cannot become unhandled, but never let it publish a second terminal.
|
||||
void previewPromise.catch(() => {});
|
||||
try {
|
||||
const preview = await Promise.race<RewindFilesResult | null>([
|
||||
previewPromise,
|
||||
new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => resolve(null), timeoutMs);
|
||||
timer.unref?.();
|
||||
}),
|
||||
]);
|
||||
if (preview === null) {
|
||||
await finishWithoutPreview(state, turn.editedPaths, "timeout");
|
||||
return;
|
||||
}
|
||||
if (!preview.canRewind || !Array.isArray(preview.filesChanged)) {
|
||||
await finishWithoutPreview(state, turn.editedPaths, "invalidOutput");
|
||||
return;
|
||||
}
|
||||
|
||||
await publishReported(state, [...preview.filesChanged, ...(turn.editedPaths ?? [])]);
|
||||
} catch (error) {
|
||||
options.logError(`Failed to inspect Claude file checkpoint ${turn.promptUuid}: ${error}`);
|
||||
await finishWithoutPreview(state, turn.editedPaths, "providerError");
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
request(meta) {
|
||||
const requestId = agentFileChangeReportRequestId(meta);
|
||||
if (!requestId || requestIds.has(requestId)) return undefined;
|
||||
requestIds.add(requestId);
|
||||
return { requestId, phase: "requested" };
|
||||
},
|
||||
report,
|
||||
finish(state, reason) {
|
||||
if (!state) return;
|
||||
void finishUnavailable(state, reason);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeWorkspace(
|
||||
cwd: string,
|
||||
additionalDirectories: string[],
|
||||
): FileChangeReportWorkspace {
|
||||
const normalizedCwd = canonicalizeWorkspaceRoot(path.resolve(cwd));
|
||||
const seen = new Set([pathKey(normalizedCwd)]);
|
||||
const normalizedAdditionalDirectories: string[] = [];
|
||||
for (const directory of additionalDirectories) {
|
||||
const normalized = canonicalizeWorkspaceRoot(path.resolve(normalizedCwd, directory));
|
||||
const key = pathKey(normalized);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
normalizedAdditionalDirectories.push(normalized);
|
||||
}
|
||||
return {
|
||||
cwd: normalizedCwd,
|
||||
additionalDirectories: normalizedAdditionalDirectories,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeReportedPaths(
|
||||
reportedPaths: string[],
|
||||
workspace: FileChangeReportWorkspace,
|
||||
): { paths: string[]; truncated: boolean } {
|
||||
const roots = [workspace.cwd, ...workspace.additionalDirectories];
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
let totalBytes = 0;
|
||||
let truncated = false;
|
||||
for (const reportedPath of reportedPaths) {
|
||||
if (
|
||||
typeof reportedPath !== "string" ||
|
||||
reportedPath.trim().length === 0 ||
|
||||
reportedPath.length > MAX_REPORTED_PATH_LENGTH ||
|
||||
hasControlCharacter(reportedPath)
|
||||
) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
let normalized: string;
|
||||
try {
|
||||
normalized = canonicalizeReportedPath(path.resolve(workspace.cwd, reportedPath));
|
||||
} catch {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
if (normalized.length > MAX_REPORTED_PATH_LENGTH || hasControlCharacter(normalized)) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
if (!roots.some((root) => isWithinRoot(normalized, root))) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
const key = pathKey(normalized);
|
||||
if (roots.some((root) => pathKey(root) === key)) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
if (seen.has(key)) continue;
|
||||
const pathBytes = Buffer.byteLength(normalized, "utf8");
|
||||
if (
|
||||
result.length >= MAX_REPORTED_PATHS ||
|
||||
totalBytes + pathBytes > AGENT_FILE_CHANGE_REPORT_MAX_BYTES
|
||||
) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
seen.add(key);
|
||||
result.push(normalized);
|
||||
totalBytes += pathBytes;
|
||||
}
|
||||
return { paths: result, truncated };
|
||||
}
|
||||
|
||||
function fitReportedAgentFileChangeReport(
|
||||
report: Extract<AgentFileChangeReportResult, { status: "reported" }>,
|
||||
): Extract<AgentFileChangeReportResult, { status: "reported" }> {
|
||||
const paths = [...report.paths];
|
||||
let fitted = report;
|
||||
while (Buffer.byteLength(JSON.stringify(fitted), "utf8") > AGENT_FILE_CHANGE_REPORT_MAX_BYTES) {
|
||||
if (paths.length === 0) {
|
||||
throw new Error("Agent file-change report exceeds the wire limit without paths");
|
||||
}
|
||||
paths.pop();
|
||||
fitted = {
|
||||
...report,
|
||||
paths: [...paths],
|
||||
declaredComplete: false,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
return fitted;
|
||||
}
|
||||
|
||||
function isWithinRoot(candidate: string, root: string): boolean {
|
||||
const relative = path.relative(root, candidate);
|
||||
return !path.isAbsolute(relative) && !relative.startsWith(`..${path.sep}`) && relative !== "..";
|
||||
}
|
||||
|
||||
function canonicalizeWorkspaceRoot(value: string): string {
|
||||
return canonicalizeFromExistingAncestor(value);
|
||||
}
|
||||
|
||||
function canonicalizeReportedPath(value: string): string {
|
||||
const parent = canonicalizeFromExistingAncestor(path.dirname(value));
|
||||
return path.resolve(parent, path.basename(value));
|
||||
}
|
||||
|
||||
function canonicalizeFromExistingAncestor(value: string): string {
|
||||
const original = path.resolve(value);
|
||||
let current = original;
|
||||
const missingSegments: string[] = [];
|
||||
while (true) {
|
||||
try {
|
||||
const canonical = fs.realpathSync.native(current);
|
||||
return path.resolve(canonical, ...missingSegments.reverse());
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) return original;
|
||||
}
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) return original;
|
||||
missingSegments.push(path.basename(current));
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
||||
return error.code === "ENOENT" || error.code === "ENOTDIR";
|
||||
}
|
||||
|
||||
function pathKey(value: string): string {
|
||||
return process.platform === "win32" ? value.toLowerCase() : value;
|
||||
}
|
||||
|
||||
function hasControlCharacter(value: string): boolean {
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const code = value.charCodeAt(index);
|
||||
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
import {
|
||||
ForkSessionRequest,
|
||||
ForkSessionResponse,
|
||||
RequestError,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
forkSession as forkClaudeSession,
|
||||
getSessionMessages,
|
||||
importSessionToStore,
|
||||
type SessionStore,
|
||||
type SessionStoreEntry,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createHash } from "node:crypto";
|
||||
import { assistantMessageText } from "./session-failure-extension.js";
|
||||
import { SessionTiming } from "./session-timing.js";
|
||||
|
||||
type ForkSessionMeta = {
|
||||
[key: string]: unknown;
|
||||
jetbrains?: {
|
||||
air?: {
|
||||
fork?: {
|
||||
version?: number;
|
||||
messageId?: string;
|
||||
messageFingerprint?: string;
|
||||
messageOccurrence?: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
type ForkSessionDependencies = {
|
||||
liveMessageIdToUuid?: ReadonlyMap<string, string>;
|
||||
logger?: { log: (...args: unknown[]) => void };
|
||||
messageIdForGrouping: (message: {
|
||||
type?: string;
|
||||
uuid?: string | null;
|
||||
message?: unknown;
|
||||
}) => string | undefined;
|
||||
};
|
||||
|
||||
type ForkPoint = {
|
||||
messageId: string;
|
||||
messageFingerprint?: string;
|
||||
messageOccurrence?: number;
|
||||
};
|
||||
|
||||
function forkPoint(meta: unknown): ForkPoint | undefined {
|
||||
const fork = (meta as ForkSessionMeta | null | undefined)?.jetbrains?.air?.fork;
|
||||
if (fork?.version !== 1) return undefined;
|
||||
const messageId = fork.messageId?.trim();
|
||||
if (!messageId) return undefined;
|
||||
const messageFingerprint = fork.messageFingerprint?.trim();
|
||||
const messageOccurrence = fork.messageOccurrence;
|
||||
return {
|
||||
messageId,
|
||||
...(messageFingerprint ? { messageFingerprint } : {}),
|
||||
// AIR computes this with count(...) over the visible prefix, so it is 1-based.
|
||||
...(typeof messageOccurrence === "number" &&
|
||||
Number.isSafeInteger(messageOccurrence) &&
|
||||
messageOccurrence > 0
|
||||
? { messageOccurrence }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function forkPointMessageIdCandidates(messageId: string): string[] {
|
||||
// Older AIR builds sent their visible segment id. Prefer the exact id before its ACP source id.
|
||||
const protocolMessageId = messageId.replace(/:segment:\d+$/, "");
|
||||
return protocolMessageId === messageId ? [messageId] : [messageId, protocolMessageId];
|
||||
}
|
||||
|
||||
async function loadFullSessionHistory(sessionId: string): Promise<SessionStoreEntry[]> {
|
||||
// getSessionMessages returns only the active parentUuid chain. The import keeps inactive branches that AIR can still reference.
|
||||
const entries: SessionStoreEntry[] = [];
|
||||
const store: SessionStore = {
|
||||
append: async (_key, batch) => {
|
||||
entries.push(...batch);
|
||||
},
|
||||
load: async () => null,
|
||||
};
|
||||
await importSessionToStore(sessionId, store, { includeSubagents: false });
|
||||
return entries;
|
||||
}
|
||||
|
||||
function assistantGroups(
|
||||
entries: SessionStoreEntry[],
|
||||
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
|
||||
) {
|
||||
const groups = new Map<string, { uuid?: string; text: string }>();
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
entry.type !== "assistant" ||
|
||||
entry.isSidechain === true ||
|
||||
entry.parent_tool_use_id != null ||
|
||||
entry.parent_agent_id != null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const messageId = messageIdForGrouping(entry);
|
||||
if (!messageId) continue;
|
||||
const group = groups.get(messageId) ?? { text: "" };
|
||||
if (typeof entry.uuid === "string" && entry.uuid.length > 0) group.uuid = entry.uuid;
|
||||
group.text += assistantMessageText(entry.message) ?? "";
|
||||
groups.set(messageId, group);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function fingerprint(text: string): string {
|
||||
return `sha256:${createHash("sha256").update(text).digest("hex")}`;
|
||||
}
|
||||
|
||||
function fingerprintOccurrenceOnBranch(
|
||||
targetUuid: string,
|
||||
expectedFingerprint: string,
|
||||
entries: SessionStoreEntry[],
|
||||
groups: ReturnType<typeof assistantGroups>,
|
||||
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
|
||||
): number {
|
||||
const entriesByUuid = new Map(
|
||||
entries.flatMap((entry) => (typeof entry.uuid === "string" ? [[entry.uuid, entry]] : [])),
|
||||
);
|
||||
const seenGroups = new Set<string>();
|
||||
let occurrence = 0;
|
||||
let cursor: string | undefined = targetUuid;
|
||||
while (cursor) {
|
||||
const entry = entriesByUuid.get(cursor);
|
||||
if (!entry) break;
|
||||
if (
|
||||
entry.type === "assistant" &&
|
||||
entry.isSidechain !== true &&
|
||||
entry.parent_tool_use_id == null &&
|
||||
entry.parent_agent_id == null
|
||||
) {
|
||||
const messageId = messageIdForGrouping(entry);
|
||||
if (messageId && !seenGroups.has(messageId)) {
|
||||
seenGroups.add(messageId);
|
||||
const group = groups.get(messageId);
|
||||
if (group && fingerprint(group.text) === expectedFingerprint) occurrence++;
|
||||
}
|
||||
}
|
||||
cursor = typeof entry.parentUuid === "string" ? entry.parentUuid : undefined;
|
||||
}
|
||||
return occurrence;
|
||||
}
|
||||
|
||||
function resolveFromFullHistory(
|
||||
entries: SessionStoreEntry[],
|
||||
candidates: string[],
|
||||
point: ForkPoint,
|
||||
messageIdForGrouping: ForkSessionDependencies["messageIdForGrouping"],
|
||||
): string | undefined {
|
||||
const groups = assistantGroups(entries, messageIdForGrouping);
|
||||
const exact = candidates.map((candidate) => groups.get(candidate)?.uuid).find(Boolean);
|
||||
if (exact) return exact;
|
||||
if (!point.messageFingerprint || !point.messageOccurrence) return undefined;
|
||||
|
||||
const fingerprintMatches = [...groups.values()].filter(
|
||||
(group) => group.uuid && fingerprint(group.text) === point.messageFingerprint,
|
||||
);
|
||||
// If only one persisted message has this content, the fingerprint already
|
||||
// identifies it even when an older client supplied an incompatible index.
|
||||
if (fingerprintMatches.length === 1) return fingerprintMatches[0]?.uuid;
|
||||
|
||||
const occurrenceMatches = fingerprintMatches.filter(
|
||||
(group) =>
|
||||
group.uuid &&
|
||||
fingerprintOccurrenceOnBranch(
|
||||
group.uuid,
|
||||
point.messageFingerprint!,
|
||||
entries,
|
||||
groups,
|
||||
messageIdForGrouping,
|
||||
) === point.messageOccurrence,
|
||||
);
|
||||
return occurrenceMatches.length === 1 ? occurrenceMatches[0]?.uuid : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `error` is the Claude SDK's report that `sessionId` has no
|
||||
* transcript: `forkSession` and `importSessionToStore` throw
|
||||
* `Error("Session <id> not found")`, and both throw
|
||||
* `"Invalid sessionId: <id>"` for an id that is not a UUID.
|
||||
*/
|
||||
function isUnknownSessionError(error: unknown, sessionId: string): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return (
|
||||
error.message === `Session ${sessionId} not found` ||
|
||||
error.message === `Invalid sessionId: ${sessionId}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function forkSession(
|
||||
params: ForkSessionRequest,
|
||||
dependencies: ForkSessionDependencies,
|
||||
): Promise<ForkSessionResponse> {
|
||||
try {
|
||||
return await forkTranscript(params, dependencies);
|
||||
} catch (error) {
|
||||
if (isUnknownSessionError(error, params.sessionId)) {
|
||||
throw RequestError.sessionNotFound(params.sessionId);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function forkTranscript(
|
||||
params: ForkSessionRequest,
|
||||
dependencies: ForkSessionDependencies,
|
||||
): Promise<ForkSessionResponse> {
|
||||
const timing = new SessionTiming(dependencies.logger, "fork", params.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);
|
||||
timing.phase("sdk-fork", " resolution=latest");
|
||||
return { sessionId: forked.sessionId };
|
||||
}
|
||||
|
||||
const candidateIds = forkPointMessageIdCandidates(point.messageId);
|
||||
const liveUuid = candidateIds
|
||||
.map((candidateId) => dependencies.liveMessageIdToUuid?.get(candidateId))
|
||||
.find(Boolean);
|
||||
const history = liveUuid ? undefined : await getSessionMessages(params.sessionId);
|
||||
timing.phase("active-history", ` resolution=${liveUuid ? "live" : "pending"}`);
|
||||
const messageUuid =
|
||||
liveUuid ??
|
||||
candidateIds
|
||||
.map(
|
||||
(candidateId) =>
|
||||
history
|
||||
?.slice()
|
||||
.reverse()
|
||||
.find((message) => dependencies.messageIdForGrouping(message) === candidateId)?.uuid,
|
||||
)
|
||||
.find(Boolean);
|
||||
const fullHistoryUuid = messageUuid
|
||||
? undefined
|
||||
: resolveFromFullHistory(
|
||||
await loadFullSessionHistory(params.sessionId),
|
||||
candidateIds,
|
||||
point,
|
||||
dependencies.messageIdForGrouping,
|
||||
);
|
||||
timing.phase(
|
||||
"full-history",
|
||||
` resolution=${liveUuid ? "live" : messageUuid ? "active" : fullHistoryUuid ? "full" : "missing"}`,
|
||||
);
|
||||
|
||||
if (!messageUuid && !fullHistoryUuid) {
|
||||
throw RequestError.invalidParams(
|
||||
{ messageId: point.messageId },
|
||||
`Fork point message ${point.messageId} was not found in session ${params.sessionId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const forked = await forkClaudeSession(params.sessionId, {
|
||||
upToMessageId: messageUuid ?? fullHistoryUuid,
|
||||
});
|
||||
timing.phase("sdk-fork");
|
||||
return { sessionId: forked.sessionId };
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
/**
|
||||
* Model discovery for a gateway set via `providers/set`.
|
||||
*
|
||||
* An organization can restrict which models its gateway serves, and the
|
||||
* gateway's listing returns only those: `GET /v1/models` for an `anthropic`
|
||||
* gateway, `GET /foundation-models` (Bedrock `ListFoundationModels`) for a
|
||||
* `bedrock` one. The adapter lists them once when the provider is set, and the
|
||||
* model picker then offers only the SDK models the gateway listed (see
|
||||
* `narrowToGatewayModels` in `session-model.ts`). A listing that fails fails
|
||||
* `providers/set` with a {@link GatewayListingError}.
|
||||
*/
|
||||
|
||||
const LISTING_TIMEOUT_MS = 10_000;
|
||||
const ANTHROPIC_PAGE_LIMIT = "1000";
|
||||
const MAX_LISTING_PAGES = 20;
|
||||
const MAX_LOGGED_BODY_CHARS = 500;
|
||||
const ANTHROPIC_VERSION = "2023-06-01";
|
||||
|
||||
/**
|
||||
* The bearer token `createEnvForProvider` sets as `ANTHROPIC_AUTH_TOKEN` and
|
||||
* `AWS_BEARER_TOKEN_BEDROCK`, so the CLI sends `Authorization: Bearer acp-proxy`
|
||||
* unless the provider headers replace it. The listing sends the same, so the
|
||||
* gateway sees the same auth as on chat requests.
|
||||
*/
|
||||
export const PROVIDER_AUTH_TOKEN_PLACEHOLDER = "acp-proxy";
|
||||
|
||||
/**
|
||||
* The cross-region inference profile prefixes the CLI knows:
|
||||
* `eu.anthropic.claude-sonnet-5`. `ANTHROPIC_BEDROCK_REGION_PREFIX` accepts all
|
||||
* of them but `us-gov`, which the CLI takes only from a `us-gov-*` AWS region;
|
||||
* a gateway listing only `us-gov.*` ids would then get an empty picker. That
|
||||
* case is theoretical, so it is left as is.
|
||||
*/
|
||||
const BEDROCK_REGION_PREFIXES = ["us", "eu", "apac", "jp", "au", "us-gov", "global"];
|
||||
|
||||
type ListingLogger = { log: (...args: any[]) => void; error: (...args: any[]) => void };
|
||||
|
||||
type ListingPage = { ids: string[]; nextQuery?: Record<string, string> };
|
||||
|
||||
/**
|
||||
* A gateway listing that failed: a network error, a status other than 2xx or
|
||||
* 4xx, a body that is not the expected listing, or the 10 s timeout. The
|
||||
* message names the request path and the reason, never a header value.
|
||||
*/
|
||||
export class GatewayListingError extends Error {
|
||||
override name = "GatewayListingError";
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the model ids an `anthropic` gateway at `baseUrl` serves, following
|
||||
* `has_more` / `last_id` pagination. Returns `undefined` when the gateway
|
||||
* answers 4xx: it has no listing, and nothing is narrowed. Throws a
|
||||
* {@link GatewayListingError} when the listing fails. Header values are never
|
||||
* logged.
|
||||
*/
|
||||
export async function listGatewayModels(
|
||||
baseUrl: string,
|
||||
providerHeaders: Record<string, string>,
|
||||
logger: ListingLogger,
|
||||
): Promise<string[] | undefined> {
|
||||
return listPages(
|
||||
`${baseUrl.replace(/\/+$/, "")}/v1/models`,
|
||||
{ limit: ANTHROPIC_PAGE_LIMIT },
|
||||
listingHeaders(providerHeaders, { "anthropic-version": ANTHROPIC_VERSION }),
|
||||
logger,
|
||||
(body) => {
|
||||
const page = body as { data?: unknown; has_more?: unknown; last_id?: unknown };
|
||||
if (!Array.isArray(page.data)) return undefined;
|
||||
return {
|
||||
ids: stringField(page.data, "id"),
|
||||
nextQuery:
|
||||
page.has_more === true && typeof page.last_id === "string"
|
||||
? { limit: ANTHROPIC_PAGE_LIMIT, after_id: page.last_id }
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the Anthropic models a `bedrock` gateway at `baseUrl` serves
|
||||
* (`GET /foundation-models`, Bedrock `ListFoundationModels`, one page), the
|
||||
* listing AI Router answers on its Bedrock route. Returns the listed ids, such
|
||||
* as `global.anthropic.claude-sonnet-5-5`; `undefined` and the errors are
|
||||
* those of {@link listGatewayModels}.
|
||||
*/
|
||||
export async function listBedrockModels(
|
||||
baseUrl: string,
|
||||
providerHeaders: Record<string, string>,
|
||||
logger: ListingLogger,
|
||||
): Promise<string[] | undefined> {
|
||||
const ids = await listPages(
|
||||
`${baseUrl.replace(/\/+$/, "")}/foundation-models`,
|
||||
{},
|
||||
listingHeaders(providerHeaders, {}),
|
||||
logger,
|
||||
(body) => {
|
||||
const page = body as { modelSummaries?: unknown };
|
||||
if (!Array.isArray(page.modelSummaries)) return undefined;
|
||||
return { ids: stringField(page.modelSummaries, "modelId") };
|
||||
},
|
||||
);
|
||||
return ids?.filter((id) => id.includes("anthropic."));
|
||||
}
|
||||
|
||||
/** The cross-region prefix of a Bedrock model id or ARN, if it has one. */
|
||||
export function bedrockRegionPrefix(modelId: string): string | undefined {
|
||||
const id = modelId.slice(modelId.lastIndexOf("/") + 1).toLowerCase();
|
||||
return BEDROCK_REGION_PREFIXES.find((prefix) => id.startsWith(`${prefix}.anthropic.`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the region of the listed Bedrock models: `global` when the gateway
|
||||
* lists it, else the prefix of the first id that has one. A gateway that lists
|
||||
* `eu.*` and `us.*` ids gets the prefix that comes first, and the ids of the
|
||||
* other prefixes are dropped, so the picker offers only models the CLI can
|
||||
* call under that prefix. Ids without a prefix (`anthropic.claude-…`) are
|
||||
* dropped too once a prefix is picked; without any prefix every id is kept.
|
||||
*/
|
||||
export function selectBedrockRegion(modelIds: readonly string[]): {
|
||||
regionPrefix?: string;
|
||||
modelIds: string[];
|
||||
} {
|
||||
const prefixes = modelIds.map(bedrockRegionPrefix);
|
||||
const regionPrefix = prefixes.includes("global")
|
||||
? "global"
|
||||
: prefixes.find((prefix) => prefix !== undefined);
|
||||
if (!regionPrefix) return { modelIds: [...modelIds] };
|
||||
return {
|
||||
regionPrefix,
|
||||
modelIds: modelIds.filter((id) => bedrockRegionPrefix(id) === regionPrefix),
|
||||
};
|
||||
}
|
||||
|
||||
// Provider headers win over the defaults, matched case-insensitively, the way
|
||||
// `ANTHROPIC_CUSTOM_HEADERS` overrides the CLI's own headers.
|
||||
function listingHeaders(
|
||||
providerHeaders: Record<string, string>,
|
||||
protocolHeaders: Record<string, string>,
|
||||
): Headers {
|
||||
const headers = new Headers({
|
||||
authorization: `Bearer ${PROVIDER_AUTH_TOKEN_PLACEHOLDER}`,
|
||||
accept: "application/json",
|
||||
...protocolHeaders,
|
||||
});
|
||||
for (const [name, value] of Object.entries(providerHeaders)) {
|
||||
// `Headers.set` puts an invalid value into its error message, so name only the header.
|
||||
try {
|
||||
headers.set(name, value);
|
||||
} catch {
|
||||
throw new GatewayListingError(`Model listing cannot send the invalid header "${name}"`);
|
||||
}
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function stringField(entries: unknown[], field: string): string[] {
|
||||
return entries.flatMap((entry) => {
|
||||
const value = (entry as Record<string, unknown> | null)?.[field];
|
||||
return typeof value === "string" && value.trim() !== "" ? [value] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `endpoint` page by page; `parse` returns `undefined` for a body it does
|
||||
* not understand. A 4xx answer on any page means the gateway has no listing:
|
||||
* the result is `undefined`, and nothing is narrowed.
|
||||
*/
|
||||
async function listPages(
|
||||
endpoint: string,
|
||||
firstQuery: Record<string, string>,
|
||||
headers: Headers,
|
||||
logger: ListingLogger,
|
||||
parse: (body: unknown) => ListingPage | undefined,
|
||||
): Promise<string[] | undefined> {
|
||||
const { pathname: path, username, password } = new URL(endpoint);
|
||||
const failure = (reason: string): GatewayListingError => {
|
||||
const error = new GatewayListingError(`Model listing GET ${path} ${reason}`);
|
||||
logger.error(`[providers/set] ${error.message}`);
|
||||
return error;
|
||||
};
|
||||
// fetch refuses such a URL and repeats it, credentials included, in its error.
|
||||
if (username || password) throw failure("cannot be sent: the base URL carries credentials");
|
||||
const signal = AbortSignal.timeout(LISTING_TIMEOUT_MS);
|
||||
const ids: string[] = [];
|
||||
let query: Record<string, string> | undefined = firstQuery;
|
||||
for (let page = 0; page < MAX_LISTING_PAGES && query; page++) {
|
||||
const url = new URL(endpoint);
|
||||
for (const [name, value] of Object.entries(query)) url.searchParams.set(name, value);
|
||||
let response: Response;
|
||||
let body: string;
|
||||
try {
|
||||
response = await fetch(url, { headers, signal });
|
||||
body = await response.text();
|
||||
} catch (error) {
|
||||
throw failure(`failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (response.status >= 400 && response.status < 500) {
|
||||
logger.log(
|
||||
`[providers/set] Model listing GET ${path} returned ${response.status}: the gateway has no listing, models are not narrowed`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw failure(`returned ${response.status}: ${body.slice(0, MAX_LOGGED_BODY_CHARS)}`);
|
||||
}
|
||||
let parsed: ListingPage | undefined;
|
||||
try {
|
||||
parsed = parse(JSON.parse(body));
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
if (!parsed) throw failure("returned an unexpected body");
|
||||
ids.push(...parsed.ids);
|
||||
query = parsed.nextQuery;
|
||||
}
|
||||
if (query) {
|
||||
logger.error(
|
||||
`[providers/set] Model listing GET ${path} still had more pages after ${MAX_LISTING_PAGES}; using what was read`,
|
||||
);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
/**
|
||||
* `--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.
|
||||
*
|
||||
* 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
|
||||
* a login or logout made elsewhere. So the cached account can go stale: a
|
||||
* session started on an API key keeps passing the guard after the user swaps
|
||||
* the key for a claude.ai login, and the subscription pays.
|
||||
*
|
||||
* `authStatus` cannot fix this: it only reports to the client, and the guard
|
||||
* does not read it. The agent therefore recreates the query whenever the
|
||||
* account may have changed, and the new `initialize` gives the guard a current
|
||||
* account. Two signals trigger it:
|
||||
*
|
||||
* - A turn fails with `auth_required`, which means a sign-out. The query is
|
||||
* closed at once and recreated on the next turn.
|
||||
* - The `claude auth status` check that runs at the start of every prompt (the
|
||||
* same check that feeds `authStatus`) reports a different kind of identity
|
||||
* than the session started with. The session is flagged and recreated at the
|
||||
* next turn boundary, so a running turn is never interrupted.
|
||||
*
|
||||
* The recreation resumes the conversation, or starts a new one under the same
|
||||
* session id when the CLI never saved it. Session creation also refuses an
|
||||
* account with no credential this integration accepts. So a signed-out session
|
||||
* never exists, and a sign-in always leads to a fresh `initialize`.
|
||||
*
|
||||
* The check is not awaited, so a credential swapped after it ran stays unseen
|
||||
* until the next prompt. Awaiting it would add a CLI run to every turn.
|
||||
*/
|
||||
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { AccountInfo, Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
export function shouldHideClaudeAuth(): boolean {
|
||||
return process.argv.includes("--hide-claude-auth");
|
||||
}
|
||||
|
||||
/**
|
||||
* `data.reason` carried by the `authRequired` JSON-RPC error when the flag
|
||||
* blocks a turn. From the client's point of view the agent is logged out (same
|
||||
* error code and flow as a signed-out CLI); the reason lets it render a
|
||||
* different hint. A string enum so further reasons can be added without a
|
||||
* shape change.
|
||||
*/
|
||||
export const CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON = "claude_subscription_not_supported";
|
||||
export type AuthRequiredReason = typeof CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON;
|
||||
|
||||
export const CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_MESSAGE =
|
||||
"This integration does not support using claude.ai subscriptions.";
|
||||
|
||||
/** The message of the plain sign-out refusal. It carries no `reason`: the
|
||||
* account holds nothing this integration can bill, which is the ordinary
|
||||
* signed-out state every ACP client already knows how to answer. */
|
||||
export const CLAUDE_LOGIN_REQUIRED_MESSAGE =
|
||||
"Sign in with an API key or a Console account to use this integration.";
|
||||
|
||||
/**
|
||||
* The `apiKeySource` values that outrank a stored subscription.
|
||||
*
|
||||
* The SDK documents its `ApiKeySource` type as the origin of the credential
|
||||
* used for API requests. `ANTHROPIC_API_KEY` is the environment variable,
|
||||
* `apiKeyHelper` is the configured helper command, and `/login managed key` is
|
||||
* a key that `/login` created with an Anthropic Console account. Each of the
|
||||
* three is an API key that pays instead of the subscription. Every other
|
||||
* member means no API key is in use: `none`, and the legacy `user`, `project`,
|
||||
* `org`, `temporary` and `oauth` that current CLIs never emit.
|
||||
*/
|
||||
const API_KEY_SOURCES_ABOVE_SUBSCRIPTION: ReadonlySet<string> = new Set([
|
||||
"ANTHROPIC_API_KEY",
|
||||
"apiKeyHelper",
|
||||
"/login managed key",
|
||||
]);
|
||||
|
||||
/**
|
||||
* True when a turn on this account is paid by a claude.ai subscription.
|
||||
*
|
||||
* The SDK types `apiKeySource` and `tokenSource` as an open `string`, so this
|
||||
* is an allowlist. An account bills the subscription only when every field
|
||||
* 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.
|
||||
* - `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
|
||||
* fields are absent and the authentication is external.
|
||||
* - `apiKeySource` must not be one of {@link API_KEY_SOURCES_ABOVE_SUBSCRIPTION}.
|
||||
* Claude Code's credential precedence puts those keys above the `/login`
|
||||
* subscription, so the key pays and the stored subscription is inert.
|
||||
*/
|
||||
export function billsClaudeSubscription(account: AccountInfo | undefined): boolean {
|
||||
if (!account?.subscriptionType) {
|
||||
return false;
|
||||
}
|
||||
if (account.tokenSource) {
|
||||
return false;
|
||||
}
|
||||
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
|
||||
return false;
|
||||
}
|
||||
return !API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* API key sources in {@link API_KEY_SOURCES_ABOVE_SUBSCRIPTION}.
|
||||
*
|
||||
* False therefore covers both the signed-out CLI and the account whose only
|
||||
* credential is a claude.ai subscription. {@link billsClaudeSubscription} runs
|
||||
* first and separates the two, so a caller that reaches a `false` here is
|
||||
* looking at a session with no way to pay.
|
||||
*/
|
||||
export function holdsNonSubscriptionCredential(account: AccountInfo | undefined): boolean {
|
||||
if (!account) {
|
||||
return false;
|
||||
}
|
||||
if (account.apiProvider !== undefined && account.apiProvider !== "firstParty") {
|
||||
return true;
|
||||
}
|
||||
if (account.tokenSource) {
|
||||
return true;
|
||||
}
|
||||
return API_KEY_SOURCES_ABOVE_SUBSCRIPTION.has(account.apiKeySource ?? "");
|
||||
}
|
||||
|
||||
export function claudeSubscriptionNotSupportedError(): RequestError {
|
||||
return RequestError.authRequired(
|
||||
{ reason: CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_REASON satisfies AuthRequiredReason },
|
||||
CLAUDE_SUBSCRIPTION_NOT_SUPPORTED_MESSAGE,
|
||||
);
|
||||
}
|
||||
|
||||
/** The signed-out refusal. Deliberately without `data`, so a client that reads
|
||||
* `data.reason` sees the plain ACP sign-out it already handles. */
|
||||
export function claudeLoginRequiredError(): RequestError {
|
||||
return RequestError.authRequired(undefined, CLAUDE_LOGIN_REQUIRED_MESSAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* The state the guard keeps for one session. It lives on the session so that a
|
||||
* concurrent pair of turns shares one account read, and so
|
||||
* that each degraded-guard warning is logged once.
|
||||
*/
|
||||
export type ClaudeSubscriptionGuardState = {
|
||||
/** The in-flight guard run. Set before the first `await`. */
|
||||
pendingRun?: Promise<RequestError | undefined>;
|
||||
/** True after the "no account source" warning was logged for this session. */
|
||||
degradedWarningLogged?: boolean;
|
||||
};
|
||||
|
||||
export type GuardLogger = {
|
||||
error: (...args: unknown[]) => void;
|
||||
warn?: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
function warn(logger: GuardLogger, message: string): void {
|
||||
(logger.warn ?? logger.error).call(logger, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Report once per session that the guard cannot read the account at all. The
|
||||
* guard is then absent, not passing. The CLI build decides this, not the user,
|
||||
* so a message on every turn would only add noise.
|
||||
*/
|
||||
export function warnClaudeSubscriptionGuardDegraded(options: {
|
||||
sessionId: string;
|
||||
guardState: ClaudeSubscriptionGuardState;
|
||||
logger: GuardLogger;
|
||||
cause: string;
|
||||
}): void {
|
||||
const { guardState } = options;
|
||||
if (guardState.degradedWarningLogged) {
|
||||
return;
|
||||
}
|
||||
guardState.degradedWarningLogged = true;
|
||||
warn(
|
||||
options.logger,
|
||||
`Session ${options.sessionId}: the --hide-claude-auth subscription guard is degraded ` +
|
||||
`(${options.cause}). This session cannot detect a claude.ai subscription.`,
|
||||
);
|
||||
}
|
||||
|
||||
type GuardOptions = {
|
||||
sessionId: string;
|
||||
query: Pick<Query, "accountInfo">;
|
||||
guardState: ClaudeSubscriptionGuardState;
|
||||
logger: GuardLogger;
|
||||
/** Display hook: called with the account the guard just read, before the
|
||||
* guard decides on it. It exists so a refused turn still reports which
|
||||
* account it was refused for. Purely observational — this module knows
|
||||
* nothing about what the caller does with it, and a throw from here never
|
||||
* changes the verdict. */
|
||||
onAccount?: (account: AccountInfo) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The per-turn guard for a live session.
|
||||
*
|
||||
* It decides on the account the SDK cached at `initialize`, which is this
|
||||
* integration's source of truth. That account is a constant for the life of
|
||||
* the query, so the check costs microseconds. It still earns its place: it
|
||||
* covers a session created under a provider override that `providers/disable`
|
||||
* later removed, so the create-time check never ran for the routing in force
|
||||
* now. A sign-out ends the query (see `markSessionForSignOutRespawn` in
|
||||
* `v1/acp-agent.ts`), so the next turn recreates it and `initialize` reports the
|
||||
* 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
|
||||
* 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
|
||||
* flow. The guard sends no separate access message.
|
||||
*
|
||||
* Fails open when no account can be read at all: session creation already
|
||||
* refused every account without a usable credential, and an unavailable probe
|
||||
* must not block a session that passed that check.
|
||||
*/
|
||||
export async function refuseClaudeSubscriptionTurn(options: GuardOptions): Promise<void> {
|
||||
// Concurrent turns must not each re-read the account and each publish a row.
|
||||
// Store the run before the first await, and let the others await the same one.
|
||||
const { guardState } = options;
|
||||
const run = (guardState.pendingRun ??= evaluateGuard(options).finally(() => {
|
||||
if (guardState.pendingRun === run) {
|
||||
guardState.pendingRun = undefined;
|
||||
}
|
||||
}));
|
||||
const refusal = await run;
|
||||
if (refusal) {
|
||||
throw refusal;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the account and return the error for the refused turn.
|
||||
* Never throws: an unreadable account fails open. */
|
||||
async function evaluateGuard(options: GuardOptions): Promise<RequestError | undefined> {
|
||||
const account = await readGuardAccount(options);
|
||||
if (!account) {
|
||||
return undefined;
|
||||
}
|
||||
// Before the decision, so the client learns the identity even when the next
|
||||
// lines refuse the turn. A display hook must never fail a guard.
|
||||
try {
|
||||
options.onAccount?.(account);
|
||||
} catch (error) {
|
||||
options.logger.error(
|
||||
`Session ${options.sessionId}: the guard's onAccount hook threw:`,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
if (billsClaudeSubscription(account)) {
|
||||
return claudeSubscriptionNotSupportedError();
|
||||
}
|
||||
if (!holdsNonSubscriptionCredential(account)) {
|
||||
return claudeLoginRequiredError();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The account the SDK cached at `initialize`. `undefined` when the query
|
||||
* cannot answer at all. */
|
||||
async function readGuardAccount(options: GuardOptions): Promise<AccountInfo | undefined> {
|
||||
const { query } = options;
|
||||
if (typeof query.accountInfo !== "function") {
|
||||
warnClaudeSubscriptionGuardDegraded({
|
||||
...options,
|
||||
cause: "the SDK query has no accountInfo method",
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return await query.accountInfo();
|
||||
} catch (error) {
|
||||
options.logger.error(
|
||||
`Session ${options.sessionId}: accountInfo failed; skipping the subscription check for this turn:`,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
export type PromptCacheTtl = "5m" | "1h";
|
||||
|
||||
export type IdleCompactionHost = {
|
||||
/** Claude is working (`startTurn`'s check) or a permission request / user input is pending. */
|
||||
isBusy(): boolean;
|
||||
/** Context size after the last main-thread request, or undefined if unknown. */
|
||||
contextTokens(): number | undefined;
|
||||
/** Current merged Claude Code settings. */
|
||||
settings(): {
|
||||
idleCompaction?: boolean;
|
||||
autoCompactEnabled?: boolean;
|
||||
env?: Record<string, string | undefined>;
|
||||
};
|
||||
/** Runs `/compact` as an adapter-originated turn; settles with that turn. */
|
||||
compact(): Promise<unknown>;
|
||||
/** Debug-level log. */
|
||||
log(message: string): void;
|
||||
};
|
||||
|
||||
export type IdleCompactionOptions = {
|
||||
env?: Record<string, string | undefined>;
|
||||
setTimeout?: (callback: () => void, ms: number) => unknown;
|
||||
};
|
||||
|
||||
/** The longest delay `setTimeout` takes; a longer one fires at once. */
|
||||
const MAX_TIMER_MS = 2_147_483_647;
|
||||
const HOUR_MS = 3_600_000;
|
||||
const DEFAULT_MIN_TOKENS = 200_000;
|
||||
const MIN_TOKENS_FLOOR = 100_000;
|
||||
// 54 min for a 1h cache: leaves a margin for the gap between the provider
|
||||
// writing the cache and the adapter receiving the response.
|
||||
const DEFAULT_DELAY_MS = 0.9 * HOUR_MS;
|
||||
// Node timers do not run while the machine sleeps, so one can fire hours after
|
||||
// its deadline, on a cache that expired meanwhile. Same threshold as Claude Code.
|
||||
const LAPSED_AFTER_MS = 60_000;
|
||||
// The values Claude Code reads as "on" for env flags such as DISABLE_COMPACT
|
||||
// (case-insensitive, trimmed).
|
||||
const TRUTHY_ENV = new Set(["1", "true", "yes", "on"]);
|
||||
|
||||
function isTruthyEnv(value: string | undefined): boolean {
|
||||
return value !== undefined && TRUTHY_ENV.has(value.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function parseCacheTtl(usage: unknown): PromptCacheTtl | undefined {
|
||||
const creation = (usage as { cache_creation?: unknown } | null | undefined)?.cache_creation;
|
||||
if (typeof creation !== "object" || creation === null) return undefined;
|
||||
const { ephemeral_1h_input_tokens: hour, ephemeral_5m_input_tokens: fiveMin } = creation as {
|
||||
ephemeral_1h_input_tokens?: unknown;
|
||||
ephemeral_5m_input_tokens?: unknown;
|
||||
};
|
||||
if (typeof hour === "number" && hour > 0) return "1h";
|
||||
if (typeof fiveMin === "number" && fiveMin > 0) return "5m";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compacts a session shortly before its one-hour prompt cache expires, so the
|
||||
* next prompt writes a short summary instead of the whole context. Claude Code
|
||||
* has this feature but arms it only for "attended" sessions, which SDK sessions
|
||||
* are not. One instance per session.
|
||||
*/
|
||||
export class IdleCompaction {
|
||||
private readonly env: Record<string, string | undefined>;
|
||||
private readonly setTimer: (callback: () => void, ms: number) => unknown;
|
||||
private ttl: PromptCacheTtl | undefined;
|
||||
private lastRequestAt: number | undefined;
|
||||
private lastMessageId: string | undefined;
|
||||
/** Set when `/compact` was sent, cleared by the next request: a compaction that failed,
|
||||
* or left the context large, would otherwise re-arm at once and loop until the user prompts. */
|
||||
private compactedSinceLastRequest = false;
|
||||
private timer: unknown;
|
||||
private compacting = false;
|
||||
private disposed = false;
|
||||
private warnedInvalidDelay = false;
|
||||
/** `status` of the last `rate_limit_event`; unknown until one arrives. */
|
||||
private rateLimitStatus: string | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly host: IdleCompactionHost,
|
||||
options: IdleCompactionOptions = {},
|
||||
) {
|
||||
this.env = options.env ?? process.env;
|
||||
this.setTimer = options.setTimeout ?? ((cb, ms) => setTimeout(cb, ms));
|
||||
}
|
||||
|
||||
/** Whether an idle compaction it started is still running. `v1/acp-agent.ts` reports
|
||||
* `trigger: "idle"` while it is true. A client's `/compact` queued behind is read
|
||||
* only after the adapter's turn's `result`, which clears `compacting`; this relies
|
||||
* on the CLI emitting that compaction's `compact_boundary` after the previous
|
||||
* result, which nothing here enforces. */
|
||||
get isCompacting(): boolean {
|
||||
return this.compacting;
|
||||
}
|
||||
|
||||
/** A main-thread response arrived. Records its time and cache TTL, and drops any armed timer.
|
||||
* The provider writes the cache when the request starts, so the deadline is measured from the
|
||||
* response's first sighting: the `message_start` stream event, or its first `assistant` message
|
||||
* when it was not streamed. The CLI sends one `assistant` message per content block, and a
|
||||
* 7-minute response would otherwise put the deadline 7 minutes after the cache was written.
|
||||
* A later call with the same `messageId` only updates the TTL. */
|
||||
noteRequest(usage: unknown, messageId?: string): void {
|
||||
if (this.disposed) return;
|
||||
this.ttl = parseCacheTtl(usage) ?? this.ttl;
|
||||
if (messageId !== undefined && messageId === this.lastMessageId) return;
|
||||
this.lastMessageId = messageId;
|
||||
this.lastRequestAt = Date.now();
|
||||
this.compactedSinceLastRequest = false;
|
||||
this.disarm("new request");
|
||||
}
|
||||
|
||||
/** The session became idle. Arms the timer if every condition holds, else logs why not. */
|
||||
onIdle(): void {
|
||||
if (this.disposed) return;
|
||||
const skip = this.skipReason();
|
||||
if (skip) {
|
||||
this.host.log(`[idle-compaction] skip: ${skip}`);
|
||||
return;
|
||||
}
|
||||
this.disarm("rearm");
|
||||
const deadline = this.lastRequestAt! + this.delayMs();
|
||||
this.timer = this.setTimer(() => void this.fire(), Math.max(0, deadline - Date.now()));
|
||||
(this.timer as { unref?: () => void } | undefined)?.unref?.();
|
||||
this.host.log(`[idle-compaction] armed deadline=${new Date(deadline).toISOString()}`);
|
||||
}
|
||||
|
||||
/** A `rate_limit_event` arrived (`SDKRateLimitInfo`). Anything but `allowed` skips compaction,
|
||||
* as in Claude Code. This is account state, so `reset()` keeps it. */
|
||||
noteRateLimit(info: unknown): void {
|
||||
const status = (info as { status?: unknown } | null | undefined)?.status;
|
||||
if (typeof status === "string") this.rateLimitStatus = status;
|
||||
}
|
||||
|
||||
/** Claude Code reported its compaction as failed. Its turn still ends normally, so `compact()` does not reject. */
|
||||
noteCompactionFailed(error: string | undefined): void {
|
||||
if (!this.compacting) return;
|
||||
this.host.log(`[idle-compaction] compaction failed: ${error ?? "no reason given"}`);
|
||||
}
|
||||
|
||||
/** The conversation was replaced (`/clear`): forgets the recorded request and TTL, and drops any armed timer. */
|
||||
reset(): void {
|
||||
this.ttl = undefined;
|
||||
this.lastRequestAt = undefined;
|
||||
this.lastMessageId = undefined;
|
||||
this.compactedSinceLastRequest = false;
|
||||
this.disarm("conversation reset");
|
||||
}
|
||||
|
||||
/** Drops the armed timer, if any. `reason` is only logged. */
|
||||
disarm(reason: string): void {
|
||||
if (this.timer === undefined) return;
|
||||
clearTimeout(this.timer as ReturnType<typeof setTimeout>);
|
||||
this.timer = undefined;
|
||||
this.host.log(`[idle-compaction] disarmed: ${reason}`);
|
||||
}
|
||||
|
||||
/** Disarms and ignores every later call. */
|
||||
dispose(): void {
|
||||
this.disarm("disposed");
|
||||
this.disposed = true;
|
||||
}
|
||||
|
||||
private async fire(): Promise<void> {
|
||||
this.timer = undefined;
|
||||
if (this.disposed) return;
|
||||
const skip = this.skipReason();
|
||||
if (skip) {
|
||||
this.host.log(`[idle-compaction] skip at fire: ${skip}`);
|
||||
return;
|
||||
}
|
||||
this.host.log("[idle-compaction] firing /compact");
|
||||
this.compacting = true;
|
||||
this.compactedSinceLastRequest = true;
|
||||
try {
|
||||
await this.host.compact();
|
||||
} catch (error) {
|
||||
this.host.log(`[idle-compaction] compaction failed: ${error}`);
|
||||
} finally {
|
||||
this.compacting = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Why no compaction should be scheduled right now, or undefined if all conditions hold. */
|
||||
private skipReason(): string | undefined {
|
||||
if (this.compacting) return "compaction already running";
|
||||
const disabled = this.disabledBy();
|
||||
if (disabled) return `disabled by ${disabled}`;
|
||||
if (this.lastRequestAt === undefined) return "no request recorded in this process";
|
||||
if (Date.now() > this.lastRequestAt + this.delayMs() + LAPSED_AFTER_MS) {
|
||||
return "cache lapsed: more than 60 s past the deadline";
|
||||
}
|
||||
if (this.rateLimitStatus !== undefined && this.rateLimitStatus !== "allowed") {
|
||||
return `rate limit status is ${this.rateLimitStatus}`;
|
||||
}
|
||||
if (this.compactedSinceLastRequest) return "already compacted for this request";
|
||||
if (this.ttl !== "1h") return `cache TTL is ${this.ttl ?? "unknown"}, not 1h`;
|
||||
const tokens = this.host.contextTokens();
|
||||
const min = this.minTokens();
|
||||
if (tokens === undefined || tokens < min) {
|
||||
return `context ${tokens ?? "unknown"} tokens is below the ${min} minimum`;
|
||||
}
|
||||
if (this.host.isBusy()) return "session is busy";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private disabledBy(): string | undefined {
|
||||
const settings = this.host.settings();
|
||||
if (settings.idleCompaction === false) return "idleCompaction setting";
|
||||
if (settings.autoCompactEnabled === false) return "autoCompactEnabled setting";
|
||||
for (const name of ["DISABLE_COMPACT", "DISABLE_AUTO_COMPACT"]) {
|
||||
if (isTruthyEnv(this.claudeCodeEnv(name))) return name;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The CLI applies the settings `env` block after the launch env, so it wins. */
|
||||
private claudeCodeEnv(name: string): string | undefined {
|
||||
return this.host.settings().env?.[name] ?? this.env[name];
|
||||
}
|
||||
|
||||
/** `0` and invalid values fall back to 200,000, as in the CLI, which declares the variable
|
||||
* with `min: 1` and computes `Math.max(100000, env ?? 200000)`. */
|
||||
private minTokens(): number {
|
||||
const raw = this.claudeCodeEnv("CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS");
|
||||
const parsed = raw !== undefined && /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : 0;
|
||||
return Math.max(MIN_TOKENS_FLOOR, parsed > 0 ? parsed : DEFAULT_MIN_TOKENS);
|
||||
}
|
||||
|
||||
private delayMs(): number {
|
||||
const raw = this.env.CLAUDE_AGENT_ACP_IDLE_COMPACT_DELAY_MS;
|
||||
if (raw === undefined) return DEFAULT_DELAY_MS;
|
||||
if (/^\d+$/.test(raw.trim()) && Number(raw.trim()) <= MAX_TIMER_MS) return Number(raw.trim());
|
||||
if (!this.warnedInvalidDelay) {
|
||||
this.warnedInvalidDelay = true;
|
||||
this.host.log(
|
||||
`[idle-compaction] ignoring invalid CLAUDE_AGENT_ACP_IDLE_COMPACT_DELAY_MS=${raw}`,
|
||||
);
|
||||
}
|
||||
return DEFAULT_DELAY_MS;
|
||||
}
|
||||
}
|
||||
125
src/index.ts
125
src/index.ts
@@ -1,107 +1,26 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { claudeCliPath } from "./claude-cli.js";
|
||||
import { applyManagedPolicyEnv } from "./managed-policy.js";
|
||||
import { acpProtocolsFromEnv, serveAcp } from "./serve.js";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { appendFileSync, mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
// Load managed settings and apply environment variables
|
||||
import { loadManagedSettings, applyEnvironmentSettings } from "./utils.js";
|
||||
|
||||
// `--cli` is checked first so that `--version`/`-v` (and any other flags) are
|
||||
// forwarded to the wrapped native CLI rather than swallowed by our own version
|
||||
// handler below. Our version flag only applies when not delegating.
|
||||
if (process.argv.includes("--cli")) {
|
||||
const { spawn } = await import("node:child_process");
|
||||
const args = process.argv.slice(2).filter((arg) => arg !== "--cli");
|
||||
const child = spawn(await claudeCliPath(), args, { stdio: "inherit" });
|
||||
|
||||
const signals =
|
||||
process.platform === "win32"
|
||||
? (["SIGINT", "SIGTERM"] as const)
|
||||
: (["SIGINT", "SIGTERM", "SIGHUP"] as const);
|
||||
for (const sig of signals) {
|
||||
process.on(sig, () => {
|
||||
if (!child.killed) child.kill(sig);
|
||||
});
|
||||
}
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal && process.platform !== "win32") {
|
||||
// Remove our listener so re-raising actually terminates instead of
|
||||
// re-entering the no-op handler, which would let us exit with code 0
|
||||
// instead of the signal's conventional 128+N.
|
||||
process.removeAllListeners(signal);
|
||||
process.kill(process.pid, signal);
|
||||
} else {
|
||||
process.exit(code ?? 1);
|
||||
}
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
} else if (process.argv.includes("--version") || process.argv.includes("-v")) {
|
||||
console.log(packageJson.version);
|
||||
process.exit(0);
|
||||
} else {
|
||||
// Apply env vars from the managed-policy tier before any SDK call so the
|
||||
// SDK subprocess inherits them. Reading the tier is best-effort: a transient
|
||||
// failure leaves the agent running with no policy env instead of aborting
|
||||
// module evaluation here, before any ACP traffic.
|
||||
await applyManagedPolicyEnv();
|
||||
|
||||
// stdout is used to send messages to the client
|
||||
// we redirect everything else to stderr to make sure it doesn't interfere with ACP
|
||||
console.log = console.error;
|
||||
console.info = console.error;
|
||||
console.warn = console.error;
|
||||
console.debug = console.error;
|
||||
|
||||
process.on("unhandledRejection", (reason, promise) => {
|
||||
console.error("Unhandled Rejection at:", promise, "reason:", reason);
|
||||
});
|
||||
|
||||
const logDirectory = process.env.CLAUDE_AGENT_LOGS;
|
||||
const logger = logDirectory
|
||||
? (() => {
|
||||
mkdirSync(logDirectory, { recursive: true });
|
||||
const logFile = join(logDirectory, "agent.log");
|
||||
const writeLog = (...args: unknown[]) => {
|
||||
const rendered = args
|
||||
.map((arg) => (arg instanceof Error ? (arg.stack ?? arg.message) : String(arg)))
|
||||
.join(" ");
|
||||
appendFileSync(logFile, `${new Date().toISOString()} pid=${process.pid} ${rendered}\n`);
|
||||
};
|
||||
return {
|
||||
log: writeLog,
|
||||
error: (...args: unknown[]) => {
|
||||
console.error(...args);
|
||||
writeLog(...args);
|
||||
},
|
||||
};
|
||||
})()
|
||||
: undefined;
|
||||
logger?.log("Claude ACP started");
|
||||
|
||||
const acp = serveAcp(logger, {
|
||||
protocols: acpProtocolsFromEnv(process.env.CLAUDE_AGENT_ACP_PROTOCOL),
|
||||
});
|
||||
|
||||
async function shutdown() {
|
||||
await acp.dispose().catch((err) => {
|
||||
console.error("Error during cleanup:", err);
|
||||
});
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Exit cleanly when the ACP connection closes (e.g. stdin EOF, transport
|
||||
// error). Without this, `process.stdin.resume()` keeps the event loop
|
||||
// alive indefinitely, causing orphan process accumulation in oneshot mode.
|
||||
acp.closed.then(shutdown);
|
||||
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
|
||||
// Keep process alive while connection is open
|
||||
process.stdin.resume();
|
||||
const managedSettings = loadManagedSettings();
|
||||
if (managedSettings) {
|
||||
applyEnvironmentSettings(managedSettings);
|
||||
}
|
||||
|
||||
// stdout is used to send messages to the client
|
||||
// we redirect everything else to stderr to make sure it doesn't interfere with ACP
|
||||
console.log = console.error;
|
||||
console.info = console.error;
|
||||
console.warn = console.error;
|
||||
console.debug = console.error;
|
||||
|
||||
process.on("unhandledRejection", (reason, promise) => {
|
||||
console.error("Unhandled Rejection at:", promise, "reason:", reason);
|
||||
});
|
||||
|
||||
import { runAcp } from "./acp-agent.js";
|
||||
runAcp();
|
||||
|
||||
// Keep process alive
|
||||
process.stdin.resume();
|
||||
|
||||
36
src/lib.ts
36
src/lib.ts
@@ -1,26 +1,22 @@
|
||||
// Export the main agent class and utilities for library usage
|
||||
export { ClaudeAcpAgent, runAcp } from "./v1/acp-agent.js";
|
||||
export { isLocalCommandMetadata, stripLocalCommandMetadata } from "./message-filters.js";
|
||||
export { toAcpNotifications, streamEventToAcpNotifications } from "./sdk-to-acp.js";
|
||||
export type { NewSessionMeta, SDKMessageFilter } from "./new-session-meta.js";
|
||||
export type { ToolUpdateMeta } from "./tool-calls/renderer.js";
|
||||
export { nodeToWebReadable, nodeToWebWritable, Pushable, unreachable } from "./utils.js";
|
||||
export {
|
||||
toolInfoFromToolUse,
|
||||
toDisplayPath,
|
||||
planEntries,
|
||||
toolUpdateFromToolResult,
|
||||
} from "./tools.js";
|
||||
export { SettingsManager, type SettingsManagerOptions } from "./settings.js";
|
||||
// The `authStatus` extension's wire surface: the notification's method name and
|
||||
// the payload types needed to read the traffic. The mappers stay internal.
|
||||
ClaudeAcpAgent,
|
||||
runAcp,
|
||||
toAcpNotifications,
|
||||
streamEventToAcpNotifications,
|
||||
type ToolUpdateMeta,
|
||||
type NewSessionMeta,
|
||||
} from "./acp-agent.js";
|
||||
export {
|
||||
AUTH_STATUS_UPDATE_METHOD,
|
||||
type AuthStatus,
|
||||
type AuthStatusAccount,
|
||||
type AuthStatusKind,
|
||||
type AuthStatusUpdateNotification,
|
||||
} from "./auth-status.js";
|
||||
loadManagedSettings,
|
||||
applyEnvironmentSettings,
|
||||
nodeToWebReadable,
|
||||
nodeToWebWritable,
|
||||
Pushable,
|
||||
unreachable,
|
||||
} from "./utils.js";
|
||||
export { createMcpServer, toolNames } from "./mcp-server.js";
|
||||
export { toolInfoFromToolUse, planEntries, toolUpdateFromToolResult } from "./tools.js";
|
||||
|
||||
// Export types
|
||||
export type { ClaudePlanEntry } from "./tools.js";
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Logger interface for customizing logging output
|
||||
*/
|
||||
export interface Logger {
|
||||
log: (...args: any[]) => void;
|
||||
error: (...args: any[]) => void;
|
||||
/** Optional: a caller that supplies no `warn` gets its warnings on `error`. */
|
||||
warn?: (...args: any[]) => void;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/**
|
||||
* Applies the managed-policy tier's env vars to `process.env` before any SDK
|
||||
* call, so the SDK subprocess inherits them. Going through `resolveSettings`
|
||||
* rather than a raw read of `managed-settings.json` also picks up MDM sources on
|
||||
* macOS and `HKLM`/`HKCU` on Windows.
|
||||
*
|
||||
* Reading the tier is best-effort by nature: on a host with no MDM and no
|
||||
* managed policy the result is empty and the agent behaves identically. So a
|
||||
* transient failure to read it — `EINTR`, `EMFILE`, `EAGAIN` — must leave the
|
||||
* agent running with no policy env rather than stop it from starting.
|
||||
*
|
||||
* That guard matters because the caller awaits this at module scope in an ESM
|
||||
* entry point, where a rejection aborts module evaluation and the process exits
|
||||
* before serving any ACP traffic. `SettingsManager.loadAllSettings` wraps the
|
||||
* same SDK call for the same reason.
|
||||
*/
|
||||
export async function applyManagedPolicyEnv(
|
||||
resolve: typeof resolveSettings = resolveSettings,
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): Promise<void> {
|
||||
let policy: Awaited<ReturnType<typeof resolveSettings>>;
|
||||
try {
|
||||
policy = await resolve({ settingSources: [] });
|
||||
} catch (error) {
|
||||
// stderr, so the ACP stream on stdout stays clean.
|
||||
console.error("Failed to resolve managed policy settings:", error);
|
||||
return;
|
||||
}
|
||||
for (const [key, value] of Object.entries(policy.effective.env ?? {})) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
@@ -1,395 +0,0 @@
|
||||
import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { McpServerStatus, Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { escapeMarkdown } from "./usage-markdown.js";
|
||||
import { raceTimeoutAndAbort } from "./utils.js";
|
||||
|
||||
/** The `/mcp` entry of `available_commands_update`. The adapter shows the
|
||||
* servers as a list, and runs a reconnect, an enable, or a disable through
|
||||
* the SDK control API. */
|
||||
export const MCP_AVAILABLE_COMMAND: AvailableCommand = {
|
||||
name: "mcp",
|
||||
description: "Show the MCP servers and their status, or reconnect, enable, or disable a server",
|
||||
input: { hint: "[reconnect|enable|disable [<server>|all]]" },
|
||||
};
|
||||
|
||||
/** The time that the status read after a `/mcp` command can take. */
|
||||
const MCP_STATUS_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** The time that one reconnect, enable, or disable can take. */
|
||||
const MCP_ACTION_TIMEOUT_MS = 30_000;
|
||||
|
||||
/** A `/mcp` prompt that gets a replacement for its Claude Code text. `all` is
|
||||
* true for `all` and for a reconnect without a server name, as in Claude
|
||||
* Code. `server` is undefined for an enable or a disable without a name. */
|
||||
export type McpCommand =
|
||||
| { action: "status" }
|
||||
| { action: "reconnect" | "enable" | "disable"; all: boolean; server?: string };
|
||||
|
||||
/** Parse a prompt that is exactly `/mcp`, or `/mcp reconnect`, `/mcp enable`,
|
||||
* or `/mcp disable` with an optional server name or `all`. Any other `/mcp`
|
||||
* argument gives null, and the prompt gets no replacement. */
|
||||
export function parseMcpCommand(text: string): McpCommand | null {
|
||||
// The first word is `/mcp` only when the text starts with it after the
|
||||
// leading whitespace. Checking that first keeps a long prompt from being
|
||||
// split into words. `trimStart` removes the characters that `\s` matches.
|
||||
if (!text.trimStart().startsWith("/mcp")) return null;
|
||||
const words = text.trim().split(/\s+/);
|
||||
if (words[0] !== "/mcp") return null;
|
||||
if (words.length === 1) return { action: "status" };
|
||||
const action = words[1]?.toLowerCase();
|
||||
if (action !== "reconnect" && action !== "enable" && action !== "disable") return null;
|
||||
const server = words.slice(2).join(" ");
|
||||
if (server === "all" || (server === "" && action === "reconnect")) {
|
||||
return { action, all: true };
|
||||
}
|
||||
return server === "" ? { action, all: false } : { action, all: false, server };
|
||||
}
|
||||
|
||||
/** Read the MCP server status for the list after a `/mcp` command. Resolves
|
||||
* to null when the read fails, takes too long, or `signal` aborts. Then the
|
||||
* turn keeps the text of Claude Code. */
|
||||
export async function readMcpServerStatus(
|
||||
query: Pick<Query, "mcpServerStatus">,
|
||||
signal: AbortSignal,
|
||||
logError: (message: string) => void,
|
||||
): Promise<McpServerStatus[] | null> {
|
||||
if (signal.aborted) return null;
|
||||
try {
|
||||
const outcome = await raceTimeoutAndAbort(
|
||||
query.mcpServerStatus(),
|
||||
MCP_STATUS_TIMEOUT_MS,
|
||||
signal,
|
||||
);
|
||||
if (outcome.type === "timeout") {
|
||||
logError("The MCP server status read timed out; keeping the Claude Code text of /mcp");
|
||||
}
|
||||
return outcome.type === "done" ? outcome.value : null;
|
||||
} catch (error) {
|
||||
if (!signal.aborted) {
|
||||
logError(`The MCP server status read failed; keeping the Claude Code text of /mcp: ${error}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The known statuses in the order of the groups and of the summary counts.
|
||||
* A disabled server is not a group. It is on one line at the end. */
|
||||
const GROUP_ORDER: McpServerStatus["status"][] = ["failed", "needs-auth", "pending", "connected"];
|
||||
|
||||
const GROUP_TITLES: Partial<Record<McpServerStatus["status"], string>> = {
|
||||
failed: "Failed",
|
||||
"needs-auth": "Needs authentication",
|
||||
pending: "Connecting",
|
||||
connected: "Connected",
|
||||
};
|
||||
|
||||
const SUMMARY_LABELS: Record<McpServerStatus["status"], string> = {
|
||||
connected: "connected",
|
||||
failed: "failed",
|
||||
"needs-auth": "need authentication",
|
||||
pending: "connecting",
|
||||
disabled: "disabled",
|
||||
};
|
||||
|
||||
const KNOWN_STATUSES: string[] = [...GROUP_ORDER, "disabled"];
|
||||
|
||||
const MAX_ERROR_LENGTH = 160;
|
||||
|
||||
/** The longest segment that can be a wrapper. A longer segment is content. */
|
||||
const MAX_WRAPPER_LENGTH = 60;
|
||||
|
||||
/** True for a server that a `/mcp reconnect` without a name must retry. */
|
||||
function needsReconnect(status: McpServerStatus): boolean {
|
||||
return (
|
||||
status.status === "failed" || status.status === "pending" || status.status === "needs-auth"
|
||||
);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** True for a segment that only wraps the real error, such as
|
||||
* `MCP startup failed`, `McpError`, `MCP error -32001`, an error code, or a
|
||||
* Rust or TypeScript type path. */
|
||||
function isWrapperSegment(segment: string): boolean {
|
||||
return (
|
||||
isErrorCode(segment) ||
|
||||
segment.includes("::") ||
|
||||
(segment.length <= MAX_WRAPPER_LENGTH &&
|
||||
!/[.!?]/.test(segment) &&
|
||||
/(failed|error|exception)(\s+-?\d+)?$/i.test(segment))
|
||||
);
|
||||
}
|
||||
|
||||
/** Cut the text to `MAX_ERROR_LENGTH` code points, so a surrogate pair stays whole. */
|
||||
function truncate(text: string): string {
|
||||
const chars = Array.from(text);
|
||||
if (chars.length <= MAX_ERROR_LENGTH) return text;
|
||||
const cut = chars.slice(0, MAX_ERROR_LENGTH - 1).join("");
|
||||
return `${cut.trimEnd()}…`;
|
||||
}
|
||||
|
||||
/** Make an MCP error short and readable for one list item. The result has
|
||||
* no leading wrapper segments, at most two sentences, and at most
|
||||
* `MAX_ERROR_LENGTH` code points. A wrapper before an error code stays, so
|
||||
* an error code is never alone. The result is empty for an error with only
|
||||
* whitespace. */
|
||||
export function cleanMcpError(error: string): string {
|
||||
const segments = error.replace(/\s+/g, " ").trim().split(": ");
|
||||
let start = 0;
|
||||
while (
|
||||
start < segments.length - 1 &&
|
||||
isWrapperSegment(segments[start]!) &&
|
||||
!segments.slice(start + 1).every(isErrorCode)
|
||||
) {
|
||||
start++;
|
||||
}
|
||||
const content = segments.slice(start).join(": ");
|
||||
return truncate(
|
||||
content
|
||||
.split(/(?<=[.!?]) /)
|
||||
.slice(0, 2)
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
|
||||
function toolCount(status: McpServerStatus): string | undefined {
|
||||
if (!status.tools) return undefined;
|
||||
return status.tools.length === 1 ? "1 tool" : `${status.tools.length} tools`;
|
||||
}
|
||||
|
||||
/** The server name as inline code. Claude Code keys the servers by name, so
|
||||
* two servers have the same name only from different scopes. Then the
|
||||
* scope tells them apart. */
|
||||
function serverName(status: McpServerStatus, duplicates: Set<string>): string {
|
||||
const origin = status.scope ?? status.source;
|
||||
return duplicates.has(status.name) && origin
|
||||
? `${codeSpan(status.name)} (${escapeMarkdown(origin)})`
|
||||
: codeSpan(status.name);
|
||||
}
|
||||
|
||||
function serverItem(status: McpServerStatus, duplicates: Set<string>): string {
|
||||
const error = status.error ? cleanMcpError(status.error) : "";
|
||||
const details = [error === "" ? undefined : escapeMarkdown(error), toolCount(status)]
|
||||
.filter((detail) => detail !== undefined)
|
||||
.join("; ");
|
||||
const name = serverName(status, duplicates);
|
||||
return details === "" ? `- ${name}` : `- ${name}: ${details}`;
|
||||
}
|
||||
|
||||
function summaryLine(statuses: McpServerStatus[]): string {
|
||||
// The counts follow the group order. An unknown status also counts, so the counts add up to the total.
|
||||
const counts = [...GROUP_ORDER, ...unknownStatuses(statuses), "disabled"]
|
||||
.map((state) => ({
|
||||
state,
|
||||
count: statuses.filter((status) => status.status === state).length,
|
||||
}))
|
||||
.filter(({ count }) => count > 0);
|
||||
const parts = counts.map(({ state, count }) =>
|
||||
count === 1 && state === "needs-auth"
|
||||
? "1 needs authentication"
|
||||
: `${count} ${SUMMARY_LABELS[state as McpServerStatus["status"]] ?? escapeMarkdown(state)}`,
|
||||
);
|
||||
return `**MCP servers:** ${statuses.length} (${parts.join(", ")})`;
|
||||
}
|
||||
|
||||
/** The statuses that this adapter does not know, in the SDK order. The SDK
|
||||
* can report a new status before the adapter knows it. */
|
||||
function unknownStatuses(statuses: McpServerStatus[]): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
statuses
|
||||
.map((status) => status.status as string)
|
||||
.filter((state) => !KNOWN_STATUSES.includes(state)),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** The group title of a status that the adapter does not know. It starts with a capital letter, as a known title does. */
|
||||
function unknownTitle(state: string): string {
|
||||
return escapeMarkdown(state.charAt(0).toUpperCase() + state.slice(1));
|
||||
}
|
||||
|
||||
/** Markdown for `/mcp`: a summary line, one group of servers for each
|
||||
* status, and the disabled servers on one line. A list reads better than a
|
||||
* table in a narrow chat. */
|
||||
export function formatMcpStatus(statuses: McpServerStatus[]): string {
|
||||
if (statuses.length === 0) return "No MCP servers are configured.";
|
||||
const blocks: string[] = [];
|
||||
const names = statuses.map((status) => status.name);
|
||||
const duplicates = new Set(names.filter((name, index) => names.indexOf(name) !== index));
|
||||
blocks.push(summaryLine(statuses));
|
||||
const groups: [string, string][] = [
|
||||
...GROUP_ORDER.map((state): [string, string] => [state, GROUP_TITLES[state]!]),
|
||||
...unknownStatuses(statuses).map((state): [string, string] => [state, unknownTitle(state)]),
|
||||
];
|
||||
for (const [state, title] of groups) {
|
||||
const members = statuses.filter((status) => status.status === state);
|
||||
if (members.length === 0) continue;
|
||||
blocks.push(
|
||||
[`**${title}**`, ...members.map((status) => serverItem(status, duplicates))].join("\n"),
|
||||
);
|
||||
}
|
||||
const disabled = statuses.filter((status) => status.status === "disabled");
|
||||
if (disabled.length > 0) {
|
||||
blocks.push(
|
||||
`**Disabled:** ${disabled.map((status) => serverName(status, duplicates)).join(", ")}`,
|
||||
);
|
||||
}
|
||||
if (statuses.some(needsReconnect)) {
|
||||
blocks.push(
|
||||
"Run `/mcp reconnect <server>` to reconnect one server, or `/mcp reconnect` to reconnect every server that is not connected and not disabled.",
|
||||
);
|
||||
}
|
||||
return blocks.join("\n\n");
|
||||
}
|
||||
|
||||
/** The SDK query methods that `/mcp` uses. */
|
||||
export type McpControlQuery = Pick<
|
||||
Query,
|
||||
"mcpServerStatus" | "reconnectMcpServer" | "toggleMcpServer"
|
||||
>;
|
||||
|
||||
/** The result of {@link runMcpCommand}. `markdown` is null when the turn
|
||||
* keeps the text of Claude Code. `reconnected` holds the servers that the
|
||||
* adapter tried to reconnect. */
|
||||
export type McpCommandOutcome = { markdown: string | null; reconnected: string[] };
|
||||
|
||||
type CallResult = { type: "done" } | { type: "failed"; error: string } | { type: "aborted" };
|
||||
|
||||
/** Wait for one control call. The wait stops when `signal` aborts or the
|
||||
* call takes more than {@link MCP_ACTION_TIMEOUT_MS}. */
|
||||
async function awaitCall(call: () => Promise<void>, signal: AbortSignal): Promise<CallResult> {
|
||||
if (signal.aborted) return { type: "aborted" };
|
||||
try {
|
||||
const outcome = await raceTimeoutAndAbort(call(), MCP_ACTION_TIMEOUT_MS, signal);
|
||||
if (outcome.type === "timeout") return { type: "failed", error: "The request timed out." };
|
||||
return outcome.type === "done" ? { type: "done" } : outcome;
|
||||
} catch (error) {
|
||||
return signal.aborted
|
||||
? { type: "aborted" }
|
||||
: { type: "failed", error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
const ACTION_DONE = { reconnect: "Reconnected", enable: "Enabled", disable: "Disabled" };
|
||||
|
||||
/** The Claude Code sentence that refuses an action in SDK mode. */
|
||||
const UNAVAILABLE_SENTENCE = /aren't available in this session/i;
|
||||
|
||||
/** A Claude Code sentence that points to a terminal, which an ACP client
|
||||
* does not have. */
|
||||
function isTerminalSentence(sentence: string): boolean {
|
||||
return /in the terminal/i.test(sentence) || sentence.includes("`/mcp reconnect all` here");
|
||||
}
|
||||
|
||||
function sentences(text: string): string[] {
|
||||
return text
|
||||
.trim()
|
||||
.split(/(?<=[.!?])\s+/)
|
||||
.filter((sentence) => sentence !== "");
|
||||
}
|
||||
|
||||
/** The servers that the action changes. A named server is always a target,
|
||||
* so the control API reports its own error. */
|
||||
function actionTargets(
|
||||
command: Extract<McpCommand, { all: boolean }>,
|
||||
statuses: McpServerStatus[],
|
||||
): string[] {
|
||||
if (!command.all) return command.server === undefined ? [] : [command.server];
|
||||
const names = statuses
|
||||
.filter((status) => {
|
||||
if (command.action === "reconnect") return needsReconnect(status);
|
||||
if (command.action === "enable") return status.status === "disabled";
|
||||
return status.status !== "disabled";
|
||||
})
|
||||
.map((status) => status.name);
|
||||
return [...new Set(names)];
|
||||
}
|
||||
|
||||
function nothingToDoLine(action: McpCommand["action"]): string {
|
||||
if (action === "enable") return "Every MCP server is already enabled.";
|
||||
if (action === "disable") return "Every MCP server is already disabled.";
|
||||
return "Every MCP server is connected or disabled. There is nothing to reconnect.";
|
||||
}
|
||||
|
||||
/** Run a `/mcp` command after Claude Code sent `originalOutput`, its text for
|
||||
* the command. Claude Code refuses a reconnect, an enable, and a disable in
|
||||
* SDK mode, so the adapter runs them through the SDK control API. The result
|
||||
* of each server goes above the server list. An error of one server does
|
||||
* not stop the others. When the first status read fails or `signal`
|
||||
* aborts, the turn keeps the text of Claude Code. */
|
||||
export async function runMcpCommand(
|
||||
query: McpControlQuery,
|
||||
command: McpCommand,
|
||||
originalOutput: string,
|
||||
signal: AbortSignal,
|
||||
logError: (message: string) => void,
|
||||
): Promise<McpCommandOutcome> {
|
||||
const reconnected: string[] = [];
|
||||
const keep: McpCommandOutcome = { markdown: null, reconnected };
|
||||
if (command.action === "status") {
|
||||
// The list replaces the Claude Code summary line.
|
||||
const statuses = await readMcpServerStatus(query, signal, logError);
|
||||
return { markdown: statuses ? formatMcpStatus(statuses) : null, reconnected };
|
||||
}
|
||||
const before = await readMcpServerStatus(query, signal, logError);
|
||||
if (!before) return keep;
|
||||
|
||||
const cliSentences = sentences(originalOutput).filter(
|
||||
(sentence) => !isTerminalSentence(sentence),
|
||||
);
|
||||
const cliNamesUnknown = cliSentences.some((sentence) => /no MCP server named/i.test(sentence));
|
||||
const results: string[] = [];
|
||||
if (!command.all && command.server === undefined) {
|
||||
results.push(`Name a server or \`all\`, for example \`/mcp ${command.action} <server>\`.`);
|
||||
}
|
||||
const known = new Set(before.map((status) => status.name));
|
||||
const targets = actionTargets(command, before);
|
||||
if (command.all && targets.length === 0) results.push(nothingToDoLine(command.action));
|
||||
for (const server of targets) {
|
||||
if (!known.has(server)) {
|
||||
// Claude Code checks the name first. Its sentence then stays.
|
||||
if (!cliNamesUnknown) results.push(`There's no MCP server named ${codeSpan(server)}.`);
|
||||
continue;
|
||||
}
|
||||
if (command.action === "reconnect") reconnected.push(server);
|
||||
const call =
|
||||
command.action === "reconnect"
|
||||
? () => query.reconnectMcpServer(server)
|
||||
: () => query.toggleMcpServer(server, command.action === "enable");
|
||||
const result = await awaitCall(call, signal);
|
||||
if (result.type === "aborted") return keep;
|
||||
if (result.type === "done") {
|
||||
results.push(`- ${ACTION_DONE[command.action]} ${codeSpan(server)}`);
|
||||
} else {
|
||||
const error = cleanMcpError(result.error);
|
||||
const failure = `- Couldn't ${command.action} ${codeSpan(server)}`;
|
||||
results.push(error === "" ? failure : `${failure}: ${escapeMarkdown(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
const blocks: string[] = [];
|
||||
const kept = cliSentences.filter((sentence) => !UNAVAILABLE_SENTENCE.test(sentence));
|
||||
if (kept.length > 0) blocks.push(kept.join(" "));
|
||||
if (results.length > 0) blocks.push(results.join("\n"));
|
||||
const after = await readMcpServerStatus(query, signal, logError);
|
||||
if (signal.aborted) return keep;
|
||||
if (after) blocks.push(formatMcpStatus(after));
|
||||
return { markdown: blocks.join("\n\n"), reconnected };
|
||||
}
|
||||
214
src/mcp-oauth.ts
214
src/mcp-oauth.ts
@@ -1,214 +0,0 @@
|
||||
/**
|
||||
* OAuth for the MCP servers that Claude Code reports as `needs-auth`, as an
|
||||
* ACP URL elicitation. Protocol-neutral: the v1 core and the v2 core
|
||||
* both start it once a session's setup response is sent.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type {
|
||||
CompleteElicitationNotification,
|
||||
CreateElicitationRequest,
|
||||
CreateElicitationResponse,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { McpServerStatus, Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/** Claude Code keeps the OAuth callback listener open in the background after
|
||||
* `mcpAuthenticate` returns the authorization URL. The SDK does not expose
|
||||
* that listener's completion promise, so watch the server status while the
|
||||
* ACP client has the URL elicitation open. */
|
||||
const MCP_OAUTH_STATUS_POLL_MS = 1_000;
|
||||
const MCP_OAUTH_TIMEOUT_MS = 10 * 60_000;
|
||||
|
||||
/** Runtime MCP OAuth control exposed by the pinned Agent SDK. It is not yet in
|
||||
* the public `Query` declaration, even though the method is present on the
|
||||
* SDK query object and backed by Claude Code's `mcp_authenticate` control. */
|
||||
type McpOAuthQuery = Query & {
|
||||
mcpAuthenticate(
|
||||
serverName: string,
|
||||
redirectUri?: string,
|
||||
): Promise<{
|
||||
authUrl?: string;
|
||||
requiresUserAction: boolean;
|
||||
callbackExpected: boolean;
|
||||
redirectScheme?: "localhost" | "custom";
|
||||
callbackPort?: number;
|
||||
state?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
export function supportsMcpOAuth(query: Query): query is McpOAuthQuery {
|
||||
return typeof (query as Partial<McpOAuthQuery>).mcpAuthenticate === "function";
|
||||
}
|
||||
|
||||
/** What an OAuth run needs of the client connection. */
|
||||
export type McpOAuthClient = {
|
||||
/** Whether the client advertised URL elicitation. Without it, OAuth does not start. */
|
||||
readonly urlElicitation: boolean;
|
||||
createElicitation(
|
||||
params: CreateElicitationRequest,
|
||||
signal: AbortSignal,
|
||||
): Promise<CreateElicitationResponse>;
|
||||
completeElicitation(params: CompleteElicitationNotification): Promise<void>;
|
||||
readonly logger: { error: (...args: unknown[]) => void };
|
||||
};
|
||||
|
||||
/** What an OAuth run needs of the session. */
|
||||
export type McpOAuthSession = {
|
||||
/** One OAuth run at a time per key: the session object. */
|
||||
readonly key: object;
|
||||
readonly sessionId: string;
|
||||
/** The session's query now, or `undefined` once the session is gone. */
|
||||
currentQuery(): Query | undefined;
|
||||
/** Aborts when the session closes. */
|
||||
readonly closed: AbortSignal;
|
||||
};
|
||||
|
||||
const mcpAuthentications = new WeakMap<object, Promise<void>>();
|
||||
|
||||
/** Start OAuth in the background for the servers in `requestedServers` that
|
||||
* Claude reports as needing authentication. It does nothing while another
|
||||
* OAuth run of the session is in progress. */
|
||||
export function startMcpServerAuthentication(
|
||||
client: McpOAuthClient,
|
||||
session: McpOAuthSession,
|
||||
requestedServers: Set<string>,
|
||||
): void {
|
||||
if (!client.urlElicitation || requestedServers.size === 0) return;
|
||||
const query = session.currentQuery();
|
||||
if (!query || mcpAuthentications.has(session.key)) return;
|
||||
|
||||
const authentication = authenticateMcpServers(client, session, query, requestedServers)
|
||||
.catch((error) => {
|
||||
if (!session.closed.aborted) {
|
||||
client.logger.error(`Failed to inspect MCP servers for OAuth: ${error}`);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (mcpAuthentications.get(session.key) === authentication) {
|
||||
mcpAuthentications.delete(session.key);
|
||||
}
|
||||
});
|
||||
mcpAuthentications.set(session.key, authentication);
|
||||
}
|
||||
|
||||
async function authenticateMcpServers(
|
||||
client: McpOAuthClient,
|
||||
session: McpOAuthSession,
|
||||
query: Query,
|
||||
requestedServers: Set<string>,
|
||||
): Promise<void> {
|
||||
if (!supportsMcpOAuth(query)) {
|
||||
client.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
|
||||
return;
|
||||
}
|
||||
|
||||
const statuses = await query.mcpServerStatus();
|
||||
for (const status of statuses) {
|
||||
if (status.status !== "needs-auth" || !requestedServers.has(status.name)) continue;
|
||||
try {
|
||||
await authenticateMcpServer(client, session, query, status.name);
|
||||
} catch (error) {
|
||||
if (session.currentQuery() && !session.closed.aborted) {
|
||||
client.logger.error(`Failed to authenticate MCP server ${status.name}: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Bridge Claude Code's startup MCP OAuth control to ACP URL elicitation.
|
||||
* Claude opens and owns the localhost callback listener; the ACP client only
|
||||
* needs to present the returned authorization URL. */
|
||||
async function authenticateMcpServer(
|
||||
client: McpOAuthClient,
|
||||
session: McpOAuthSession,
|
||||
query: McpOAuthQuery,
|
||||
serverName: string,
|
||||
): Promise<void> {
|
||||
if (!session.currentQuery()) return;
|
||||
|
||||
const login = await query.mcpAuthenticate(serverName);
|
||||
if (!login.requiresUserAction) return;
|
||||
if (!login.authUrl) {
|
||||
throw new Error("Claude Code requested user action without returning an authorization URL");
|
||||
}
|
||||
|
||||
const elicitationId = `mcp-oauth-${randomUUID()}`;
|
||||
const flowAbort = new AbortController();
|
||||
const abortFlow = () => flowAbort.abort(session.closed.reason);
|
||||
session.closed.addEventListener("abort", abortFlow, { once: true });
|
||||
if (session.closed.aborted) abortFlow();
|
||||
|
||||
try {
|
||||
const completed = waitForMcpAuthentication(session, query, serverName, flowAbort.signal);
|
||||
const elicitation = client.createElicitation(
|
||||
{
|
||||
mode: "url",
|
||||
sessionId: session.sessionId,
|
||||
message: `Authenticate with MCP server ${serverName}`,
|
||||
url: login.authUrl,
|
||||
elicitationId,
|
||||
},
|
||||
flowAbort.signal,
|
||||
);
|
||||
const first = await Promise.race([
|
||||
completed.then((authenticated) => ({ type: "completed" as const, authenticated })),
|
||||
elicitation.then((response) => ({ type: "elicitation" as const, response })),
|
||||
]);
|
||||
|
||||
// A url-mode accept carries no content to check. The guard
|
||||
// `CreateElicitationResponse.isAccept` would also reject an accept whose
|
||||
// `content` holds a v2-only value, such as an object.
|
||||
if (first.type === "elicitation" && first.response.action !== "accept") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (first.type === "elicitation") {
|
||||
await completed;
|
||||
}
|
||||
try {
|
||||
await client.completeElicitation({ elicitationId });
|
||||
} catch (error) {
|
||||
if (!flowAbort.signal.aborted) {
|
||||
client.logger.error(`Failed to complete MCP OAuth elicitation: ${error}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
flowAbort.abort();
|
||||
session.closed.removeEventListener("abort", abortFlow);
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForMcpAuthentication(
|
||||
session: McpOAuthSession,
|
||||
query: Query,
|
||||
serverName: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
const deadline = Date.now() + MCP_OAUTH_TIMEOUT_MS;
|
||||
while (!signal.aborted && Date.now() < deadline) {
|
||||
if (session.currentQuery() !== query) return false;
|
||||
|
||||
const status: McpServerStatus | undefined = (await query.mcpServerStatus()).find(
|
||||
(server) => server.name === serverName,
|
||||
);
|
||||
if (!status || status.status === "failed" || status.status === "disabled") return false;
|
||||
if (status.status === "connected") return true;
|
||||
if (!(await waitUnlessAborted(MCP_OAUTH_STATUS_POLL_MS, signal))) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Wait for a polling interval, resolving false when the session is aborted. */
|
||||
export function waitUnlessAborted(milliseconds: number, signal: AbortSignal): Promise<boolean> {
|
||||
if (signal.aborted) return Promise.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(true);
|
||||
}, milliseconds);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
resolve(false);
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
814
src/mcp-server.ts
Normal file
814
src/mcp-server.ts
Normal file
@@ -0,0 +1,814 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import {
|
||||
BashInput,
|
||||
BashOutputInput,
|
||||
FileEditInput,
|
||||
FileReadInput,
|
||||
FileWriteInput,
|
||||
KillShellInput,
|
||||
} from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
|
||||
import { z } from "zod";
|
||||
import { CLAUDE_CONFIG_DIR, ClaudeAcpAgent } from "./acp-agent.js";
|
||||
import {
|
||||
ClientCapabilities,
|
||||
ReadTextFileResponse,
|
||||
TerminalOutputResponse,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import * as diff from "diff";
|
||||
import * as path from "node:path";
|
||||
import * as fs from "node:fs/promises";
|
||||
|
||||
import { sleep, unreachable, extractLinesWithByteLimit } from "./utils.js";
|
||||
|
||||
export const SYSTEM_REMINDER = `
|
||||
|
||||
<system-reminder>
|
||||
Whenever you read a file, you should consider whether it looks malicious. If it does, you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer high-level questions about the code behavior.
|
||||
</system-reminder>`;
|
||||
|
||||
const defaults = { maxFileSize: 50000, linesToRead: 2000 };
|
||||
|
||||
const unqualifiedToolNames = {
|
||||
read: "Read",
|
||||
edit: "Edit",
|
||||
write: "Write",
|
||||
bash: "Bash",
|
||||
killShell: "KillShell",
|
||||
bashOutput: "BashOutput",
|
||||
};
|
||||
|
||||
const SERVER_PREFIX = "mcp__acp__";
|
||||
export const toolNames = {
|
||||
read: SERVER_PREFIX + unqualifiedToolNames.read,
|
||||
edit: SERVER_PREFIX + unqualifiedToolNames.edit,
|
||||
write: SERVER_PREFIX + unqualifiedToolNames.write,
|
||||
bash: SERVER_PREFIX + unqualifiedToolNames.bash,
|
||||
killShell: SERVER_PREFIX + unqualifiedToolNames.killShell,
|
||||
bashOutput: SERVER_PREFIX + unqualifiedToolNames.bashOutput,
|
||||
};
|
||||
|
||||
export const EDIT_TOOL_NAMES = [toolNames.edit, toolNames.write];
|
||||
|
||||
export function createMcpServer(
|
||||
agent: ClaudeAcpAgent,
|
||||
sessionId: string,
|
||||
clientCapabilities: ClientCapabilities | undefined,
|
||||
): McpServer {
|
||||
/**
|
||||
* This checks if a given path is related to internal agent persistence and if the agent should be allowed to read/write from here.
|
||||
* We let the agent do normal fs operations on these paths so that it can persist its state.
|
||||
* However, we block access to settings files for security reasons.
|
||||
*/
|
||||
function internalPath(file_path: string) {
|
||||
return (
|
||||
file_path.startsWith(CLAUDE_CONFIG_DIR) &&
|
||||
!file_path.startsWith(path.join(CLAUDE_CONFIG_DIR, "settings.json")) &&
|
||||
!file_path.startsWith(path.join(CLAUDE_CONFIG_DIR, "session-env"))
|
||||
);
|
||||
}
|
||||
|
||||
async function readTextFile(input: FileReadInput): Promise<ReadTextFileResponse> {
|
||||
if (internalPath(input.file_path)) {
|
||||
const content = await fs.readFile(input.file_path, "utf8");
|
||||
|
||||
// eslint-disable-next-line eqeqeq
|
||||
if (input.offset != null || input.limit != null) {
|
||||
const lines = content.split("\n");
|
||||
|
||||
// Apply offset and limit if provided
|
||||
const offset = input.offset ?? 1;
|
||||
const limit = input.limit ?? lines.length;
|
||||
|
||||
// Extract the requested lines (offset is 1-based)
|
||||
const startIndex = Math.max(0, offset - 1);
|
||||
const endIndex = Math.min(lines.length, startIndex + limit);
|
||||
const selectedLines = lines.slice(startIndex, endIndex);
|
||||
|
||||
return { content: selectedLines.join("\n") };
|
||||
} else {
|
||||
return { content };
|
||||
}
|
||||
}
|
||||
|
||||
return agent.readTextFile({
|
||||
sessionId,
|
||||
path: input.file_path,
|
||||
line: input.offset,
|
||||
limit: input.limit,
|
||||
});
|
||||
}
|
||||
|
||||
async function writeTextFile(input: FileWriteInput): Promise<void> {
|
||||
if (internalPath(input.file_path)) {
|
||||
await fs.writeFile(input.file_path, input.content, "utf8");
|
||||
} else {
|
||||
await agent.writeTextFile({
|
||||
sessionId,
|
||||
path: input.file_path,
|
||||
content: input.content,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create MCP server
|
||||
const server = new McpServer({ name: "acp", version: "1.0.0" }, { capabilities: { tools: {} } });
|
||||
|
||||
if (clientCapabilities?.fs?.readTextFile) {
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.read,
|
||||
{
|
||||
title: unqualifiedToolNames.read,
|
||||
description: `Reads the content of the given file in the project.
|
||||
|
||||
In sessions with ${toolNames.read} always use it instead of Read as it contains the most up-to-date contents.
|
||||
|
||||
Reads a file from the local filesystem. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
||||
|
||||
Usage:
|
||||
- The file_path parameter must be an absolute path, not a relative path
|
||||
- By default, it reads up to ${defaults.linesToRead} lines starting from the beginning of the file
|
||||
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
|
||||
- Any files larger than ${defaults.maxFileSize} bytes will be truncated
|
||||
- This tool allows Claude Code to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.
|
||||
- This tool can only read files, not directories. To read a directory, use an ls command via the ${toolNames.bash} tool.
|
||||
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.`,
|
||||
inputSchema: {
|
||||
file_path: z.string().describe("The absolute path to the file to read"),
|
||||
offset: z
|
||||
.number()
|
||||
.optional()
|
||||
.default(1)
|
||||
.describe(
|
||||
"The line number to start reading from. Only provide if the file is too large to read at once",
|
||||
),
|
||||
limit: z
|
||||
.number()
|
||||
.optional()
|
||||
.default(defaults.linesToRead)
|
||||
.describe(
|
||||
`The number of lines to read. Only provide if the file is too large to read at once.`,
|
||||
),
|
||||
},
|
||||
annotations: {
|
||||
title: "Read file",
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
openWorldHint: false,
|
||||
idempotentHint: false,
|
||||
},
|
||||
},
|
||||
async (input: FileReadInput) => {
|
||||
try {
|
||||
const session = agent.sessions[sessionId];
|
||||
if (!session) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "The user has left the building",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const readResponse = await readTextFile(input);
|
||||
|
||||
if (typeof readResponse?.content !== "string") {
|
||||
throw new Error(`No file contents for ${input.file_path}.`);
|
||||
}
|
||||
|
||||
// Extract lines with byte limit enforcement
|
||||
const result = extractLinesWithByteLimit(readResponse.content, defaults.maxFileSize);
|
||||
|
||||
// Construct informative message about what was read
|
||||
let readInfo = "";
|
||||
if ((input.offset && input.offset > 1) || result.wasLimited) {
|
||||
readInfo = "\n\n<file-read-info>";
|
||||
|
||||
if (result.wasLimited) {
|
||||
readInfo += `Read ${result.linesRead} lines (hit 50KB limit). `;
|
||||
} else {
|
||||
readInfo += `Read lines ${input.offset}-${result.linesRead}. `;
|
||||
}
|
||||
|
||||
if (result.wasLimited) {
|
||||
readInfo += `Continue with offset=${result.linesRead}.`;
|
||||
}
|
||||
|
||||
readInfo += "</file-read-info>";
|
||||
}
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: result.content + readInfo + SYSTEM_REMINDER,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Reading file failed: " + error.message,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (clientCapabilities?.fs?.writeTextFile) {
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.write,
|
||||
{
|
||||
title: unqualifiedToolNames.write,
|
||||
description: `Writes a file to the local filesystem..
|
||||
|
||||
In sessions with ${toolNames.write} always use it instead of Write as it will
|
||||
allow the user to conveniently review changes.
|
||||
|
||||
Usage:
|
||||
- This tool will overwrite the existing file if there is one at the provided path.
|
||||
- If this is an existing file, you MUST use the ${toolNames.read} tool first to read the file's contents. This tool will fail if you did not read the file first.
|
||||
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
|
||||
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
|
||||
- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`,
|
||||
inputSchema: {
|
||||
file_path: z
|
||||
.string()
|
||||
.describe("The absolute path to the file to write (must be absolute, not relative)"),
|
||||
content: z.string().describe("The content to write to the file"),
|
||||
},
|
||||
annotations: {
|
||||
title: "Write file",
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
openWorldHint: false,
|
||||
idempotentHint: false,
|
||||
},
|
||||
},
|
||||
async (input: FileWriteInput) => {
|
||||
try {
|
||||
const session = agent.sessions[sessionId];
|
||||
if (!session) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "The user has left the building",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
await writeTextFile(input);
|
||||
|
||||
return {
|
||||
content: [],
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Writing file failed: " + error.message,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.edit,
|
||||
{
|
||||
title: unqualifiedToolNames.edit,
|
||||
description: `Performs exact string replacements in files.
|
||||
|
||||
In sessions with ${toolNames.edit} always use it instead of Edit as it will
|
||||
allow the user to conveniently review changes.
|
||||
|
||||
Usage:
|
||||
- You must use your \`${toolNames.read}\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
|
||||
- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears.
|
||||
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
|
||||
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
|
||||
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`,
|
||||
inputSchema: {
|
||||
file_path: z.string().describe("The absolute path to the file to modify"),
|
||||
old_string: z.string().describe("The text to replace"),
|
||||
new_string: z
|
||||
.string()
|
||||
.describe("The text to replace it with (must be different from old_string)"),
|
||||
replace_all: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.optional()
|
||||
.describe("Replace all occurrences of old_string (default false)"),
|
||||
},
|
||||
annotations: {
|
||||
title: "Edit file",
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
openWorldHint: false,
|
||||
idempotentHint: false,
|
||||
},
|
||||
},
|
||||
async (input: FileEditInput) => {
|
||||
try {
|
||||
const session = agent.sessions[sessionId];
|
||||
if (!session) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "The user has left the building",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const readResponse = await readTextFile({
|
||||
file_path: input.file_path,
|
||||
});
|
||||
|
||||
if (typeof readResponse?.content !== "string") {
|
||||
throw new Error(`No file contents for ${input.file_path}.`);
|
||||
}
|
||||
|
||||
const { newContent } = replaceAndCalculateLocation(readResponse.content, [
|
||||
{
|
||||
oldText: input.old_string,
|
||||
newText: input.new_string,
|
||||
replaceAll: input.replace_all,
|
||||
},
|
||||
]);
|
||||
|
||||
const patch = diff.createPatch(input.file_path, readResponse.content, newContent);
|
||||
|
||||
await writeTextFile({ file_path: input.file_path, content: newContent });
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: patch,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Editing file failed: " + (error?.message ?? String(error)),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (agent.clientCapabilities?.terminal) {
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.bash,
|
||||
{
|
||||
title: unqualifiedToolNames.bash,
|
||||
description: `Executes a bash command
|
||||
|
||||
In sessions with ${toolNames.bash} always use it instead of Bash`,
|
||||
inputSchema: {
|
||||
command: z.string().describe("The command to execute"),
|
||||
timeout: z.number().describe(`Optional timeout in milliseconds (max ${2 * 60 * 1000})`),
|
||||
description: z.string().optional()
|
||||
.describe(`Clear, concise description of what this command does in 5-10 words, in active voice. Examples:
|
||||
Input: ls
|
||||
Output: List files in current directory
|
||||
|
||||
Input: git status
|
||||
Output: Show working tree status
|
||||
|
||||
Input: npm install
|
||||
Output: Install package dependencies
|
||||
|
||||
Input: mkdir foo
|
||||
Output: Create directory 'foo'`),
|
||||
run_in_background: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe(
|
||||
`Set to true to run this command in the background. The tool returns an \`id\` that can be used with the \`${toolNames.bashOutput}\` tool to retrieve the current output, or the \`${toolNames.killShell}\` tool to stop it early.`,
|
||||
),
|
||||
},
|
||||
},
|
||||
async (input: BashInput, extra) => {
|
||||
const session = agent.sessions[sessionId];
|
||||
if (!session) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "The user has left the building",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const toolCallId = extra._meta?.["claudecode/toolUseId"];
|
||||
|
||||
if (typeof toolCallId !== "string") {
|
||||
throw new Error("No tool call ID found");
|
||||
}
|
||||
|
||||
if (!agent.clientCapabilities?.terminal || !agent.client.createTerminal) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
|
||||
const handle = await agent.client.createTerminal({
|
||||
command: input.command,
|
||||
env: [{ name: "CLAUDECODE", value: "1" }],
|
||||
sessionId,
|
||||
outputByteLimit: 32_000,
|
||||
});
|
||||
|
||||
await agent.client.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
title: input.description,
|
||||
content: [{ type: "terminal", terminalId: handle.id }],
|
||||
},
|
||||
});
|
||||
|
||||
const abortPromise = new Promise((resolve) => {
|
||||
if (extra.signal.aborted) {
|
||||
resolve(null);
|
||||
} else {
|
||||
extra.signal.addEventListener("abort", () => {
|
||||
resolve(null);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const statusPromise = Promise.race([
|
||||
handle.waitForExit().then((exitStatus) => ({ status: "exited" as const, exitStatus })),
|
||||
abortPromise.then(() => ({ status: "aborted" as const, exitStatus: null })),
|
||||
sleep(input.timeout ?? 2 * 60 * 1000).then(async () => {
|
||||
if (agent.backgroundTerminals[handle.id]?.status === "started") {
|
||||
await handle.kill();
|
||||
}
|
||||
return { status: "timedOut" as const, exitStatus: null };
|
||||
}),
|
||||
]);
|
||||
|
||||
if (input.run_in_background) {
|
||||
agent.backgroundTerminals[handle.id] = {
|
||||
handle,
|
||||
lastOutput: null,
|
||||
status: "started",
|
||||
};
|
||||
|
||||
statusPromise.then(async ({ status, exitStatus }) => {
|
||||
const bgTerm = agent.backgroundTerminals[handle.id];
|
||||
|
||||
if (bgTerm.status !== "started") {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentOutput = await handle.currentOutput();
|
||||
|
||||
agent.backgroundTerminals[handle.id] = {
|
||||
status,
|
||||
pendingOutput: {
|
||||
...currentOutput,
|
||||
output: stripCommonPrefix(bgTerm.lastOutput?.output ?? "", currentOutput.output),
|
||||
exitStatus: exitStatus ?? currentOutput.exitStatus,
|
||||
},
|
||||
};
|
||||
|
||||
return handle.release();
|
||||
});
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Command started in background with id: ${handle.id}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
await using terminal = handle;
|
||||
|
||||
const { status } = await statusPromise;
|
||||
|
||||
if (status === "aborted") {
|
||||
return {
|
||||
content: [{ type: "text", text: "Tool cancelled by user" }],
|
||||
};
|
||||
}
|
||||
|
||||
const output = await terminal.currentOutput();
|
||||
|
||||
return {
|
||||
content: [{ type: "text", text: toolCommandOutput(status, output) }],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.bashOutput,
|
||||
{
|
||||
title: unqualifiedToolNames.bashOutput,
|
||||
description: `- Retrieves output from a running or completed background bash shell
|
||||
- Takes a bash_id parameter identifying the shell
|
||||
- Always returns only new output since the last check
|
||||
- Returns stdout and stderr output along with shell status
|
||||
- Use this tool when you need to monitor or check the output of a long-running shell
|
||||
|
||||
In sessions with ${toolNames.bashOutput} always use it instead of BashOutput.`,
|
||||
inputSchema: {
|
||||
bash_id: z
|
||||
.string()
|
||||
.describe(`The id of the background bash command as returned by \`${toolNames.bash}\``),
|
||||
},
|
||||
},
|
||||
async (input: BashOutputInput) => {
|
||||
const bgTerm = agent.backgroundTerminals[input.bash_id];
|
||||
|
||||
if (!bgTerm) {
|
||||
throw new Error(`Unknown shell ${input.bash_id}`);
|
||||
}
|
||||
|
||||
if (bgTerm.status === "started") {
|
||||
const newOutput = await bgTerm.handle.currentOutput();
|
||||
const strippedOutput = stripCommonPrefix(
|
||||
bgTerm.lastOutput?.output ?? "",
|
||||
newOutput.output,
|
||||
);
|
||||
bgTerm.lastOutput = newOutput;
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: toolCommandOutput(bgTerm.status, {
|
||||
...newOutput,
|
||||
output: strippedOutput,
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: toolCommandOutput(bgTerm.status, bgTerm.pendingOutput),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
unqualifiedToolNames.killShell,
|
||||
{
|
||||
title: unqualifiedToolNames.killShell,
|
||||
description: `- Kills a running background bash shell by its ID
|
||||
- Takes a shell_id parameter identifying the shell to kill
|
||||
- Returns a success or failure status
|
||||
- Use this tool when you need to terminate a long-running shell
|
||||
|
||||
In sessions with ${toolNames.killShell} always use it instead of KillShell.`,
|
||||
inputSchema: {
|
||||
shell_id: z
|
||||
.string()
|
||||
.describe(`The id of the background bash command as returned by \`${toolNames.bash}\``),
|
||||
},
|
||||
},
|
||||
async (input: KillShellInput) => {
|
||||
const bgTerm = agent.backgroundTerminals[input.shell_id];
|
||||
|
||||
if (!bgTerm) {
|
||||
throw new Error(`Unknown shell ${input.shell_id}`);
|
||||
}
|
||||
|
||||
switch (bgTerm.status) {
|
||||
case "started": {
|
||||
await bgTerm.handle.kill();
|
||||
const currentOutput = await bgTerm.handle.currentOutput();
|
||||
agent.backgroundTerminals[bgTerm.handle.id] = {
|
||||
status: "killed",
|
||||
pendingOutput: {
|
||||
...currentOutput,
|
||||
output: stripCommonPrefix(bgTerm.lastOutput?.output ?? "", currentOutput.output),
|
||||
},
|
||||
};
|
||||
await bgTerm.handle.release();
|
||||
|
||||
return {
|
||||
content: [{ type: "text", text: "Command killed successfully." }],
|
||||
};
|
||||
}
|
||||
case "aborted":
|
||||
return {
|
||||
content: [{ type: "text", text: "Command aborted by user." }],
|
||||
};
|
||||
case "exited":
|
||||
return {
|
||||
content: [{ type: "text", text: "Command had already exited." }],
|
||||
};
|
||||
case "killed":
|
||||
return {
|
||||
content: [{ type: "text", text: "Command was already killed." }],
|
||||
};
|
||||
case "timedOut":
|
||||
return {
|
||||
content: [{ type: "text", text: "Command killed by timeout." }],
|
||||
};
|
||||
default: {
|
||||
unreachable(bgTerm);
|
||||
throw new Error("Unexpected background terminal status");
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
function stripCommonPrefix(a: string, b: string): string {
|
||||
let i = 0;
|
||||
while (i < a.length && i < b.length && a[i] === b[i]) {
|
||||
i++;
|
||||
}
|
||||
return b.slice(i);
|
||||
}
|
||||
|
||||
function toolCommandOutput(
|
||||
status: "started" | "aborted" | "exited" | "killed" | "timedOut",
|
||||
output: TerminalOutputResponse,
|
||||
): string {
|
||||
const { exitStatus, output: commandOutput, truncated } = output;
|
||||
|
||||
let toolOutput = "";
|
||||
|
||||
switch (status) {
|
||||
case "started":
|
||||
case "exited": {
|
||||
if (exitStatus && (exitStatus.exitCode ?? null) === null) {
|
||||
toolOutput += `Interrupted by the user. `;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "killed":
|
||||
toolOutput += `Killed. `;
|
||||
break;
|
||||
case "timedOut":
|
||||
toolOutput += `Timed out. `;
|
||||
break;
|
||||
case "aborted":
|
||||
break;
|
||||
default: {
|
||||
const unreachable: never = status;
|
||||
return unreachable;
|
||||
}
|
||||
}
|
||||
|
||||
if (exitStatus) {
|
||||
if (typeof exitStatus.exitCode === "number") {
|
||||
toolOutput += `Exited with code ${exitStatus.exitCode}.`;
|
||||
}
|
||||
|
||||
if (typeof exitStatus.signal === "string") {
|
||||
toolOutput += `Signal \`${exitStatus.signal}\`. `;
|
||||
}
|
||||
|
||||
toolOutput += "Final output:\n\n";
|
||||
} else {
|
||||
toolOutput += "New output:\n\n";
|
||||
}
|
||||
|
||||
toolOutput += commandOutput;
|
||||
|
||||
if (truncated) {
|
||||
toolOutput += `\n\nCommand output was too long, so it was truncated to ${commandOutput.length} bytes.`;
|
||||
}
|
||||
|
||||
return toolOutput;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace text in a file and calculate the line numbers where the edits occurred.
|
||||
*
|
||||
* @param fileContent - The full file content
|
||||
* @param edits - Array of edit operations to apply sequentially
|
||||
* @returns the new content and the line numbers where replacements occurred in the final content
|
||||
*/
|
||||
export function replaceAndCalculateLocation(
|
||||
fileContent: string,
|
||||
edits: Array<{
|
||||
oldText: string;
|
||||
newText: string;
|
||||
replaceAll?: boolean;
|
||||
}>,
|
||||
): { newContent: string; lineNumbers: number[] } {
|
||||
let currentContent = fileContent;
|
||||
|
||||
// Use unique markers to track where replacements happen
|
||||
const markerPrefix = `__REPLACE_MARKER_${Math.random().toString(36).substr(2, 9)}_`;
|
||||
let markerCounter = 0;
|
||||
const markers: string[] = [];
|
||||
|
||||
// Apply edits sequentially, inserting markers at replacement positions
|
||||
for (const edit of edits) {
|
||||
// Skip empty oldText
|
||||
if (edit.oldText === "") {
|
||||
throw new Error(`The provided \`old_string\` is empty.\n\nNo edits were applied.`);
|
||||
}
|
||||
|
||||
if (edit.replaceAll) {
|
||||
// Replace all occurrences with marker + newText
|
||||
const parts: string[] = [];
|
||||
let lastIndex = 0;
|
||||
let searchIndex = 0;
|
||||
|
||||
while (true) {
|
||||
const index = currentContent.indexOf(edit.oldText, searchIndex);
|
||||
if (index === -1) {
|
||||
if (searchIndex === 0) {
|
||||
throw new Error(
|
||||
`The provided \`old_string\` does not appear in the file: "${edit.oldText}".\n\nNo edits were applied.`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Add content before the match
|
||||
parts.push(currentContent.substring(lastIndex, index));
|
||||
|
||||
// Add marker and replacement
|
||||
const marker = `${markerPrefix}${markerCounter++}__`;
|
||||
markers.push(marker);
|
||||
parts.push(marker + edit.newText);
|
||||
|
||||
lastIndex = index + edit.oldText.length;
|
||||
searchIndex = lastIndex;
|
||||
}
|
||||
|
||||
// Add remaining content
|
||||
parts.push(currentContent.substring(lastIndex));
|
||||
currentContent = parts.join("");
|
||||
} else {
|
||||
// Replace first occurrence only
|
||||
const index = currentContent.indexOf(edit.oldText);
|
||||
if (index === -1) {
|
||||
throw new Error(
|
||||
`The provided \`old_string\` does not appear in the file: "${edit.oldText}".\n\nNo edits were applied.`,
|
||||
);
|
||||
} else {
|
||||
const marker = `${markerPrefix}${markerCounter++}__`;
|
||||
markers.push(marker);
|
||||
currentContent =
|
||||
currentContent.substring(0, index) +
|
||||
marker +
|
||||
edit.newText +
|
||||
currentContent.substring(index + edit.oldText.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find line numbers where markers appear in the content
|
||||
const lineNumbers: number[] = [];
|
||||
for (const marker of markers) {
|
||||
const index = currentContent.indexOf(marker);
|
||||
if (index !== -1) {
|
||||
const lineNumber = Math.max(
|
||||
0,
|
||||
currentContent.substring(0, index).split(/\r\n|\r|\n/).length - 1,
|
||||
);
|
||||
lineNumbers.push(lineNumber);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all markers from the final content
|
||||
let finalContent = currentContent;
|
||||
for (const marker of markers) {
|
||||
finalContent = finalContent.replace(marker, "");
|
||||
}
|
||||
|
||||
// Dedupe and sort line numbers
|
||||
const uniqueLineNumbers = [...new Set(lineNumbers)].sort();
|
||||
|
||||
return { newContent: finalContent, lineNumbers: uniqueLineNumbers };
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { McpServer } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function sdkMcpServers(
|
||||
servers: readonly McpServer[] | null | undefined,
|
||||
): Record<string, McpServerConfig> {
|
||||
const configs: Record<string, McpServerConfig> = {};
|
||||
for (const server of servers ?? []) {
|
||||
if ("type" in server && (server.type === "http" || server.type === "sse")) {
|
||||
configs[server.name] = {
|
||||
type: server.type,
|
||||
url: server.url,
|
||||
headers: server.headers
|
||||
? Object.fromEntries(server.headers.map((e) => [e.name, e.value]))
|
||||
: undefined,
|
||||
};
|
||||
} else if (!("type" in server)) {
|
||||
configs[server.name] = {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
env: server.env ? Object.fromEntries(server.env.map((e) => [e.name, e.value])) : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
return configs;
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
/**
|
||||
* The Claude Code messages and content that a client never sees as the user's
|
||||
* or the agent's text: local slash command markers, context the CLI injects,
|
||||
* the synthetic `/login` message and meta messages from other agents. The live
|
||||
* stream and the `session/load` replay both filter with these.
|
||||
*/
|
||||
import { isLoginRequiredText } from "./result-end.js";
|
||||
import { isSyntheticUsageLimitMessage } from "./session-failure-extension.js";
|
||||
import { markerTagText, TASK_NOTIFICATION_TAG } from "./task-notifications.js";
|
||||
|
||||
// Slash commands that the SDK handles locally without replaying the user
|
||||
// message and without invoking the model.
|
||||
export const LOCAL_ONLY_COMMANDS = new Set(["/context", "/heapdump", "/extra-usage"]);
|
||||
|
||||
// Commands whose marker-only transcript records are ACP/client-local UI noise,
|
||||
// not model-visible user prompts. Marker-only custom slash skills are not in
|
||||
// this list, so replay can reconstruct them from `<command-name>`/`<command-args>`.
|
||||
const REPLAY_HIDDEN_COMMANDS = new Set([
|
||||
...LOCAL_ONLY_COMMANDS,
|
||||
"/compact",
|
||||
"/model",
|
||||
"/mcp",
|
||||
"/status",
|
||||
"/usage",
|
||||
]);
|
||||
|
||||
// The Claude SDK persists local slash command invocations (e.g. `/model`) and
|
||||
// their output as user messages in the session transcript, wrapping the
|
||||
// payload in these XML-like markers that the CLI uses for its own display.
|
||||
// The live prompt loop drops them; replay must strip them too or they leak
|
||||
// into the UI on session/load.
|
||||
const LOCAL_COMMAND_MARKERS = [
|
||||
"command-name",
|
||||
"command-message",
|
||||
"command-args",
|
||||
"local-command-stdout",
|
||||
"local-command-stderr",
|
||||
].map((tag) => ({ open: `<${tag}>`, close: `</${tag}>` }));
|
||||
|
||||
// Context the CLI injects into a user turn to steer the model, appended to
|
||||
// whatever the user typed. Nobody wrote it and no client sees it live — the
|
||||
// prompt loop's user-message skip covers the whole message — but it is
|
||||
// persisted alongside that prose, so replay would hand the client a prompt
|
||||
// with instructions in it the user never gave. A `task-notification` tells the
|
||||
// model that a background task stopped; live, the SDK `task_notification`
|
||||
// frame reports the same stop, so replay restores the task state from it (see
|
||||
// taskNotificationsOf) instead of showing it.
|
||||
const INJECTED_CONTEXT_MARKERS = ["system-reminder", TASK_NOTIFICATION_TAG].map((tag) => ({
|
||||
open: `<${tag}>`,
|
||||
close: `</${tag}>`,
|
||||
}));
|
||||
|
||||
// Everything a replayed user message may be wrapped in that is not speech.
|
||||
const TRANSCRIPT_MARKERS = [...LOCAL_COMMAND_MARKERS, ...INJECTED_CONTEXT_MARKERS];
|
||||
|
||||
// Single-pass scanner that removes each `<tag>…</tag>` marker (matching the
|
||||
// nearest closing tag of the same name, like a lazy regex would).
|
||||
function stripMarkerTags(text: string): string {
|
||||
const dead = new Set<string>();
|
||||
let result = "";
|
||||
let copiedUpTo = 0;
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
if (text[i] === "<") {
|
||||
const marker = TRANSCRIPT_MARKERS.find(
|
||||
(m) => !dead.has(m.open) && text.startsWith(m.open, i),
|
||||
);
|
||||
if (marker) {
|
||||
const end = text.indexOf(marker.close, i + marker.open.length);
|
||||
if (end !== -1) {
|
||||
result += text.slice(copiedUpTo, i);
|
||||
i = copiedUpTo = end + marker.close.length;
|
||||
continue;
|
||||
}
|
||||
// No closing marker remains anywhere ahead, and `indexOf` only ever
|
||||
// searches forward from here on, so stop treating this tag as an
|
||||
// opener — that avoids rescanning the tail for it on every match.
|
||||
dead.add(marker.open);
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return result + text.slice(copiedUpTo);
|
||||
}
|
||||
|
||||
function hasMarkerTag(text: string, tag: string): boolean {
|
||||
return markerTagText(text, tag) !== undefined;
|
||||
}
|
||||
|
||||
function commandInvocationFromMarkerOnlyText(text: string): string | null {
|
||||
if (hasMarkerTag(text, "local-command-stdout") || hasMarkerTag(text, "local-command-stderr")) {
|
||||
return null;
|
||||
}
|
||||
const commandName = markerTagText(text, "command-name")?.trim();
|
||||
if (!commandName?.startsWith("/")) return null;
|
||||
if (REPLAY_HIDDEN_COMMANDS.has(commandName.split(" ", 1)[0])) return null;
|
||||
|
||||
const commandArgs = markerTagText(text, "command-args")?.trim();
|
||||
return commandArgs ? `${commandName} ${commandArgs}` : commandName;
|
||||
}
|
||||
|
||||
function stripLocalCommandMetadataText(text: string): string | null {
|
||||
const stripped = stripMarkerTags(text);
|
||||
if (stripped.trim() !== "") return stripped;
|
||||
return commandInvocationFromMarkerOnlyText(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return user-message content with local-command and injected-context marker
|
||||
* tags removed, or `null` if nothing meaningful remains (caller should skip
|
||||
* the message). Preserves real prose that's mixed in alongside the markers —
|
||||
* e.g. a message like `<command-name>…</command-name>hi` becomes `hi`, and
|
||||
* `hi<system-reminder>…</system-reminder>` becomes `hi`.
|
||||
*/
|
||||
export function stripLocalCommandMetadata(content: unknown): unknown | null {
|
||||
if (typeof content === "string") {
|
||||
return stripLocalCommandMetadataText(content);
|
||||
}
|
||||
if (!Array.isArray(content)) return content;
|
||||
|
||||
const kept: unknown[] = [];
|
||||
for (const block of content) {
|
||||
if (
|
||||
block &&
|
||||
typeof block === "object" &&
|
||||
"type" in block &&
|
||||
(block as { type: unknown }).type === "text" &&
|
||||
"text" in block &&
|
||||
typeof (block as { text: unknown }).text === "string"
|
||||
) {
|
||||
const stripped = stripLocalCommandMetadataText((block as { text: string }).text);
|
||||
if (stripped === null) continue;
|
||||
kept.push({ ...(block as object), text: stripped });
|
||||
} else {
|
||||
kept.push(block);
|
||||
}
|
||||
}
|
||||
if (kept.length === 0) return null;
|
||||
return kept;
|
||||
}
|
||||
|
||||
export function isLocalCommandMetadata(content: unknown): boolean {
|
||||
return stripLocalCommandMetadata(content) === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True for the synthetic assistant message the CLI injects into the transcript
|
||||
* when a turn fails authentication (e.g. "Not logged in · Please run /login",
|
||||
* "Session expired. Please run /login to sign in again."). The `/login`
|
||||
* instruction is Claude Code TUI-specific and meaningless to ACP clients
|
||||
* (issue #863). The live prompt loop suppresses the text and fails the turn
|
||||
* with `authRequired` so the client can run its own auth flow; replay must
|
||||
* skip it too — both for parity with what the client saw live and because the
|
||||
* message stays in the transcript forever, so it would resurface on every
|
||||
* session/load even after the user has logged back in.
|
||||
*
|
||||
* Takes the API message (`message.message`), which replay only knows as
|
||||
* `unknown`. The persisted record's structured `error` marker is stripped by
|
||||
* `getSessionMessages`, and the CLI does not always set it to
|
||||
* `authentication_failed` anyway: an expired login with no refresh token
|
||||
* ("Login expired · Run /login to sign in again, …") arrives as
|
||||
* `invalid_request`. So the synthetic model + text is what both paths match on.
|
||||
* Usage-limit banners are excluded because some of them also mention `/login`
|
||||
* (to switch accounts) and have their own handling.
|
||||
*/
|
||||
export function isSyntheticLoginMessage(apiMessage: unknown): boolean {
|
||||
if (!apiMessage || typeof apiMessage !== "object") {
|
||||
return false;
|
||||
}
|
||||
const { model, content } = apiMessage as { model?: unknown; content?: unknown };
|
||||
if (model !== "<synthetic>" || !Array.isArray(content) || content.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
const block = content[0] as { type?: unknown; text?: unknown } | null;
|
||||
return (
|
||||
!!block &&
|
||||
block.type === "text" &&
|
||||
typeof block.text === "string" &&
|
||||
isLoginRequiredText(block.text) &&
|
||||
!isSyntheticUsageLimitMessage(apiMessage)
|
||||
);
|
||||
}
|
||||
|
||||
/** Origin kinds of the meta user messages `getSessionMessages` returns since
|
||||
* SDK 0.3.284 (messages from other agents, sessions and channels). */
|
||||
const REPLAY_HIDDEN_META_ORIGIN_KINDS = new Set([
|
||||
"peer",
|
||||
"channel",
|
||||
"observer",
|
||||
"observer-activity",
|
||||
"slack-ping",
|
||||
]);
|
||||
|
||||
/**
|
||||
* True for a transcript message delivered to the model from another agent,
|
||||
* session or channel. Since SDK 0.3.284 `getSessionMessages` returns these as
|
||||
* `is_meta` user messages whose content is the full harness framing (envelope
|
||||
* XML plus the "not typed by your user" preamble). The live prompt loop never
|
||||
* renders them, so replay skips them too rather than presenting them as text
|
||||
* the user typed. Other `is_meta` messages (compact summaries) are kept.
|
||||
*
|
||||
* `is_meta` and `origin` are runtime fields not declared on `SessionMessage`.
|
||||
*/
|
||||
export function isReplayHiddenMetaMessage(message: unknown): boolean {
|
||||
if (!message || typeof message !== "object") return false;
|
||||
const { type, is_meta, origin } = message as {
|
||||
type?: unknown;
|
||||
is_meta?: unknown;
|
||||
origin?: { kind?: unknown } | null;
|
||||
};
|
||||
return (
|
||||
type === "user" &&
|
||||
is_meta === true &&
|
||||
typeof origin?.kind === "string" &&
|
||||
REPLAY_HIDDEN_META_ORIGIN_KINDS.has(origin.kind)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,41 +0,0 @@
|
||||
import type { Options, SDKMessageOrigin } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
export type SDKMessageFilter = {
|
||||
type: string;
|
||||
subtype?: string;
|
||||
origin?: SDKMessageOrigin["kind"];
|
||||
};
|
||||
|
||||
/**
|
||||
* Extra metadata that can be given when creating a new session.
|
||||
*/
|
||||
export type NewSessionMeta = {
|
||||
claudeCode?: {
|
||||
/**
|
||||
* Options forwarded to Claude Code when starting a new session.
|
||||
* Those parameters will be ignored and managed by ACP:
|
||||
* - cwd
|
||||
* - includePartialMessages
|
||||
* - permissionMode
|
||||
* - canUseTool
|
||||
* - executable
|
||||
* Those parameters will be used and updated to work with ACP:
|
||||
* - hooks (merged with ACP's hooks)
|
||||
* - mcpServers (merged with ACP's mcpServers)
|
||||
* - disallowedTools (merged with ACP's disallowedTools)
|
||||
* - tools (passed through; defaults to claude_code preset if not provided)
|
||||
* - allowDangerouslySkipPermissions (set to `false` to remove bypassPermissions
|
||||
* from this session; repeat it on session/load. `true` cannot override root)
|
||||
*/
|
||||
options?: Options;
|
||||
/**
|
||||
* When set, raw SDK messages are emitted as extNotification("_claude/sdkMessage", message)
|
||||
* in addition to normal processing.
|
||||
* - true: emit all messages
|
||||
* - false/undefined: emit nothing (default)
|
||||
* - SDKMessageFilter[]: emit only messages matching at least one filter
|
||||
*/
|
||||
emitRawSDKMessages?: boolean | SDKMessageFilter[];
|
||||
};
|
||||
additionalRoots?: string[];
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
/** The Claude configuration directory: `CLAUDE_CONFIG_DIR`, or `~/.claude`. */
|
||||
export function claudeConfigDir(): string {
|
||||
return process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude");
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
import type { RequestPermissionResponse } from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
PermissionMode,
|
||||
PermissionResult,
|
||||
PermissionUpdate,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { DurablePermissionChangeSet } from "./normalization.js";
|
||||
import { PERMISSION_OPTION_ID } from "./options.js";
|
||||
|
||||
export interface ClaudePermissionSelection {
|
||||
optionId: string;
|
||||
contextResetMode?: PermissionMode;
|
||||
}
|
||||
|
||||
export interface ClaudePermissionEffectContext {
|
||||
toolName: string;
|
||||
input: Record<string, unknown>;
|
||||
toolUseID: string;
|
||||
durableChangeSet?: DurablePermissionChangeSet;
|
||||
}
|
||||
|
||||
/** Parse the ACP envelope once before dispatching to a tool-specific effect. */
|
||||
export function parseClaudePermissionSelection(
|
||||
response: RequestPermissionResponse,
|
||||
toolName: string,
|
||||
): ClaudePermissionSelection {
|
||||
if (response.outcome?.outcome !== "selected") throw new Error("Tool use aborted");
|
||||
const optionId = response.outcome.optionId;
|
||||
const contextResetMode =
|
||||
toolName === "ExitPlanMode" ? exitPlanClearContextMode(optionId) : undefined;
|
||||
return { optionId, ...(contextResetMode ? { contextResetMode } : {}) };
|
||||
}
|
||||
|
||||
function allow(
|
||||
context: ClaudePermissionEffectContext,
|
||||
updatedPermissions?: PermissionUpdate[],
|
||||
permanent = false,
|
||||
): PermissionResult {
|
||||
return {
|
||||
behavior: "allow",
|
||||
updatedInput: context.input,
|
||||
...(updatedPermissions ? { updatedPermissions } : {}),
|
||||
toolUseID: context.toolUseID,
|
||||
decisionClassification: permanent ? "user_permanent" : "user_temporary",
|
||||
};
|
||||
}
|
||||
|
||||
function deny(
|
||||
context: ClaudePermissionEffectContext,
|
||||
message = "User refused permission to run tool",
|
||||
interrupt = false,
|
||||
): PermissionResult {
|
||||
return {
|
||||
behavior: "deny",
|
||||
message,
|
||||
...(interrupt ? { interrupt: true } : {}),
|
||||
toolUseID: context.toolUseID,
|
||||
decisionClassification: "user_reject",
|
||||
};
|
||||
}
|
||||
|
||||
function skillName(input: Record<string, unknown>): string {
|
||||
const value = typeof input.skill === "string" ? input.skill.trim() : "";
|
||||
if (!value || value.length > 1_000) throw new Error("Invalid Skill permission input");
|
||||
return value;
|
||||
}
|
||||
|
||||
function localAllowRuleUpdate(toolName: string, ruleContent?: string): PermissionUpdate[] {
|
||||
return [
|
||||
{
|
||||
type: "addRules",
|
||||
rules: [{ toolName, ...(ruleContent === undefined ? {} : { ruleContent }) }],
|
||||
behavior: "allow",
|
||||
destination: "localSettings",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function webFetchPermissionUpdate(input: Record<string, unknown>): PermissionUpdate[] {
|
||||
if (typeof input.url !== "string") throw new Error("Invalid WebFetch permission input");
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(input.url).hostname;
|
||||
} catch {
|
||||
throw new Error("Invalid WebFetch permission input");
|
||||
}
|
||||
if (!hostname) throw new Error("Invalid WebFetch permission input");
|
||||
return localAllowRuleUpdate("WebFetch", `domain:${hostname}`);
|
||||
}
|
||||
|
||||
function applySkillSelection(
|
||||
selection: ClaudePermissionSelection,
|
||||
context: ClaudePermissionEffectContext,
|
||||
): PermissionResult {
|
||||
switch (selection.optionId) {
|
||||
case PERMISSION_OPTION_ID.allowSkillExact: {
|
||||
return allow(context, localAllowRuleUpdate("Skill", skillName(context.input)), true);
|
||||
}
|
||||
case PERMISSION_OPTION_ID.allowSkillPrefix: {
|
||||
const skill = skillName(context.input);
|
||||
const spaceIndex = skill.indexOf(" ");
|
||||
if (spaceIndex <= 0) throw new Error("Skill prefix permission requires arguments");
|
||||
return allow(context, localAllowRuleUpdate("Skill", `${skill.slice(0, spaceIndex)}:*`), true);
|
||||
}
|
||||
default:
|
||||
return applyCommonSelection(selection, context);
|
||||
}
|
||||
}
|
||||
|
||||
function exitPlanMode(optionId: string): PermissionMode | undefined {
|
||||
switch (optionId) {
|
||||
case PERMISSION_OPTION_ID.exitPlanBypass:
|
||||
return "bypassPermissions";
|
||||
case PERMISSION_OPTION_ID.exitPlanAuto:
|
||||
return "auto";
|
||||
case PERMISSION_OPTION_ID.exitPlanAcceptEdits:
|
||||
return "acceptEdits";
|
||||
case PERMISSION_OPTION_ID.exitPlanDefault:
|
||||
return "default";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function exitPlanClearContextMode(optionId: string): PermissionMode | undefined {
|
||||
switch (optionId) {
|
||||
case PERMISSION_OPTION_ID.exitPlanClearAuto:
|
||||
return "auto";
|
||||
case PERMISSION_OPTION_ID.exitPlanClearBypass:
|
||||
return "bypassPermissions";
|
||||
case PERMISSION_OPTION_ID.exitPlanClearAcceptEdits:
|
||||
return "acceptEdits";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function applyExitPlanModeSelection(
|
||||
selection: ClaudePermissionSelection,
|
||||
context: ClaudePermissionEffectContext,
|
||||
): PermissionResult {
|
||||
if (selection.contextResetMode) {
|
||||
// The adapter consumes this interrupt and continues the same ACP turn on a
|
||||
// fresh Claude query. Returning allow here would execute ExitPlanMode in
|
||||
// the old context before the handoff.
|
||||
return deny(context, "User accepted the plan and requested a fresh context", true);
|
||||
}
|
||||
const mode = exitPlanMode(selection.optionId);
|
||||
if (mode) {
|
||||
return allow(context, [{ type: "setMode", mode, destination: "session" }], mode !== "default");
|
||||
}
|
||||
if (selection.optionId === PERMISSION_OPTION_ID.reject) {
|
||||
// A regular deny lets Claude continue planning and ask another question.
|
||||
// Interrupt stops this ACP turn; the adapter maps Claude's internal
|
||||
// diagnostic for that intentional stop back to cancellation.
|
||||
return deny(context, "User chose to keep planning", true);
|
||||
}
|
||||
return applyCommonSelection(selection, context);
|
||||
}
|
||||
|
||||
function applyCommonSelection(
|
||||
selection: ClaudePermissionSelection,
|
||||
context: ClaudePermissionEffectContext,
|
||||
): PermissionResult {
|
||||
switch (selection.optionId) {
|
||||
case PERMISSION_OPTION_ID.allowOnce:
|
||||
return allow(context);
|
||||
case PERMISSION_OPTION_ID.allowWithUpdates:
|
||||
if (!context.durableChangeSet) throw new Error("Invalid durable permission selection");
|
||||
return allow(context, context.durableChangeSet.updates, true);
|
||||
case PERMISSION_OPTION_ID.reject:
|
||||
return deny(context);
|
||||
default:
|
||||
throw new Error(`Unknown permission option: ${selection.optionId}`);
|
||||
}
|
||||
}
|
||||
|
||||
function applyGeneratedDurableSelection(
|
||||
selection: ClaudePermissionSelection,
|
||||
context: ClaudePermissionEffectContext,
|
||||
updates: () => PermissionUpdate[],
|
||||
): PermissionResult {
|
||||
if (selection.optionId !== PERMISSION_OPTION_ID.allowWithUpdates) {
|
||||
return applyCommonSelection(selection, context);
|
||||
}
|
||||
return allow(context, updates(), true);
|
||||
}
|
||||
|
||||
/** Apply a parsed selection using the semantics of the tool that produced it. */
|
||||
export function applyClaudePermissionSelection(
|
||||
selection: ClaudePermissionSelection,
|
||||
context: ClaudePermissionEffectContext,
|
||||
): PermissionResult {
|
||||
switch (context.toolName) {
|
||||
case "Skill":
|
||||
return applySkillSelection(selection, context);
|
||||
case "WebFetch":
|
||||
return applyGeneratedDurableSelection(selection, context, () =>
|
||||
webFetchPermissionUpdate(context.input),
|
||||
);
|
||||
case "EnterPlanMode":
|
||||
return applyCommonSelection(selection, context);
|
||||
case "ExitPlanMode":
|
||||
return applyExitPlanModeSelection(selection, context);
|
||||
case "Read":
|
||||
case "Bash":
|
||||
case "PowerShell":
|
||||
case "Glob":
|
||||
case "Grep":
|
||||
case "Edit":
|
||||
case "Write":
|
||||
case "NotebookEdit":
|
||||
case "SandboxNetworkAccess":
|
||||
return applyCommonSelection(selection, context);
|
||||
default:
|
||||
if (context.toolName.startsWith("mcp__")) {
|
||||
return applyCommonSelection(selection, context);
|
||||
}
|
||||
return applyGeneratedDurableSelection(selection, context, () =>
|
||||
localAllowRuleUpdate(context.toolName),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import type { PermissionMode, Settings } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
interface PermissionModeLogger {
|
||||
error: (...args: unknown[]) => void;
|
||||
}
|
||||
|
||||
// Bypass Permissions doesn't work if we are a root/sudo user.
|
||||
const IS_ROOT = (process.geteuid?.() ?? process.getuid?.()) === 0;
|
||||
export const ALLOW_BYPASS = !IS_ROOT || !!process.env.IS_SANDBOX;
|
||||
|
||||
const PERMISSION_MODE_ALIASES: Record<string, PermissionMode> = {
|
||||
// Settings use user-facing, case-insensitive spellings while the SDK uses
|
||||
// camel-cased wire values. Keep legacy shorthand accepted by Claude Code too.
|
||||
auto: "auto",
|
||||
default: "default",
|
||||
// Claude Code 2.1.200 renamed the "default" mode to "Manual" and accepts
|
||||
// `"defaultMode": "manual"` in settings.json; honor the same alias here.
|
||||
manual: "default",
|
||||
acceptedits: "acceptEdits",
|
||||
dontask: "dontAsk",
|
||||
plan: "plan",
|
||||
bypasspermissions: "bypassPermissions",
|
||||
bypass: "bypassPermissions",
|
||||
};
|
||||
|
||||
/** When `allowBypass` is false, `bypassPermissions` clamps to `default` so the SDK
|
||||
* is never spawned in a mode it would reject. */
|
||||
export function resolvePermissionMode(
|
||||
defaultMode?: unknown,
|
||||
logger: PermissionModeLogger = console,
|
||||
allowBypass: boolean = ALLOW_BYPASS,
|
||||
): PermissionMode {
|
||||
if (defaultMode === undefined) {
|
||||
return "default";
|
||||
}
|
||||
|
||||
if (typeof defaultMode !== "string") {
|
||||
logger.error("Ignoring permissions.defaultMode from settings: expected a string.");
|
||||
return "default";
|
||||
}
|
||||
|
||||
const normalized = defaultMode.trim().toLowerCase();
|
||||
if (normalized === "") {
|
||||
logger.error("Ignoring permissions.defaultMode from settings: expected a non-empty string.");
|
||||
return "default";
|
||||
}
|
||||
|
||||
const mapped = PERMISSION_MODE_ALIASES[normalized];
|
||||
if (!mapped) {
|
||||
logger.error(`Ignoring permissions.defaultMode from settings: unknown value '${defaultMode}'.`);
|
||||
return "default";
|
||||
}
|
||||
|
||||
if (mapped === "bypassPermissions" && !allowBypass) {
|
||||
logger.error("Ignoring permission mode bypassPermissions: not available in this session.");
|
||||
return "default";
|
||||
}
|
||||
|
||||
return mapped;
|
||||
}
|
||||
|
||||
/** Claude Code reads `disableAutoMode` both at the top level and under `permissions`. */
|
||||
export function autoModeDisabled(settings: Settings): boolean {
|
||||
return (
|
||||
settings.disableAutoMode === "disable" || settings.permissions?.disableAutoMode === "disable"
|
||||
);
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import type {
|
||||
PermissionBehavior,
|
||||
PermissionMode,
|
||||
PermissionUpdate,
|
||||
PermissionUpdateDestination,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
export interface DurablePermissionChangeSet {
|
||||
updates: PermissionUpdate[];
|
||||
}
|
||||
|
||||
const MAX_UPDATES = 100;
|
||||
const MAX_RULES_PER_UPDATE = 100;
|
||||
const MAX_DIRECTORIES_PER_UPDATE = 100;
|
||||
const MAX_TOOL_NAME_LENGTH = 512;
|
||||
const MAX_RULE_CONTENT_LENGTH = 10_000;
|
||||
const MAX_DIRECTORY_LENGTH = 4_096;
|
||||
|
||||
const DESTINATIONS = new Set<PermissionUpdateDestination>([
|
||||
"session",
|
||||
"cliArg",
|
||||
"userSettings",
|
||||
"projectSettings",
|
||||
"localSettings",
|
||||
]);
|
||||
const BEHAVIORS = new Set<PermissionBehavior>(["allow", "deny", "ask"]);
|
||||
const MODES = new Set<PermissionMode>([
|
||||
"default",
|
||||
"acceptEdits",
|
||||
"bypassPermissions",
|
||||
"plan",
|
||||
"dontAsk",
|
||||
"auto",
|
||||
]);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isDestination(value: unknown): value is PermissionUpdateDestination {
|
||||
return typeof value === "string" && DESTINATIONS.has(value as PermissionUpdateDestination);
|
||||
}
|
||||
|
||||
function safePlainString(value: unknown, maxLength: number): value is string {
|
||||
if (typeof value !== "string") return false;
|
||||
const normalized = value.trim();
|
||||
return (
|
||||
normalized.length > 0 &&
|
||||
value.length <= maxLength &&
|
||||
!Array.from(normalized).some((character) => {
|
||||
const code = character.charCodeAt(0);
|
||||
return (
|
||||
code <= 0x08 ||
|
||||
code === 0x0b ||
|
||||
code === 0x0c ||
|
||||
(code >= 0x0e && code <= 0x1f) ||
|
||||
code === 0x7f
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function isRule(value: unknown): value is { toolName: string; ruleContent?: string } {
|
||||
if (!isRecord(value) || !safePlainString(value.toolName, MAX_TOOL_NAME_LENGTH)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
value.ruleContent === undefined || safePlainString(value.ruleContent, MAX_RULE_CONTENT_LENGTH)
|
||||
);
|
||||
}
|
||||
|
||||
function isKnownUpdate(value: unknown): value is PermissionUpdate {
|
||||
if (!isRecord(value) || !isDestination(value.destination) || typeof value.type !== "string") {
|
||||
return false;
|
||||
}
|
||||
switch (value.type) {
|
||||
case "addRules":
|
||||
case "replaceRules":
|
||||
case "removeRules":
|
||||
return (
|
||||
Array.isArray(value.rules) &&
|
||||
value.rules.length <= MAX_RULES_PER_UPDATE &&
|
||||
(value.type === "replaceRules" || value.rules.length > 0) &&
|
||||
value.rules.every(isRule) &&
|
||||
typeof value.behavior === "string" &&
|
||||
BEHAVIORS.has(value.behavior as PermissionBehavior)
|
||||
);
|
||||
case "setMode":
|
||||
return typeof value.mode === "string" && MODES.has(value.mode as PermissionMode);
|
||||
case "addDirectories":
|
||||
case "removeDirectories":
|
||||
return (
|
||||
Array.isArray(value.directories) &&
|
||||
value.directories.length > 0 &&
|
||||
value.directories.length <= MAX_DIRECTORIES_PER_UPDATE &&
|
||||
value.directories.every((directory) => safePlainString(directory, MAX_DIRECTORY_LENGTH))
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeDurablePermissionChangeSet(
|
||||
suggestions: unknown,
|
||||
forcedAsk = false,
|
||||
): DurablePermissionChangeSet | undefined {
|
||||
if (forcedAsk) return undefined;
|
||||
try {
|
||||
if (
|
||||
!Array.isArray(suggestions) ||
|
||||
suggestions.length === 0 ||
|
||||
suggestions.length > MAX_UPDATES ||
|
||||
!suggestions.every(isKnownUpdate)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
// The ACP prompt may stay open for an arbitrary amount of time. Snapshot the
|
||||
// provider payload so the label the user approved and the effect returned to
|
||||
// Claude cannot diverge through later mutation of the callback argument.
|
||||
updates: structuredClone(suggestions as PermissionUpdate[]),
|
||||
};
|
||||
} catch {
|
||||
// SDK data is expected to be plain structured-cloneable input. Treat an
|
||||
// accessor, function, proxy, or other non-wire value as an invalid bundle.
|
||||
// Validation belongs in this boundary too because merely reading one of those
|
||||
// values can throw before structuredClone gets a chance to reject it.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
buildEditPermissionOptions,
|
||||
buildGlobPermissionOptions,
|
||||
buildGrepPermissionOptions,
|
||||
buildNotebookEditPermissionOptions,
|
||||
buildReadPermissionOptions,
|
||||
buildWritePermissionOptions,
|
||||
} from "./options/filesystem.js";
|
||||
import { buildBashPermissionOptions, buildPowerShellPermissionOptions } from "./options/shell.js";
|
||||
import type { PermissionOptionContext } from "./options/shared.js";
|
||||
import {
|
||||
buildComputerUseMcpPermissionOptions,
|
||||
buildEnterPlanModePermissionOptions,
|
||||
buildExitPlanModePermissionOptions,
|
||||
buildFallbackPermissionOptions,
|
||||
buildSandboxNetworkPermissionOptions,
|
||||
buildSkillPermissionOptions,
|
||||
buildWebFetchPermissionOptions,
|
||||
isComputerUseMcpTool,
|
||||
} from "./options/tools.js";
|
||||
|
||||
export { PERMISSION_OPTION_ID } from "./options/shared.js";
|
||||
|
||||
export function buildClaudePermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
// ACP has no "pre-selected option" field, so option order is the only lever
|
||||
// for the CLI's `defaultToNo` hint ("open on the decline option"): lead with
|
||||
// the reject options instead of the approvals.
|
||||
const order = context.defaultToNo === true ? declineFirstOptionOrder : permissionOptionOrder;
|
||||
return buildUnsortedClaudePermissionOptions(context).sort(
|
||||
(left, right) => order(left) - order(right),
|
||||
);
|
||||
}
|
||||
|
||||
function buildUnsortedClaudePermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
if (isComputerUseMcpTool(context.toolName)) {
|
||||
return buildComputerUseMcpPermissionOptions(context);
|
||||
}
|
||||
switch (context.toolName) {
|
||||
case "AskUserQuestion":
|
||||
throw new Error("AskUserQuestion must be handled by ACP elicitation, not permission options");
|
||||
case "Bash":
|
||||
return buildBashPermissionOptions(context);
|
||||
case "PowerShell":
|
||||
return buildPowerShellPermissionOptions(context);
|
||||
case "Read":
|
||||
return buildReadPermissionOptions(context);
|
||||
case "Glob":
|
||||
return buildGlobPermissionOptions(context);
|
||||
case "Grep":
|
||||
return buildGrepPermissionOptions(context);
|
||||
case "Edit":
|
||||
return buildEditPermissionOptions(context);
|
||||
case "Write":
|
||||
return buildWritePermissionOptions(context);
|
||||
case "NotebookEdit":
|
||||
return buildNotebookEditPermissionOptions(context);
|
||||
case "WebFetch":
|
||||
return buildWebFetchPermissionOptions(context);
|
||||
case "Skill":
|
||||
return buildSkillPermissionOptions(context);
|
||||
case "EnterPlanMode":
|
||||
return buildEnterPlanModePermissionOptions();
|
||||
case "ExitPlanMode":
|
||||
return buildExitPlanModePermissionOptions(context);
|
||||
case "SandboxNetworkAccess":
|
||||
return buildSandboxNetworkPermissionOptions(context);
|
||||
case "WebSearch":
|
||||
case "Agent":
|
||||
case "Task":
|
||||
default:
|
||||
return buildFallbackPermissionOptions(context);
|
||||
}
|
||||
}
|
||||
|
||||
function declineFirstOptionOrder(option: PermissionOption): number {
|
||||
switch (option.kind) {
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
return 0;
|
||||
default:
|
||||
return 1 + permissionOptionOrder(option);
|
||||
}
|
||||
}
|
||||
|
||||
function permissionOptionOrder(option: PermissionOption): number {
|
||||
switch (option.kind) {
|
||||
case "allow_once":
|
||||
return 0;
|
||||
case "allow_always":
|
||||
return 1;
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
return 3;
|
||||
default:
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { DurablePermissionChangeSet } from "../normalization.js";
|
||||
import { plainString, type PermissionOptionContext, withOptionalUpdate } from "./shared.js";
|
||||
|
||||
function isFileSessionChangeSet(
|
||||
changeSet: DurablePermissionChangeSet | undefined,
|
||||
operation: "read" | "write",
|
||||
): boolean {
|
||||
return (
|
||||
!!changeSet &&
|
||||
changeSet.updates.every((update) => {
|
||||
if (update.destination !== "session") return false;
|
||||
if (update.type === "setMode") {
|
||||
return operation === "write" && update.mode === "acceptEdits";
|
||||
}
|
||||
if (update.type === "addDirectories") return operation === "write";
|
||||
if (update.type !== "addRules" || update.behavior !== "allow") return false;
|
||||
return update.rules.every((rule) =>
|
||||
operation === "read" ? rule.toolName === "Read" : rule.toolName === "Edit",
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function inputPath(context: PermissionOptionContext, key: string): string | undefined {
|
||||
return plainString(context.input[key]);
|
||||
}
|
||||
|
||||
function isInside(directory: string, candidate: string): boolean {
|
||||
const relative = path.relative(path.resolve(directory), path.resolve(candidate));
|
||||
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== "..");
|
||||
}
|
||||
|
||||
function hasSessionAllowRuleFor(
|
||||
changeSet: DurablePermissionChangeSet | undefined,
|
||||
toolName: string,
|
||||
): boolean {
|
||||
return !!changeSet?.updates.some(
|
||||
(update) =>
|
||||
update.type === "addRules" &&
|
||||
update.destination === "session" &&
|
||||
update.behavior === "allow" &&
|
||||
update.rules.some((rule) => rule.toolName === toolName),
|
||||
);
|
||||
}
|
||||
|
||||
function hasBroadSessionAllowRuleFor(
|
||||
changeSet: DurablePermissionChangeSet,
|
||||
toolName: string,
|
||||
): boolean {
|
||||
return changeSet.updates.some(
|
||||
(update) =>
|
||||
update.type === "addRules" &&
|
||||
update.destination === "session" &&
|
||||
update.behavior === "allow" &&
|
||||
update.rules.some((rule) => rule.toolName === toolName && rule.ruleContent === undefined),
|
||||
);
|
||||
}
|
||||
|
||||
function hasAcceptEditsMode(changeSet: DurablePermissionChangeSet): boolean {
|
||||
return changeSet.updates.some(
|
||||
(update) =>
|
||||
update.type === "setMode" &&
|
||||
update.destination === "session" &&
|
||||
update.mode === "acceptEdits",
|
||||
);
|
||||
}
|
||||
|
||||
function permissionPath(ruleContent: string | undefined): string | undefined {
|
||||
const value = plainString(ruleContent);
|
||||
if (!value) return undefined;
|
||||
return value.replace(/[/\\]\*\*$/, "");
|
||||
}
|
||||
|
||||
function effectCoversFilePath(
|
||||
changeSet: DurablePermissionChangeSet,
|
||||
filePath: string,
|
||||
operation: "read" | "write",
|
||||
cwd: string,
|
||||
): boolean {
|
||||
const directory = path.dirname(filePath);
|
||||
const comparable = (candidate: string): boolean => {
|
||||
const resolved = path.resolve(cwd, candidate);
|
||||
return resolved === directory || isInside(resolved, filePath);
|
||||
};
|
||||
const paths = changeSet.updates.flatMap((update) => {
|
||||
if (update.type === "addDirectories") return update.directories;
|
||||
if (update.type !== "addRules" || update.behavior !== "allow") return [];
|
||||
return update.rules
|
||||
.filter((rule) =>
|
||||
operation === "read" ? rule.toolName === "Read" : rule.toolName === "Edit",
|
||||
)
|
||||
.map((rule) => permissionPath(rule.ruleContent))
|
||||
.filter((value): value is string => value !== undefined);
|
||||
});
|
||||
return paths.some(comparable);
|
||||
}
|
||||
|
||||
function fileSessionLabel(
|
||||
context: PermissionOptionContext,
|
||||
filePath: string | undefined,
|
||||
operation: "read" | "write",
|
||||
): string | undefined {
|
||||
if (!isFileSessionChangeSet(context.durableChangeSet, operation)) return undefined;
|
||||
const resolvedFilePath = filePath ? path.resolve(context.cwd, filePath) : undefined;
|
||||
const isClaudePath =
|
||||
operation === "write" &&
|
||||
!!resolvedFilePath &&
|
||||
(isInside(path.join(context.cwd, ".claude"), resolvedFilePath) ||
|
||||
isInside(path.join(os.homedir(), ".claude"), resolvedFilePath));
|
||||
const broadRule = hasBroadSessionAllowRuleFor(
|
||||
context.durableChangeSet!,
|
||||
operation === "read" ? "Read" : "Edit",
|
||||
);
|
||||
if (resolvedFilePath) {
|
||||
const coversCurrentPath =
|
||||
effectCoversFilePath(context.durableChangeSet!, resolvedFilePath, operation, context.cwd) ||
|
||||
broadRule ||
|
||||
(operation === "write" && !isClaudePath && hasAcceptEditsMode(context.durableChangeSet!));
|
||||
if (!coversCurrentPath) return undefined;
|
||||
} else if (
|
||||
!broadRule &&
|
||||
!(operation === "write" && hasAcceptEditsMode(context.durableChangeSet!))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
operation === "write" &&
|
||||
resolvedFilePath &&
|
||||
isClaudePath &&
|
||||
hasSessionAllowRuleFor(context.durableChangeSet, "Edit")
|
||||
) {
|
||||
return "Yes, and allow Claude to edit its own settings for this session";
|
||||
}
|
||||
if (!resolvedFilePath || isInside(context.cwd, resolvedFilePath)) {
|
||||
return operation === "read"
|
||||
? "Yes, during this session"
|
||||
: "Yes, allow all edits during this session";
|
||||
}
|
||||
const directory = path.dirname(resolvedFilePath);
|
||||
const directoryName = path.basename(directory) || "this directory";
|
||||
return operation === "read"
|
||||
? `Yes, allow reading from ${directoryName}${path.sep} during this session`
|
||||
: `Yes, allow all edits in ${directoryName}${path.sep} during this session`;
|
||||
}
|
||||
|
||||
function buildFilePermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
filePath: string | undefined,
|
||||
operation: "read" | "write",
|
||||
): PermissionOption[] {
|
||||
return withOptionalUpdate(
|
||||
context.durableChangeSet,
|
||||
fileSessionLabel(context, filePath, operation),
|
||||
"Yes",
|
||||
"No",
|
||||
);
|
||||
}
|
||||
|
||||
export function buildReadPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "file_path"), "read");
|
||||
}
|
||||
|
||||
export function buildGlobPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "path") ?? context.cwd, "read");
|
||||
}
|
||||
|
||||
export function buildGrepPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "path") ?? context.cwd, "read");
|
||||
}
|
||||
|
||||
export function buildEditPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "file_path"), "write");
|
||||
}
|
||||
|
||||
export function buildWritePermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "file_path"), "write");
|
||||
}
|
||||
|
||||
export function buildNotebookEditPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
return buildFilePermissionOptions(context, inputPath(context, "notebook_path"), "write");
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { DurablePermissionChangeSet } from "../normalization.js";
|
||||
|
||||
export const PERMISSION_OPTION_ID = {
|
||||
allowOnce: "allow-once",
|
||||
allowWithUpdates: "allow-with-updates",
|
||||
allowSkillExact: "allow-skill-exact",
|
||||
allowSkillPrefix: "allow-skill-prefix",
|
||||
exitPlanBypass: "exit-plan-bypass",
|
||||
exitPlanAuto: "exit-plan-auto",
|
||||
exitPlanAcceptEdits: "exit-plan-accept-edits",
|
||||
exitPlanDefault: "exit-plan-default",
|
||||
exitPlanClearAuto: "exit-plan-clear-auto",
|
||||
exitPlanClearBypass: "exit-plan-clear-bypass",
|
||||
exitPlanClearAcceptEdits: "exit-plan-clear-accept-edits",
|
||||
reject: "reject",
|
||||
} as const;
|
||||
|
||||
export interface PermissionOptionContext {
|
||||
toolName: string;
|
||||
displayName?: string;
|
||||
input: Record<string, unknown>;
|
||||
cwd: string;
|
||||
durableChangeSet?: DurablePermissionChangeSet;
|
||||
allowPersistentOptions?: boolean;
|
||||
/** The CLI's `defaultToNo` hint (SDK 0.3.268+): the ask must not be
|
||||
* approvable by a stray keystroke, so the decline option leads. */
|
||||
defaultToNo?: boolean;
|
||||
availableModes?: readonly string[];
|
||||
/** The mode the session left when it entered plan mode. */
|
||||
prePlanMode?: string;
|
||||
contextUsedPercent?: number;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
export function allowOnce(name = "Yes"): PermissionOption {
|
||||
return { optionId: PERMISSION_OPTION_ID.allowOnce, name, kind: "allow_once" };
|
||||
}
|
||||
|
||||
export function allowWithUpdates(name: string): PermissionOption {
|
||||
return { optionId: PERMISSION_OPTION_ID.allowWithUpdates, name, kind: "allow_always" };
|
||||
}
|
||||
|
||||
export function reject(name = "No"): PermissionOption {
|
||||
return { optionId: PERMISSION_OPTION_ID.reject, name, kind: "reject_once" };
|
||||
}
|
||||
|
||||
export function withOptionalUpdate(
|
||||
changeSet: DurablePermissionChangeSet | undefined,
|
||||
updateName: string | undefined,
|
||||
allowName = "Yes",
|
||||
rejectName = "No",
|
||||
): PermissionOption[] {
|
||||
const options = [allowOnce(allowName)];
|
||||
if (changeSet && updateName) options.push(allowWithUpdates(updateName));
|
||||
options.push(reject(rejectName));
|
||||
return options;
|
||||
}
|
||||
|
||||
export function plainString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
export function exactLocalAllowRule(
|
||||
changeSet: DurablePermissionChangeSet | undefined,
|
||||
toolName: string,
|
||||
ruleContent?: string,
|
||||
): boolean {
|
||||
if (!changeSet || changeSet.updates.length !== 1) return false;
|
||||
const update = changeSet.updates[0];
|
||||
if (
|
||||
update?.type !== "addRules" ||
|
||||
update.behavior !== "allow" ||
|
||||
update.destination !== "localSettings" ||
|
||||
update.rules.length !== 1
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const rule = update.rules[0];
|
||||
return (
|
||||
rule?.toolName === toolName &&
|
||||
(ruleContent === undefined
|
||||
? rule.ruleContent === undefined
|
||||
: plainString(rule.ruleContent) === ruleContent)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* An MCP "don't ask again" option is only truthful when every provider update
|
||||
* adds an unrestricted allow rule for the tool currently being prompted.
|
||||
*/
|
||||
export function isMcpAllowChangeSet(
|
||||
changeSet: DurablePermissionChangeSet | undefined,
|
||||
toolName: string,
|
||||
): boolean {
|
||||
return (
|
||||
!!changeSet &&
|
||||
changeSet.updates.length > 0 &&
|
||||
changeSet.updates.every(
|
||||
(update) =>
|
||||
update.type === "addRules" &&
|
||||
update.behavior === "allow" &&
|
||||
update.rules.length > 0 &&
|
||||
update.rules.every((rule) => rule.toolName === toolName && rule.ruleContent === undefined),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function withGeneratedUpdate(name: string, rejectName = "No"): PermissionOption[] {
|
||||
return [allowOnce(), allowWithUpdates(name), reject(rejectName)];
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import path from "node:path";
|
||||
import type { DurablePermissionChangeSet } from "../normalization.js";
|
||||
import { plainString, type PermissionOptionContext, withOptionalUpdate } from "./shared.js";
|
||||
|
||||
function permissionRulePrefix(value: string): string {
|
||||
return value.endsWith(":*") ? value.slice(0, -2) : value;
|
||||
}
|
||||
|
||||
function displayList(values: string[]): string {
|
||||
if (values.join(", ").length > 50) return "similar";
|
||||
if (values.length === 1) return values[0]!;
|
||||
if (values.length === 2) return `${values[0]} and ${values[1]}`;
|
||||
return `${values.slice(0, -1).join(", ")}, and ${values.at(-1)}`;
|
||||
}
|
||||
|
||||
/** Shorten paths only as much as needed to distinguish them in prompt text. */
|
||||
function displayPaths(paths: string[]): string {
|
||||
const normalizedPaths = [...new Set(paths.map((value) => path.normalize(value)))];
|
||||
const segments = normalizedPaths.map((value) => value.split(path.sep).filter(Boolean));
|
||||
|
||||
// Compare equally deep suffixes so duplicate basenames gain the smallest
|
||||
// useful parent prefix (for example, codex-acp/src/ vs claude-acp/src/).
|
||||
const suffix = (index: number, depth: number): string =>
|
||||
segments[index]!.slice(-depth).join(path.sep) || normalizedPaths[index]!;
|
||||
const names = normalizedPaths.map((value, index) => {
|
||||
const parts = segments[index]!;
|
||||
let name = path.basename(value) || value;
|
||||
for (let depth = 1; depth <= parts.length; depth++) {
|
||||
const candidate = suffix(index, depth);
|
||||
if (
|
||||
normalizedPaths.every((_, other) => other === index || suffix(other, depth) !== candidate)
|
||||
) {
|
||||
name = candidate;
|
||||
break;
|
||||
}
|
||||
if (depth === parts.length) name = value;
|
||||
}
|
||||
return name.endsWith(path.sep) ? name : `${name}${path.sep}`;
|
||||
});
|
||||
|
||||
// Native Claude labels enumerate two paths and summarize larger sets.
|
||||
if (names.length <= 2) return displayList(names);
|
||||
return `${names[0]}, ${names[1]} and ${names.length - 2} more`;
|
||||
}
|
||||
|
||||
/** Plain-text port of Claude Code's generateShellSuggestionsLabel. */
|
||||
function shellSuggestionsLabel(
|
||||
toolName: "Bash" | "PowerShell",
|
||||
changeSet: DurablePermissionChangeSet,
|
||||
): string | undefined {
|
||||
const representable = changeSet.updates.every((update) => {
|
||||
if (update.type === "addDirectories") return update.destination === "session";
|
||||
if (update.type !== "addRules" || update.behavior !== "allow") return false;
|
||||
return update.rules.every(
|
||||
(rule) =>
|
||||
(rule.toolName === toolName || rule.toolName === "Read") &&
|
||||
plainString(rule.ruleContent) !== undefined,
|
||||
);
|
||||
});
|
||||
if (!representable) return undefined;
|
||||
|
||||
const rules = changeSet.updates
|
||||
.filter((update) => update.type === "addRules")
|
||||
.flatMap((update) => update.rules);
|
||||
const readPaths = rules
|
||||
.filter((rule) => rule.toolName === "Read")
|
||||
.map((rule) => rule.ruleContent?.replace(/\/\*\*$/, ""))
|
||||
.filter((value): value is string => !!value);
|
||||
const commands = [
|
||||
...new Set(
|
||||
rules
|
||||
.filter((rule) => rule.toolName === toolName && rule.ruleContent)
|
||||
.map((rule) => permissionRulePrefix(rule.ruleContent!)),
|
||||
),
|
||||
];
|
||||
const directories = changeSet.updates
|
||||
.filter((update) => update.type === "addDirectories")
|
||||
.flatMap((update) => update.directories);
|
||||
const hasPaths = readPaths.length > 0 || directories.length > 0;
|
||||
|
||||
if (readPaths.length > 0 && directories.length === 0 && commands.length === 0) {
|
||||
return `Yes, allow reading from ${displayPaths(readPaths)} from this project`;
|
||||
}
|
||||
if (directories.length > 0 && readPaths.length === 0 && commands.length === 0) {
|
||||
return `Yes, and always allow access to ${displayPaths(directories)} from this project`;
|
||||
}
|
||||
if (commands.length > 0 && !hasPaths) {
|
||||
return `Yes, and don't ask again for ${displayList(commands)} commands`;
|
||||
}
|
||||
if (hasPaths && commands.length === 0) {
|
||||
return `Yes, and always allow access to ${displayPaths([...directories, ...readPaths])} from this project`;
|
||||
}
|
||||
if (hasPaths && commands.length > 0) {
|
||||
const paths = [...directories, ...readPaths];
|
||||
return paths.length === 1 && commands.length === 1
|
||||
? `Yes, and allow access to ${displayPaths(paths)} and ${displayList(commands)} commands`
|
||||
: `Yes, and allow ${displayPaths(paths)} access and ${displayList(commands)} commands`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildShellPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
toolName: "Bash" | "PowerShell",
|
||||
): PermissionOption[] {
|
||||
const name = context.durableChangeSet
|
||||
? shellSuggestionsLabel(toolName, context.durableChangeSet)
|
||||
: undefined;
|
||||
return withOptionalUpdate(context.durableChangeSet, name, "Yes", "No");
|
||||
}
|
||||
|
||||
export function buildBashPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
return buildShellPermissionOptions(context, "Bash");
|
||||
}
|
||||
|
||||
export function buildPowerShellPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
return buildShellPermissionOptions(context, "PowerShell");
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
allowOnce,
|
||||
exactLocalAllowRule,
|
||||
isMcpAllowChangeSet,
|
||||
PERMISSION_OPTION_ID,
|
||||
plainString,
|
||||
type PermissionOptionContext,
|
||||
reject,
|
||||
withGeneratedUpdate,
|
||||
withOptionalUpdate,
|
||||
} from "./shared.js";
|
||||
|
||||
export function buildWebFetchPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
const url = plainString(context.input.url);
|
||||
if (url && context.allowPersistentOptions !== false) {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
if (hostname) {
|
||||
return withGeneratedUpdate(`Yes, and don't ask again for ${hostname}`);
|
||||
}
|
||||
} catch {
|
||||
// Invalid input cannot produce Claude Code's domain-specific option.
|
||||
}
|
||||
}
|
||||
return [allowOnce(), reject("No")];
|
||||
}
|
||||
|
||||
export function buildSkillPermissionOptions(context: PermissionOptionContext): PermissionOption[] {
|
||||
const skill = plainString(context.input.skill);
|
||||
const options = [allowOnce()];
|
||||
if (skill && context.allowPersistentOptions !== false) {
|
||||
options.push({
|
||||
optionId: PERMISSION_OPTION_ID.allowSkillExact,
|
||||
name: `Yes, and don't ask again for ${skill}`,
|
||||
kind: "allow_always",
|
||||
});
|
||||
const spaceIndex = skill.indexOf(" ");
|
||||
if (spaceIndex > 0) {
|
||||
const prefix = `${skill.slice(0, spaceIndex)}:*`;
|
||||
options.push({
|
||||
optionId: PERMISSION_OPTION_ID.allowSkillPrefix,
|
||||
name: `Yes, and don't ask again for ${prefix} commands`,
|
||||
kind: "allow_always",
|
||||
});
|
||||
}
|
||||
}
|
||||
options.push(reject("No"));
|
||||
return options;
|
||||
}
|
||||
|
||||
export function buildEnterPlanModePermissionOptions(): PermissionOption[] {
|
||||
return [allowOnce("Yes, enter plan mode"), reject("No, start implementing now")];
|
||||
}
|
||||
|
||||
export function buildExitPlanModePermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
const modes = new Set(context.availableModes);
|
||||
const options: PermissionOption[] = [];
|
||||
// Claude Code offers bypass only when the user launched with it, so it can
|
||||
// prefer bypass outright. The adapter advertises bypass by default, so Auto
|
||||
// leads unless the session was in bypass before entering plan mode. Both stay
|
||||
// selectable: they have different permission semantics.
|
||||
const elevatedModes = (
|
||||
context.prePlanMode === "bypassPermissions"
|
||||
? (["bypassPermissions", "auto"] as const)
|
||||
: (["auto", "bypassPermissions"] as const)
|
||||
).filter((mode) => modes.has(mode));
|
||||
const preferredMode = elevatedModes[0] ?? "acceptEdits";
|
||||
if (context.allowContextReset !== false && plainString(context.input.plan)) {
|
||||
const usage =
|
||||
context.contextUsedPercent === undefined ? "" : ` (${context.contextUsedPercent}% used)`;
|
||||
options.push(
|
||||
preferredMode === "auto"
|
||||
? {
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanClearAuto,
|
||||
name: `Yes, clear context${usage} and use auto mode`,
|
||||
kind: "allow_always",
|
||||
}
|
||||
: preferredMode === "bypassPermissions"
|
||||
? {
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanClearBypass,
|
||||
name: `Yes, clear context${usage} and bypass permissions`,
|
||||
kind: "allow_always",
|
||||
}
|
||||
: {
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanClearAcceptEdits,
|
||||
name: `Yes, clear context${usage} and auto-accept edits`,
|
||||
kind: "allow_always",
|
||||
},
|
||||
);
|
||||
}
|
||||
for (const mode of elevatedModes) {
|
||||
options.push(
|
||||
mode === "auto"
|
||||
? {
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanAuto,
|
||||
name: "Yes, and use auto mode",
|
||||
kind: "allow_always",
|
||||
}
|
||||
: {
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanBypass,
|
||||
name: "Yes, and bypass permissions",
|
||||
kind: "allow_always",
|
||||
},
|
||||
);
|
||||
}
|
||||
if (elevatedModes.length === 0) {
|
||||
options.push({
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanAcceptEdits,
|
||||
name: "Yes, auto-accept edits",
|
||||
kind: "allow_always",
|
||||
});
|
||||
}
|
||||
options.push({
|
||||
optionId: PERMISSION_OPTION_ID.exitPlanDefault,
|
||||
name: "Yes, manually approve edits",
|
||||
kind: "allow_once",
|
||||
});
|
||||
options.push(reject("No, keep planning"));
|
||||
return options;
|
||||
}
|
||||
|
||||
export function buildSandboxNetworkPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
const host = plainString(context.input.host);
|
||||
const name =
|
||||
host && exactLocalAllowRule(context.durableChangeSet, context.toolName, host)
|
||||
? `Yes, and don't ask again for ${host}`
|
||||
: undefined;
|
||||
return withOptionalUpdate(context.durableChangeSet, name, "Yes", "No");
|
||||
}
|
||||
|
||||
export function buildFallbackPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
const toolLabel = plainString(context.displayName) ?? context.toolName;
|
||||
if (context.toolName.startsWith("mcp__")) {
|
||||
const changeSet =
|
||||
context.allowPersistentOptions !== false &&
|
||||
isMcpAllowChangeSet(context.durableChangeSet, context.toolName)
|
||||
? context.durableChangeSet
|
||||
: undefined;
|
||||
return withOptionalUpdate(
|
||||
changeSet,
|
||||
changeSet ? `Yes, and don't ask again for ${toolLabel} commands` : undefined,
|
||||
);
|
||||
}
|
||||
if (context.allowPersistentOptions !== false) {
|
||||
return withGeneratedUpdate(`Yes, and don't ask again for ${toolLabel} commands`);
|
||||
}
|
||||
return [allowOnce(), reject("No")];
|
||||
}
|
||||
|
||||
const COMPUTER_USE_MCP_TOOL_PREFIX = "mcp__computer-use__";
|
||||
|
||||
export function isComputerUseMcpTool(toolName: string): boolean {
|
||||
return toolName.startsWith(COMPUTER_USE_MCP_TOOL_PREFIX);
|
||||
}
|
||||
|
||||
export function buildComputerUseMcpPermissionOptions(
|
||||
context: PermissionOptionContext,
|
||||
): PermissionOption[] {
|
||||
const toolLabel = plainString(context.displayName) ?? context.toolName;
|
||||
const changeSet =
|
||||
context.allowPersistentOptions !== false &&
|
||||
isMcpAllowChangeSet(context.durableChangeSet, context.toolName)
|
||||
? context.durableChangeSet
|
||||
: undefined;
|
||||
return withOptionalUpdate(
|
||||
changeSet,
|
||||
changeSet ? `Yes, and don't ask again for ${toolLabel}` : undefined,
|
||||
);
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import type { RequestPermissionRequest, ToolCallContent } from "@agentclientprotocol/sdk/unstable";
|
||||
import { AIR_PERMISSION_KEY, withAirMeta } from "../air-extension.js";
|
||||
import { ClientCapabilities } from "../tool-calls/client-capabilities.js";
|
||||
import { AcpToolCallRenderer } from "../tool-calls/renderer.js";
|
||||
|
||||
/**
|
||||
* A permission request as the agent builds it. For a v2 client it also
|
||||
* carries the heading and the explanation of the prompt, which ACP v2 sends as
|
||||
* the request's `title` and `description`. v1 has no field for them; AIR gets
|
||||
* them in `_meta`.
|
||||
*/
|
||||
export type AcpPermissionRequest = RequestPermissionRequest & {
|
||||
/** The heading of the prompt. It is not the title of the tool call. */
|
||||
title?: string;
|
||||
/** Why the permission is asked. */
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export interface ClaudePermissionPresentationInput {
|
||||
toolName: string;
|
||||
input: Record<string, unknown>;
|
||||
toolUseID: string;
|
||||
cwd?: string;
|
||||
capabilities?: ClientCapabilities;
|
||||
/** The exact patch of the change to approve, for a negotiated `diffPatch` client or a v2 client. */
|
||||
previewContent?: ToolCallContent[];
|
||||
blockedPath?: string;
|
||||
title?: string;
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
decisionReason?: string;
|
||||
defaultToNo?: boolean;
|
||||
}
|
||||
|
||||
function humanText(value: unknown, maxLength: number, singleLine = false): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const withoutControls = Array.from(value)
|
||||
.filter((character) => {
|
||||
const code = character.charCodeAt(0);
|
||||
return !(
|
||||
code <= 0x08 ||
|
||||
code === 0x0b ||
|
||||
code === 0x0c ||
|
||||
(code >= 0x0e && code <= 0x1f) ||
|
||||
code === 0x7f
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
const normalized = singleLine
|
||||
? withoutControls.replace(/\s+/gu, " ").trim()
|
||||
: withoutControls.trim();
|
||||
return normalized && normalized.length <= maxLength ? normalized : undefined;
|
||||
}
|
||||
|
||||
function compactText(value: unknown): string | undefined {
|
||||
return humanText(value, 160, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The permission request presentation.
|
||||
*
|
||||
* The request `toolCall` carries `toolCallId`, `title`, and `rawInput`. The
|
||||
* adapter emits the `tool_call` before the request, so the client already
|
||||
* holds the rest. The request adds only what it shows new: the exact preview
|
||||
* patch, and the blocked path when the tool call has no such location.
|
||||
*
|
||||
* The heading and the explanation of the prompt go to AIR in `_meta`, and to a
|
||||
* v2 client as `title` and `description`.
|
||||
*/
|
||||
export function buildClaudePermissionPresentation(
|
||||
value: ClaudePermissionPresentationInput,
|
||||
): Pick<AcpPermissionRequest, "toolCall" | "_meta" | "title" | "description"> {
|
||||
const capabilities = value.capabilities ?? new ClientCapabilities();
|
||||
const renderer = new AcpToolCallRenderer(capabilities);
|
||||
const toolUse = { id: value.toolUseID, name: value.toolName, input: value.input };
|
||||
const facts = renderer.facts(toolUse, value.cwd);
|
||||
const host =
|
||||
value.toolName === "SandboxNetworkAccess" ? compactText(value.input.host) : undefined;
|
||||
const isComputerUse = value.toolName.startsWith("mcp__computer-use__");
|
||||
const subjectTitle = host ?? (isComputerUse ? compactText(value.displayName) : undefined);
|
||||
// Reuse the exact standard tool-call heading as the permission heading so
|
||||
// the approval never maintains a second, divergent name for the operation.
|
||||
// decisionReason is temporarily exposed as the permission description so
|
||||
// its actual SDK values can be inspected; it remains diagnostic policy text.
|
||||
const toolCallTitle = subjectTitle ?? facts.title;
|
||||
const permissionTitle = value.toolName === "ExitPlanMode" ? "Ready to code?" : toolCallTitle;
|
||||
// Shell titles are executable input: compacting whitespace changes quoted
|
||||
// arguments and comment boundaries, and length limits can hide the command.
|
||||
const title =
|
||||
value.toolName === "Bash" || value.toolName === "PowerShell"
|
||||
? permissionTitle
|
||||
: (humanText(permissionTitle, 4_000, true) ?? "Use tool?");
|
||||
const decisionReason = humanText(value.decisionReason, 4_000);
|
||||
const description = decisionReason ? `Reason: ${decisionReason}` : undefined;
|
||||
const blockedPath = humanText(value.blockedPath, 4_096, true);
|
||||
const extraLocations =
|
||||
blockedPath && !(facts.locations ?? []).some((location) => location.path === blockedPath)
|
||||
? [{ path: blockedPath }]
|
||||
: undefined;
|
||||
return {
|
||||
toolCall: renderer.permissionToolCall(toolUse, {
|
||||
cwd: value.cwd,
|
||||
title: toolCallTitle,
|
||||
previewContent: value.previewContent,
|
||||
extraLocations,
|
||||
// The upstream request shows the input of a network or computer-use
|
||||
// request that has no content of its own.
|
||||
fallbackContent:
|
||||
host || isComputerUse
|
||||
? [
|
||||
{
|
||||
type: "content" as const,
|
||||
content: {
|
||||
type: "text" as const,
|
||||
text: `\`\`\`json\n${JSON.stringify(value.input, null, 2)}\n\`\`\``,
|
||||
},
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
}),
|
||||
// Only AIR gets the permission presentation.
|
||||
...(title && capabilities.air.client
|
||||
? { _meta: airPermissionMeta({ title, description, defaultToNo: value.defaultToNo }) }
|
||||
: {}),
|
||||
...(capabilities.v2 ? { title, ...(description ? { description } : {}) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The `_meta.jetbrains.air.permission` of a permission request, from the
|
||||
* heading and explanation that {@link buildClaudePermissionPresentation}
|
||||
* built. The v2 core adds it for an AIR client, whose tool calls it
|
||||
* renders without the AIR tool call contract.
|
||||
*/
|
||||
export function airPermissionMeta({
|
||||
title,
|
||||
description,
|
||||
defaultToNo,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
defaultToNo?: boolean;
|
||||
}): Record<string, unknown> {
|
||||
return withAirMeta(undefined, AIR_PERMISSION_KEY, {
|
||||
version: 1,
|
||||
title,
|
||||
...(description ? { description } : {}),
|
||||
// The CLI's own hint, forwarded so a client that can pre-select an
|
||||
// option keeps the decline focused; the option order already leads with
|
||||
// the reject options when this is set.
|
||||
...(defaultToNo === true ? { defaultToNo: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The `_meta.claudeCode` of a permission request's tool call: which MCP
|
||||
* server serves an `mcp__*` tool and where its definition came from
|
||||
* (`mcpServer`, SDK 0.3.274+), so a client can key trust on `source`, and,
|
||||
* for clients other than AIR, the tool name and the Agent or Task call of a
|
||||
* subagent's request. Undefined when there is nothing to add.
|
||||
*/
|
||||
export function permissionToolCallMeta({
|
||||
toolName,
|
||||
parentToolUseId,
|
||||
mcpServer,
|
||||
airClient,
|
||||
}: {
|
||||
toolName: string;
|
||||
parentToolUseId: string | undefined;
|
||||
mcpServer: { name: string; source: string } | undefined;
|
||||
airClient: boolean;
|
||||
}): { claudeCode: Record<string, unknown> } | undefined {
|
||||
if (!mcpServer && !(parentToolUseId && !airClient)) return undefined;
|
||||
// The name is the config key as authored: untrusted text, so it rides
|
||||
// `_meta` rather than the title.
|
||||
return {
|
||||
claudeCode: {
|
||||
...(airClient ? {} : { toolName }),
|
||||
...(parentToolUseId && !airClient ? { parentToolUseId } : {}),
|
||||
...(mcpServer ? { mcpServer: { name: mcpServer.name, source: mcpServer.source } } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { RequestPermissionResponse } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { PermissionOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { PermissionMode, PermissionResult } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { DurablePermissionChangeSet } from "./normalization.js";
|
||||
import { applyClaudePermissionSelection, parseClaudePermissionSelection } from "./effects.js";
|
||||
|
||||
export interface ClaudePermissionDecision {
|
||||
permissionResult: PermissionResult;
|
||||
contextResetMode?: PermissionMode;
|
||||
}
|
||||
|
||||
/** Decode, validate, and interpret an ACP response exactly once. */
|
||||
export function decodeClaudePermissionResponse(
|
||||
response: RequestPermissionResponse,
|
||||
toolName: string,
|
||||
input: Record<string, unknown>,
|
||||
toolUseID: string,
|
||||
offeredOptions: readonly PermissionOption[],
|
||||
durableChangeSet?: DurablePermissionChangeSet,
|
||||
): ClaudePermissionDecision {
|
||||
const selection = parseClaudePermissionSelection(response, toolName);
|
||||
const offeredOption = offeredOptions.find((option) => option.optionId === selection.optionId);
|
||||
if (!offeredOption) {
|
||||
throw new Error(`Permission option was not offered: ${selection.optionId}`);
|
||||
}
|
||||
const permissionResult = applyClaudePermissionSelection(selection, {
|
||||
toolName,
|
||||
input,
|
||||
toolUseID,
|
||||
durableChangeSet,
|
||||
});
|
||||
return {
|
||||
permissionResult,
|
||||
...(selection.contextResetMode ? { contextResetMode: selection.contextResetMode } : {}),
|
||||
};
|
||||
}
|
||||
110
src/plans.ts
110
src/plans.ts
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import type {
|
||||
PlanEntry,
|
||||
PlanItems,
|
||||
PlanRemoved,
|
||||
SessionNotification,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import { PLAN_MODE_PLAN_ID } from "./exit-plan.js";
|
||||
|
||||
type PlanRemovalUpdate = PlanRemoved & { sessionUpdate: "plan_removed" };
|
||||
|
||||
/** The ID of the session's checklist, from TodoWrite and the Task tools. Every
|
||||
* update replaces it whole. An approved ExitPlanMode plan is a separate plan
|
||||
* ({@link PLAN_MODE_PLAN_ID}), and so is a subagent's TodoWrite checklist in
|
||||
* its parent's session ({@link subagentChecklistPlanId}). */
|
||||
export const CHECKLIST_PLAN_ID = "plan";
|
||||
|
||||
/** The ID of the TodoWrite checklist of the subagent that the tool call
|
||||
* `parentToolUseId` launched, when the checklist goes to its parent's session.
|
||||
* Claude Code keeps a TodoWrite list per agent, so it is a separate plan from
|
||||
* the main conversation's checklist. The Task tools share one task list
|
||||
* between all agents of a session, so their checklist is always
|
||||
* {@link CHECKLIST_PLAN_ID}. */
|
||||
export function subagentChecklistPlanId(parentToolUseId: string): string {
|
||||
return `${CHECKLIST_PLAN_ID}:${parentToolUseId}`;
|
||||
}
|
||||
|
||||
/** The plan operation that shows the checklist `entries` as the plan `planId`:
|
||||
* `plan_update`, or `plan_removed` for an empty checklist. */
|
||||
export function checklistPlanOperation(
|
||||
entries: PlanEntry[],
|
||||
planId: string = CHECKLIST_PLAN_ID,
|
||||
): { sessionUpdate: "plan_update"; plan: PlanItems & { type: "items" } } | PlanRemovalUpdate {
|
||||
if (entries.length === 0) return { sessionUpdate: "plan_removed", planId };
|
||||
return { sessionUpdate: "plan_update", plan: { type: "items", planId, entries } };
|
||||
}
|
||||
|
||||
/** The update that shows the checklist `entries`: a plan operation (see
|
||||
* {@link checklistPlanOperation}), else a legacy `plan`, which with no entries
|
||||
* clears the client's plan. */
|
||||
export function checklistPlanUpdate(
|
||||
entries: PlanEntry[],
|
||||
planOperations: boolean,
|
||||
): SessionNotification["update"] {
|
||||
return planOperations ? checklistPlanOperation(entries) : { sessionUpdate: "plan", entries };
|
||||
}
|
||||
|
||||
/** The plan IDs of the subagent checklists that the client holds in a session
|
||||
* (see {@link subagentChecklistPlanId}). */
|
||||
export type SubagentChecklists = Set<string>;
|
||||
|
||||
/**
|
||||
* The update that shows the TodoWrite checklist `entries` of the agent that
|
||||
* made the call: the main conversation, or the subagent that the tool call
|
||||
* `parentToolUseId` launched.
|
||||
*
|
||||
* A subagent's checklist gets its own plan ID, recorded in `shown` while the
|
||||
* client holds it, when it goes to the parent's session. It does not with
|
||||
* `childSessions` (native subagent sessions), where it goes to the subagent's
|
||||
* own session, which holds no other checklist. A client without plan
|
||||
* operations holds one plan per session, so there a subagent's checklist
|
||||
* replaces the main one.
|
||||
*/
|
||||
export function todoWritePlanUpdate(
|
||||
entries: PlanEntry[],
|
||||
options: {
|
||||
planOperations: boolean;
|
||||
parentToolUseId?: string | null;
|
||||
childSessions: boolean;
|
||||
shown?: SubagentChecklists;
|
||||
},
|
||||
): SessionNotification["update"] {
|
||||
const { planOperations, parentToolUseId, childSessions, shown } = options;
|
||||
if (!planOperations || !parentToolUseId || childSessions) {
|
||||
return checklistPlanUpdate(entries, planOperations);
|
||||
}
|
||||
const planId = subagentChecklistPlanId(parentToolUseId);
|
||||
if (entries.length === 0) shown?.delete(planId);
|
||||
else shown?.add(planId);
|
||||
return checklistPlanOperation(entries, planId);
|
||||
}
|
||||
|
||||
/** The updates that dismiss the plans of a conversation that a reset (`/clear`)
|
||||
* replaced: the checklist, the subagent checklists in `subagentChecklists`
|
||||
* (which it then empties), and the approved ExitPlanMode plan. AIR keeps its
|
||||
* approved plans, each joined to its approval card in the transcript (see
|
||||
* planModeUpdate). Without plan operations, a legacy empty `plan` clears the
|
||||
* one plan the client holds. */
|
||||
export function resetPlanUpdates(
|
||||
planOperations: boolean,
|
||||
airClient: boolean,
|
||||
subagentChecklists?: SubagentChecklists,
|
||||
): SessionNotification["update"][] {
|
||||
const updates = [checklistPlanUpdate([], planOperations)];
|
||||
if (planOperations) {
|
||||
for (const planId of subagentChecklists ?? []) {
|
||||
updates.push({ sessionUpdate: "plan_removed", planId });
|
||||
}
|
||||
}
|
||||
subagentChecklists?.clear();
|
||||
if (planOperations && !airClient) {
|
||||
updates.push({ sessionUpdate: "plan_removed", planId: PLAN_MODE_PLAN_ID });
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* The follow-up prompt the SDK predicts for the next turn.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* AIR renders the first non-blank `suggestions[].text` as gray text in an empty
|
||||
* composer, where Tab fills the composer without sending.
|
||||
*
|
||||
* The CLI sends no suggestion on the first turn of a session, after an API
|
||||
* error, in plan mode, and at the account's usage limit, so most sessions have
|
||||
* turns that end with no prediction at all.
|
||||
*/
|
||||
|
||||
/** The `_meta` key the suggestion travels under. It names no vendor. */
|
||||
export const PROMPT_SUGGESTIONS_META_KEY = "promptSuggestions";
|
||||
|
||||
/** One predicted prompt, as the `_meta` value carries it. */
|
||||
export type PromptSuggestionsMetaValue = {
|
||||
suggestions: { text: string }[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function promptSuggestionText(raw: string | null | undefined): string | null {
|
||||
const text = raw?.trim();
|
||||
return text ? text : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `_meta` of the session info update that publishes `text`. `null` sends an
|
||||
* empty `suggestions` list, which clears the prompt the client holds — the turn
|
||||
* predicted nothing, so the composer must not keep the previous prediction.
|
||||
*/
|
||||
export function promptSuggestionsMeta(text: string | null): Record<string, unknown> {
|
||||
const value: PromptSuggestionsMetaValue = { suggestions: text === null ? [] : [{ text }] };
|
||||
return { [PROMPT_SUGGESTIONS_META_KEY]: value };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export class PromptSuggestions {
|
||||
/** The last text sent (`null` after a clear). Undefined until the first send. */
|
||||
private published: string | null | undefined;
|
||||
/**
|
||||
* Set at a turn's result, cleared when the next prompt arrives. A
|
||||
* prediction that the next prompt outran (sent before the prediction was
|
||||
* read off the stream) follows a turn that is answered already, so it is
|
||||
* dropped instead of published mid-turn.
|
||||
*/
|
||||
private expected = false;
|
||||
|
||||
/** A result came: the CLI predicts the next prompt right after it. */
|
||||
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 {
|
||||
if (!this.expected) return undefined;
|
||||
this.expected = false;
|
||||
return this.publish(promptSuggestionText(raw));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
this.expected = false;
|
||||
return this.publish(null);
|
||||
}
|
||||
|
||||
private publish(text: string | null): Record<string, unknown> | undefined {
|
||||
// An unchanged prediction is not sent again.
|
||||
if ((this.published ?? null) === text) return undefined;
|
||||
this.published = text;
|
||||
return promptSuggestionsMeta(text);
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/**
|
||||
* The conversion of an ACP prompt into the Claude Code user message.
|
||||
*/
|
||||
import type { PromptRequest } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { blobResourceToClaude } from "./blob-resources.js";
|
||||
|
||||
function formatUriAsLink(uri: string): string {
|
||||
try {
|
||||
if (uri.startsWith("file://")) {
|
||||
const path = uri.slice(7); // Remove "file://"
|
||||
const name = path.split("/").pop() || path;
|
||||
return `[@${name}](${uri})`;
|
||||
} else if (uri.startsWith("zed://")) {
|
||||
const parts = uri.split("/");
|
||||
const name = parts[parts.length - 1] || uri;
|
||||
return `[@${name}](${uri})`;
|
||||
}
|
||||
return uri;
|
||||
} catch {
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
|
||||
/** The prompt content block types that `promptToClaude` converts. The agent
|
||||
* advertises no `audio` prompt capability. */
|
||||
export const SUPPORTED_PROMPT_CONTENT_TYPES: readonly string[] = [
|
||||
"text",
|
||||
"image",
|
||||
"resource_link",
|
||||
"resource",
|
||||
];
|
||||
|
||||
export function promptToClaude(prompt: PromptRequest): SDKUserMessage {
|
||||
const content: any[] = [];
|
||||
const context: any[] = [];
|
||||
|
||||
const firstText = prompt.prompt.find((chunk) => chunk.type === "text");
|
||||
for (const chunk of prompt.prompt) {
|
||||
switch (chunk.type) {
|
||||
case "text": {
|
||||
let text = chunk.text;
|
||||
// A slash command is the first text block. Change
|
||||
// `/mcp:server:command args` to `/server:command (MCP) args`; the
|
||||
// arguments can span lines.
|
||||
const mcpMatch =
|
||||
chunk === firstText ? text.match(/^\/mcp:([^:\s]+):(\S+)(?:\s+([\s\S]*))?$/) : null;
|
||||
if (mcpMatch) {
|
||||
const [, server, command, args] = mcpMatch;
|
||||
text = `/${server}:${command} (MCP)${args ? ` ${args}` : ""}`;
|
||||
}
|
||||
content.push({ type: "text", text });
|
||||
break;
|
||||
}
|
||||
case "resource_link": {
|
||||
const formattedUri = formatUriAsLink(chunk.uri);
|
||||
content.push({
|
||||
type: "text",
|
||||
text: formattedUri,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "resource": {
|
||||
const { uri } = chunk.resource;
|
||||
// A blob resource becomes an image or document block, or its decoded
|
||||
// text. A v1 prompt skips a blob of any other type, e.g.
|
||||
// `application/zip`; a v2 prompt rejects it (see `v1PromptRequest`).
|
||||
const blob = "blob" in chunk.resource ? blobResourceToClaude(chunk.resource) : undefined;
|
||||
const text =
|
||||
"text" in chunk.resource
|
||||
? chunk.resource.text
|
||||
: blob?.kind === "text"
|
||||
? blob.text
|
||||
: undefined;
|
||||
if (blob?.kind === "image" || blob?.kind === "document") {
|
||||
content.push({ type: "text", text: formatUriAsLink(uri) }, blob.block);
|
||||
} else if (text !== undefined) {
|
||||
content.push({ type: "text", text: formatUriAsLink(uri) });
|
||||
context.push({
|
||||
type: "text",
|
||||
text: `\n<context ref="${uri}">\n${text}\n</context>`,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "image":
|
||||
if (chunk.data) {
|
||||
content.push({
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
data: chunk.data,
|
||||
media_type: chunk.mimeType,
|
||||
},
|
||||
});
|
||||
} else if (chunk.uri && chunk.uri.startsWith("http")) {
|
||||
content.push({
|
||||
type: "image",
|
||||
source: {
|
||||
type: "url",
|
||||
url: chunk.uri,
|
||||
},
|
||||
});
|
||||
}
|
||||
break;
|
||||
// Ignore audio and other unsupported types
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
content.push(...context);
|
||||
|
||||
return {
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: content,
|
||||
},
|
||||
session_id: prompt.sessionId,
|
||||
parent_tool_use_id: null,
|
||||
// ACP prompts are the user's own input relayed by the client. Stamp the
|
||||
// provenance explicitly: per the SDK, a host wrapping keyboard input must
|
||||
// send `{kind: "human"}` — an absent `origin` is treated as unattributed
|
||||
// and fails closed at the CLI's strict isHuman() trust gates (e.g. the
|
||||
// ultracode keyword opt-in honors only human-originated turns).
|
||||
origin: { kind: "human" },
|
||||
};
|
||||
}
|
||||
421
src/providers.ts
421
src/providers.ts
@@ -1,421 +0,0 @@
|
||||
/**
|
||||
* Client-managed LLM routing, shared by the v1 core and the v2 core:
|
||||
* the `main` provider of `providers/list`, `providers/set` and
|
||||
* `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}.
|
||||
*/
|
||||
import {
|
||||
RequestError,
|
||||
type AuthenticateRequest,
|
||||
type AuthMethod,
|
||||
type ListProvidersResponse,
|
||||
type LlmProtocol,
|
||||
type ProviderInfo,
|
||||
type SetProviderRequest,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
GatewayListingError,
|
||||
listBedrockModels,
|
||||
listGatewayModels,
|
||||
PROVIDER_AUTH_TOKEN_PLACEHOLDER,
|
||||
selectBedrockRegion,
|
||||
} from "./gateway-models.js";
|
||||
|
||||
type ProviderLogger = { log: (...args: any[]) => void; error: (...args: any[]) => void };
|
||||
|
||||
/**
|
||||
* Extra metadata for 'gateway' authentication requests.
|
||||
*/
|
||||
export type GatewayAuthMeta = {
|
||||
/**
|
||||
* These parameters are mapped to environment variables to:
|
||||
* - Redirect API calls via baseUrl
|
||||
* - Inject custom headers
|
||||
* - Bypass the default Claude login requirement
|
||||
*
|
||||
* Both members are optional in the type because the payload arrives
|
||||
* unvalidated from the client. `authenticate` rejects a request that lacks a
|
||||
* usable `baseUrl`.
|
||||
*/
|
||||
gateway?: {
|
||||
baseUrl?: string;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
};
|
||||
|
||||
export type GatewayAuthRequest = AuthenticateRequest & { _meta?: GatewayAuthMeta };
|
||||
|
||||
export const SUPPORTED_PROTOCOLS: LlmProtocol[] = ["anthropic", "bedrock", "vertex"];
|
||||
export const PROVIDER_ID = "main";
|
||||
export const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com";
|
||||
export const DEFAULT_VERTEX_BASE_URL = "https://aiplatform.googleapis.com";
|
||||
|
||||
/**
|
||||
* Vertex needs project + region that the standard `providers/set` payload
|
||||
* (`apiType`/`baseUrl`/`headers`) does not model, so clients pass them through
|
||||
* `_meta.claudeCode.vertex`. Required only when `apiType === "vertex"`.
|
||||
*/
|
||||
export type SetProviderMeta = {
|
||||
claudeCode?: {
|
||||
vertex?: {
|
||||
projectId: string;
|
||||
region: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolved, non-secret + secret routing config for the `main` provider. This is
|
||||
* the shared shape produced by both `providers/set` and the legacy gateway auth
|
||||
* path, and consumed by {@link createEnvForProvider}. `null` means the provider
|
||||
* is unconfigured (no client-managed routing in effect).
|
||||
*/
|
||||
export type ProviderConfig = {
|
||||
apiType: LlmProtocol;
|
||||
baseUrl: string;
|
||||
headers: Record<string, string>;
|
||||
/** Present only for `apiType === "vertex"`. */
|
||||
vertex?: {
|
||||
projectId: string;
|
||||
region: string;
|
||||
};
|
||||
/**
|
||||
* Model ids an `anthropic` or `bedrock` gateway listed when it was set via
|
||||
* `providers/set`; the model picker offers only these. Absent when the
|
||||
* listing failed or the config came from elsewhere (gateway `authenticate`),
|
||||
* so nothing is narrowed.
|
||||
*/
|
||||
listedModels?: string[];
|
||||
/**
|
||||
* The cross-region prefix of the model ids a `bedrock` gateway
|
||||
* listed (`eu` for `eu.anthropic.claude-sonnet-5`), passed to the CLI as
|
||||
* `ANTHROPIC_BEDROCK_REGION_PREFIX` so it calls the models under that prefix.
|
||||
*/
|
||||
bedrockRegionPrefix?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adapt a legacy gateway `authenticate` request into the shared
|
||||
* {@link ProviderConfig} shape. Returns `null` when no gateway request is
|
||||
* present. `methodId` selects the protocol: `gateway-bedrock` → bedrock,
|
||||
* otherwise anthropic.
|
||||
*/
|
||||
export function gatewayRequestToProviderConfig(
|
||||
request?: GatewayAuthRequest,
|
||||
): ProviderConfig | null {
|
||||
// `authenticate` validates the payload before it stores one, so a stored
|
||||
// request always carries a usable gateway. Re-check the shape here anyway:
|
||||
// this function decides whether a provider override is active, and the
|
||||
// `--hide-claude-auth` guard is off while one is.
|
||||
const gateway = request?._meta?.gateway;
|
||||
if (!gateway || !isValidBaseUrl(gateway.baseUrl)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
apiType: request?.methodId === "gateway-bedrock" ? "bedrock" : "anthropic",
|
||||
baseUrl: gateway.baseUrl,
|
||||
headers: gateway.headers ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a resolved provider config into the Claude Code env vars that redirect API
|
||||
* traffic and inject headers. Returns an empty object when routing is
|
||||
* unconfigured. The token/bypass placeholders (`" "`) are required so the CLI
|
||||
* skips its normal login/credential checks when a gateway is in use.
|
||||
*/
|
||||
export function createEnvForProvider(config: ProviderConfig | null): Record<string, string> {
|
||||
if (!config) {
|
||||
return {};
|
||||
}
|
||||
const resetRouting = {
|
||||
ANTHROPIC_BASE_URL: "",
|
||||
ANTHROPIC_BEDROCK_BASE_URL: "",
|
||||
ANTHROPIC_VERTEX_BASE_URL: "",
|
||||
CLAUDE_CODE_USE_BEDROCK: "0",
|
||||
CLAUDE_CODE_USE_VERTEX: "0",
|
||||
ANTHROPIC_VERTEX_PROJECT_ID: "",
|
||||
CLOUD_ML_REGION: "",
|
||||
AWS_REGION: "",
|
||||
ANTHROPIC_API_KEY: "",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
CLAUDE_CODE_OAUTH_TOKEN: "",
|
||||
};
|
||||
const customHeaders = Object.entries(config.headers)
|
||||
.map(([key, value]) => `${key}: ${value}`)
|
||||
.join("\n");
|
||||
|
||||
if (config.apiType === "bedrock") {
|
||||
return {
|
||||
...resetRouting,
|
||||
CLAUDE_CODE_USE_BEDROCK: "1",
|
||||
AWS_BEARER_TOKEN_BEDROCK: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local AWS credential checks
|
||||
ANTHROPIC_BEDROCK_BASE_URL: config.baseUrl,
|
||||
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
||||
...(config.bedrockRegionPrefix
|
||||
? { ANTHROPIC_BEDROCK_REGION_PREFIX: config.bedrockRegionPrefix }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (config.apiType === "vertex") {
|
||||
// `config.vertex` is guaranteed present for vertex by `unstable_setProvider`
|
||||
// validation; fall back to empty strings defensively.
|
||||
// Leaving ANTHROPIC_VERTEX_BASE_URL empty for the default endpoint lets
|
||||
// Claude Code use its native Vertex endpoint/model resolution. Supplying
|
||||
// even the default host marks the session as a custom Vertex deployment and
|
||||
// can hide otherwise-valid models.
|
||||
return {
|
||||
...resetRouting,
|
||||
CLAUDE_CODE_USE_VERTEX: "1",
|
||||
...(config.baseUrl !== DEFAULT_VERTEX_BASE_URL
|
||||
? { ANTHROPIC_VERTEX_BASE_URL: config.baseUrl }
|
||||
: {}),
|
||||
ANTHROPIC_VERTEX_PROJECT_ID: config.vertex?.projectId ?? "",
|
||||
CLOUD_ML_REGION: config.vertex?.region ?? "",
|
||||
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...resetRouting,
|
||||
ANTHROPIC_BASE_URL: config.baseUrl,
|
||||
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
||||
ANTHROPIC_AUTH_TOKEN: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local Claude login checks
|
||||
};
|
||||
}
|
||||
|
||||
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]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider base URL as logs may show it: its origin only. The URL can come
|
||||
* from the env or the client and can carry credentials (`https://user:key@host`)
|
||||
* or a key in its path or query, so a log line must not print it whole.
|
||||
*/
|
||||
export function loggableBaseUrl(baseUrl: string | undefined): string {
|
||||
if (baseUrl === undefined) return "native";
|
||||
try {
|
||||
return new URL(baseUrl).origin;
|
||||
} catch {
|
||||
return "invalid";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a provider base URL: must be a non-empty absolute http(s) URL.
|
||||
*/
|
||||
export function isValidBaseUrl(baseUrl: string | undefined): baseUrl is string {
|
||||
if (typeof baseUrl !== "string" || baseUrl.trim() === "") {
|
||||
return false;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(baseUrl);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:";
|
||||
}
|
||||
|
||||
/** The gateway login methods, advertised to a client with `auth._meta.gateway`. */
|
||||
export function gatewayAuthMethods(): AuthMethod[] {
|
||||
return (["anthropic", "bedrock"] as const).map((protocol) => ({
|
||||
id: protocol === "anthropic" ? "gateway" : "gateway-bedrock",
|
||||
name: "Custom model gateway",
|
||||
description: "Use a custom gateway to authenticate and access models",
|
||||
_meta: { gateway: { protocol } },
|
||||
}));
|
||||
}
|
||||
|
||||
export function isGatewayAuthMethod(methodId: string): boolean {
|
||||
return methodId === "gateway" || methodId === "gateway-bedrock";
|
||||
}
|
||||
|
||||
/**
|
||||
* The gateway login `params` asks for, once its payload is usable: the same
|
||||
* base URL rule as `providers/set`. An unchecked payload either throws a
|
||||
* `TypeError` deep in session creation, or installs an empty base URL that
|
||||
* silently turns the `--hide-claude-auth` subscription guard off.
|
||||
*
|
||||
* A request that carries no gateway payload at all keeps its historical
|
||||
* meaning: it installs no override and succeeds. A client that probes the
|
||||
* method this way must keep working. Only a payload that IS present has to be
|
||||
* usable.
|
||||
*/
|
||||
export function validatedGatewayAuthRequest(params: AuthenticateRequest): GatewayAuthRequest {
|
||||
const gateway = (params as GatewayAuthRequest)._meta?.gateway;
|
||||
if (gateway !== undefined && gateway !== null) {
|
||||
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.",
|
||||
);
|
||||
}
|
||||
if (gateway.headers !== undefined && typeof gateway.headers !== "object") {
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
"`_meta.gateway.headers` must be an object of header names to values.",
|
||||
);
|
||||
}
|
||||
}
|
||||
return params as GatewayAuthRequest;
|
||||
}
|
||||
|
||||
/** The native routing of the agent: a gateway login, else the process env. */
|
||||
export function defaultProviderConfig(gatewayAuthRequest?: GatewayAuthRequest): ProviderConfig {
|
||||
const gatewayConfig = gatewayRequestToProviderConfig(gatewayAuthRequest);
|
||||
if (gatewayConfig) {
|
||||
return gatewayConfig;
|
||||
}
|
||||
if (process.env.CLAUDE_CODE_USE_BEDROCK) {
|
||||
return {
|
||||
apiType: "bedrock",
|
||||
baseUrl: process.env.ANTHROPIC_BEDROCK_BASE_URL ?? "https://bedrock-runtime.amazonaws.com",
|
||||
headers: {},
|
||||
};
|
||||
}
|
||||
if (process.env.CLAUDE_CODE_USE_VERTEX) {
|
||||
return {
|
||||
apiType: "vertex",
|
||||
baseUrl: process.env.ANTHROPIC_VERTEX_BASE_URL ?? DEFAULT_VERTEX_BASE_URL,
|
||||
headers: {},
|
||||
};
|
||||
}
|
||||
return {
|
||||
apiType: "anthropic",
|
||||
baseUrl: process.env.ANTHROPIC_BASE_URL ?? DEFAULT_ANTHROPIC_BASE_URL,
|
||||
headers: {},
|
||||
};
|
||||
}
|
||||
|
||||
/** The `providers/list` response for the `main` provider routed by `config`. */
|
||||
export function listProvidersResponse(config: ProviderConfig): ListProvidersResponse {
|
||||
const provider: ProviderInfo = {
|
||||
providerId: PROVIDER_ID,
|
||||
supported: SUPPORTED_PROTOCOLS,
|
||||
required: false,
|
||||
current: { apiType: config.apiType, baseUrl: config.baseUrl },
|
||||
};
|
||||
return { providers: [provider] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The configuration a `providers/set` request asks for. Rejects unknown IDs,
|
||||
* unsupported protocols, empty or invalid base URLs, and a `vertex` request
|
||||
* without its project and region, with `invalid_params`.
|
||||
*/
|
||||
export function providerConfigFromSetRequest(params: SetProviderRequest): ProviderConfig {
|
||||
if (params.providerId !== PROVIDER_ID) {
|
||||
throw RequestError.invalidParams(
|
||||
{ providerId: params.providerId },
|
||||
`Unknown provider ID "${params.providerId}"; expected "${PROVIDER_ID}".`,
|
||||
);
|
||||
}
|
||||
if (!SUPPORTED_PROTOCOLS.includes(params.apiType)) {
|
||||
throw RequestError.invalidParams(
|
||||
{ apiType: params.apiType, supported: SUPPORTED_PROTOCOLS },
|
||||
`Unsupported apiType "${params.apiType}" for provider "${PROVIDER_ID}".`,
|
||||
);
|
||||
}
|
||||
if (!isValidBaseUrl(params.baseUrl)) {
|
||||
throw RequestError.invalidParams(
|
||||
{ baseUrl: params.baseUrl },
|
||||
"baseUrl must be a non-empty absolute http(s) URL.",
|
||||
);
|
||||
}
|
||||
|
||||
const config: ProviderConfig = {
|
||||
apiType: params.apiType,
|
||||
baseUrl: params.baseUrl,
|
||||
headers: params.headers ?? {},
|
||||
};
|
||||
|
||||
// Vertex requires project + region, which the standard payload cannot
|
||||
// carry, so they arrive via `_meta.claudeCode.vertex`.
|
||||
if (params.apiType === "vertex") {
|
||||
const vertex = (params._meta as SetProviderMeta | undefined)?.claudeCode?.vertex;
|
||||
if (
|
||||
!vertex ||
|
||||
typeof vertex.projectId !== "string" ||
|
||||
vertex.projectId.trim() === "" ||
|
||||
typeof vertex.region !== "string" ||
|
||||
vertex.region.trim() === ""
|
||||
) {
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
"vertex apiType requires non-empty `_meta.claudeCode.vertex.projectId` and `_meta.claudeCode.vertex.region`.",
|
||||
);
|
||||
}
|
||||
config.vertex = { projectId: vertex.projectId, region: vertex.region };
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds to `config` the model ids its gateway lists, and for `bedrock` the
|
||||
* region prefix picked from them, so the sessions it routes offer only those.
|
||||
* Setting the same gateway as `current` again reuses its listing. `vertex`
|
||||
* gateways are not listed. A failed listing throws an `internal_error`.
|
||||
*/
|
||||
export async function withListedModels(
|
||||
config: ProviderConfig,
|
||||
current: ProviderConfig | undefined,
|
||||
logger: ProviderLogger,
|
||||
): Promise<ProviderConfig> {
|
||||
try {
|
||||
Object.assign(config, await listProviderModels(config, current, logger));
|
||||
} catch (error) {
|
||||
if (error instanceof GatewayListingError) {
|
||||
throw RequestError.internalError(
|
||||
{ providerId: PROVIDER_ID, apiType: config.apiType, baseUrl: config.baseUrl },
|
||||
`Model discovery for provider "${PROVIDER_ID}" failed: ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
logger.log(
|
||||
`[providers/set] listedModels=${config.listedModels?.length ?? "none"} bedrockRegionPrefix=${config.bedrockRegionPrefix ?? "none"}`,
|
||||
);
|
||||
return config;
|
||||
}
|
||||
|
||||
async function listProviderModels(
|
||||
config: ProviderConfig,
|
||||
current: ProviderConfig | undefined,
|
||||
logger: ProviderLogger,
|
||||
): Promise<Pick<ProviderConfig, "listedModels" | "bedrockRegionPrefix">> {
|
||||
// Reuse needs the very same headers, so a rotated token lists again, and a
|
||||
// failed listing then fails that `providers/set`. Deliberate: AIR keeps its
|
||||
// proxy key for the IDE's lifetime and does not rotate it.
|
||||
if (
|
||||
current?.listedModels &&
|
||||
current.apiType === config.apiType &&
|
||||
current.baseUrl === config.baseUrl &&
|
||||
sameHeaders(current.headers, config.headers)
|
||||
) {
|
||||
return {
|
||||
listedModels: current.listedModels,
|
||||
bedrockRegionPrefix: current.bedrockRegionPrefix,
|
||||
};
|
||||
}
|
||||
if (config.apiType === "anthropic") {
|
||||
return { listedModels: await listGatewayModels(config.baseUrl, config.headers, logger) };
|
||||
}
|
||||
if (config.apiType === "bedrock") {
|
||||
const modelIds = await listBedrockModels(config.baseUrl, config.headers, logger);
|
||||
if (!modelIds) return {};
|
||||
const region = selectBedrockRegion(modelIds);
|
||||
if (region.modelIds.length < modelIds.length) {
|
||||
logger.log(
|
||||
`[providers/set] Bedrock models span several region prefixes; using ${region.regionPrefix} and dropping ${modelIds.length - region.modelIds.length} id(s) of other prefixes`,
|
||||
);
|
||||
}
|
||||
return { listedModels: region.modelIds, bedrockRegionPrefix: region.regionPrefix };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/**
|
||||
* `/remote-control`, which the adapter serves itself, 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.
|
||||
*/
|
||||
/** The content blocks of a prompt, in v1 or v2 form: the command is one text block. */
|
||||
type PromptContent = ReadonlyArray<{ type: string; text?: unknown }>;
|
||||
|
||||
import type {
|
||||
Query,
|
||||
SDKUserMessage,
|
||||
SDKUserMessageReplay,
|
||||
SlashCommand,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/** Runtime Remote Control control exposed by the pinned Agent SDK. Like
|
||||
* `mcpAuthenticate`, it is not in the public `Query` declaration yet. The CLI's
|
||||
* own `/remote-control` is terminal-bound and not offered to SDK hosts, so the
|
||||
* adapter handles the command itself and answers with the session URL. */
|
||||
export type RemoteControlQuery = Query & {
|
||||
enableRemoteControl(
|
||||
enabled: boolean,
|
||||
name?: string,
|
||||
): Promise<{ session_url?: string; connect_url?: string }>;
|
||||
};
|
||||
|
||||
export function supportsRemoteControl(query: Query): query is RemoteControlQuery {
|
||||
return typeof (query as Partial<RemoteControlQuery>).enableRemoteControl === "function";
|
||||
}
|
||||
|
||||
export const REMOTE_CONTROL_COMMAND_NAME = "remote-control";
|
||||
|
||||
export type RemoteControlCommand = { action: "connect"; name?: string } | { action: "disconnect" };
|
||||
|
||||
/** Parses `/remote-control [name]` and `/remote-control off` from a single-text
|
||||
* prompt. Connecting is idempotent, so the command never needs to know whether
|
||||
* Remote Control is already on. */
|
||||
export function parseRemoteControlCommand(prompt: PromptContent): RemoteControlCommand | null {
|
||||
const [first] = prompt;
|
||||
if (prompt.length !== 1 || first?.type !== "text" || typeof first.text !== "string") return null;
|
||||
const match = /^\/remote-control(?:\s+([\s\S]*))?$/.exec(first.text.trim());
|
||||
if (!match) return null;
|
||||
const argument = match[1]?.trim();
|
||||
if (argument?.toLowerCase() === "off") return { action: "disconnect" };
|
||||
return argument ? { action: "connect", name: argument } : { action: "connect" };
|
||||
}
|
||||
|
||||
/** Whether Claude Code offers a slash command of this name to an ACP client.
|
||||
* This is the rule `getAvailableSlashCommands` applies when it lists the
|
||||
* commands, so the adapter stands in for the command exactly when the client
|
||||
* sees the adapter's entry: Claude Code's terminal-bound commands are not
|
||||
* offered, and a user's own command or skill of the name is never shadowed. */
|
||||
export function claudeCodeOffersCommand(
|
||||
commands: readonly SlashCommand[],
|
||||
terminalCommands: readonly string[] | undefined,
|
||||
name: string,
|
||||
): boolean {
|
||||
return commands.some(
|
||||
(command) => command.name === name && !terminalCommands?.includes(command.name),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `/remote-control` command of `prompt` that the adapter runs: the query
|
||||
* serves Remote Control and Claude Code does not offer a command of that name.
|
||||
* `null` for any other prompt, which goes to Claude Code.
|
||||
*/
|
||||
export async function adapterRemoteControlCommand(
|
||||
prompt: PromptContent,
|
||||
query: Query,
|
||||
terminalCommands: readonly string[] | undefined,
|
||||
): Promise<{ query: RemoteControlQuery; command: RemoteControlCommand } | null> {
|
||||
const command = parseRemoteControlCommand(prompt);
|
||||
if (!command || !supportsRemoteControl(query)) return null;
|
||||
if (
|
||||
claudeCodeOffersCommand(
|
||||
await query.supportedCommands(),
|
||||
terminalCommands,
|
||||
REMOTE_CONTROL_COMMAND_NAME,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { query, command };
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects Remote Control (again, if it is already on) or disconnects it, and
|
||||
* returns the text that tells the user how it went. A failure is in the text:
|
||||
* this never throws.
|
||||
*/
|
||||
export async function runRemoteControlCommand(
|
||||
query: RemoteControlQuery,
|
||||
command: RemoteControlCommand,
|
||||
logError: (message: string) => void,
|
||||
): Promise<string> {
|
||||
if (command.action === "disconnect") {
|
||||
try {
|
||||
await query.enableRemoteControl(false);
|
||||
return "Remote Control is off. Run /remote-control to reconnect.";
|
||||
} catch (error) {
|
||||
logError(`Failed to disable Remote Control: ${error}`);
|
||||
return `Could not stop Remote Control: ${error instanceof Error ? error.message : error}`;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await query.enableRemoteControl(true, command.name);
|
||||
return result.session_url
|
||||
? `Remote Control is active. Continue this session from claude.ai/code or the Claude mobile app:\n\n${result.session_url}\n\nRun /remote-control off to disconnect.`
|
||||
: "Remote Control is active, but Claude Code did not return a session URL.";
|
||||
} catch (error) {
|
||||
logError(`Failed to enable Remote Control: ${error}`);
|
||||
return `Could not start Remote Control: ${error instanceof Error ? error.message : error}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
* origin. */
|
||||
export function isRemoteHumanMessage(message: SDKUserMessage | SDKUserMessageReplay): boolean {
|
||||
return (
|
||||
message.type === "user" &&
|
||||
message.origin?.kind === "human" &&
|
||||
message.parent_tool_use_id === null &&
|
||||
!message.isSynthetic
|
||||
);
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
/**
|
||||
* How Claude Code's `result` ends the work that it reports, and whether that
|
||||
* work was the user's turn or a cycle Claude Code started on its own: the
|
||||
* rules that both cores read a turn's result with (the v1 prompt loop in
|
||||
* `v1/acp-agent.ts` and `v2/`). Each core adds its own side effects, such as v1's
|
||||
* session failure category.
|
||||
*/
|
||||
import type {
|
||||
SDKMessage,
|
||||
SDKMessageOrigin,
|
||||
SDKResultMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
export type ResultEnd =
|
||||
| { stopReason: "refusal" | "max_tokens" | "end_turn" | "max_turn_requests" }
|
||||
/**
|
||||
* The result failed the work, with Claude Code's error text. `loginRequired`:
|
||||
* the text of a `success` result tells the user to run `/login`.
|
||||
*/
|
||||
| { error: string; loginRequired: boolean };
|
||||
|
||||
/**
|
||||
* True when CLI error text tells the user to sign in with `/login`. The CLI
|
||||
* words this several ways — "Not logged in · Please run /login", "Not logged
|
||||
* in · Run /login", "Login expired · Run /login to sign in again, or
|
||||
* re-authenticate your Anthropic profile" — so match the "run /login"
|
||||
* instruction rather than one sentence.
|
||||
*/
|
||||
export function isLoginRequiredText(text: string): boolean {
|
||||
return /\brun \/login\b/i.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* - Any subtype with `stop_reason: "refusal"`: `refusal`, also on an error.
|
||||
* - `success`: an error with the `/login` text fails the work, then
|
||||
* `stop_reason: "max_tokens"` is `max_tokens`, then any other error fails
|
||||
* the work. Otherwise `end_turn`.
|
||||
* - `error_during_execution`: `max_tokens` as for `success`, then an error
|
||||
* fails the work. Otherwise `end_turn`.
|
||||
* - `error_max_turns`, `error_max_budget_usd` and
|
||||
* `error_max_structured_output_retries`: an error fails the work, whatever
|
||||
* the stop reason. Otherwise `max_turn_requests`.
|
||||
*/
|
||||
export function resultEnd(result: SDKResultMessage): ResultEnd {
|
||||
if (result.stop_reason === "refusal") return { stopReason: "refusal" };
|
||||
switch (result.subtype) {
|
||||
case "success":
|
||||
if (result.is_error && isLoginRequiredText(result.result)) {
|
||||
return { error: result.result, loginRequired: true };
|
||||
}
|
||||
if (result.stop_reason === "max_tokens") return { stopReason: "max_tokens" };
|
||||
if (result.is_error) return { error: result.result, loginRequired: false };
|
||||
return { stopReason: "end_turn" };
|
||||
case "error_during_execution":
|
||||
if (result.stop_reason === "max_tokens") return { stopReason: "max_tokens" };
|
||||
if (result.is_error) return failed(result);
|
||||
return { stopReason: "end_turn" };
|
||||
default:
|
||||
// `error_max_turns`, `error_max_budget_usd`, `error_max_structured_output_retries`.
|
||||
if (result.is_error) return failed(result);
|
||||
return { stopReason: "max_turn_requests" };
|
||||
}
|
||||
}
|
||||
|
||||
function failed(result: Exclude<SDKResultMessage, { subtype: "success" }>): ResultEnd {
|
||||
return { error: result.errors.join(", ") || result.subtype, loginRequired: false };
|
||||
}
|
||||
|
||||
/** Result-message origin kinds that mark an AUTONOMOUS cycle — work the
|
||||
* model did on its own (a task-notification followup, a peer/coordinator/
|
||||
* observer message it handled) rather than the user's prompt. Absent,
|
||||
* `human`, and `channel` origins are the user's own turn (this adapter's
|
||||
* prompts arrive as the ACP channel on some CLI configurations — ALL
|
||||
* channel servers are treated as user, so a foreign channel integration's
|
||||
* autonomously-handled result is misclassified as the user's; accepted,
|
||||
* see below), and `auto-continuation` continues the user's turn, so its
|
||||
* result is the turn's real terminal.
|
||||
*
|
||||
* Deliberately fail-OPEN: an unknown future kind defaults to the user
|
||||
* lane — including `unclassified` (SDK 0.3.232+), the CLI's own "couldn't
|
||||
* attribute this" marker, which gets the same safe default. Misrouting a
|
||||
* USER result into the autonomous lane hangs the prompt un-detectably
|
||||
* (the result is skipped, its trailing idle absorbed as owed, so the
|
||||
* #825 detector can't fire); misrouting an autonomous result into the
|
||||
* user lane is the bounded misattribution class this set exists to
|
||||
* reduce.
|
||||
*
|
||||
* Exception: a result from one of these origins that names a pending prompt
|
||||
* in `user_message_uuids` consumed that folded prompt and takes the user
|
||||
* lane (see the result handler of each core). */
|
||||
export const AUTONOMOUS_RESULT_ORIGINS: ReadonlySet<SDKMessageOrigin["kind"]> = new Set([
|
||||
"task-notification",
|
||||
"peer",
|
||||
"coordinator",
|
||||
"observer",
|
||||
"observer-activity",
|
||||
]);
|
||||
|
||||
/** Whether Claude Code ended the work of `result` because an interrupt
|
||||
* stopped it, while the model streamed or while a tool ran. */
|
||||
export function isAbortedResult(result: Extract<SDKMessage, { type: "result" }>): boolean {
|
||||
return (
|
||||
result.terminal_reason === "aborted_streaming" || result.terminal_reason === "aborted_tools"
|
||||
);
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
import { getSessionMessages, type SessionMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { access, open, readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { claudeConfigDir } from "./paths.js";
|
||||
import { SessionTiming } from "./session-timing.js";
|
||||
|
||||
/** The size of one backward read of a transcript. */
|
||||
const TAIL_CHUNK_BYTES = 64 * 1024;
|
||||
|
||||
type ResumeLogger = {
|
||||
log: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
export type ResumedSessionSnapshot = {
|
||||
messages?: SessionMessage[];
|
||||
model?: string;
|
||||
};
|
||||
|
||||
/** Return the concrete model recorded by the last real assistant response.
|
||||
* Claude Code restores a resumed query from this same transcript field.
|
||||
* Synthetic assistant records use angle-bracket placeholders and do not
|
||||
* describe a model the resumed query can run. */
|
||||
export function resumedModelFromTranscript(messages: SessionMessage[]): string | undefined {
|
||||
for (let index = messages.length - 1; index >= 0; index--) {
|
||||
const entry = messages[index];
|
||||
if (
|
||||
entry?.type !== "assistant" ||
|
||||
entry.parent_tool_use_id != null ||
|
||||
entry.parent_agent_id != null ||
|
||||
!entry.message ||
|
||||
typeof entry.message !== "object"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const model = concreteModel((entry.message as { model?: unknown }).model);
|
||||
if (model) return model;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The model name, or undefined for a missing or a synthetic `<…>` model. */
|
||||
function concreteModel(model: unknown): string | undefined {
|
||||
if (typeof model !== "string") return undefined;
|
||||
const name = model.trim();
|
||||
return name.length > 0 && !/^<[^>]+>$/.test(name) ? name : undefined;
|
||||
}
|
||||
|
||||
/** Read the resume model from the local transcript without starting a Claude
|
||||
* control request. This is intentionally on the load critical path. */
|
||||
export async function readResumedSession(
|
||||
sessionId: string,
|
||||
logger?: ResumeLogger,
|
||||
): Promise<ResumedSessionSnapshot> {
|
||||
const timing = new SessionTiming(logger, "models", sessionId);
|
||||
try {
|
||||
// Deliberately search all project directories, matching replaySessionHistory.
|
||||
// A client may reopen a session from a worktree or normalized path that is
|
||||
// different from the directory under which Claude persisted the transcript.
|
||||
const messages = await getSessionMessages(sessionId);
|
||||
const model = resumedModelFromTranscript(messages);
|
||||
timing.phase("read-transcript", ` messages=${messages.length} model=${model ?? "unknown"}`);
|
||||
return { messages, model };
|
||||
} catch (error) {
|
||||
timing.phase("read-transcript", " outcome=error");
|
||||
logger?.error(`Failed to read transcript for resumed session ${sessionId}:`, error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** What a resume restores from the end of the local transcript. */
|
||||
export type ResumedTail = {
|
||||
model?: string;
|
||||
/** The last permission mode of the main thread. See {@link TailScan}. */
|
||||
permissionMode?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Read the resume model and the permission mode of a session from the end
|
||||
* of its local transcript.
|
||||
*
|
||||
* A resume needs only these two values, not the messages. The transcript file
|
||||
* is read backwards until both are known, so the cost does not grow with the
|
||||
* length of the session. A session without a local transcript file falls back
|
||||
* to {@link readResumedSession} for the model.
|
||||
*
|
||||
* A caller that already has the model passes `withModel: false`. The read then
|
||||
* looks for the permission mode only and has no fallback.
|
||||
*/
|
||||
export async function readResumedTail(
|
||||
sessionId: string,
|
||||
logger?: ResumeLogger,
|
||||
withModel = true,
|
||||
): Promise<ResumedTail> {
|
||||
const timing = new SessionTiming(logger, "models", sessionId);
|
||||
try {
|
||||
const filePath = await findTranscript(sessionId);
|
||||
if (filePath) {
|
||||
const tail = await lastTailRecords(filePath, withModel);
|
||||
timing.phase(
|
||||
"read-transcript-tail",
|
||||
` model=${tail.model ?? "unknown"} permissionMode=${tail.permissionMode ?? "unknown"}`,
|
||||
);
|
||||
return tail;
|
||||
}
|
||||
} catch (error) {
|
||||
timing.phase("read-transcript-tail", " outcome=error");
|
||||
logger?.error(`Failed to read the transcript tail of resumed session ${sessionId}:`, error);
|
||||
}
|
||||
return withModel ? { model: (await readResumedSession(sessionId, logger)).model } : {};
|
||||
}
|
||||
|
||||
/** The local transcript of a session in any project directory, as the SDK looks it up. */
|
||||
export async function findTranscript(sessionId: string): Promise<string | undefined> {
|
||||
const projects = path.join(claudeConfigDir(), "projects");
|
||||
let directories: string[];
|
||||
try {
|
||||
directories = await readdir(projects);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
for (const directory of directories) {
|
||||
const candidate = path.join(projects, directory, `${sessionId}.jsonl`);
|
||||
try {
|
||||
await access(candidate);
|
||||
return candidate;
|
||||
} catch {
|
||||
// Not in this project directory.
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The model of the last real assistant record and the last permission mode
|
||||
* of the main thread in a JSONL transcript. */
|
||||
async function lastTailRecords(filePath: string, withModel: boolean): Promise<ResumedTail> {
|
||||
const handle = await open(filePath, "r");
|
||||
const scan = new TailScan(withModel);
|
||||
try {
|
||||
let end = (await handle.stat()).size;
|
||||
// The bytes of the line whose start is not read yet, in file order.
|
||||
let pending: Buffer[] = [];
|
||||
while (end > 0) {
|
||||
const start = Math.max(0, end - TAIL_CHUNK_BYTES);
|
||||
let chunk = Buffer.alloc(end - start);
|
||||
await handle.read(chunk, 0, chunk.length, start);
|
||||
for (let at = chunk.lastIndexOf(0x0a); at >= 0; at = chunk.lastIndexOf(0x0a)) {
|
||||
if (scan.visit(Buffer.concat([chunk.subarray(at + 1), ...pending]))) return scan.tail;
|
||||
pending = [];
|
||||
chunk = chunk.subarray(0, at);
|
||||
}
|
||||
pending.unshift(chunk);
|
||||
end = start;
|
||||
}
|
||||
scan.visit(Buffer.concat(pending));
|
||||
return scan.tail;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
type TranscriptRecord = {
|
||||
type?: unknown;
|
||||
isSidechain?: unknown;
|
||||
message?: { model?: unknown };
|
||||
permissionMode?: unknown;
|
||||
origin?: { kind?: unknown };
|
||||
attachment?: { type?: unknown };
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads the lines of a transcript from the end and keeps what a resume needs.
|
||||
*
|
||||
* Claude Code records the permission mode on each prompt record of type `user`.
|
||||
* The `permission-mode` records of the CLI metadata block are not used: they
|
||||
* can disagree with the prompts, and the SDK does not write them.
|
||||
* The SDK writes no record when it leaves plan mode through ExitPlanMode.
|
||||
* It writes a `plan_mode_exit` attachment only, without the new mode. Thus a
|
||||
* `plan` mode before a later plan exit is not the current mode, and the scan
|
||||
* gives no mode.
|
||||
*
|
||||
* The mode search stops at the first mode record or at the last human prompt.
|
||||
* Each human prompt of a current Claude Code has the mode, so a prompt without
|
||||
* it means that the transcript does not record modes. A compaction does not
|
||||
* stop the search: the mode of the prompt before it is still current.
|
||||
*/
|
||||
class TailScan {
|
||||
readonly tail: ResumedTail = {};
|
||||
private modeDone = false;
|
||||
private planExited = false;
|
||||
|
||||
constructor(private readonly withModel: boolean) {}
|
||||
|
||||
/** Visit the previous line. Return true when the scan has all it needs. */
|
||||
visit(line: Buffer): boolean {
|
||||
let parsed: TranscriptRecord | null | undefined;
|
||||
// Most lines have no marker of interest. The check skips their JSON parse.
|
||||
const record = (marker: string): TranscriptRecord | undefined => {
|
||||
if (line.indexOf(marker) < 0) return undefined;
|
||||
if (parsed === undefined) parsed = parseMainThreadRecord(line);
|
||||
return parsed ?? undefined;
|
||||
};
|
||||
if (this.withModel && this.tail.model === undefined) {
|
||||
const entry = record('"assistant"');
|
||||
if (entry?.type === "assistant") this.tail.model = concreteModel(entry.message?.model);
|
||||
}
|
||||
if (!this.modeDone) this.visitForMode(record);
|
||||
return (!this.withModel || this.tail.model !== undefined) && this.modeDone;
|
||||
}
|
||||
|
||||
private visitForMode(record: (marker: string) => TranscriptRecord | undefined): void {
|
||||
const modeEntry = record('"permissionMode"');
|
||||
if (
|
||||
modeEntry?.type === "user" &&
|
||||
typeof modeEntry.permissionMode === "string" &&
|
||||
modeEntry.permissionMode.trim() !== ""
|
||||
) {
|
||||
const mode = modeEntry.permissionMode.trim();
|
||||
this.modeDone = true;
|
||||
if (!(this.planExited && mode === "plan")) this.tail.permissionMode = mode;
|
||||
return;
|
||||
}
|
||||
if (record('"plan_mode_exit"')?.attachment?.type === "plan_mode_exit") {
|
||||
this.planExited = true;
|
||||
return;
|
||||
}
|
||||
const human = record('"human"');
|
||||
if (human?.type === "user" && human.origin?.kind === "human") this.modeDone = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The parsed record of one line, or null for a subagent record or a bad line. */
|
||||
function parseMainThreadRecord(line: Buffer): TranscriptRecord | null {
|
||||
let entry: unknown;
|
||||
try {
|
||||
entry = JSON.parse(line.toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!entry || typeof entry !== "object") return null;
|
||||
const record = entry as TranscriptRecord;
|
||||
return record.isSidechain === true ? null : record;
|
||||
}
|
||||
@@ -1,853 +0,0 @@
|
||||
/**
|
||||
* The mapping of Claude Code output to ACP session updates: content blocks
|
||||
* (`toAcpNotifications`) and partial stream events
|
||||
* (`streamEventToAcpNotifications`) become message chunks, thoughts, tool
|
||||
* calls and plans. The live stream and the `session/load` replay of both
|
||||
* protocol versions use it; v2 converts the v1 updates it returns.
|
||||
*/
|
||||
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { SDKPartialAssistantMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
|
||||
import type {
|
||||
BetaContentBlock,
|
||||
BetaRawContentBlockDelta,
|
||||
} from "@anthropic-ai/sdk/resources/beta.mjs";
|
||||
import type { AcpClient } from "./acp-client.js";
|
||||
import { clientSupportsSubagents } from "./acp-subagents.js";
|
||||
import { approvedPlan, planModeUpdate } from "./exit-plan.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { checklistPlanUpdate, todoWritePlanUpdate, type SubagentChecklists } from "./plans.js";
|
||||
import { ClientCapabilities as ToolCallClientCapabilities } from "./tool-calls/client-capabilities.js";
|
||||
import type { ToolCallFieldTracker } from "./tool-calls/field-tracker.js";
|
||||
import { AcpToolCallRenderer, type ToolUpdateMeta } from "./tool-calls/renderer.js";
|
||||
import { parseToolResultMeta } from "./tool-result-meta.js";
|
||||
import {
|
||||
applyTaskCreate,
|
||||
applyTaskList,
|
||||
applyTaskUpdate,
|
||||
changedTaskPlanEntries,
|
||||
type ClaudePlanEntry,
|
||||
completeHookCallback,
|
||||
hasHookCallback,
|
||||
parseTaskCreateOutput,
|
||||
parseTaskListOutput,
|
||||
parseTaskUpdateOutput,
|
||||
planEntries,
|
||||
registerHookCallback,
|
||||
type TaskState,
|
||||
unregisterHookCallback,
|
||||
} from "./tools.js";
|
||||
import { unreachable } from "./utils.js";
|
||||
|
||||
/** Attributes a report to the Agent/Task tool call of the subagent that made it. */
|
||||
export function stampParentToolUseId(
|
||||
update: SessionNotification["update"],
|
||||
parentToolUseId: string,
|
||||
) {
|
||||
update._meta = {
|
||||
...update._meta,
|
||||
claudeCode: {
|
||||
...((update._meta?.claudeCode as Record<string, unknown> | undefined) ?? {}),
|
||||
parentToolUseId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type ToolUseCache = {
|
||||
[key: string]: {
|
||||
type: "tool_use" | "server_tool_use" | "mcp_tool_use";
|
||||
id: string;
|
||||
name: string;
|
||||
input: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
type StreamedToolInput = {
|
||||
id: string;
|
||||
name: string;
|
||||
partialJson: string;
|
||||
inString: boolean;
|
||||
escaped: boolean;
|
||||
objectDepth: number;
|
||||
arrayDepth: number;
|
||||
/** Offset of the most recent comma at the top level of the input object
|
||||
* (-1 before the first). Everything before it is a complete field. */
|
||||
lastTopLevelComma: number;
|
||||
/** The comma offset the last emitted refinement was sliced at (-1 before the
|
||||
* first), so a field boundary only triggers one recovery attempt. */
|
||||
emittedThroughComma: number;
|
||||
};
|
||||
|
||||
export type StreamedToolInputCache = Map<string, Map<number, StreamedToolInput>>;
|
||||
|
||||
/**
|
||||
* Advance the lexer state across the fragment appended since the last delta:
|
||||
* just enough JSON awareness (string/escape, nesting depth) to spot commas
|
||||
* that sit at the top level of the input object — everything before such a
|
||||
* comma is a set of complete fields. Returns true once the input object's
|
||||
* closing brace arrives.
|
||||
*
|
||||
* The lexer reads the fragment itself, never `partialJson` by index. V8 keeps a
|
||||
* string built with `+=` as a chain of parts, and the first index access
|
||||
* copies the whole chain into one flat string. An index scan of `partialJson`
|
||||
* would copy the whole input on each delta, so a large Write would cost
|
||||
* quadratic time. A test in `acp-agent.test.ts` checks this.
|
||||
*/
|
||||
function scanStreamedToolInput(state: StreamedToolInput, fragment: string): boolean {
|
||||
const offset = state.partialJson.length;
|
||||
state.partialJson += fragment;
|
||||
let complete = false;
|
||||
for (let index = 0; index < fragment.length; index++) {
|
||||
const character = fragment[index];
|
||||
if (state.inString) {
|
||||
if (state.escaped) {
|
||||
state.escaped = false;
|
||||
} else if (character === "\\") {
|
||||
state.escaped = true;
|
||||
} else if (character === '"') {
|
||||
state.inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === '"') {
|
||||
state.inString = true;
|
||||
} else if (character === "{") {
|
||||
state.objectDepth++;
|
||||
} else if (character === "}") {
|
||||
state.objectDepth--;
|
||||
if (state.objectDepth === 0) {
|
||||
complete = true;
|
||||
}
|
||||
} else if (character === "[") {
|
||||
state.arrayDepth++;
|
||||
} else if (character === "]") {
|
||||
state.arrayDepth--;
|
||||
} else if (character === "," && state.objectDepth === 1 && state.arrayDepth === 0) {
|
||||
state.lastTopLevelComma = offset + index;
|
||||
}
|
||||
}
|
||||
return complete;
|
||||
}
|
||||
|
||||
/** Parse the complete top-level fields before a top-level comma by closing the
|
||||
* object at that boundary. */
|
||||
function recoveredToolInput(prefix: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const value: unknown = JSON.parse(prefix + "}");
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the ACP `messageId` for a Claude SDK message (live) or a persisted
|
||||
* transcript message (replay) so chunk grouping is identical in both views.
|
||||
*
|
||||
* Assistant turns are keyed by the Anthropic API message id (`message.id`),
|
||||
* which is identical at `message_start`, on the consolidated assistant message,
|
||||
* and in the persisted transcript — unlike the per-`stream_event` uuid, which is
|
||||
* unique per event and never persisted. User messages have no API id, but they
|
||||
* are never streamed, so their (stable) SDK uuid is used instead. ACP message
|
||||
* ids are opaque strings, so no particular format is required.
|
||||
*/
|
||||
export function messageIdForGrouping(message: {
|
||||
type?: string;
|
||||
uuid?: string | null;
|
||||
message?: unknown;
|
||||
}): string | undefined {
|
||||
if (message.type === "assistant") {
|
||||
const inner = message.message;
|
||||
const apiId =
|
||||
inner && typeof inner === "object" && "id" in inner
|
||||
? (inner as { id?: unknown }).id
|
||||
: undefined;
|
||||
if (typeof apiId === "string" && apiId.length > 0) {
|
||||
return apiId;
|
||||
}
|
||||
}
|
||||
return typeof message.uuid === "string" && message.uuid.length > 0 ? message.uuid : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamps an ACP `messageId` onto a session update, but only on the message/
|
||||
* thought chunk variants that carry one — tool_call/plan/etc. updates never do.
|
||||
* No-op when `messageId` is falsy, so callers can pass it through unconditionally.
|
||||
*/
|
||||
function applyMessageId(
|
||||
update: SessionNotification["update"],
|
||||
messageId: string | undefined,
|
||||
): void {
|
||||
if (
|
||||
messageId &&
|
||||
(update.sessionUpdate === "agent_message_chunk" ||
|
||||
update.sessionUpdate === "user_message_chunk" ||
|
||||
update.sessionUpdate === "agent_thought_chunk")
|
||||
) {
|
||||
update.messageId = messageId;
|
||||
}
|
||||
}
|
||||
|
||||
/** Built-in tools that drive the task list (headless/SDK sessions use these
|
||||
* instead of TodoWrite). Their tool_use/tool_result are surfaced as `plan`
|
||||
* snapshots rather than as tool_calls. */
|
||||
function isTaskTool(toolName: string): boolean {
|
||||
return (
|
||||
toolName === "TaskCreate" ||
|
||||
toolName === "TaskUpdate" ||
|
||||
toolName === "TaskList" ||
|
||||
toolName === "TaskGet"
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the streamed tool_use path surfaces this tool as a standalone
|
||||
* `tool_call`. TodoWrite is rendered as a `plan` and Task* tools are
|
||||
* suppressed (their plan snapshot is emitted at tool_result time), so neither
|
||||
* produces a streamed tool_call/tool_call_update — which means a
|
||||
* permission-surfaced tool_call for them (see `ensureToolCallEmitted`) must be
|
||||
* resolved explicitly at tool_result time. */
|
||||
function shouldEmitToolCall(toolName: string): boolean {
|
||||
return toolName !== "TodoWrite" && !isTaskTool(toolName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderer of the notification functions: the agent's tool call
|
||||
* capabilities when they are passed, else those of the ACP capabilities.
|
||||
*/
|
||||
function toolCallRenderer(options?: {
|
||||
clientCapabilities?: ClientCapabilities;
|
||||
toolCallCapabilities?: ToolCallClientCapabilities;
|
||||
replay?: boolean;
|
||||
}): AcpToolCallRenderer {
|
||||
return options?.toolCallCapabilities
|
||||
? new AcpToolCallRenderer(options.toolCallCapabilities, options.replay)
|
||||
: AcpToolCallRenderer.for(options?.clientCapabilities, options?.replay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an SDKAssistantMessage (Claude) to a SessionNotification (ACP).
|
||||
* Only handles text, image, and thinking chunks for now.
|
||||
*/
|
||||
export function toAcpNotifications(
|
||||
content: string | ContentBlockParam[] | BetaContentBlock[] | BetaRawContentBlockDelta[],
|
||||
role: "assistant" | "user",
|
||||
sessionId: string,
|
||||
toolUseCache: ToolUseCache,
|
||||
client: AcpClient,
|
||||
logger: Logger,
|
||||
options?: {
|
||||
registerHooks?: boolean;
|
||||
clientCapabilities?: ClientCapabilities;
|
||||
// The agent's tool call capabilities. They win over clientCapabilities,
|
||||
// and carry what ACP capabilities cannot (ToolCallClientCapabilities.v2).
|
||||
toolCallCapabilities?: ToolCallClientCapabilities;
|
||||
parentToolUseId?: string | null;
|
||||
cwd?: string;
|
||||
taskState?: TaskState;
|
||||
// The subagent TodoWrite checklists that the client holds in the session.
|
||||
// Mutated in place.
|
||||
subagentChecklists?: SubagentChecklists;
|
||||
// Tracks tool_use ids already emitted as a `tool_call` so a permission
|
||||
// request (which emits the tool_call eagerly) and the streamed tool_use
|
||||
// chunk don't both emit one — whichever arrives second emits a
|
||||
// `tool_call_update` instead. Mutated in place. When omitted, the
|
||||
// tool_call/update decision falls back to `toolUseCache` presence (the
|
||||
// historical single-source behavior).
|
||||
emittedToolCalls?: Set<string>;
|
||||
// False while the input of a streamed tool_use still streams: the first
|
||||
// tool_call then leaves `rawInput` out, and the consolidated message
|
||||
// sends it once it is complete.
|
||||
inputComplete?: boolean;
|
||||
// Remembers the fields sent for each open tool call. When present, a
|
||||
// tool_call_update carries only the fields that changed, and an update
|
||||
// with nothing new is dropped. Mutated in place.
|
||||
toolCallFields?: ToolCallFieldTracker;
|
||||
// Opaque id identifying the message these chunks belong to (ACP message ids
|
||||
// are opaque strings — no particular format is required). Attached to
|
||||
// user/agent message and thought chunks so clients can group streamed chunks
|
||||
// into a single message. Omit it (leave undefined) when unknown — never send
|
||||
// an explicit `null`.
|
||||
messageId?: string;
|
||||
// The SDK user message's `tool_use_result`: the structured Output object of
|
||||
// the tool_result this message carries (shape is per-tool). Used to render
|
||||
// Agent/Task results from the structured subagent report instead of the raw
|
||||
// text (which ends in a model-directed agentId/usage trailer).
|
||||
toolUseResult?: unknown;
|
||||
// The SDK user message's `tool_result_meta` sidecar, passed raw (it's
|
||||
// untyped in sdk.d.ts) and validated by `parseToolResultMeta`. Stamps
|
||||
// denied/interrupted tool_call_updates with why the tool never ran.
|
||||
toolResultMeta?: unknown;
|
||||
// True when the content is a result of the work that a `session/cancel`
|
||||
// stopped. An error result then ends a run that the cancel aborted,
|
||||
// whichever kind the SDK stamped on it (see `resultStatus`).
|
||||
cancelled?: boolean;
|
||||
// True when the content comes from the history of a loaded session.
|
||||
replay?: boolean;
|
||||
},
|
||||
): SessionNotification[] {
|
||||
const taskState = options?.taskState ?? new Map();
|
||||
const registerHooks = options?.registerHooks !== false;
|
||||
const renderer = toolCallRenderer(options);
|
||||
if (typeof content === "string") {
|
||||
if (content.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const update: SessionNotification["update"] = {
|
||||
sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: content,
|
||||
},
|
||||
};
|
||||
applyMessageId(update, options?.messageId);
|
||||
|
||||
if (options?.parentToolUseId) stampParentToolUseId(update, options.parentToolUseId);
|
||||
|
||||
return [{ sessionId, update }];
|
||||
}
|
||||
|
||||
// `tool_use_result` is message-level and carries no tool_use_id of its own:
|
||||
// it describes "the" tool_result block of the message it rode in on. If
|
||||
// several tool_result blocks were ever batched into one message it couldn't
|
||||
// be attributed, so it is only honored when the message carries exactly one.
|
||||
const toolUseResult =
|
||||
options?.toolUseResult !== undefined &&
|
||||
content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result")
|
||||
.length === 1
|
||||
? options.toolUseResult
|
||||
: undefined;
|
||||
|
||||
// Unlike `tool_use_result`, entries carry their own tool_use_id, so batched
|
||||
// messages need no single-block guard.
|
||||
const toolResultMeta = parseToolResultMeta(options?.toolResultMeta);
|
||||
const output = [];
|
||||
// Only handle the first chunk for streaming; extend as needed for batching
|
||||
for (const chunk of content) {
|
||||
let update: SessionNotification["update"] | null = null;
|
||||
// The tool call that this chunk finishes, if it is a tool result.
|
||||
let finishedToolCallId: string | undefined;
|
||||
// The plan that this chunk approves, if it is an ExitPlanMode result.
|
||||
let approvedPlanUpdate: SessionNotification["update"] | undefined;
|
||||
switch (chunk.type) {
|
||||
case "text":
|
||||
case "text_delta": {
|
||||
if (chunk.text) {
|
||||
update = {
|
||||
sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: chunk.text,
|
||||
},
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "image":
|
||||
update = {
|
||||
sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
||||
content: {
|
||||
type: "image",
|
||||
data: chunk.source.type === "base64" ? chunk.source.data : "",
|
||||
mimeType: chunk.source.type === "base64" ? chunk.source.media_type : "",
|
||||
uri: chunk.source.type === "url" ? chunk.source.url : undefined,
|
||||
},
|
||||
};
|
||||
break;
|
||||
case "thinking":
|
||||
case "thinking_delta": {
|
||||
// Recent models default `thinking.display` to "omitted", which streams
|
||||
// signature-only thinking blocks whose text is empty.
|
||||
if (chunk.thinking) {
|
||||
update = {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: chunk.thinking,
|
||||
},
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "tool_use":
|
||||
case "server_tool_use":
|
||||
case "mcp_tool_use": {
|
||||
const alreadyCached = chunk.id in toolUseCache;
|
||||
toolUseCache[chunk.id] = chunk;
|
||||
if (chunk.name === "TodoWrite") {
|
||||
// @ts-expect-error - sometimes input is empty object or undefined
|
||||
if (Array.isArray(chunk.input?.todos)) {
|
||||
update = todoWritePlanUpdate(planEntries(chunk.input as { todos: ClaudePlanEntry[] }), {
|
||||
planOperations: options?.clientCapabilities?.plan != null,
|
||||
parentToolUseId: options?.parentToolUseId,
|
||||
// With native subagent sessions, an update of a subagent goes
|
||||
// to the subagent's session (see NativeSubagentRuntime).
|
||||
childSessions: clientSupportsSubagents(options?.clientCapabilities),
|
||||
shown: options?.subagentChecklists,
|
||||
});
|
||||
}
|
||||
} else if (isTaskTool(chunk.name)) {
|
||||
// Task* tool_use is suppressed; the plan update is emitted at
|
||||
// tool_result time once we have the task ID (for TaskCreate) and
|
||||
// confirmation that the change took effect.
|
||||
} else {
|
||||
// Only register hooks on first encounter to avoid double-firing
|
||||
if (registerHooks && !alreadyCached) {
|
||||
// Capture the tool name in the closure rather than re-reading the
|
||||
// cache when the hook fires. The cache entry is pruned at
|
||||
// tool_result time, and a PostToolUse hook can fire after that, so
|
||||
// closing over the name keeps the diff working without depending on
|
||||
// (or pinning) the cache entry's lifetime.
|
||||
const toolName = chunk.name;
|
||||
const hookToolCallId = chunk.id;
|
||||
registerHookCallback(
|
||||
chunk.id,
|
||||
{
|
||||
onPostToolUseHook: async (toolUseId, _toolInput, toolResponse) => {
|
||||
// The final diff of an Edit or a Write replaces the
|
||||
// optimistic content built from the input. Only the marker
|
||||
// fields of the tool_response travel: the rest repeats
|
||||
// output that the content already carries.
|
||||
const update = await renderer.hookResult(
|
||||
{ id: toolUseId, name: toolName },
|
||||
toolResponse,
|
||||
options?.cwd,
|
||||
);
|
||||
if (!update) return;
|
||||
if (options?.parentToolUseId) {
|
||||
stampParentToolUseId(update, options.parentToolUseId);
|
||||
}
|
||||
// The final result may replace a pinned approval patch.
|
||||
if (
|
||||
options?.toolCallFields &&
|
||||
!options.toolCallFields.apply(update, { replacePinnedContent: true })
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await client.sessionUpdate({ sessionId, update });
|
||||
},
|
||||
onRelease: () => options?.toolCallFields?.finishHook(hookToolCallId),
|
||||
},
|
||||
sessionId,
|
||||
);
|
||||
}
|
||||
|
||||
let rawInput;
|
||||
try {
|
||||
rawInput = JSON.parse(JSON.stringify(chunk.input));
|
||||
} catch {
|
||||
// ignore if we can't turn it to JSON
|
||||
}
|
||||
const toolUse = { id: chunk.id, name: chunk.name, input: rawInput };
|
||||
|
||||
// Emit a `tool_call` only the first time this id surfaces to the
|
||||
// client; afterwards refine it with a `tool_call_update`. The first
|
||||
// surface may be this stream chunk OR an earlier permission request
|
||||
// (see `ensureToolCallEmitted`), so emission is tracked separately
|
||||
// from `toolUseCache`. Without an `emittedToolCalls` set we fall back
|
||||
// to cache presence — the historical streaming-only behavior.
|
||||
const emittedToolCalls = options?.emittedToolCalls;
|
||||
const alreadyEmitted = emittedToolCalls ? emittedToolCalls.has(chunk.id) : alreadyCached;
|
||||
emittedToolCalls?.add(chunk.id);
|
||||
|
||||
// A permission request surfaced the tool call with its complete
|
||||
// input. The empty input at the stream start has nothing to add.
|
||||
if (alreadyEmitted && options?.inputComplete === false) break;
|
||||
update = alreadyEmitted
|
||||
? // Already surfaced (full assistant message after streaming, or a
|
||||
// permission request emitted it first): refine it with the
|
||||
// complete input.
|
||||
renderer.refinement(toolUse, options?.cwd)
|
||||
: // First surface (streaming content_block_start or replay).
|
||||
renderer.toolCall(toolUse, {
|
||||
cwd: options?.cwd,
|
||||
inputComplete: options?.inputComplete,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "advisor_tool_result": {
|
||||
// Advisor results arrive in assistant content, including encrypted advice.
|
||||
// Resolve the server tool through the normal result path without rendering
|
||||
// opaque ciphertext. Server tools have no later PostToolUse hook to await.
|
||||
const result = chunk.content;
|
||||
unregisterHookCallback(chunk.tool_use_id);
|
||||
output.push(
|
||||
...toAcpNotifications(
|
||||
[
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: chunk.tool_use_id,
|
||||
is_error: result.type === "advisor_tool_result_error",
|
||||
content:
|
||||
result.type === "advisor_result"
|
||||
? result.text
|
||||
: result.type === "advisor_redacted_result"
|
||||
? "Advisor guidance applied server-side."
|
||||
: `Advisor error: ${result.error_code}`,
|
||||
},
|
||||
],
|
||||
role,
|
||||
sessionId,
|
||||
toolUseCache,
|
||||
client,
|
||||
logger,
|
||||
options,
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case "tool_result":
|
||||
case "tool_search_tool_result":
|
||||
case "web_fetch_tool_result":
|
||||
case "web_search_tool_result":
|
||||
case "code_execution_tool_result":
|
||||
case "bash_code_execution_tool_result":
|
||||
case "text_editor_code_execution_tool_result":
|
||||
case "mcp_tool_result": {
|
||||
const wasEmitted = options?.emittedToolCalls?.has(chunk.tool_use_id) === true;
|
||||
options?.emittedToolCalls?.delete(chunk.tool_use_id);
|
||||
completeHookCallback(chunk.tool_use_id);
|
||||
finishedToolCallId = chunk.tool_use_id;
|
||||
// Why this is_error result carries harness prose instead of tool
|
||||
// output (user-rejected / interrupted / …), when the SDK said so.
|
||||
// Spread into the claudeCode meta of every update emitted below; the
|
||||
// untracked-tool fallback can't carry it (claudeCode metas always
|
||||
// carry `toolName`, which is unknown there).
|
||||
const nonExecution = toolResultMeta?.get(chunk.tool_use_id);
|
||||
const toolUse = toolUseCache[chunk.tool_use_id];
|
||||
if (!toolUse) {
|
||||
// The permission flow may have surfaced this tool_call even though
|
||||
// its tool_use never reached the cache (e.g. the assistant message
|
||||
// carrying it was dropped by the cancelled-turn guard and a straggler
|
||||
// result landed later). Resolve the surfaced call anyway so it can't
|
||||
// stay pending in the client forever; without the cache entry the
|
||||
// tool name is unknown, so no claudeCode meta is attached.
|
||||
if (wasEmitted) {
|
||||
output.push({
|
||||
sessionId,
|
||||
update: {
|
||||
toolCallId: chunk.tool_use_id,
|
||||
sessionUpdate: "tool_call_update" as const,
|
||||
status: renderer.resultStatus(
|
||||
"is_error" in chunk && chunk.is_error === true,
|
||||
nonExecution,
|
||||
{ cancelled: options?.cancelled },
|
||||
),
|
||||
rawOutput: chunk.content,
|
||||
},
|
||||
});
|
||||
}
|
||||
logger.error(
|
||||
`[claude-agent-acp] Got a tool result for tool use that wasn't tracked: ${chunk.tool_use_id}`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// A permission request may have surfaced a plan-rendered (TodoWrite) or
|
||||
// suppressed (Task*) tool as a real tool_call so the request referenced
|
||||
// a tool call the client knows about (see `ensureToolCallEmitted`,
|
||||
// issue #851). The branches below never emit a tool_call_update for
|
||||
// those tools, which would leave the surfaced call pending in the
|
||||
// client forever — resolve it here. `wasEmitted` is only ever true for
|
||||
// these tools via the permission flow: the streamed plan/suppressed
|
||||
// branches don't record emissions.
|
||||
if (wasEmitted && !shouldEmitToolCall(toolUse.name)) {
|
||||
output.push({
|
||||
sessionId,
|
||||
update: {
|
||||
_meta: {
|
||||
claudeCode: {
|
||||
toolName: toolUse.name,
|
||||
...(nonExecution ?? {}),
|
||||
...(options?.parentToolUseId ? { parentToolUseId: options.parentToolUseId } : {}),
|
||||
},
|
||||
} satisfies ToolUpdateMeta,
|
||||
toolCallId: chunk.tool_use_id,
|
||||
sessionUpdate: "tool_call_update" as const,
|
||||
status: renderer.resultStatus(
|
||||
"is_error" in chunk && chunk.is_error === true,
|
||||
nonExecution,
|
||||
{ cancelled: options?.cancelled },
|
||||
),
|
||||
rawOutput: chunk.content,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (isTaskTool(toolUse.name)) {
|
||||
// Headless/SDK sessions emit Task* tools instead of TodoWrite.
|
||||
// TaskCreate / TaskUpdate mutate the accumulated task list. TaskList
|
||||
// reconciles it from the SDK's authoritative snapshot, which repairs
|
||||
// resumed or compacted sessions whose creating calls are no longer in
|
||||
// replay history. TaskGet is read-only and remains suppressed. Plan
|
||||
// updates always carry the full accumulated snapshot, mirroring the
|
||||
// legacy TodoWrite behavior.
|
||||
const isError = "is_error" in chunk && chunk.is_error;
|
||||
let shouldEmitTaskPlan = false;
|
||||
if (!isError) {
|
||||
if (toolUse.name === "TaskCreate") {
|
||||
applyTaskCreate(
|
||||
taskState,
|
||||
toolUse.input as Parameters<typeof applyTaskCreate>[1],
|
||||
parseTaskCreateOutput(toolUseResult) ?? parseTaskCreateOutput(chunk.content),
|
||||
);
|
||||
shouldEmitTaskPlan = true;
|
||||
} else if (toolUse.name === "TaskUpdate") {
|
||||
const input = toolUse.input as Parameters<typeof applyTaskUpdate>[1];
|
||||
const output =
|
||||
parseTaskUpdateOutput(toolUseResult, input?.taskId) ??
|
||||
parseTaskUpdateOutput(chunk.content, input?.taskId);
|
||||
// Older CLI transcripts have no structured output, so retain the
|
||||
// input-based fallback. When an output is available, only apply a
|
||||
// confirmed update for the same task.
|
||||
if (!output || (output.success && output.taskId === input?.taskId)) {
|
||||
applyTaskUpdate(taskState, input);
|
||||
shouldEmitTaskPlan = true;
|
||||
}
|
||||
} else if (toolUse.name === "TaskList") {
|
||||
const output =
|
||||
parseTaskListOutput(toolUseResult) ?? parseTaskListOutput(chunk.content);
|
||||
if (output) {
|
||||
applyTaskList(taskState, output);
|
||||
shouldEmitTaskPlan = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
const entries = shouldEmitTaskPlan
|
||||
? changedTaskPlanEntries(taskState, renderer.capabilities.air.client)
|
||||
: undefined;
|
||||
if (entries) {
|
||||
update = checklistPlanUpdate(entries, options?.clientCapabilities?.plan != null);
|
||||
}
|
||||
} else if (toolUse.name !== "TodoWrite") {
|
||||
// A command sends its output first, then the exit and the status.
|
||||
const [finalUpdate, ...rest] = renderer
|
||||
.result(toolUse, chunk as Parameters<AcpToolCallRenderer["result"]>[1], {
|
||||
structured: toolUseResult,
|
||||
nonExecution,
|
||||
cancelled: options?.cancelled,
|
||||
})
|
||||
.reverse();
|
||||
for (const outputUpdate of rest.reverse()) {
|
||||
if (options?.parentToolUseId) {
|
||||
stampParentToolUseId(outputUpdate, options.parentToolUseId);
|
||||
}
|
||||
output.push({ sessionId, update: outputUpdate });
|
||||
}
|
||||
// An approved plan of the main conversation becomes the session's
|
||||
// markdown plan, after the tool call's result. An approval that
|
||||
// clears the context ends the tool with an error result instead, and
|
||||
// the restart into the fresh context publishes that plan (see
|
||||
// ExitPlanCoordinator.restart).
|
||||
if (
|
||||
toolUse.name === "ExitPlanMode" &&
|
||||
options?.clientCapabilities?.plan &&
|
||||
!options.parentToolUseId &&
|
||||
!("is_error" in chunk && chunk.is_error)
|
||||
) {
|
||||
const plan = approvedPlan(toolUse.input, toolUseResult);
|
||||
if (plan) {
|
||||
approvedPlanUpdate = planModeUpdate(
|
||||
plan,
|
||||
renderer.capabilities.air.client ? toolUse.id : undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
update = finalUpdate;
|
||||
}
|
||||
// The tool_use is fully resolved now — drop it so a long session doesn't
|
||||
// retain every tool call. The PostToolUse hook (Edit/Write diffs) closes
|
||||
// over the tool name and no longer reads the cache, so pruning here is
|
||||
// safe regardless of hook/result ordering.
|
||||
delete toolUseCache[chunk.tool_use_id];
|
||||
break;
|
||||
}
|
||||
|
||||
case "document":
|
||||
case "search_result":
|
||||
case "redacted_thinking":
|
||||
case "input_json_delta":
|
||||
case "citations_delta":
|
||||
case "signature_delta":
|
||||
case "container_upload":
|
||||
case "compaction":
|
||||
case "compaction_delta":
|
||||
case "fallback":
|
||||
case "mcp_tool_listing":
|
||||
break;
|
||||
|
||||
default:
|
||||
unreachable(chunk, logger);
|
||||
break;
|
||||
}
|
||||
if (update) {
|
||||
if (options?.parentToolUseId) stampParentToolUseId(update, options.parentToolUseId);
|
||||
applyMessageId(update, options?.messageId);
|
||||
// A tool result is final, so it may replace a pinned approval patch,
|
||||
// for example with the error text of a rejected Edit.
|
||||
if (
|
||||
!options?.toolCallFields ||
|
||||
options.toolCallFields.apply(update, {
|
||||
replacePinnedContent: finishedToolCallId !== undefined,
|
||||
})
|
||||
) {
|
||||
output.push({ sessionId, update });
|
||||
}
|
||||
}
|
||||
if (approvedPlanUpdate) output.push({ sessionId, update: approvedPlanUpdate });
|
||||
if (finishedToolCallId !== undefined) {
|
||||
// The PostToolUse hook can still send the final diff, so the fields
|
||||
// stay tracked until its callback leaves the registry.
|
||||
options?.toolCallFields?.finishResult(
|
||||
finishedToolCallId,
|
||||
hasHookCallback(finishedToolCallId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export function streamEventToAcpNotifications(
|
||||
message: SDKPartialAssistantMessage,
|
||||
sessionId: string,
|
||||
toolUseCache: ToolUseCache,
|
||||
client: AcpClient,
|
||||
logger: Logger,
|
||||
options?: {
|
||||
clientCapabilities?: ClientCapabilities;
|
||||
// See toAcpNotifications.
|
||||
toolCallCapabilities?: ToolCallClientCapabilities;
|
||||
cwd?: string;
|
||||
taskState?: TaskState;
|
||||
subagentChecklists?: SubagentChecklists;
|
||||
emittedToolCalls?: Set<string>;
|
||||
toolCallFields?: ToolCallFieldTracker;
|
||||
messageId?: string;
|
||||
streamedToolInputs?: StreamedToolInputCache;
|
||||
},
|
||||
): SessionNotification[] {
|
||||
const event = message.event;
|
||||
const streamKey = message.parent_tool_use_id ?? "";
|
||||
const streamedToolInputs = options?.streamedToolInputs;
|
||||
const forwardedOptions = {
|
||||
clientCapabilities: options?.clientCapabilities,
|
||||
toolCallCapabilities: options?.toolCallCapabilities,
|
||||
parentToolUseId: message.parent_tool_use_id,
|
||||
cwd: options?.cwd,
|
||||
taskState: options?.taskState,
|
||||
subagentChecklists: options?.subagentChecklists,
|
||||
emittedToolCalls: options?.emittedToolCalls,
|
||||
toolCallFields: options?.toolCallFields,
|
||||
messageId: options?.messageId,
|
||||
};
|
||||
switch (event.type) {
|
||||
case "content_block_start": {
|
||||
const block = event.content_block;
|
||||
if (
|
||||
streamedToolInputs &&
|
||||
(block.type === "tool_use" ||
|
||||
block.type === "server_tool_use" ||
|
||||
block.type === "mcp_tool_use")
|
||||
) {
|
||||
let inputsForMessage = streamedToolInputs.get(streamKey);
|
||||
if (!inputsForMessage) {
|
||||
inputsForMessage = new Map();
|
||||
streamedToolInputs.set(streamKey, inputsForMessage);
|
||||
}
|
||||
inputsForMessage.set(event.index, {
|
||||
id: block.id,
|
||||
name: block.name,
|
||||
partialJson: "",
|
||||
inString: false,
|
||||
escaped: false,
|
||||
objectDepth: 0,
|
||||
arrayDepth: 0,
|
||||
lastTopLevelComma: -1,
|
||||
emittedThroughComma: -1,
|
||||
});
|
||||
}
|
||||
// The input of a streamed tool_use starts empty and streams after this
|
||||
// event, so the tool_call waits for the complete input.
|
||||
return toAcpNotifications([block], "assistant", sessionId, toolUseCache, client, logger, {
|
||||
...forwardedOptions,
|
||||
inputComplete: false,
|
||||
});
|
||||
}
|
||||
case "content_block_delta": {
|
||||
if (event.delta.type === "input_json_delta") {
|
||||
const streamedInput = streamedToolInputs?.get(streamKey)?.get(event.index);
|
||||
if (!streamedInput) return [];
|
||||
|
||||
if (scanStreamedToolInput(streamedInput, event.delta.partial_json)) {
|
||||
// Input complete: the consolidated assistant message replays the
|
||||
// block with its full input and refines the call there; emitting
|
||||
// here too would send a duplicate identical update.
|
||||
const inputsForMessage = streamedToolInputs?.get(streamKey);
|
||||
inputsForMessage?.delete(event.index);
|
||||
if (inputsForMessage?.size === 0) streamedToolInputs?.delete(streamKey);
|
||||
return [];
|
||||
}
|
||||
if (streamedInput.lastTopLevelComma <= streamedInput.emittedThroughComma) {
|
||||
return [];
|
||||
}
|
||||
streamedInput.emittedThroughComma = streamedInput.lastTopLevelComma;
|
||||
const input = recoveredToolInput(
|
||||
streamedInput.partialJson.slice(0, streamedInput.lastTopLevelComma),
|
||||
);
|
||||
if (!input) return [];
|
||||
// TodoWrite and the Task* tools never surfaced a tool_call to refine.
|
||||
if (!shouldEmitToolCall(streamedInput.name)) return [];
|
||||
const update: SessionNotification["update"] = toolCallRenderer(options).partialRefinement(
|
||||
streamedInput,
|
||||
input,
|
||||
options?.cwd,
|
||||
);
|
||||
if (message.parent_tool_use_id) stampParentToolUseId(update, message.parent_tool_use_id);
|
||||
applyMessageId(update, options?.messageId);
|
||||
// A refinement resends only what changed: rawInput grows with every
|
||||
// field, and title, kind, and locations usually stay the same.
|
||||
if (options?.toolCallFields && !options.toolCallFields.apply(update)) return [];
|
||||
return [{ sessionId, update }];
|
||||
}
|
||||
return toAcpNotifications(
|
||||
[event.delta],
|
||||
"assistant",
|
||||
sessionId,
|
||||
toolUseCache,
|
||||
client,
|
||||
logger,
|
||||
forwardedOptions,
|
||||
);
|
||||
}
|
||||
// No content. `ping` is a Messages-API keep-alive event that the SDK's
|
||||
// `BetaRawMessageStreamEvent` union doesn't include even though the
|
||||
// wire format emits it; the `as never` cast lets us no-op it here
|
||||
// instead of letting it fall through to `unreachable`.
|
||||
case "ping" as never:
|
||||
case "message_delta":
|
||||
return [];
|
||||
// A message boundary ends every input stream on this lane: message_stop is
|
||||
// the normal end, and a message_start clears anything a prior message on
|
||||
// the lane left behind (e.g. a stream cut short mid-block).
|
||||
case "message_start":
|
||||
case "message_stop":
|
||||
streamedToolInputs?.delete(streamKey);
|
||||
return [];
|
||||
case "content_block_stop": {
|
||||
const inputsForMessage = streamedToolInputs?.get(streamKey);
|
||||
inputsForMessage?.delete(event.index);
|
||||
if (inputsForMessage?.size === 0) streamedToolInputs?.delete(streamKey);
|
||||
return [];
|
||||
}
|
||||
|
||||
default:
|
||||
unreachable(event, logger);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
73
src/serve.ts
73
src/serve.ts
@@ -1,73 +0,0 @@
|
||||
import * as v2 from "@agentclientprotocol/sdk/experimental/v2";
|
||||
import { v1AgentApp, type ClaudeAcpAgent } from "./v1/acp-agent.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { nodeToWebReadable, nodeToWebWritable } from "./utils.js";
|
||||
import { v2AgentApp, type AgentHandle } from "./v2/agent.js";
|
||||
|
||||
/**
|
||||
* The ACP versions that the adapter serves: `v1` or `v2` alone, or both with
|
||||
* `auto`, where the client's `initialize` picks the version.
|
||||
*/
|
||||
export type AcpProtocols = "auto" | "v1" | "v2";
|
||||
|
||||
/**
|
||||
* Reads `CLAUDE_AGENT_ACP_PROTOCOL`: unset, empty, or `auto` serves both
|
||||
* versions, and `v1` or `v2` serves that version alone. Throws on any other
|
||||
* value, so that a typo such as `CLAUDE_AGENT_ACP_PROTOCOL=1` fails at startup
|
||||
* instead of silently serving both.
|
||||
*/
|
||||
export function acpProtocolsFromEnv(value: string | undefined): AcpProtocols {
|
||||
if (value === undefined || value === "") return "auto";
|
||||
if (value === "auto" || value === "v1" || value === "v2") return value;
|
||||
throw new Error(
|
||||
`CLAUDE_AGENT_ACP_PROTOCOL must be "auto", "v1", or "v2", not ${JSON.stringify(value)}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Serves ACP on stdio through {@link acpProtocolRouter}. */
|
||||
export function serveAcp(
|
||||
logger: Logger | undefined,
|
||||
options: { protocols: AcpProtocols },
|
||||
): { closed: Promise<void>; dispose(): Promise<void> } {
|
||||
const output = nodeToWebWritable(process.stdout);
|
||||
const input = nodeToWebReadable(process.stdin);
|
||||
// The router opens the connection of the negotiated version only when it
|
||||
// reads `initialize`, so a client that leaves before then leaves no agent.
|
||||
let agent: AgentHandle | undefined;
|
||||
const onAgent = (created: AgentHandle) => {
|
||||
agent = created;
|
||||
};
|
||||
const { closed } = acpProtocolRouter(logger, onAgent, options.protocols, {
|
||||
onV2Agent: onAgent,
|
||||
}).connect(v2.ndJsonStream(output, input));
|
||||
return {
|
||||
closed,
|
||||
dispose: async () => {
|
||||
await agent?.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* 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
|
||||
* has opened it, and `onV2Agent` the agent of a v2 connection, which the
|
||||
* v2 core (`src/v2/`) serves.
|
||||
*/
|
||||
export function acpProtocolRouter(
|
||||
logger: Logger | undefined,
|
||||
onAgent: (agent: ClaudeAcpAgent) => void,
|
||||
protocols: AcpProtocols = "auto",
|
||||
{ onV2Agent = () => {} }: { onV2Agent?: (agent: AgentHandle) => void } = {},
|
||||
): v2.AgentProtocolRouter {
|
||||
const router = v2.agentProtocolRouter();
|
||||
if (protocols !== "v2") router.withV1(v1AgentApp(logger, onAgent));
|
||||
if (protocols !== "v1") {
|
||||
router.withV2(v2AgentApp(logger, onV2Agent));
|
||||
}
|
||||
return router;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/** Shared sentinels and ids for session preferences managed by the adapter. */
|
||||
export const DEFAULT_MODEL_ID = "default";
|
||||
export const DEFAULT_AGENT_ID = "default";
|
||||
export const AGENT_CONFIG_ID = "agent";
|
||||
export const EFFORT_CONFIG_ID = "effort";
|
||||
export const ULTRACODE_CONFIG_ID = "ultracode";
|
||||
@@ -1,244 +0,0 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import {
|
||||
RequestError,
|
||||
type ClientCapabilities,
|
||||
type SessionConfigOption,
|
||||
type SessionModeState,
|
||||
type SetSessionConfigOptionRequest,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { AgentInfo, ModelInfo, Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY,
|
||||
clientSupportsAirCapability,
|
||||
} from "./air-extension.js";
|
||||
import { AGENT_CONFIG_ID, DEFAULT_AGENT_ID } from "./session-config-ids.js";
|
||||
import { buildEffortConfigOption } from "./session-effort.js";
|
||||
import {
|
||||
createFastModeConfigOption,
|
||||
FAST_MODE_CONFIG_ID,
|
||||
resolveFastModeEnabled,
|
||||
type FastModeOptionState,
|
||||
} from "./session-fast-mode.js";
|
||||
import { MODE_CONFIG_ID, SessionModeManager } from "./session-mode.js";
|
||||
import {
|
||||
buildModelConfigOption,
|
||||
MODEL_CONFIG_ID,
|
||||
resolveModelPreference,
|
||||
type SessionModelState,
|
||||
} from "./session-model.js";
|
||||
import {
|
||||
createUltracodeConfigOption,
|
||||
resolveUltracodeEnabled,
|
||||
ULTRACODE_CONFIG_ID,
|
||||
type UltracodeOptionState,
|
||||
} from "./session-ultracode.js";
|
||||
|
||||
// `supportedAgents()` always returns Claude Code's built-in subagents — the
|
||||
// ones used for Task-tool delegation (Explore, Plan, etc.) — even when the user
|
||||
// has configured none of their own. Those aren't meaningful *main-thread*
|
||||
// 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.
|
||||
export const BUILTIN_AGENT_NAMES = new Set([
|
||||
"claude",
|
||||
"general-purpose",
|
||||
"Explore",
|
||||
"Plan",
|
||||
"statusline-setup",
|
||||
]);
|
||||
|
||||
// Value of the synthetic "Default" entry in the agent picker, which maps to the
|
||||
// standard Claude Code agent (`applyFlagSettings({ agent: null })`). It is a
|
||||
// reserved sentinel: a custom agent named exactly this would collide with it
|
||||
// (two options sharing the value, selection silently routing to `null`), so we
|
||||
// exclude that name from discovery.
|
||||
/** Discover user/plugin/project-configured main-thread agents, excluding the
|
||||
* built-in subagents and the reserved "default" sentinel. Returns an empty
|
||||
* list if discovery fails so a flaky control request never blocks session
|
||||
* creation. */
|
||||
export async function discoverCustomAgents(q: Query): Promise<AgentInfo[]> {
|
||||
try {
|
||||
return customAgents(await q.supportedAgents());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** The configured agents of `agents`: neither a built-in subagent nor the "default" sentinel. */
|
||||
export function customAgents(agents: readonly AgentInfo[]): AgentInfo[] {
|
||||
return agents.filter((a) => !BUILTIN_AGENT_NAMES.has(a.name) && a.name !== DEFAULT_AGENT_ID);
|
||||
}
|
||||
|
||||
/** Stable ids for the session config options surfaced via `configOptions`.
|
||||
* Centralized so the option declarations in `buildConfigOptions` and the
|
||||
* handlers in `setSessionConfigOption`/`applyConfigOptionValue` reference the
|
||||
* same identifiers and can't drift apart. */
|
||||
export { MODE_CONFIG_ID };
|
||||
export { AGENT_CONFIG_ID };
|
||||
|
||||
/** Whether the Client advertised support for boolean session config options
|
||||
* (`session.configOptions.boolean`). Agents MUST only send `type: "boolean"`
|
||||
* config options to Clients that opt in; otherwise we fall back to a `select`.
|
||||
* See https://agentclientprotocol.com/rfds/boolean-config-option. */
|
||||
export function clientSupportsBooleanConfigOptions(
|
||||
clientCapabilities?: ClientCapabilities | null,
|
||||
): boolean {
|
||||
return clientCapabilities?.session?.configOptions?.boolean != null;
|
||||
}
|
||||
|
||||
/** Whether the Client advertised the AIR `recommendedValue` capability for
|
||||
* select-style model and effort options. Missing or malformed AIR metadata
|
||||
* retains the legacy `default` entries. */
|
||||
export function clientSupportsRecommendedConfigValue(
|
||||
clientCapabilities?: ClientCapabilities | null,
|
||||
): boolean {
|
||||
return clientSupportsAirCapability(clientCapabilities, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY);
|
||||
}
|
||||
|
||||
export type ConfigOptionPresentation = {
|
||||
/** Replace ambiguous `default` rows with concrete values and advertise the
|
||||
* SDK/adapter recommendation as `_meta.jetbrains.air.recommendedValue`. */
|
||||
useRecommendedValue: boolean;
|
||||
};
|
||||
|
||||
export function buildConfigOptions(
|
||||
modes: SessionModeState,
|
||||
models: SessionModelState,
|
||||
modelInfos: ModelInfo[],
|
||||
currentEffortLevel?: string,
|
||||
agents: AgentInfo[] = [],
|
||||
currentAgent: string = DEFAULT_AGENT_ID,
|
||||
fastMode?: FastModeOptionState,
|
||||
presentation?: ConfigOptionPresentation,
|
||||
ultracode?: UltracodeOptionState,
|
||||
): SessionConfigOption[] {
|
||||
const options: SessionConfigOption[] = [SessionModeManager.configOption(modes)];
|
||||
// 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),
|
||||
);
|
||||
}
|
||||
const effort = buildEffortConfigOption(
|
||||
modelInfos,
|
||||
models.currentModelId,
|
||||
currentEffortLevel,
|
||||
presentation?.useRecommendedValue === true,
|
||||
);
|
||||
if (effort) options.push(effort);
|
||||
|
||||
// Surface the Fast mode toggle only when the current model supports it. The
|
||||
// option renders as a native boolean toggle for Clients that opted in, and a
|
||||
// two-value select otherwise.
|
||||
if (fastMode?.supported) {
|
||||
options.push(
|
||||
createFastModeConfigOption(
|
||||
fastMode.enabled,
|
||||
fastMode.useBooleanOption,
|
||||
fastMode.disabledReason,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Surface the ultracode toggle only while the CLI can run it: dynamic
|
||||
// workflows are enabled and the current model supports it.
|
||||
if (ultracode?.supported) {
|
||||
options.push(createUltracodeConfigOption(ultracode.enabled, ultracode.useBooleanOption));
|
||||
}
|
||||
|
||||
// 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
|
||||
// entry, so we omit the option entirely.
|
||||
if (agents.length > 0) {
|
||||
options.push({
|
||||
id: AGENT_CONFIG_ID,
|
||||
name: "Agent",
|
||||
description: "Main-thread agent persona",
|
||||
type: "select",
|
||||
currentValue: currentAgent,
|
||||
options: [
|
||||
{ value: DEFAULT_AGENT_ID, name: "Default", description: "Standard Claude Code agent" },
|
||||
...agents.map((a) => ({
|
||||
value: a.name,
|
||||
name: a.name,
|
||||
description: a.description || undefined,
|
||||
})),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value that a `session/set_config_option` request sets on `option`, the
|
||||
* option as the session advertised it. The value must match the option's
|
||||
* type: a `type: "boolean"` option takes `true`/`false`, not "on"/"off", and a
|
||||
* `type: "select"` option takes one of its values.
|
||||
*
|
||||
* Fast mode and ultracode give `enabled`: a boolean, or the "on"/"off" select
|
||||
* fallback for clients without boolean config options. A model takes an alias
|
||||
* too, such as "opus" or "sonnet" for a full model id. It is resolved against
|
||||
* `modelInfos` first: those entries carry `resolvedModel`, so a full model id
|
||||
* (in either hint spelling) lands on the right row via the exact tier instead
|
||||
* of a fuzzier one picking a same-family sibling from a different context
|
||||
* lane. The option's own entries (which never carry `resolvedModel`) remain as
|
||||
* 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.
|
||||
*/
|
||||
export function configOptionValue(
|
||||
option: SessionConfigOption,
|
||||
params: SetSessionConfigOptionRequest,
|
||||
modelInfos: ModelInfo[],
|
||||
): { enabled: boolean } | { value: string } {
|
||||
const expectedType = option.type === "boolean" ? "boolean" : "string";
|
||||
if (typeof params.value !== expectedType) {
|
||||
throw RequestError.invalidParams(
|
||||
{ configId: params.configId, value: params.value },
|
||||
`Config option ${params.configId} takes a ${expectedType} value, but received: ${JSON.stringify(params.value)}`,
|
||||
);
|
||||
}
|
||||
if (params.configId === FAST_MODE_CONFIG_ID) return { enabled: resolveFastModeEnabled(params) };
|
||||
if (params.configId === ULTRACODE_CONFIG_ID) {
|
||||
return { enabled: resolveUltracodeEnabled(params) };
|
||||
}
|
||||
if (typeof params.value !== "string") {
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Invalid value for config option ${params.configId}: ${params.value}`,
|
||||
);
|
||||
}
|
||||
const requested = params.value;
|
||||
const allValues =
|
||||
"options" in option && Array.isArray(option.options)
|
||||
? option.options.flatMap((o) => ("options" in o ? o.options : [o]))
|
||||
: [];
|
||||
let validValue = allValues.find((o) => o.value === requested);
|
||||
if (!validValue && params.configId === MODEL_CONFIG_ID) {
|
||||
const toOptionValue = (resolved: ModelInfo | null) =>
|
||||
resolved ? allValues.find((o) => o.value === resolved.value) : undefined;
|
||||
validValue = toOptionValue(resolveModelPreference(modelInfos, requested));
|
||||
if (!validValue) {
|
||||
const optionInfos: ModelInfo[] = allValues.map((o) => ({
|
||||
value: o.value,
|
||||
displayName: o.name,
|
||||
description: o.description ?? "",
|
||||
}));
|
||||
validValue = toOptionValue(resolveModelPreference(optionInfos, requested));
|
||||
}
|
||||
}
|
||||
if (!validValue) {
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Invalid value for config option ${params.configId}: ${requested}`,
|
||||
);
|
||||
}
|
||||
return { value: validValue.value };
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
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 { EFFORT_CONFIG_ID } from "./session-config-ids.js";
|
||||
|
||||
export { EFFORT_CONFIG_ID } from "./session-config-ids.js";
|
||||
|
||||
// The SDK drops `undefined` during JSON transport and only clears a flag-layer
|
||||
// setting when it receives an explicit `null`. Map both an absent picker and
|
||||
// the legacy "default" row to null so a previously applied effort is cleared.
|
||||
export function toSdkEffortLevel(value: string | undefined): EffortLevel | null {
|
||||
return value === undefined || value === "default" ? null : (value as EffortLevel);
|
||||
}
|
||||
|
||||
// Since CLI 2.1.284 an `effortLevel` that changes the level, sent without an
|
||||
// `ultracode` key, turns ultracode off. The CLI's own effort control keeps
|
||||
// ultracode on at any level, so send `ultracode: true` with every effort apply
|
||||
// while the session has ultracode on. When it is off, the key is omitted: an
|
||||
// effort change then leaves ultracode off, as it already was.
|
||||
export function effortFlagSettings(
|
||||
value: string | undefined,
|
||||
ultracode: boolean,
|
||||
): { effortLevel: EffortLevel | null; ultracode?: true } {
|
||||
const effortLevel = toSdkEffortLevel(value);
|
||||
return ultracode ? { effortLevel, ultracode: true } : { effortLevel };
|
||||
}
|
||||
|
||||
/**
|
||||
* `params` without `_meta.claudeCode.options.effort`, for a restart of the
|
||||
* session's query: the restart restores the current effort pin instead of
|
||||
* the one the session was created with.
|
||||
*/
|
||||
export function withoutEffort<T extends { _meta?: unknown }>(params: T): T {
|
||||
const meta = params._meta as
|
||||
{ claudeCode?: { options?: { effort?: unknown } } } | null | undefined;
|
||||
if (meta?.claudeCode?.options?.effort === undefined) {
|
||||
return params;
|
||||
}
|
||||
const options = { ...meta.claudeCode.options };
|
||||
delete options.effort;
|
||||
return { ...params, _meta: { ...meta, claudeCode: { ...meta.claudeCode, options } } };
|
||||
}
|
||||
|
||||
function canonicalizeModelSettingsKey(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/-(\d+m)$/i, "[$1]");
|
||||
}
|
||||
|
||||
/** Resolve the effort the CLI will use: per-model settings first, then the
|
||||
* legacy top-level effort setting. Model settings are keyed by canonical
|
||||
* model name, so try the resolved SDK model before picker and raw IDs. */
|
||||
export function settingsEffortForModel(
|
||||
settings: Settings,
|
||||
modelInfo: ModelInfo | undefined,
|
||||
modelId?: string,
|
||||
): string | undefined {
|
||||
const modelSettings = settings.modelSettings;
|
||||
if (modelSettings) {
|
||||
for (const key of [modelInfo?.resolvedModel, modelInfo?.value, modelId]) {
|
||||
if (key === undefined) continue;
|
||||
const exact = modelSettings[key]?.effortLevel;
|
||||
if (typeof exact === "string") return exact;
|
||||
const canonicalKey = canonicalizeModelSettingsKey(key);
|
||||
const matchingEntry = Object.entries(modelSettings).find(
|
||||
([candidate]) => canonicalizeModelSettingsKey(candidate) === canonicalKey,
|
||||
);
|
||||
const perModel = matchingEntry?.[1]?.effortLevel;
|
||||
if (typeof perModel === "string") return perModel;
|
||||
}
|
||||
}
|
||||
return settings.effortLevel;
|
||||
}
|
||||
|
||||
/** Programmatic query settings have higher priority than file-backed settings,
|
||||
* matching the SDK. Keep unrelated per-model entries from lower tiers while
|
||||
* replacing entries supplied at the programmatic tier. */
|
||||
export function mergeEffortSettings(base: Settings, override: Settings | undefined): Settings {
|
||||
if (!override) return base;
|
||||
const overriddenModelKeys = new Set(
|
||||
Object.keys(override.modelSettings ?? {}).map(canonicalizeModelSettingsKey),
|
||||
);
|
||||
const unshadowedBaseModelSettings = Object.fromEntries(
|
||||
Object.entries(base.modelSettings ?? {}).filter(
|
||||
([key]) => !overriddenModelKeys.has(canonicalizeModelSettingsKey(key)),
|
||||
),
|
||||
);
|
||||
return {
|
||||
...base,
|
||||
...override,
|
||||
modelSettings:
|
||||
base.modelSettings || override.modelSettings
|
||||
? { ...unshadowedBaseModelSettings, ...override.modelSettings }
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function effortLevelName(level: string): string {
|
||||
return level
|
||||
.split(/[_-]/)
|
||||
.map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
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 options = [
|
||||
...(useRecommendedValue ? [] : [{ value: "default", name: "Default" }]),
|
||||
...supportedLevels.map((level) => ({
|
||||
value: level,
|
||||
name: effortLevelName(level),
|
||||
})),
|
||||
];
|
||||
const includes = (level: string) =>
|
||||
(!useRecommendedValue && level === "default") || (supportedLevels as string[]).includes(level);
|
||||
const currentValue =
|
||||
currentEffortLevel && includes(currentEffortLevel)
|
||||
? currentEffortLevel
|
||||
: useRecommendedValue
|
||||
? recommendedEffort
|
||||
: "default";
|
||||
|
||||
return {
|
||||
id: EFFORT_CONFIG_ID,
|
||||
name: "Effort",
|
||||
description: "Available effort levels for this model",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue,
|
||||
options,
|
||||
...(useRecommendedValue
|
||||
? {
|
||||
_meta: withAirMeta(undefined, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, recommendedEffort),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A session's effort bookkeeping: the level the user pinned through the
|
||||
* picker, and the level last applied to the SDK's flag layer. */
|
||||
export type EffortState = {
|
||||
pinned: string | undefined;
|
||||
applied: string | undefined;
|
||||
};
|
||||
|
||||
/** The effort after a switch to `newModelInfo`, before the option is rebuilt
|
||||
* (see {@link settleEffortAfterModelSwitch}). */
|
||||
export type EffortSwitch = {
|
||||
/** The effort to build the new model's option with. */
|
||||
seed: string | undefined;
|
||||
/** Whether the user's pin is one of the new model's levels. */
|
||||
pinnedForNewModel: boolean;
|
||||
before: EffortState;
|
||||
/** The level applied before the switch, restored if the sync fails. */
|
||||
appliedBeforeSwitch: string | undefined;
|
||||
};
|
||||
|
||||
/** The effort seed of a model switch. It depends on who owns the choice: a
|
||||
* user pin made through the ACP picker this session lives at the SDK's flag
|
||||
* layer and follows the session across switches, so it carries forward.
|
||||
* Otherwise the CLI resolves effort itself from the persisted settings — the
|
||||
* NEW model's `modelSettings` entry first (the CLI persists /effort per
|
||||
* model), then the legacy top-level value — so the option shows what it
|
||||
* will actually run instead of dragging the old model's value along. */
|
||||
export function effortForModelSwitch(input: {
|
||||
state: EffortState;
|
||||
/** The current value of the effort option, if it is shown. */
|
||||
displayed: string | undefined;
|
||||
newModelInfo: ModelInfo | undefined;
|
||||
modelId: string;
|
||||
/** The merged effort settings (see {@link mergeEffortSettings}). */
|
||||
settings: Settings;
|
||||
useRecommendedValue: boolean;
|
||||
}): EffortSwitch {
|
||||
const { state, displayed, newModelInfo, useRecommendedValue } = input;
|
||||
const pinned = state.pinned;
|
||||
const pinnedForNewModel =
|
||||
pinned !== undefined &&
|
||||
newModelInfo?.supportsEffort === true &&
|
||||
newModelInfo.supportedEffortLevels?.some((level) => level === pinned) === true;
|
||||
return {
|
||||
seed: pinnedForNewModel
|
||||
? pinned
|
||||
: settingsEffortForModel(input.settings, newModelInfo, input.modelId),
|
||||
pinnedForNewModel,
|
||||
before: state,
|
||||
appliedBeforeSwitch:
|
||||
state.applied ??
|
||||
(useRecommendedValue && typeof displayed === "string" && displayed !== "default"
|
||||
? displayed
|
||||
: pinned),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the effort of a model switch to the SDK's flag layer, once the new
|
||||
* model's effort `option` is built from `change.seed`. Returns the new state
|
||||
* and the option to show (undefined to hide it).
|
||||
*
|
||||
* Opted-in clients (`useRecommendedValue`) apply the concrete displayed effort
|
||||
* on every switch, including settings-derived values, so a previous automatic
|
||||
* flag cannot shadow the new model's settings. This does not create a user
|
||||
* pin. For other clients, the flag is synced only when a user pin is lost
|
||||
* across the switch — the new model clamped it away, where the flag must be
|
||||
* cleared too or the SDK would keep running the old pin invisibly.
|
||||
* Settings-derived seeds are display-only: the CLI resolves persisted effort
|
||||
* itself, and pinning it at the flag layer would shadow the per-model values
|
||||
* on every later switch.
|
||||
*
|
||||
* The model switch already succeeded, so a failed sync is returned as
|
||||
* `error`, not thrown. The old bookkeeping stays, and the unapplied value is
|
||||
* never shown: the option shows the last applied value when the new model can
|
||||
* select it, else it is hidden until a later switch rebuilds it.
|
||||
*/
|
||||
export async function settleEffortAfterModelSwitch(
|
||||
change: EffortSwitch,
|
||||
option: SessionConfigOption | undefined,
|
||||
ultracode: boolean,
|
||||
useRecommendedValue: boolean,
|
||||
applyFlagSettings: (settings: ReturnType<typeof effortFlagSettings>) => Promise<void>,
|
||||
): Promise<{ state: EffortState; option: SessionConfigOption | undefined; error?: unknown }> {
|
||||
const { pinnedForNewModel, before } = change;
|
||||
const sync = useRecommendedValue || (before.pinned !== undefined && !pinnedForNewModel);
|
||||
if (!sync) {
|
||||
return {
|
||||
state: pinnedForNewModel ? { pinned: before.pinned, applied: before.pinned } : before,
|
||||
option,
|
||||
};
|
||||
}
|
||||
const newEffort = typeof option?.currentValue === "string" ? option.currentValue : undefined;
|
||||
try {
|
||||
// A legacy client's unpinned effort is display-only: the CLI resolves the
|
||||
// persisted value for the new model. When an old user pin is no longer
|
||||
// supported, clear the flag layer instead of replacing it with that
|
||||
// displayed value. Opted-in clients deliberately apply their concrete
|
||||
// displayed effort.
|
||||
await applyFlagSettings(
|
||||
effortFlagSettings(useRecommendedValue ? newEffort : undefined, ultracode),
|
||||
);
|
||||
return {
|
||||
state: {
|
||||
pinned: pinnedForNewModel ? before.pinned : undefined,
|
||||
applied: useRecommendedValue && newEffort !== "default" ? newEffort : undefined,
|
||||
},
|
||||
option,
|
||||
};
|
||||
} catch (error) {
|
||||
const applied = change.appliedBeforeSwitch;
|
||||
const selectable =
|
||||
applied !== undefined &&
|
||||
option?.type === "select" &&
|
||||
option.options.some((entry) =>
|
||||
"value" in entry
|
||||
? entry.value === applied
|
||||
: entry.options.some((nested) => nested.value === applied),
|
||||
);
|
||||
return {
|
||||
state: { pinned: before.pinned, applied },
|
||||
option:
|
||||
selectable && option?.type === "select" ? { ...option, currentValue: applied } : undefined,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/**
|
||||
* Session options that come from the agent's environment, shared by the v1
|
||||
* core and the v2 core.
|
||||
*/
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as path from "node:path";
|
||||
import type { Options, Settings, ThinkingConfig } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/** Translate the legacy `MAX_THINKING_TOKENS` env var, plus the optional
|
||||
* `CLAUDE_CODE_THINKING_DISPLAY` env var, into the SDK's `thinking` option.
|
||||
* The `maxThinkingTokens` option it used to feed is deprecated and reduced
|
||||
* to on/off on current models, so map the value to explicit thinking config
|
||||
* instead: unset → `undefined` (SDK default, adaptive on models that support
|
||||
* it) unless a display mode is requested, in which case it becomes explicit
|
||||
* `adaptive`; `0` → disabled; a positive integer → a fixed token budget.
|
||||
* Anything else is ignored with a warning. `CLAUDE_CODE_THINKING_DISPLAY`
|
||||
* must be `summarized` or `omitted`; it has no effect when thinking is
|
||||
* disabled. */
|
||||
export function resolveThinkingConfig(
|
||||
rawTokens: string | undefined,
|
||||
rawDisplay: string | undefined,
|
||||
logger: { error: (...args: unknown[]) => void },
|
||||
): ThinkingConfig | undefined {
|
||||
let display: "summarized" | "omitted" | undefined;
|
||||
if (rawDisplay !== undefined) {
|
||||
if (rawDisplay === "summarized" || rawDisplay === "omitted") {
|
||||
display = rawDisplay;
|
||||
} else {
|
||||
logger.error(
|
||||
`Ignoring CLAUDE_CODE_THINKING_DISPLAY: expected 'summarized' or 'omitted', got '${rawDisplay}'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (rawTokens === undefined) {
|
||||
return display ? { type: "adaptive", display } : undefined;
|
||||
}
|
||||
const parsed = Number.parseInt(rawTokens, 10);
|
||||
if (Number.isNaN(parsed) || parsed < 0) {
|
||||
logger.error(
|
||||
`Ignoring MAX_THINKING_TOKENS: expected a non-negative integer, got '${rawTokens}'.`,
|
||||
);
|
||||
return display ? { type: "adaptive", display } : undefined;
|
||||
}
|
||||
return parsed === 0
|
||||
? { type: "disabled" }
|
||||
: { type: "enabled", budgetTokens: parsed, ...(display && { display }) };
|
||||
}
|
||||
|
||||
/** The `CLAUDE_MODEL_CONFIG` JSON: Bedrock model overrides and an allowlist, say. */
|
||||
function parseModelConfig(
|
||||
raw: string | undefined,
|
||||
): { modelOverrides?: Record<string, string>; availableModels?: string[] } | undefined {
|
||||
if (!raw) return undefined;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error("CLAUDE_MODEL_CONFIG must be a JSON object");
|
||||
}
|
||||
const result: { modelOverrides?: Record<string, string>; availableModels?: string[] } = {};
|
||||
if (parsed.modelOverrides !== undefined) result.modelOverrides = parsed.modelOverrides;
|
||||
if (parsed.availableModels !== undefined) result.availableModels = parsed.availableModels;
|
||||
return Object.keys(result).length > 0 ? result : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The programmatic settings of a session, before the provider routing: the
|
||||
* models of `CLAUDE_MODEL_CONFIG`, then the client's `settings` option, an
|
||||
* object or a file path relative to `cwd`. Throws for a `CLAUDE_MODEL_CONFIG`
|
||||
* that is no JSON object, before it reads the file.
|
||||
*/
|
||||
export async function configuredSettings(
|
||||
provided: Options["settings"],
|
||||
cwd: string,
|
||||
): Promise<Settings | undefined> {
|
||||
const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG);
|
||||
const object =
|
||||
typeof provided === "string"
|
||||
? (JSON.parse(await fs.readFile(path.resolve(cwd, provided), "utf8")) as Settings)
|
||||
: (provided as Settings | undefined);
|
||||
return modelConfig ? { ...modelConfig, ...object } : object;
|
||||
}
|
||||
@@ -1,486 +0,0 @@
|
||||
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
getSessionMessages,
|
||||
type SDKAssistantMessageError,
|
||||
USAGE_LIMIT_ERROR_PREFIXES,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
AIR_SESSION_FAILURE_CAPABILITY,
|
||||
airCapabilityMeta,
|
||||
clientSupportsAirCapability,
|
||||
withAirMeta,
|
||||
} from "./air-extension.js";
|
||||
|
||||
export function airSessionFailureCapabilityMeta(...additionalCapabilities: string[]) {
|
||||
return airCapabilityMeta(AIR_SESSION_FAILURE_CAPABILITY, ...additionalCapabilities);
|
||||
}
|
||||
|
||||
export type ClaudeFailureKind =
|
||||
| "access_denied"
|
||||
| "advisory"
|
||||
| "auth_required"
|
||||
| "bad_request"
|
||||
| "budget_exhausted"
|
||||
| "context_exhausted"
|
||||
| "internal_error"
|
||||
| "overloaded"
|
||||
| "provider_error"
|
||||
| "quota_exhausted"
|
||||
| "rate_limited"
|
||||
| "transport_lost"
|
||||
| "worker_shutdown";
|
||||
|
||||
type AirSessionFailureCategory =
|
||||
"connection" | "access" | "limit" | "request" | "service" | "unknown";
|
||||
|
||||
type AirSessionFailureSeverity = "warning" | "error";
|
||||
type AirSessionFailureAction = "retry" | "login" | "new_session";
|
||||
|
||||
type SessionFailureRecoveryPolicy =
|
||||
"never" | "next_attempt" | "real_model_success" | "auth_status" | "runtime_rebind";
|
||||
|
||||
export type PublishedSessionFailure = {
|
||||
id: string;
|
||||
revision: number;
|
||||
kind: ClaudeFailureKind;
|
||||
category: AirSessionFailureCategory;
|
||||
turnId?: string;
|
||||
severity: AirSessionFailureSeverity;
|
||||
title: string;
|
||||
details?: string;
|
||||
/** A machine-readable refinement of `kind`, e.g. the `--hide-claude-auth`
|
||||
* subscription guard's reason on an `auth_required` failure. Absent for a
|
||||
* plain sign-out. */
|
||||
reason?: string;
|
||||
actions: AirSessionFailureAction[];
|
||||
recoveryPolicy: SessionFailureRecoveryPolicy;
|
||||
};
|
||||
|
||||
type SessionFailureOptions = {
|
||||
turnId?: string;
|
||||
sessionScoped?: boolean;
|
||||
title?: string;
|
||||
details?: string;
|
||||
severity?: AirSessionFailureSeverity;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
export type SessionFailureState = {
|
||||
epoch: string;
|
||||
revisions: Map<string, number>;
|
||||
active: Map<string, PublishedSessionFailure>;
|
||||
nextIncident?: number;
|
||||
lastNotice?: { title: string; id: string };
|
||||
};
|
||||
|
||||
type Logger = {
|
||||
error: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
export function createSessionFailureState(): SessionFailureState {
|
||||
return {
|
||||
epoch: randomUUID(),
|
||||
revisions: new Map(),
|
||||
active: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
const AIR_FAILURE_POLICY: Record<
|
||||
ClaudeFailureKind,
|
||||
{
|
||||
category: AirSessionFailureCategory;
|
||||
actions: AirSessionFailureAction[];
|
||||
fallbackTitle: string;
|
||||
}
|
||||
> = {
|
||||
// Account or credential blocks that signing in again cannot fix: the
|
||||
// organization must complete verification, or the cloud provider's
|
||||
// credentials must be refreshed outside Claude. No `login` action, and not
|
||||
// sticky like `auth_required` (nothing clears at `auth_status`).
|
||||
access_denied: {
|
||||
category: "service",
|
||||
actions: ["retry"],
|
||||
fallbackTitle: "Claude could not access the account or provider credentials.",
|
||||
},
|
||||
advisory: {
|
||||
category: "unknown",
|
||||
actions: [],
|
||||
fallbackTitle: "Claude reported a notice.",
|
||||
},
|
||||
auth_required: {
|
||||
category: "access",
|
||||
actions: ["login"],
|
||||
fallbackTitle: "Sign in to continue using Claude.",
|
||||
},
|
||||
bad_request: {
|
||||
category: "request",
|
||||
actions: [],
|
||||
fallbackTitle: "Claude could not process this request.",
|
||||
},
|
||||
budget_exhausted: {
|
||||
category: "limit",
|
||||
actions: ["new_session"],
|
||||
fallbackTitle: "This Claude session reached its configured budget.",
|
||||
},
|
||||
context_exhausted: {
|
||||
category: "limit",
|
||||
actions: ["new_session"],
|
||||
fallbackTitle: "This Claude turn reached its configured limit.",
|
||||
},
|
||||
internal_error: {
|
||||
category: "service",
|
||||
actions: ["retry", "new_session"],
|
||||
fallbackTitle: "Claude Agent encountered an internal error.",
|
||||
},
|
||||
overloaded: {
|
||||
category: "service",
|
||||
actions: ["retry"],
|
||||
fallbackTitle: "Claude is temporarily overloaded.",
|
||||
},
|
||||
provider_error: {
|
||||
category: "service",
|
||||
actions: ["retry"],
|
||||
fallbackTitle: "The model provider reported an error.",
|
||||
},
|
||||
quota_exhausted: {
|
||||
category: "limit",
|
||||
actions: [],
|
||||
fallbackTitle: "The Claude account has no available quota.",
|
||||
},
|
||||
rate_limited: {
|
||||
category: "limit",
|
||||
actions: ["retry"],
|
||||
fallbackTitle: "Claude is temporarily rate limited.",
|
||||
},
|
||||
transport_lost: {
|
||||
category: "connection",
|
||||
actions: ["new_session"],
|
||||
fallbackTitle: "The connection to Claude was lost.",
|
||||
},
|
||||
worker_shutdown: {
|
||||
category: "connection",
|
||||
actions: ["new_session"],
|
||||
fallbackTitle: "The Claude worker is shutting down.",
|
||||
},
|
||||
};
|
||||
|
||||
export function sessionFailureMeta(failure: PublishedSessionFailure) {
|
||||
return withAirMeta(undefined, AIR_SESSION_FAILURE_CAPABILITY, {
|
||||
id: failure.id,
|
||||
revision: failure.revision,
|
||||
category: failure.category,
|
||||
severity: failure.severity,
|
||||
title: failure.title,
|
||||
...(failure.details ? { details: failure.details } : {}),
|
||||
...(failure.reason ? { reason: failure.reason } : {}),
|
||||
actions: failure.actions,
|
||||
});
|
||||
}
|
||||
|
||||
/** `getSessionMessages` deliberately exposes only the API message and strips
|
||||
* transcript-level `error` / `isApiErrorMessage` fields. The SDK exports the
|
||||
* exact stable prefixes used by its synthetic usage-limit errors, so replay
|
||||
* can recover this one typed failure without matching arbitrary model prose. */
|
||||
export function assistantMessageText(apiMessage: unknown): string | undefined {
|
||||
if (!apiMessage || typeof apiMessage !== "object") return undefined;
|
||||
const { content } = apiMessage as { content?: unknown };
|
||||
if (typeof content === "string") return content || undefined;
|
||||
if (!Array.isArray(content)) return undefined;
|
||||
const text = content
|
||||
.map((block) =>
|
||||
block &&
|
||||
typeof block === "object" &&
|
||||
"type" in block &&
|
||||
block.type === "text" &&
|
||||
"text" in block &&
|
||||
typeof block.text === "string"
|
||||
? block.text
|
||||
: "",
|
||||
)
|
||||
.join("");
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
export function isSyntheticUsageLimitMessage(apiMessage: unknown): boolean {
|
||||
if (!apiMessage || typeof apiMessage !== "object") return false;
|
||||
const { model } = apiMessage as { model?: unknown };
|
||||
if (model !== "<synthetic>") return false;
|
||||
const text = assistantMessageText(apiMessage);
|
||||
if (!text) return false;
|
||||
return USAGE_LIMIT_ERROR_PREFIXES.some((prefix) => text.startsWith(prefix));
|
||||
}
|
||||
|
||||
export function activeUsageLimitMessage(
|
||||
messages: Awaited<ReturnType<typeof getSessionMessages>>,
|
||||
): { uuid: string; title: string } | undefined {
|
||||
let active: { uuid: string; title: string } | undefined;
|
||||
for (const message of messages) {
|
||||
if (message.type !== "assistant" || message.parent_tool_use_id !== null) continue;
|
||||
if (isSyntheticUsageLimitMessage(message.message)) {
|
||||
const title = assistantMessageText(message.message);
|
||||
if (title) active = { uuid: message.uuid, title };
|
||||
continue;
|
||||
}
|
||||
const model =
|
||||
message.message && typeof message.message === "object" && "model" in message.message
|
||||
? message.message.model
|
||||
: undefined;
|
||||
// A later real model answer proves the account recovered. Synthetic
|
||||
// local-command/interruption messages do not: they can be appended while
|
||||
// the provider remains unavailable.
|
||||
if (model !== undefined && model !== "<synthetic>") active = undefined;
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
export function supportsAirSessionFailures(capabilities?: ClientCapabilities): boolean {
|
||||
return clientSupportsAirCapability(capabilities, AIR_SESSION_FAILURE_CAPABILITY);
|
||||
}
|
||||
|
||||
function sessionFailureRecoveryPolicy(
|
||||
kind: ClaudeFailureKind,
|
||||
turnId?: string,
|
||||
): SessionFailureRecoveryPolicy {
|
||||
switch (kind) {
|
||||
case "advisory":
|
||||
return "never";
|
||||
case "auth_required":
|
||||
return "auth_status";
|
||||
case "transport_lost":
|
||||
case "worker_shutdown":
|
||||
return "runtime_rebind";
|
||||
case "quota_exhausted":
|
||||
return "real_model_success";
|
||||
default:
|
||||
return turnId ? "next_attempt" : "real_model_success";
|
||||
}
|
||||
}
|
||||
|
||||
/** Owns the AIR failure lifecycle for both the live consumer and history replay.
|
||||
* Published revisions become active only after delivery succeeds; recovery only
|
||||
* removes internal active state because transcript records are historical. */
|
||||
export class SessionFailureController {
|
||||
private readonly sessionId: string;
|
||||
private readonly state: SessionFailureState;
|
||||
private readonly capabilities?: ClientCapabilities;
|
||||
private readonly isCurrent: () => boolean;
|
||||
private readonly sendUpdate: (notification: SessionNotification) => Promise<void>;
|
||||
private readonly logger: Logger;
|
||||
|
||||
constructor(options: {
|
||||
sessionId: string;
|
||||
state: SessionFailureState;
|
||||
capabilities?: ClientCapabilities;
|
||||
isCurrent: () => boolean;
|
||||
sendUpdate: (notification: SessionNotification) => Promise<void>;
|
||||
logger: Logger;
|
||||
}) {
|
||||
this.sessionId = options.sessionId;
|
||||
this.state = options.state;
|
||||
this.capabilities = options.capabilities;
|
||||
this.isCurrent = options.isCurrent;
|
||||
this.sendUpdate = options.sendUpdate;
|
||||
this.logger = options.logger;
|
||||
}
|
||||
|
||||
private isSupported(): boolean {
|
||||
return supportsAirSessionFailures(this.capabilities);
|
||||
}
|
||||
|
||||
private async emit(failure: PublishedSessionFailure): Promise<boolean> {
|
||||
if (!this.isCurrent()) {
|
||||
this.logger.error(
|
||||
`Session ${this.sessionId}: ignored AIR session failure from a stale consumer`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.sendUpdate({
|
||||
sessionId: this.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "session_info_update",
|
||||
_meta: sessionFailureMeta(failure),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Session ${this.sessionId}: failed to publish AIR session failure: ${error}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a session-scoped error of `kind` is active. A turn-scoped
|
||||
* warning of the same kind (an `api_retry` notice) does not count: it
|
||||
* reports a retry in progress, not the state the error would publish.
|
||||
*
|
||||
* `reason` refines `kind`, so the active record must carry the same one,
|
||||
* and an omitted `reason` matches only a record with no reason. A plain
|
||||
* sign-out and the `--hide-claude-auth` subscription refusal are both
|
||||
* `auth_required`, but they tell the user different things. Neither may
|
||||
* suppress the other. */
|
||||
hasActiveSessionError(kind: ClaudeFailureKind, reason?: string): boolean {
|
||||
for (const failure of this.state.active.values()) {
|
||||
if (
|
||||
failure.kind === kind &&
|
||||
failure.severity === "error" &&
|
||||
failure.turnId === undefined &&
|
||||
failure.reason === reason
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
recordActive(failure: PublishedSessionFailure): void {
|
||||
this.state.revisions.set(failure.id, failure.revision);
|
||||
this.state.active.set(failure.id, failure);
|
||||
this.state.lastNotice =
|
||||
failure.kind === "advisory" ? { title: failure.title, id: failure.id } : undefined;
|
||||
}
|
||||
|
||||
async clear(
|
||||
shouldClear: (failure: PublishedSessionFailure) => boolean = () => true,
|
||||
): Promise<boolean> {
|
||||
if (!this.isSupported()) return true;
|
||||
this.state.lastNotice = undefined;
|
||||
for (const failure of [...this.state.active.values()]) {
|
||||
if (!shouldClear(failure)) continue;
|
||||
this.state.active.delete(failure.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async prepare(
|
||||
kind: ClaudeFailureKind,
|
||||
failureOptions: SessionFailureOptions = {},
|
||||
): Promise<PublishedSessionFailure | undefined> {
|
||||
if (!this.isSupported() || !this.isCurrent()) return undefined;
|
||||
const policy = AIR_FAILURE_POLICY[kind];
|
||||
const title = failureOptions.title || policy.fallbackTitle;
|
||||
if (kind === "advisory") {
|
||||
const id =
|
||||
this.state.lastNotice?.title === title
|
||||
? this.state.lastNotice.id
|
||||
: `${this.sessionId}:notice:${this.state.epoch}:${this.state.nextIncident ?? 1}`;
|
||||
if (this.state.lastNotice?.title !== title) {
|
||||
this.state.nextIncident = (this.state.nextIncident ?? 1) + 1;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
revision: (this.state.revisions.get(id) ?? 0) + 1,
|
||||
kind,
|
||||
category: policy.category,
|
||||
severity: "warning",
|
||||
title,
|
||||
...(failureOptions.details ? { details: failureOptions.details } : {}),
|
||||
actions: policy.actions,
|
||||
recoveryPolicy: sessionFailureRecoveryPolicy(kind),
|
||||
};
|
||||
}
|
||||
const id =
|
||||
failureOptions.turnId && !failureOptions.sessionScoped
|
||||
? `${failureOptions.turnId}:error`
|
||||
: `${this.sessionId}:session-error:${this.state.epoch}:${this.state.nextIncident ?? 1}`;
|
||||
if (!failureOptions.turnId || failureOptions.sessionScoped) {
|
||||
this.state.nextIncident = (this.state.nextIncident ?? 1) + 1;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
revision: (this.state.revisions.get(id) ?? 0) + 1,
|
||||
kind,
|
||||
category: policy.category,
|
||||
severity: failureOptions.severity ?? "error",
|
||||
title,
|
||||
...(failureOptions.details ? { details: failureOptions.details } : {}),
|
||||
...(failureOptions.reason ? { reason: failureOptions.reason } : {}),
|
||||
actions: failureOptions.severity === "warning" ? [] : policy.actions,
|
||||
recoveryPolicy: sessionFailureRecoveryPolicy(
|
||||
kind,
|
||||
failureOptions.turnId && !failureOptions.sessionScoped ? failureOptions.turnId : undefined,
|
||||
),
|
||||
...(failureOptions.turnId && !failureOptions.sessionScoped
|
||||
? { turnId: failureOptions.turnId }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
async publish(
|
||||
kind: ClaudeFailureKind,
|
||||
failureOptions: SessionFailureOptions = {},
|
||||
): Promise<void> {
|
||||
const failure = await this.prepare(kind, failureOptions);
|
||||
if (!failure) return;
|
||||
if (await this.emit(failure)) this.recordActive(failure);
|
||||
}
|
||||
|
||||
async restore(
|
||||
id: string,
|
||||
kind: ClaudeFailureKind,
|
||||
title: string,
|
||||
active = true,
|
||||
): Promise<boolean> {
|
||||
if (!this.isSupported() || !this.isCurrent()) return false;
|
||||
const policy = AIR_FAILURE_POLICY[kind];
|
||||
const failure: PublishedSessionFailure = {
|
||||
id,
|
||||
revision: (this.state.revisions.get(id) ?? 0) + 1,
|
||||
kind,
|
||||
category: policy.category,
|
||||
severity: "error",
|
||||
title,
|
||||
actions: policy.actions,
|
||||
recoveryPolicy: sessionFailureRecoveryPolicy(kind),
|
||||
};
|
||||
if (!(await this.emit(failure))) return false;
|
||||
this.state.revisions.set(failure.id, failure.revision);
|
||||
if (active) {
|
||||
this.state.active.set(failure.id, failure);
|
||||
} else {
|
||||
this.state.active.delete(failure.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function providerFailureCategory(
|
||||
errorKind?: SDKAssistantMessageError,
|
||||
isUsageLimit = false,
|
||||
): ClaudeFailureKind {
|
||||
if (isUsageLimit) return "quota_exhausted";
|
||||
switch (errorKind) {
|
||||
case "authentication_failed":
|
||||
case "oauth_org_not_allowed":
|
||||
return "auth_required";
|
||||
case "billing_error":
|
||||
case "account_on_hold":
|
||||
return "quota_exhausted";
|
||||
// 403 `permission_error` with error_code `verification_required` (the
|
||||
// organization must verify at the console), and a Bedrock/Vertex/Foundry
|
||||
// credential the CLI could not load (transient: it retries, and asks the
|
||||
// user to check or refresh the credentials). Both are access failures
|
||||
// `/login` does not repair, so they get their own lane rather than
|
||||
// `auth_required`'s login action and sticky auth_status recovery.
|
||||
case "verification_required":
|
||||
case "cloud_credential_error":
|
||||
return "access_denied";
|
||||
case "rate_limit":
|
||||
return "rate_limited";
|
||||
case "overloaded":
|
||||
return "overloaded";
|
||||
case "invalid_request":
|
||||
case "model_not_found":
|
||||
return "bad_request";
|
||||
case "max_output_tokens":
|
||||
return "context_exhausted";
|
||||
case "server_error":
|
||||
case "unknown":
|
||||
case undefined:
|
||||
return "provider_error";
|
||||
default:
|
||||
return "provider_error";
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
/**
|
||||
* The Fast mode toggle of a session: its config option, the value a
|
||||
* `session/set_config_option` request sets, and the state Claude Code reports
|
||||
* (`fast_mode_state` and `fast_mode_disabled_reason`, on `system`/init and on
|
||||
* results). Shared by the v1 core and the v2 core.
|
||||
*/
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
SessionConfigOption,
|
||||
SetSessionConfigOptionRequest,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { FastModeDisabledReason, FastModeState } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { sentenceCase } from "./session-notices.js";
|
||||
|
||||
export const FAST_MODE_CONFIG_ID = "fast";
|
||||
|
||||
/** Select-fallback values used when the client has not opted into boolean
|
||||
* config options (see {@link createFastModeConfigOption}). */
|
||||
export const FAST_MODE_ON = "on";
|
||||
export const FAST_MODE_OFF = "off";
|
||||
const FAST_MODE_DESCRIPTION = "Faster responses on supported models";
|
||||
|
||||
/** Map the SDK's tri-state `fast_mode_state` onto the boolean config toggle.
|
||||
* `cooldown` (fast mode temporarily suspended after a rate limit, per the SDK
|
||||
* docs) keeps the toggle on so it reflects the user's intent — only an
|
||||
* explicit `off` clears it. */
|
||||
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). */
|
||||
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",
|
||||
model_not_allowed: "not available for the selected model",
|
||||
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)",
|
||||
};
|
||||
|
||||
/** 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. */
|
||||
export function normalizeFastModeDisabledReason(
|
||||
reason: FastModeDisabledReason | undefined,
|
||||
): FastModeDisabledReason | undefined {
|
||||
return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? 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
|
||||
* control.
|
||||
*
|
||||
* `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
|
||||
* stay on. Ignored while enabled: a reason reported alongside an `on`/`cooldown`
|
||||
* state isn't blocking anything right now. */
|
||||
export function createFastModeConfigOption(
|
||||
enabled: boolean,
|
||||
useBooleanOption: boolean,
|
||||
disabledReason?: FastModeDisabledReason,
|
||||
): SessionConfigOption {
|
||||
const explanation = enabled
|
||||
? undefined
|
||||
: disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
|
||||
const base = {
|
||||
id: FAST_MODE_CONFIG_ID,
|
||||
name: "Fast mode",
|
||||
description: explanation ? `${FAST_MODE_DESCRIPTION} — ${explanation}` : FAST_MODE_DESCRIPTION,
|
||||
category: "model_config",
|
||||
} as const;
|
||||
|
||||
if (useBooleanOption) {
|
||||
return { ...base, type: "boolean", currentValue: enabled };
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
type: "select",
|
||||
currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
|
||||
options: [
|
||||
{ value: FAST_MODE_ON, name: "On" },
|
||||
{ value: FAST_MODE_OFF, name: "Off" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolve the requested Fast mode value from a `session/set_config_option`
|
||||
* request. Accepts a native boolean (boolean-capable Clients) or the
|
||||
* "on"/"off" select-fallback strings. */
|
||||
export function resolveFastModeEnabled(params: SetSessionConfigOptionRequest): boolean {
|
||||
const value = params.value;
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
}
|
||||
if (value === FAST_MODE_ON) {
|
||||
return true;
|
||||
}
|
||||
if (value === FAST_MODE_OFF) {
|
||||
return false;
|
||||
}
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Invalid value for config option ${FAST_MODE_CONFIG_ID}: ${value}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Per-model Fast mode state threaded into `buildConfigOptions`. The
|
||||
* option is only surfaced when the current model `supported`s fast mode. */
|
||||
export type FastModeOptionState = {
|
||||
supported: boolean;
|
||||
enabled: boolean;
|
||||
/** Whether the Client opted into boolean config options. */
|
||||
useBooleanOption: boolean;
|
||||
/** Latest explainable `fast_mode_disabled_reason`, folded into the option's
|
||||
* description while the toggle reads off. */
|
||||
disabledReason?: FastModeDisabledReason;
|
||||
};
|
||||
|
||||
/** What a reported `fast_mode_state` changes in a Fast mode toggle that the
|
||||
* current model shows. The SDK can flip fast mode independently of the
|
||||
* user — e.g. back to `on` once a rate-limit `cooldown` clears — so
|
||||
* definitive on/off changes are mirrored into the option.
|
||||
*
|
||||
* Undefined when nothing changes: an absent state, a `cooldown` (a transient
|
||||
* suspension of an already-enabled fast mode: the toggle stays as-is rather
|
||||
* than flapping, and a stray cooldown never enables a toggle the user has
|
||||
* 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
|
||||
* 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. */
|
||||
export function fastModeStateChange(
|
||||
current: { enabled: boolean; disabledReason?: FastModeDisabledReason },
|
||||
state: FastModeState | undefined,
|
||||
reason: FastModeDisabledReason | undefined,
|
||||
):
|
||||
| { enabled: boolean; disabledReason?: FastModeDisabledReason; notice?: FastModeOffNotice }
|
||||
| undefined {
|
||||
if (state === undefined || state === "cooldown") return undefined;
|
||||
const enabled = state === "on";
|
||||
// A reason only describes an off state; drop any that rides an `on` report
|
||||
// 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;
|
||||
if (!current.enabled || enabled || explanation === undefined) {
|
||||
return { enabled, disabledReason };
|
||||
}
|
||||
return {
|
||||
enabled,
|
||||
disabledReason,
|
||||
notice: {
|
||||
notice: {
|
||||
severity: "warning",
|
||||
title: "Fast mode turned off",
|
||||
description: `${sentenceCase(explanation)}.`,
|
||||
},
|
||||
transcript: `**Fast mode turned off:** ${explanation}.`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The notice of Fast mode that the SDK turned off, and its transcript line
|
||||
* for a client without `notice` updates. */
|
||||
export type FastModeOffNotice = {
|
||||
notice: { severity: "warning"; title: string; description: string };
|
||||
transcript: string;
|
||||
};
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* The client-set title of a session (`_session/rename`), as `SessionTitles`
|
||||
* guards it against generated titles: once a client named the session, or
|
||||
* while a rename is in flight, no generated title is adopted, and a rename
|
||||
* waits for a generation in flight, whose persisted title would otherwise
|
||||
* land after it.
|
||||
*/
|
||||
export class ExplicitTitle {
|
||||
/** Set once a client named the session. Released by {@link reset}. */
|
||||
private named = false;
|
||||
/** Renames in flight. */
|
||||
private pending = 0;
|
||||
/** Renames started so far, to tell that one ran between two reads. */
|
||||
private started = 0;
|
||||
/** The title generation in flight. */
|
||||
private generation?: Promise<void>;
|
||||
|
||||
/** Whether a generated title must not be adopted. */
|
||||
get active(): boolean {
|
||||
return this.named || this.pending > 0;
|
||||
}
|
||||
|
||||
/** Whether a client named the session and no rename is in flight: a title
|
||||
* stored since by someone else (a `/rename`) may still be adopted. */
|
||||
get settledByClient(): boolean {
|
||||
return this.named && this.pending === 0;
|
||||
}
|
||||
|
||||
/** Changes with every rename that starts. */
|
||||
get renames(): number {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.named = false;
|
||||
}
|
||||
|
||||
/** Tracks a title generation until it ends. */
|
||||
track(generation: Promise<void>): void {
|
||||
this.generation = generation;
|
||||
void generation.finally(() => {
|
||||
if (this.generation === generation) this.generation = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
/** Persists a client title after the generation in flight. `persist`
|
||||
* tells whether the session is named now. When it fails or names nothing
|
||||
* (an archive of an archived session), and no other rename named the
|
||||
* session, `restore` puts the title state back, so a later turn may still
|
||||
* generate a title. */
|
||||
async apply(persist: () => Promise<boolean>, restore: () => void): Promise<void> {
|
||||
this.pending++;
|
||||
this.started++;
|
||||
try {
|
||||
await this.generation;
|
||||
if (await persist()) this.named = true;
|
||||
else if (!this.named && this.pending === 1) restore();
|
||||
} catch (error) {
|
||||
if (!this.named && this.pending === 1) restore();
|
||||
throw error;
|
||||
} finally {
|
||||
this.pending--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
import {
|
||||
RequestError,
|
||||
type SessionConfigOption,
|
||||
type SessionModeState,
|
||||
type SessionNotification,
|
||||
type SetSessionModeRequest,
|
||||
type SetSessionModeResponse,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
ModelInfo,
|
||||
PermissionMode,
|
||||
PermissionResult,
|
||||
Query,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { AIR_KIND_KEY, airOnlyMeta } from "./air-extension.js";
|
||||
import { resolvePermissionMode } from "./permissions/modes.js";
|
||||
import {
|
||||
noticeOrTranscriptUpdate,
|
||||
noticeTranscriptText,
|
||||
sentenceCase,
|
||||
type SessionNotice,
|
||||
} from "./session-notices.js";
|
||||
|
||||
export const MODE_CONFIG_ID = "mode";
|
||||
export const AUTO_MODE_FALLBACK: PermissionMode = "acceptEdits";
|
||||
|
||||
/** Reads on after the bold label in the transcript line; capitalized when it
|
||||
* stands alone as a notice description. */
|
||||
const AUTO_MODE_FALLBACK_REASON =
|
||||
"the selected model does not support Auto mode; using Accept edits instead.";
|
||||
const AUTO_MODE_FALLBACK_NOTICE: SessionNotice = {
|
||||
severity: "warning",
|
||||
title: "Auto mode unavailable",
|
||||
description: sentenceCase(AUTO_MODE_FALLBACK_REASON),
|
||||
};
|
||||
|
||||
export type SessionMode = {
|
||||
query: Pick<Query, "setPermissionMode">;
|
||||
queryClosed?: boolean;
|
||||
modes: SessionModeState;
|
||||
models: { currentModelId: string };
|
||||
modelInfos: ModelInfo[];
|
||||
/** Prevents the model-specific Auto fallback from spamming the transcript. */
|
||||
autoModeFallbackWarningShown?: boolean;
|
||||
/** Initial mode fallback is reported after session/new, on the first prompt. */
|
||||
autoModeFallbackWarningPending?: boolean;
|
||||
/** The mode the session left when it entered plan mode, if it is in plan. */
|
||||
prePlanMode?: string;
|
||||
};
|
||||
|
||||
export type SessionModeManagerOptions<S extends SessionMode> = {
|
||||
getSession(sessionId: string): S | undefined;
|
||||
sessionEndedMessage: string;
|
||||
updateConfigOption(sessionId: string, configId: string, value: string): Promise<void>;
|
||||
sessionUpdate(params: SessionNotification): Promise<void>;
|
||||
/** Whether the client can present `notice` updates; the fallback warning
|
||||
* is a transcript line otherwise. Read per call: capabilities are only
|
||||
* known after `initialize`. */
|
||||
supportsNotices?(): boolean;
|
||||
logError(...args: unknown[]): void;
|
||||
/** Whether the client is AIR. Only AIR gets the mode kind, under `_meta.jetbrains.air`. */
|
||||
airClient?(): boolean;
|
||||
};
|
||||
|
||||
type ModeConfigSession = SessionMode & {
|
||||
configOptions: SessionConfigOption[];
|
||||
};
|
||||
|
||||
/** Which optional modes the session's mode catalog offers. */
|
||||
export type ModeAvailability = {
|
||||
/** When false, bypassPermissions is omitted from the mode catalog. */
|
||||
allowBypass: boolean;
|
||||
/** When false (`disableAutoMode: "disable"` in settings), auto is omitted. */
|
||||
allowAuto: boolean;
|
||||
};
|
||||
|
||||
type InitializeSessionModeParams = ModeAvailability & {
|
||||
query: Pick<Query, "setPermissionMode">;
|
||||
requestedMode: PermissionMode;
|
||||
/** The mode is the built-in default: no request, transcript or setting chose it. */
|
||||
builtInDefault?: boolean;
|
||||
currentModelInfo?: ModelInfo;
|
||||
currentModelId: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The permission mode a new Claude query starts in.
|
||||
*
|
||||
* An explicit mode wins. A resume or a load continues in the mode of the last
|
||||
* user record of the transcript. If that mode is unknown or absent from the
|
||||
* session's mode catalog, use an available `defaultMode` from settings, or
|
||||
* `default` when that setting is unavailable too.
|
||||
*
|
||||
* With no `defaultMode` set, the session starts in `auto` when the catalog
|
||||
* offers it and in `default` otherwise (`builtInDefault: true`), like an
|
||||
* interactive Claude Code session. Claude Code also starts organizations with
|
||||
* the HIPAA configuration in `default`; the SDK does not report that
|
||||
* configuration, so those sessions start in `auto` here.
|
||||
*/
|
||||
export function resolveInitialPermissionMode(
|
||||
sources: { explicit?: PermissionMode; resumed?: string; defaultMode?: unknown },
|
||||
logger: { error: (...args: unknown[]) => void },
|
||||
availability: ModeAvailability,
|
||||
): { mode: PermissionMode; builtInDefault: boolean } {
|
||||
const { allowBypass } = availability;
|
||||
const available = (mode: PermissionMode) =>
|
||||
buildAvailableModes(availability).some((entry) => entry.id === mode);
|
||||
if (sources.explicit !== undefined) {
|
||||
return {
|
||||
mode: resolvePermissionMode(sources.explicit, logger, allowBypass),
|
||||
builtInDefault: false,
|
||||
};
|
||||
}
|
||||
if (sources.resumed !== undefined) {
|
||||
let rejected = false;
|
||||
const mode = resolvePermissionMode(
|
||||
sources.resumed,
|
||||
{ error: () => (rejected = true) },
|
||||
allowBypass,
|
||||
);
|
||||
if (!rejected && available(mode)) {
|
||||
return { mode, builtInDefault: false };
|
||||
}
|
||||
logger.error(
|
||||
`Ignoring permission mode "${sources.resumed}" of the resumed transcript: ` +
|
||||
`not available in this session.`,
|
||||
);
|
||||
}
|
||||
if (sources.defaultMode === undefined) {
|
||||
return { mode: available("auto") ? "auto" : "default", builtInDefault: true };
|
||||
}
|
||||
const configuredMode = resolvePermissionMode(sources.defaultMode, logger, allowBypass);
|
||||
// A rejected transcript mode falls back only to a mode this session can offer.
|
||||
if (sources.resumed !== undefined && !available(configuredMode)) {
|
||||
return { mode: "default", builtInDefault: false };
|
||||
}
|
||||
return { mode: configuredMode, builtInDefault: false };
|
||||
}
|
||||
|
||||
/** Owns session-mode policy and the ACP/SDK synchronization it requires. */
|
||||
export class SessionModeManager<S extends SessionMode> {
|
||||
constructor(private readonly options: SessionModeManagerOptions<S>) {}
|
||||
|
||||
async initialize({
|
||||
query,
|
||||
requestedMode,
|
||||
builtInDefault = false,
|
||||
currentModelInfo,
|
||||
currentModelId,
|
||||
allowBypass,
|
||||
allowAuto,
|
||||
}: InitializeSessionModeParams): Promise<{
|
||||
modes: SessionModeState;
|
||||
autoModeFallbackWarningPending: boolean;
|
||||
}> {
|
||||
const availableModes = buildAvailableModes(
|
||||
{ allowBypass, allowAuto },
|
||||
this.options.airClient?.() ?? false,
|
||||
);
|
||||
let effectiveMode = requestedMode;
|
||||
let autoModeFallbackWarningPending = false;
|
||||
|
||||
const autoUnsupported =
|
||||
effectiveMode === "auto" &&
|
||||
currentModelInfo !== undefined &&
|
||||
currentModelInfo.supportsAutoMode !== true;
|
||||
if (!this.isAvailable(availableModes, effectiveMode)) {
|
||||
this.options.logError(
|
||||
`permissions.defaultMode "${effectiveMode}" is not available in ` +
|
||||
`this session; falling back to "default".`,
|
||||
);
|
||||
effectiveMode = "default";
|
||||
await this.trySyncMode(query, effectiveMode, "Failed to sync clamped permissionMode to SDK:");
|
||||
} else if (autoUnsupported && builtInDefault) {
|
||||
// Like Claude Code: a built-in Auto default the model can't serve starts
|
||||
// in Manual, without a warning. Nobody chose Auto, so don't escalate to
|
||||
// acceptEdits.
|
||||
effectiveMode = "default";
|
||||
await this.trySyncMode(query, effectiveMode, "Failed to sync clamped permissionMode to SDK:");
|
||||
} else if (autoUnsupported) {
|
||||
this.options.logError(
|
||||
`permissions.defaultMode "auto" is not available for model ` +
|
||||
`"${currentModelId}"; falling back to "${AUTO_MODE_FALLBACK}".`,
|
||||
);
|
||||
effectiveMode = AUTO_MODE_FALLBACK;
|
||||
autoModeFallbackWarningPending = true;
|
||||
await this.trySyncMode(query, effectiveMode, "Failed to sync clamped permissionMode to SDK:");
|
||||
}
|
||||
|
||||
return {
|
||||
modes: { currentModeId: effectiveMode, availableModes },
|
||||
autoModeFallbackWarningPending,
|
||||
};
|
||||
}
|
||||
|
||||
static configOption(modes: SessionModeState): SessionConfigOption {
|
||||
return {
|
||||
id: MODE_CONFIG_ID,
|
||||
name: "Mode",
|
||||
description: "Session permission mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: modes.currentModeId,
|
||||
options: modes.availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
description: mode.description,
|
||||
_meta: mode._meta,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
syncConfig(session: ModeConfigSession, mode: string): void {
|
||||
const previousMode = session.modes.currentModeId;
|
||||
if (mode !== "plan") {
|
||||
session.prePlanMode = undefined;
|
||||
} else if (previousMode !== "plan") {
|
||||
session.prePlanMode = previousMode;
|
||||
}
|
||||
session.modes = { ...session.modes, currentModeId: mode };
|
||||
session.configOptions = session.configOptions.map((option) =>
|
||||
option.id === MODE_CONFIG_ID && typeof option.currentValue === "string"
|
||||
? { ...option, currentValue: mode }
|
||||
: option,
|
||||
);
|
||||
}
|
||||
|
||||
availableModeIds(modes: SessionModeState): string[] {
|
||||
return modes.availableModes.map((mode) => mode.id);
|
||||
}
|
||||
|
||||
effectiveMode(session: SessionMode, requestedMode: PermissionMode): PermissionMode {
|
||||
return requestedMode === "auto" && this.isAutoUnavailable(session)
|
||||
? AUTO_MODE_FALLBACK
|
||||
: requestedMode;
|
||||
}
|
||||
|
||||
applyPermissionFallback(
|
||||
session: SessionMode,
|
||||
permissionResult: PermissionResult,
|
||||
): { permissionResult: PermissionResult; fallbackApplied: boolean } {
|
||||
const fallbackApplied =
|
||||
this.isAutoUnavailable(session) &&
|
||||
permissionResult.behavior === "allow" &&
|
||||
permissionResult.updatedPermissions?.some(
|
||||
(update) => update.type === "setMode" && update.mode === "auto",
|
||||
) === true;
|
||||
if (!fallbackApplied || permissionResult.behavior !== "allow") {
|
||||
return { permissionResult, fallbackApplied: false };
|
||||
}
|
||||
|
||||
return {
|
||||
permissionResult: {
|
||||
...permissionResult,
|
||||
updatedPermissions: permissionResult.updatedPermissions?.map((update) =>
|
||||
update.type === "setMode" && update.mode === "auto"
|
||||
? { ...update, mode: AUTO_MODE_FALLBACK }
|
||||
: update,
|
||||
),
|
||||
},
|
||||
fallbackApplied: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** Reconcile mode after a model switch. The caller rebuilds config options
|
||||
* before publishing the returned state change. */
|
||||
async reconcileForModel(session: SessionMode, model: ModelInfo | undefined) {
|
||||
if (
|
||||
session.modes.currentModeId !== "auto" ||
|
||||
model === undefined ||
|
||||
model.supportsAutoMode === true
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
session.modes = {
|
||||
availableModes: session.modes.availableModes,
|
||||
currentModeId: AUTO_MODE_FALLBACK,
|
||||
};
|
||||
await this.trySyncMode(
|
||||
session.query,
|
||||
AUTO_MODE_FALLBACK,
|
||||
`Failed to sync permissionMode to "${AUTO_MODE_FALLBACK}" after model switch invalidated "auto":`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
async selectMode(sessionId: string, modeId: string): Promise<PermissionMode> {
|
||||
const session = this.requireOpenSession(sessionId);
|
||||
const requestedMode = this.parseMode(modeId);
|
||||
if (!this.isAvailable(session.modes.availableModes, requestedMode)) {
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Mode ${modeId} is not available in this session`,
|
||||
);
|
||||
}
|
||||
|
||||
const effectiveMode = this.effectiveMode(session, requestedMode);
|
||||
try {
|
||||
await session.query.setPermissionMode(effectiveMode);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (!error.message) error.message = "Invalid Mode";
|
||||
throw error;
|
||||
}
|
||||
// eslint-disable-next-line preserve-caught-error
|
||||
throw new Error("Invalid Mode");
|
||||
}
|
||||
|
||||
if (effectiveMode !== requestedMode) {
|
||||
await this.publishFallbackWarning(sessionId, session);
|
||||
}
|
||||
return effectiveMode;
|
||||
}
|
||||
|
||||
async setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse> {
|
||||
const effectiveMode = await this.selectMode(params.sessionId, params.modeId);
|
||||
if (effectiveMode !== params.modeId) {
|
||||
await this.publishCurrent(params.sessionId, effectiveMode);
|
||||
}
|
||||
await this.options.updateConfigOption(params.sessionId, MODE_CONFIG_ID, effectiveMode);
|
||||
return {};
|
||||
}
|
||||
|
||||
async publishCurrent(sessionId: string, mode: string): Promise<void> {
|
||||
await this.options.sessionUpdate({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "current_mode_update", currentModeId: mode },
|
||||
});
|
||||
}
|
||||
|
||||
async publishFallbackWarning(sessionId: string, session: SessionMode): Promise<void> {
|
||||
session.autoModeFallbackWarningPending = false;
|
||||
if (session.autoModeFallbackWarningShown) return;
|
||||
session.autoModeFallbackWarningShown = true;
|
||||
try {
|
||||
await this.options.sessionUpdate({
|
||||
sessionId,
|
||||
update: noticeOrTranscriptUpdate(
|
||||
AUTO_MODE_FALLBACK_NOTICE,
|
||||
this.options.supportsNotices?.() ?? false,
|
||||
noticeTranscriptText({
|
||||
...AUTO_MODE_FALLBACK_NOTICE,
|
||||
description: AUTO_MODE_FALLBACK_REASON,
|
||||
}),
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
// The fallback has already been applied; a failed advisory must not turn
|
||||
// the successful mode change into a failed request.
|
||||
this.options.logError(`Failed to publish Auto mode fallback warning: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async publishFallbackState(sessionId: string, session: SessionMode): Promise<void> {
|
||||
await this.publishCurrent(sessionId, AUTO_MODE_FALLBACK);
|
||||
await this.publishFallbackWarning(sessionId, session);
|
||||
}
|
||||
|
||||
private requireOpenSession(sessionId: string): S {
|
||||
const session = this.options.getSession(sessionId);
|
||||
if (!session) throw RequestError.sessionNotFound(sessionId);
|
||||
if (session.queryClosed) {
|
||||
throw RequestError.internalError(undefined, this.options.sessionEndedMessage);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private isAutoUnavailable(
|
||||
session: SessionMode,
|
||||
modelId = session.models.currentModelId,
|
||||
): boolean {
|
||||
const modelInfo = session.modelInfos.find((model) => model.value === modelId);
|
||||
return modelInfo !== undefined && modelInfo.supportsAutoMode !== true;
|
||||
}
|
||||
|
||||
private isAvailable(availableModes: SessionModeState["availableModes"], modeId: string): boolean {
|
||||
return availableModes.some((mode) => mode.id === modeId);
|
||||
}
|
||||
|
||||
private parseMode(modeId: string): PermissionMode {
|
||||
switch (modeId) {
|
||||
case "auto":
|
||||
case "default":
|
||||
case "acceptEdits":
|
||||
case "bypassPermissions":
|
||||
case "dontAsk":
|
||||
case "plan":
|
||||
return modeId;
|
||||
default:
|
||||
throw RequestError.invalidParams(undefined, `Invalid Mode: ${modeId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async trySyncMode(
|
||||
query: Pick<Query, "setPermissionMode">,
|
||||
mode: PermissionMode,
|
||||
errorMessage: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await query.setPermissionMode(mode);
|
||||
} catch (error) {
|
||||
this.options.logError(errorMessage, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAvailableModes(
|
||||
{ allowBypass, allowAuto }: ModeAvailability,
|
||||
air = false,
|
||||
): SessionModeState["availableModes"] {
|
||||
// Only AIR gets the mode kind.
|
||||
const kind = (value: string) => {
|
||||
const meta = airOnlyMeta(air, AIR_KIND_KEY, value);
|
||||
return meta ? { _meta: meta } : {};
|
||||
};
|
||||
const modes: SessionModeState["availableModes"] = [
|
||||
{
|
||||
id: "default",
|
||||
name: "Manual",
|
||||
description: "Always ask before making changes",
|
||||
...kind("standard"),
|
||||
},
|
||||
{
|
||||
id: "acceptEdits",
|
||||
name: "Accept edits",
|
||||
description: "Automatically accept all file edits",
|
||||
...kind("standard"),
|
||||
},
|
||||
{
|
||||
id: "plan",
|
||||
name: "Plan",
|
||||
description: "Create a plan before making changes",
|
||||
...kind("plan"),
|
||||
},
|
||||
];
|
||||
if (allowAuto) {
|
||||
modes.push({
|
||||
id: "auto",
|
||||
name: "Auto",
|
||||
description: "Claude handles permission decisions",
|
||||
...kind("auto_review"),
|
||||
});
|
||||
}
|
||||
if (allowBypass) {
|
||||
modes.push({
|
||||
id: "bypassPermissions",
|
||||
name: "Bypass permissions",
|
||||
description: "Accepts all permissions",
|
||||
...kind("full_access"),
|
||||
});
|
||||
}
|
||||
return modes;
|
||||
}
|
||||
@@ -1,867 +0,0 @@
|
||||
import type { SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { ModelInfo, Query, Settings } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, withAirMeta } from "./air-extension.js";
|
||||
import { bedrockRegionPrefix } from "./gateway-models.js";
|
||||
|
||||
export const MODEL_CONFIG_ID = "model";
|
||||
|
||||
export type SessionModelState = {
|
||||
availableModels: Array<{ modelId: string; name: string; description?: string }>;
|
||||
currentModelId: string;
|
||||
};
|
||||
|
||||
type ModelLogger = {
|
||||
log: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
};
|
||||
type ModelSettingsSource = { getSettings(): Settings };
|
||||
|
||||
const MODEL_CONTEXT_HINT_PATTERN = /\[(\d+m)\]$/i;
|
||||
const CONTEXT_HINT_SUFFIX_PATTERN = /-(\d+m)$/i;
|
||||
const MODEL_FAMILY_VERSION_PATTERN = /\b(\d+)(?:[-.](\d+))?\b/;
|
||||
const VERSIONABLE_MODEL_DISPLAY_PATTERN =
|
||||
/^(?:Claude\s+)?([a-z][a-z0-9-]*)(?:\s+\d+(?:\.\d+)?)?(?:\s+\(\d+[mk]\s+context\))?$/i;
|
||||
const DISPLAY_CONTEXT_SUFFIX_PATTERN = /\s+\((\d+[mk])\s+context\)$/i;
|
||||
|
||||
function stripContextHints(value: string): string {
|
||||
return value.replace(/\[\d+m\]/gi, "").replace(CONTEXT_HINT_SUFFIX_PATTERN, "");
|
||||
}
|
||||
|
||||
function canonicalizeModelId(value: string): string {
|
||||
return value.trim().toLowerCase().replace(CONTEXT_HINT_SUFFIX_PATTERN, "[$1]");
|
||||
}
|
||||
|
||||
function contextHintOf(value: string): string | null {
|
||||
return canonicalizeModelId(value).match(MODEL_CONTEXT_HINT_PATTERN)?.[1] ?? null;
|
||||
}
|
||||
|
||||
function extractModelFamilyVersion(value: string): string | null {
|
||||
const match = stripContextHints(value).match(MODEL_FAMILY_VERSION_PATTERN);
|
||||
if (!match) return null;
|
||||
return match[2] ? `${match[1]}.${match[2]}` : match[1];
|
||||
}
|
||||
|
||||
function modelVersionsCompatible(preference: string, candidate: ModelInfo): boolean {
|
||||
const preferred = extractModelFamilyVersion(preference);
|
||||
if (!preferred) return true;
|
||||
const candidateVersion =
|
||||
extractModelFamilyVersion(candidate.value) ??
|
||||
extractModelFamilyVersion(candidate.displayName) ??
|
||||
extractModelFamilyVersion(candidate.description);
|
||||
return candidateVersion ? preferred === candidateVersion : true;
|
||||
}
|
||||
|
||||
function displayModelVersion(model: ModelInfo, family: string): string | undefined {
|
||||
const familyVersion = new RegExp(`\\b${family}[-\\s]+(\\d+)(?:[-.](\\d+))?`, "i");
|
||||
// The display name is the value we are deciding whether to rewrite, so it
|
||||
// cannot validate its own normalization. Require independent SDK metadata.
|
||||
for (const source of [model.resolvedModel, model.description, model.value]) {
|
||||
const match = source?.match(familyVersion);
|
||||
if (match) return match[2] ? `${match[1]}.${match[2]}` : match[1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Add concrete versions when a terse SDK label names the same family as the
|
||||
* underlying model metadata. Multi-word/custom labels remain untouched.
|
||||
* Context size remains in the option description; if normalization would
|
||||
* collide, callers fall back to the original labels. */
|
||||
function versionedModelDisplayName(model: ModelInfo): string {
|
||||
const versionable = model.displayName.match(VERSIONABLE_MODEL_DISPLAY_PATTERN);
|
||||
if (!versionable) return model.displayName;
|
||||
const version = displayModelVersion(model, versionable[1]);
|
||||
if (!version) return model.displayName;
|
||||
const contextSuffix = model.displayName.match(DISPLAY_CONTEXT_SUFFIX_PATTERN);
|
||||
const descriptionKeepsContext =
|
||||
contextSuffix !== null &&
|
||||
new RegExp(`\\b${contextSuffix[1]}\\s+context\\b`, "i").test(model.description);
|
||||
const withoutContext = model.displayName.replace(DISPLAY_CONTEXT_SUFFIX_PATTERN, "");
|
||||
if (/\b\d+(?:\.\d+)?\b/.test(withoutContext)) {
|
||||
return descriptionKeepsContext ? withoutContext : model.displayName;
|
||||
}
|
||||
if (descriptionKeepsContext || contextSuffix === null) return `${withoutContext} ${version}`;
|
||||
// Keep the suffix in its original spelling and insert the version before it.
|
||||
return `${withoutContext} ${version}${contextSuffix[0]}`;
|
||||
}
|
||||
|
||||
function modelWords(value: string): string[] {
|
||||
return value
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Whether `needle`'s words appear in `haystack`'s words, adjacent and in
|
||||
* order: "opus" in "claude-opus-4-5", but not "son" in "sonnet" or "a" in
|
||||
* "Default (recommended)". */
|
||||
function containsWords(haystack: string, needle: string): boolean {
|
||||
const words = modelWords(haystack);
|
||||
const wanted = modelWords(needle);
|
||||
if (wanted.length === 0) return false;
|
||||
for (let start = 0; start + wanted.length <= words.length; start++) {
|
||||
if (wanted.every((word, offset) => words[start + offset] === word)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** `id` without the gateway spellings that `normalizeModelId` keeps for
|
||||
* `deniedModels` and 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 {
|
||||
return id.replace(/^(?:[^/]+\/)+(?=claude-)/, "").replace(/-latest$/, "");
|
||||
}
|
||||
|
||||
/** The words of `preference` that name a model: without what
|
||||
* `normalizeModelId` drops (provider prefixes, dates, `-v1:0`, `-fast`,
|
||||
* context hints), version numbers, "claude", and "best"/"default".
|
||||
* "us.anthropic.claude-sonnet-4-5-v1:0" gives ["sonnet"], "opusplan" gives
|
||||
* ["opus"]. */
|
||||
function modelPreferenceTokens(preference: string): string[] {
|
||||
return modelWords(withoutGatewaySpelling(normalizeModelId(preference)))
|
||||
.map((token) => (token === "opusplan" ? "opus" : token))
|
||||
.filter((token) => /[a-z]/.test(token) && !["claude", "best", "default"].includes(token));
|
||||
}
|
||||
|
||||
/** Whether every one of `tokens` is a word of `model`'s value or display name. */
|
||||
function modelCoversTokens(model: ModelInfo, tokens: string[]): boolean {
|
||||
const words = new Set(modelWords(`${model.value} ${model.displayName}`));
|
||||
return tokens.length > 0 && tokens.every((token) => words.has(token));
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry of `models` that `preference` names, or null when it names none.
|
||||
* `best` names the entry `opus` resolves to, unless an entry's value is `best`.
|
||||
* In order: an entry whose value, display name or `resolvedModel` equals it
|
||||
* (in either context-hint spelling); an entry whose value or display name
|
||||
* contains its words ("opus" for "claude-opus-4-5"), or whose value it
|
||||
* contains while every model word of the preference is the entry's
|
||||
* ("sonnet" for "us.anthropic.claude-sonnet-5-v1:0"); then any entry with all
|
||||
* 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.
|
||||
*/
|
||||
export function resolveModelPreference(models: ModelInfo[], preference: string): ModelInfo | null {
|
||||
const trimmed = preference.trim();
|
||||
if (!trimmed) return null;
|
||||
const lower = trimmed.toLowerCase();
|
||||
// The CLI resolves `best` to its flagship: Opus, unless a server-side flag
|
||||
// names another family that this adapter cannot read. The CLI ignores a
|
||||
// `[1m]` hint on `best`. A listed entry named `best` still matches directly.
|
||||
if (stripContextHints(lower) === "best" && !models.some((model) => model.value === trimmed)) {
|
||||
return resolveModelPreference(models, "opus");
|
||||
}
|
||||
const canonicalPreference = canonicalizeModelId(trimmed);
|
||||
const directMatch = models.find(
|
||||
(model) =>
|
||||
model.value === trimmed ||
|
||||
canonicalizeModelId(model.value) === canonicalPreference ||
|
||||
model.displayName.toLowerCase() === lower,
|
||||
);
|
||||
if (directMatch) return directMatch;
|
||||
|
||||
const matchesResolved = (model: ModelInfo) =>
|
||||
model.resolvedModel != null && canonicalizeModelId(model.resolvedModel) === canonicalPreference;
|
||||
const resolvedMatch =
|
||||
models.find((model) => model.value !== "default" && matchesResolved(model)) ??
|
||||
models.find(matchesResolved);
|
||||
if (resolvedMatch) return resolvedMatch;
|
||||
|
||||
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))
|
||||
);
|
||||
});
|
||||
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] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export function matchResumedModel(models: ModelInfo[], liveModel: string): ModelInfo {
|
||||
const live = canonicalizeModelId(liveModel);
|
||||
const defaultEntry = models.find((model) => model.value === "default");
|
||||
const defaultResolved = defaultEntry?.resolvedModel
|
||||
? canonicalizeModelId(defaultEntry.resolvedModel)
|
||||
: undefined;
|
||||
if (defaultEntry && defaultResolved === live) return defaultEntry;
|
||||
const exactMatch = models.find(
|
||||
(model) => model.resolvedModel && canonicalizeModelId(model.resolvedModel) === live,
|
||||
);
|
||||
if (exactMatch) return exactMatch;
|
||||
if (
|
||||
defaultEntry &&
|
||||
defaultResolved &&
|
||||
stripContextHints(defaultResolved) === stripContextHints(live)
|
||||
) {
|
||||
return defaultEntry;
|
||||
}
|
||||
return (
|
||||
resolveModelPreference(models, liveModel) ?? {
|
||||
value: liveModel,
|
||||
displayName: liveModel,
|
||||
description: "",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function buildModelConfigOption(
|
||||
models: SessionModelState,
|
||||
modelInfos: ModelInfo[],
|
||||
useRecommendedValue: boolean,
|
||||
): SessionConfigOption {
|
||||
const defaultInfo = modelInfos.find((model) => model.value === "default");
|
||||
const selectableIds = new Set(models.availableModels.map((model) => model.modelId));
|
||||
const concreteInfos = modelInfos.filter(
|
||||
(model) => model.value !== "default" && selectableIds.has(model.value),
|
||||
);
|
||||
// Recommendations describe the running default, so fuzzy family matching
|
||||
// must never substitute a different generation or context window.
|
||||
const defaultResolved = defaultInfo?.resolvedModel;
|
||||
const recommended = defaultResolved
|
||||
? (concreteInfos.find(
|
||||
(model) =>
|
||||
canonicalizeModelId(model.resolvedModel ?? model.value) ===
|
||||
canonicalizeModelId(defaultResolved),
|
||||
) ?? null)
|
||||
: null;
|
||||
const concreteRecommendation = useRecommendedValue && recommended !== null;
|
||||
const available = concreteRecommendation
|
||||
? models.availableModels.filter((model) => model.modelId !== "default")
|
||||
: models.availableModels;
|
||||
|
||||
const currentValue =
|
||||
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,
|
||||
};
|
||||
}
|
||||
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
|
||||
// model as its own entry. It is not added to `models.availableModels`, so the
|
||||
// next rebuild after switching to a listed model drops it.
|
||||
if (!options.some((option) => option.value === currentValue)) {
|
||||
const info = modelInfos.find((model) => model.value === currentValue);
|
||||
options.push({
|
||||
value: currentValue,
|
||||
name: info?.displayName || currentValue,
|
||||
description: info?.description || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
id: MODEL_CONFIG_ID,
|
||||
name: "Model",
|
||||
description: "AI model to use",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue,
|
||||
...(concreteRecommendation
|
||||
? {
|
||||
_meta: withAirMeta(undefined, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, recommended.value),
|
||||
}
|
||||
: {}),
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveSettingsModel(
|
||||
models: ModelInfo[],
|
||||
settingsModel: unknown,
|
||||
logger: ModelLogger,
|
||||
): ModelInfo | null {
|
||||
if (settingsModel === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof settingsModel !== "string") {
|
||||
const typeLabel = settingsModel === null ? "null" : typeof settingsModel;
|
||||
logger.error(`Ignoring model from settings: expected a string, got ${typeLabel}.`);
|
||||
return null;
|
||||
}
|
||||
return resolveModelPreference(models, settingsModel);
|
||||
}
|
||||
|
||||
const MODEL_FAMILY_ALIASES = new Set(["opus", "sonnet", "haiku", "fable"]);
|
||||
|
||||
/** The family and version of a `claude-<family>-<major>[-<minor>]` id:
|
||||
* `claude-fable-5-1` is fable 5.1, `claude-haiku-4-5-20251001` haiku 4.5. */
|
||||
function familyVersionOf(id: string): { family: string; major: number; minor: number } | null {
|
||||
const match = id.toLowerCase().match(/^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?![\d.])/);
|
||||
if (!match) return null;
|
||||
return { family: match[1], major: Number(match[2]), minor: Number(match[3] ?? 0) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Give back the family alias value to the row the CLI lists under a resumed
|
||||
* session's model id.
|
||||
*
|
||||
* The CLI lists Fable 5.2 as `fable`, but when it resumes a session that ran
|
||||
* Fable 5.2 it lists the same row as `claude-fable-5-2` and has no `fable`
|
||||
* row. Clients store the option value as the session's choice, so a value
|
||||
* from a new session would not be offered by a resumed one, and the reverse.
|
||||
*
|
||||
* A row gets its family's alias as its value when its `value` is
|
||||
* `resumedModel`, equals its own `resolvedModel` and has no context hint, no
|
||||
* row has that alias, and no row of the family has a newer version (an alias
|
||||
* runs its family's newest model). Every other row is returned as it is.
|
||||
*
|
||||
* The CLI lists a row the same way when `ANTHROPIC_MODEL` or `settings.model`
|
||||
* pins `claude-fable-5-2`. Those rows keep the pinned id, so a client's choice
|
||||
* stays on that version after a newer Fable becomes `fable`. A resumed Fable
|
||||
* 5.1 session keeps `claude-fable-5-1` too, because Fable 5.2 is newer.
|
||||
*/
|
||||
export function aliasResumedModelRow(
|
||||
models: ModelInfo[],
|
||||
resumedModel: string | undefined,
|
||||
): ModelInfo[] {
|
||||
if (resumedModel === undefined) return models;
|
||||
const resumed = canonicalizeModelId(resumedModel);
|
||||
const values = new Set(models.map((model) => model.value));
|
||||
const versions = models.flatMap((model) => {
|
||||
const version = familyVersionOf(model.resolvedModel ?? model.value);
|
||||
return version ? [version] : [];
|
||||
});
|
||||
return models.map((model) => {
|
||||
const version = familyVersionOf(model.value);
|
||||
if (
|
||||
version === null ||
|
||||
!MODEL_FAMILY_ALIASES.has(version.family) ||
|
||||
values.has(version.family) ||
|
||||
model.resolvedModel !== model.value ||
|
||||
contextHintOf(model.value) !== null ||
|
||||
canonicalizeModelId(model.value) !== resumed ||
|
||||
versions.some(
|
||||
(other) =>
|
||||
other.family === version.family &&
|
||||
(other.major > version.major ||
|
||||
(other.major === version.major && other.minor > version.minor)),
|
||||
)
|
||||
) {
|
||||
return model;
|
||||
}
|
||||
values.add(version.family);
|
||||
return { ...model, value: version.family };
|
||||
});
|
||||
}
|
||||
|
||||
/** 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
|
||||
* to `claude-opus-5-5`; `anthropic/openai/gpt-5` keeps its `openai/` prefix and
|
||||
* matches no Claude id. */
|
||||
function normalizeModelId(value: string): string {
|
||||
let id = stripContextHints(value.trim().toLowerCase());
|
||||
const providerPrefix = id.lastIndexOf("anthropic.");
|
||||
if (providerPrefix !== -1) id = id.slice(providerPrefix + "anthropic.".length);
|
||||
return (
|
||||
id
|
||||
// Only a leading `anthropic/`: OpenRouter's `anthropic/openai/gpt-5` must
|
||||
// keep `openai/`, which `lastIndexOf` would strip along with it.
|
||||
.replace(/^anthropic\//, "")
|
||||
// `:batch`, `:free`. A letter must follow the colon, so Bedrock's `-v1:0`
|
||||
// is left for the `-vN:M` step below.
|
||||
.replace(/:[a-z][a-z0-9-]*$/, "")
|
||||
// `claude-opus-5.5` -> `claude-opus-5-5`; only dots between two digits.
|
||||
.replace(/(?<=\d)\.(?=\d)/g, "-")
|
||||
.replace(/@.*$/, "")
|
||||
.replace(/-v\d+(?::\d+)?$/, "")
|
||||
.replace(/-fast$/, "")
|
||||
.replace(/-\d{8}$/, "")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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}-`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict the SDK's model list to the user's `availableModels` allowlist
|
||||
* (already merged-and-deduped across settings sources by `SettingsManager`).
|
||||
* The user's exact entries become the model IDs surfaced via configOptions
|
||||
* and passed to `setModel`, which prevents Claude Code from silently
|
||||
* substituting a date-pinned variant (e.g. `haiku` →
|
||||
* `claude-haiku-4-5-20251001`) that the user may not have access to.
|
||||
*
|
||||
* Display info and capability flags are copied from the closest SDK match so
|
||||
* the UI still renders sensible names and effort levels.
|
||||
*
|
||||
* Semantics from https://code.claude.com/docs/en/model-config#restrict-model-selection:
|
||||
* - `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.
|
||||
*/
|
||||
export function applyAvailableModelsAllowlist(
|
||||
sdkModels: ModelInfo[],
|
||||
allowlist: string[],
|
||||
settingsModelOverrides?: Record<string, string>,
|
||||
deniedModels: readonly string[] = [],
|
||||
): 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.
|
||||
const defaultModel = sdkModels.find((m) => m.value === "default") ?? {
|
||||
value: "default",
|
||||
displayName: "Default",
|
||||
description: "",
|
||||
};
|
||||
const result: ModelInfo[] = [defaultModel];
|
||||
const seen = new Set<string>([defaultModel.value]);
|
||||
|
||||
const sdkModelsWithoutDefault = sdkModels.filter((m) => m.value !== "default");
|
||||
|
||||
// Bedrock/Vertex deployments enforce short aliases (e.g. "claude-opus-4-6")
|
||||
// in availableModels but require provider-specific IDs at the API. We still
|
||||
// resolve `sdkMatch` against the alias (`trimmed`) — that's what the
|
||||
// matching heuristics above are built for, and override targets (ARNs,
|
||||
// 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 trimmed = entry.trim();
|
||||
if (!trimmed || seen.has(trimmed)) continue;
|
||||
|
||||
const overridden = settingsModelOverrides?.[trimmed];
|
||||
const effective = overridden ?? trimmed;
|
||||
if (seen.has(effective)) continue;
|
||||
|
||||
const sdkMatch = resolveModelPreference(sdkModelsWithoutDefault, trimmed);
|
||||
if (
|
||||
[trimmed, effective, sdkMatch?.resolvedModel].some(
|
||||
(id) => id != null && isDeniedModel(id, deniedModels),
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (sdkMatch) {
|
||||
result.push({ ...sdkMatch, value: effective });
|
||||
} else {
|
||||
result.push({ value: effective, displayName: trimmed, description: "" });
|
||||
}
|
||||
seen.add(effective);
|
||||
}
|
||||
|
||||
// The custom model option (ANTHROPIC_CUSTOM_MODEL_OPTION) is exempt from the
|
||||
// allowlist, the same way Default is. Per the model-config docs it adds an
|
||||
// entry "without replacing the built-in aliases" and "appears at the bottom of
|
||||
// the /model picker", so we append it last and skip the allowlist filter; this
|
||||
// keeps a slim alias allowlist from hiding the custom model row.
|
||||
// https://code.claude.com/docs/en/model-config#add-a-custom-model-option
|
||||
const customModelOption = process.env.ANTHROPIC_CUSTOM_MODEL_OPTION?.trim();
|
||||
if (customModelOption && !seen.has(customModelOption)) {
|
||||
const customModel = sdkModels.find((m) => m.value === customModelOption);
|
||||
if (customModel) {
|
||||
result.push(customModel);
|
||||
seen.add(customModel.value);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the SDK models the `providers/set` gateway listed (`listGatewayModels`,
|
||||
* `listBedrockModels`). A row matches when its `resolvedModel` (or
|
||||
* its `value` when the SDK gives none) names a listed model in any spelling:
|
||||
* `claude-sonnet-5[1m]` matches a listed `claude-sonnet-5-20260101`, and
|
||||
* `eu.anthropic.claude-sonnet-5` matches a listed `eu.anthropic.claude-sonnet-5-v1:0`.
|
||||
*
|
||||
* With a Bedrock `regionPrefix`, a row resolved to another cross-region prefix
|
||||
* (`us.anthropic.claude-sonnet-5` under `eu`) is dropped even when the same
|
||||
* model is listed under `eu`: the CLI would call it in the other region.
|
||||
*
|
||||
* A row the SDK gives no `resolvedModel` names its model only by an alias, so
|
||||
* it is checked as far as the alias allows: `default` is kept, and a family
|
||||
* alias such as `opus` is kept when the gateway lists a model of that family.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
export function narrowToGatewayModels(
|
||||
models: ModelInfo[],
|
||||
listedModelIds: readonly string[],
|
||||
regionPrefix?: string,
|
||||
): ModelInfo[] {
|
||||
const listed = new Set(listedModelIds.map(normalizeModelId).filter(Boolean));
|
||||
const narrowed = models.filter((model) => {
|
||||
const modelId = model.resolvedModel ?? model.value;
|
||||
const prefix = bedrockRegionPrefix(modelId);
|
||||
if (regionPrefix !== undefined && prefix !== undefined && prefix !== regionPrefix) {
|
||||
return false;
|
||||
}
|
||||
const id = normalizeModelId(modelId);
|
||||
if (listed.has(id)) return true;
|
||||
if (model.resolvedModel !== undefined) return false;
|
||||
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
|
||||
: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The capabilities of the session's current model, and the model infos that
|
||||
* every later lookup reads.
|
||||
*
|
||||
* A resumed session can be running a model outside the `availableModels`
|
||||
* allowlist (currentModelId is then the verbatim live id, see
|
||||
* `matchResumedModel`); its capabilities are still known to the SDK's
|
||||
* unfiltered list, so they are resolved from that before the model is treated
|
||||
* as unknown — otherwise auto mode would be spuriously clamped and the
|
||||
* Fast-mode/Effort options hidden for a model that supports them.
|
||||
*
|
||||
* The fallback-resolved capabilities are registered under the verbatim live
|
||||
* id, so every modelInfos consumer (the effort option, later rebuilds) agrees
|
||||
* with that gating. `buildModelConfigOption` lists this model as its own
|
||||
* entry while it is current and drops it once the user switches to a listed
|
||||
* model; it is never added to `availableModels`. The spread keeps every
|
||||
* 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.
|
||||
*/
|
||||
export function withCurrentModelInfo(
|
||||
allowedModels: ModelInfo[],
|
||||
sdkModels: ModelInfo[],
|
||||
currentModelId: string,
|
||||
): {
|
||||
allowlistedModelInfo: ModelInfo | undefined;
|
||||
currentModelInfo: ModelInfo | undefined;
|
||||
modelInfos: ModelInfo[];
|
||||
} {
|
||||
const allowlistedModelInfo = allowedModels.find((m) => m.value === currentModelId);
|
||||
const fallbackModelInfo = allowlistedModelInfo
|
||||
? undefined
|
||||
: (resolveModelPreference(sdkModels, currentModelId) ?? undefined);
|
||||
return {
|
||||
allowlistedModelInfo,
|
||||
currentModelInfo: allowlistedModelInfo ?? fallbackModelInfo,
|
||||
modelInfos: fallbackModelInfo
|
||||
? [
|
||||
...allowedModels,
|
||||
{
|
||||
...fallbackModelInfo,
|
||||
value: currentModelId,
|
||||
displayName: currentModelId,
|
||||
description: "",
|
||||
resolvedModel: undefined,
|
||||
},
|
||||
]
|
||||
: allowedModels,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a rejected `setModel` was vetoed by a user-configured
|
||||
* PreModelSwitch hook. The CLI's rejection message is the stable,
|
||||
* distinguishable marker ("Model switch blocked by a PreModelSwitch hook:
|
||||
* <reason>"); a format change makes this stop matching and the failure
|
||||
* falls back to the ordinary fail-loud path, no worse than before. */
|
||||
function isPreModelSwitchHookBlock(error: unknown): boolean {
|
||||
return error instanceof Error && error.message.includes("blocked by a PreModelSwitch hook");
|
||||
}
|
||||
|
||||
export async function getAvailableModels(
|
||||
query: Query,
|
||||
models: ModelInfo[],
|
||||
sdkModels: ModelInfo[],
|
||||
settingsManager: ModelSettingsSource,
|
||||
logger: ModelLogger,
|
||||
isResumedSession: boolean,
|
||||
sessionId: string,
|
||||
resumedModelHint?: string,
|
||||
narrowedByGateway = false,
|
||||
): Promise<SessionModelState> {
|
||||
// A gateway that lists none of the SDK's models leaves none to offer
|
||||
// (`narrowToGatewayModels`). The session stays on the model the SDK runs,
|
||||
// and the gateway refuses its requests.
|
||||
if (models.length === 0) {
|
||||
return {
|
||||
availableModels: [],
|
||||
currentModelId: (isResumedSession && resumedModelHint) || sdkModels[0]?.value || "default",
|
||||
};
|
||||
}
|
||||
|
||||
const settings = settingsManager.getSettings();
|
||||
|
||||
let currentModel = models[0];
|
||||
let resolvedFromInput: string | undefined;
|
||||
// Model priority (highest to lowest):
|
||||
// 1. ANTHROPIC_MODEL environment variable
|
||||
// 2. settings.model (user configuration)
|
||||
// 3. the resumed session's live model (resumed sessions only)
|
||||
// 4. models[0] (default first model)
|
||||
if (process.env.ANTHROPIC_MODEL) {
|
||||
const match = resolveModelPreference(models, process.env.ANTHROPIC_MODEL);
|
||||
if (match) {
|
||||
currentModel = match;
|
||||
resolvedFromInput = process.env.ANTHROPIC_MODEL;
|
||||
}
|
||||
} else if (typeof settings.model === "string") {
|
||||
const match = resolveSettingsModel(models, settings.model, logger);
|
||||
if (match) {
|
||||
currentModel = match;
|
||||
resolvedFromInput = settings.model;
|
||||
}
|
||||
}
|
||||
|
||||
// A resumed session restores the model from its last real assistant
|
||||
// transcript record. Use that same local record instead of getContextUsage:
|
||||
// the latter is a control request to the live CLI process and can add tens
|
||||
// of seconds to session/load before its first turn. No `setModel` here: the
|
||||
// SDK is already running this model, and pushing a picker alias back (e.g.
|
||||
// "opus[1m]") could change the live model rather than describe it.
|
||||
if (resolvedFromInput === undefined && isResumedSession) {
|
||||
currentModel = resumedModelHint ? matchResumedModel(models, resumedModelHint) : currentModel;
|
||||
}
|
||||
|
||||
// Skip the setModel round-trip when we can prove the SDK has already landed
|
||||
// on the same model. Two cases qualify:
|
||||
// (a) No override applied — currentModel is the SDK's own default (or, on
|
||||
// resume, the live model read back from the SDK above); nothing to sync.
|
||||
// (b) The resolver returned the user's input verbatim AND that value exists
|
||||
// in the SDK's original model list — meaning no fuzzy match or
|
||||
// allowlist rewrite was involved, and the SDK (which reads the same
|
||||
// ANTHROPIC_MODEL / settings.json) will have arrived at the same entry.
|
||||
// This only holds for fresh sessions: a resumed session lands on the
|
||||
// transcript's model regardless of env/settings, so the override must
|
||||
// be re-asserted to keep the reported model truthful.
|
||||
// Anything else (fuzzy match, allowlist-synthesized value, alias) gets a
|
||||
// setModel call so we don't drift from the user's intended pin.
|
||||
// Case (a) does not hold when `narrowToGatewayModels` left the SDK on a
|
||||
// model the gateway does not list: the dropped `default` row of a fresh or
|
||||
// transcript-less session, or a resumed transcript model outside the list.
|
||||
// Such a session switches to models[0].
|
||||
const sdkSawSameValue = sdkModels.some((m) => m.value === currentModel.value);
|
||||
const sdkDefault = sdkModels.find((m) => m.value === "default");
|
||||
const sdkDefaultDropped = sdkDefault !== undefined && !models.some((m) => m.value === "default");
|
||||
let switchToListed = false;
|
||||
if (resolvedFromInput === undefined) {
|
||||
if (!isResumedSession || !resumedModelHint) {
|
||||
switchToListed = sdkDefaultDropped;
|
||||
} else if (
|
||||
narrowedByGateway &&
|
||||
(!models.some((m) => m.value === currentModel.value) ||
|
||||
// A loose match can map the transcript's model onto a listed row of
|
||||
// another version, which the CLI does not resume on.
|
||||
(currentModel.resolvedModel !== undefined &&
|
||||
normalizeModelId(currentModel.resolvedModel) !== normalizeModelId(resumedModelHint)))
|
||||
) {
|
||||
currentModel = models[0];
|
||||
switchToListed = true;
|
||||
}
|
||||
}
|
||||
// When the switch fails, the SDK stays on the model it ran before it.
|
||||
const modelBeforeSwitch = (): ModelInfo =>
|
||||
switchToListed && sdkDefault !== undefined ? sdkDefault : models[0];
|
||||
const skipSetModel =
|
||||
(resolvedFromInput === undefined && !switchToListed) ||
|
||||
(!isResumedSession && currentModel.value === resolvedFromInput && sdkSawSameValue);
|
||||
if (!skipSetModel) {
|
||||
const setModelStartedAt = performance.now();
|
||||
try {
|
||||
await query.setModel(currentModel.value);
|
||||
logger.log(
|
||||
`[session/models] sessionId=${sessionId} phase=set-model durationMs=${Math.round(performance.now() - setModelStartedAt)} model=${currentModel.value} outcome=success`,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.log(
|
||||
`[session/models] sessionId=${sessionId} phase=set-model durationMs=${Math.round(performance.now() - setModelStartedAt)} model=${currentModel.value} outcome=error`,
|
||||
);
|
||||
// On a fresh session the pin is a defining option — fail loudly. A
|
||||
// resumed session already runs fine on the transcript's model, so
|
||||
// failing the whole session/load over the re-assert would be worse
|
||||
// than loading with the pin unapplied (mirrors the setPermissionMode
|
||||
// containment in createSession). The SDK then stayed on the
|
||||
// transcript's model, so read that back rather than reporting the
|
||||
// pin the session isn't running.
|
||||
//
|
||||
// One fresh-session failure is advisory, not defining: a
|
||||
// user-configured PreModelSwitch hook can veto the pin (CLI 2.1.251+;
|
||||
// 'deny', or 'ask' — which headless sessions refuse), and the SDK
|
||||
// rejects setModel with "Model switch blocked by a PreModelSwitch
|
||||
// hook: …". Terminal Claude Code never lets a hook veto its startup
|
||||
// model (the spawn model isn't a switch), so failing session/new here
|
||||
// would make the same hook config fatal only over ACP. The session
|
||||
// stays on the SDK's own default — report that. We can't read the
|
||||
// live model back on this path: getContextUsage isn't serviced on a
|
||||
// fresh session until the first prompt turn (issues #886/#880).
|
||||
if (!isResumedSession) {
|
||||
// A switch onto a listed model is advisory too: the session stays on
|
||||
// the model the SDK runs and reports it.
|
||||
if (!switchToListed && !isPreModelSwitchHookBlock(error)) throw error;
|
||||
logger.error(
|
||||
`Model switch to "${currentModel.value}" failed or was vetoed by a PreModelSwitch hook; staying on the default model:`,
|
||||
error,
|
||||
);
|
||||
currentModel = modelBeforeSwitch();
|
||||
} else {
|
||||
logger.error(`Failed to re-assert model "${currentModel.value}" on resume:`, error);
|
||||
currentModel = resumedModelHint
|
||||
? matchResumedModel(models, resumedModelHint)
|
||||
: modelBeforeSwitch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const displayNames = models.map(versionedModelDisplayName);
|
||||
const displayNameCounts = new Map<string, number>();
|
||||
for (const name of displayNames) {
|
||||
displayNameCounts.set(name, (displayNameCounts.get(name) ?? 0) + 1);
|
||||
}
|
||||
const names = models.map((model, index) =>
|
||||
displayNameCounts.get(displayNames[index]) === 1 ? displayNames[index] : model.displayName,
|
||||
);
|
||||
const nameCounts = new Map<string, number>();
|
||||
for (const name of names) {
|
||||
nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
|
||||
}
|
||||
|
||||
return {
|
||||
availableModels: models.map((model, index) => ({
|
||||
modelId: model.value,
|
||||
// Allowlisted aliases can inherit the same SDK label. Keep every ID
|
||||
// selectable, but distinguish the rows for clients that show only names.
|
||||
name: nameCounts.get(names[index]) === 1 ? names[index] : `${names[index]} (${model.value})`,
|
||||
description: model.description,
|
||||
})),
|
||||
currentModelId: currentModel.value,
|
||||
};
|
||||
}
|
||||
|
||||
/** The display name of the model id `model` in `modelInfos`, if it is there. */
|
||||
export function modelDisplayName(modelInfos: ModelInfo[], model: string): string | undefined {
|
||||
let byModel = displayNameCache.get(modelInfos);
|
||||
if (!byModel) displayNameCache.set(modelInfos, (byModel = new Map()));
|
||||
if (!byModel.has(model)) {
|
||||
const info = modelInfos.find((info) => info.value === model || info.resolvedModel === model);
|
||||
byModel.set(model, info?.displayName);
|
||||
}
|
||||
return byModel.get(model);
|
||||
}
|
||||
|
||||
/** {@link modelDisplayName} per model list, which a session replaces and never edits. */
|
||||
const displayNameCache = new WeakMap<ModelInfo[], Map<string, string | undefined>>();
|
||||
|
||||
/** The flat entries of a session's `model` select option. */
|
||||
function modelOptionEntries(option: SessionConfigOption): Array<{ value: string; name: string }> {
|
||||
if (option.type !== "select") return [];
|
||||
return option.options.flatMap((entry) =>
|
||||
"value" in entry ? [{ value: entry.value, name: entry.name }] : entry.options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry of the `model` option among `configOptions` for `model`, a model
|
||||
* id that a response reported, so that a client can compare it with the
|
||||
* session's own model. Best first:
|
||||
*
|
||||
* 1. the current entry, when it runs that model up to a context hint: a
|
||||
* session on `opus[1m]` or `default` that answers as `claude-opus-4-6`;
|
||||
* 2. the entry whose value or resolved model is that id;
|
||||
* 3. an entry that runs that model up to a context hint.
|
||||
*
|
||||
* Among several entries for one model, a concrete entry comes before
|
||||
* `default`, as in {@link resolveModelPreference}. Undefined when no entry
|
||||
* matches. A model's resolved id comes from `modelInfos`
|
||||
* (`ModelInfo.resolvedModel`), the wire id that a response reports, as for
|
||||
* {@link matchResumedModel}. It is compared as it is: a dated id such as
|
||||
* `claude-haiku-4-5-20251001` matches only the same dated id.
|
||||
*/
|
||||
export function modelEntryFor(
|
||||
configOptions: readonly SessionConfigOption[],
|
||||
modelInfos: ModelInfo[],
|
||||
model: string,
|
||||
): { value: string; name: string } | undefined {
|
||||
// Each response of a subagent reports its model, so the result is kept per
|
||||
// list. A session replaces its lists on a change and never edits them.
|
||||
let byInfos = modelEntryCache.get(configOptions);
|
||||
if (!byInfos) modelEntryCache.set(configOptions, (byInfos = new WeakMap()));
|
||||
let byModel = byInfos.get(modelInfos);
|
||||
if (!byModel) byInfos.set(modelInfos, (byModel = new Map()));
|
||||
if (byModel.has(model)) return byModel.get(model);
|
||||
const entry = findModelEntry(configOptions, modelInfos, model);
|
||||
byModel.set(model, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
const modelEntryCache = new WeakMap<
|
||||
readonly SessionConfigOption[],
|
||||
WeakMap<ModelInfo[], Map<string, { value: string; name: string } | undefined>>
|
||||
>();
|
||||
|
||||
function findModelEntry(
|
||||
configOptions: readonly SessionConfigOption[],
|
||||
modelInfos: ModelInfo[],
|
||||
model: string,
|
||||
): { value: string; name: string } | undefined {
|
||||
const option = configOptions.find((candidate) => candidate.id === MODEL_CONFIG_ID);
|
||||
if (option?.type !== "select") return undefined;
|
||||
// Concrete entries first; `sort` keeps the list order otherwise.
|
||||
const entries = modelOptionEntries(option).sort(
|
||||
(left, right) => Number(left.value === "default") - Number(right.value === "default"),
|
||||
);
|
||||
const observed = canonicalizeModelId(model);
|
||||
const resolved = (value: string) =>
|
||||
canonicalizeModelId(modelInfos.find((info) => info.value === value)?.resolvedModel ?? value);
|
||||
const sameModel = (value: string) =>
|
||||
stripContextHints(resolved(value)) === stripContextHints(observed);
|
||||
const current = entries.find((entry) => entry.value === option.currentValue);
|
||||
if (current && sameModel(current.value)) return current;
|
||||
return (
|
||||
entries.find((entry) => entry.value === model || resolved(entry.value) === observed) ??
|
||||
entries.find((entry) => sameModel(entry.value))
|
||||
);
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
|
||||
/** Fire-and-forget advisory text for the user: live events rather than
|
||||
* conversation history. See the ACP Session Notices RFD
|
||||
* (https://agentclientprotocol.com/rfds/session-notices). */
|
||||
export type SessionNotice = {
|
||||
severity: "info" | "warning" | "error";
|
||||
/** Plain text that stands alone. */
|
||||
title: string;
|
||||
/** Plain-text detail or guidance. */
|
||||
description?: string;
|
||||
};
|
||||
|
||||
/** Longest free-form line that may serve as a notice title on its own. Past
|
||||
* this the text moves to `description` under a generic title. */
|
||||
export const MAX_NOTICE_TITLE_LENGTH = 256;
|
||||
|
||||
/** Whether the Client advertised `clientCapabilities.session.notices`. Agents
|
||||
* MUST NOT send `notice` updates otherwise; the alternative is a bold-label
|
||||
* transcript line, which was the only way to flag these before. */
|
||||
export function clientSupportsNotices(capabilities?: ClientCapabilities | null): boolean {
|
||||
const notices = capabilities?.session?.notices;
|
||||
return typeof notices === "object" && notices !== null && !Array.isArray(notices);
|
||||
}
|
||||
|
||||
export function noticeUpdate(notice: SessionNotice): SessionNotification["update"] {
|
||||
return {
|
||||
sessionUpdate: "notice",
|
||||
severity: notice.severity,
|
||||
title: notice.title,
|
||||
...(notice.description ? { description: notice.description } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The transcript rendering of a notice for clients without the capability. */
|
||||
export function noticeTranscriptText(notice: SessionNotice): string {
|
||||
return notice.description ? `**${notice.title}:** ${notice.description}` : `**${notice.title}**`;
|
||||
}
|
||||
|
||||
/** The update to send for `notice`: a `notice` when the client can present
|
||||
* one, else an agent message carrying `transcriptText` (by default the
|
||||
* bold-label rendering of the notice) and `transcriptMeta`, so clients
|
||||
* without the capability can still tell the line apart from Claude's reply. */
|
||||
export function noticeOrTranscriptUpdate(
|
||||
notice: SessionNotice,
|
||||
supportsNotices: boolean,
|
||||
transcriptText: string = noticeTranscriptText(notice),
|
||||
transcriptMeta?: Record<string, unknown>,
|
||||
): SessionNotification["update"] {
|
||||
if (supportsNotices) return noticeUpdate(notice);
|
||||
return {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: transcriptBlock(transcriptText) },
|
||||
...(transcriptMeta ? { _meta: transcriptMeta } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Clients render consecutive agent_message_chunks as one markdown stream, so
|
||||
* a bare `**Notice:** …` chunk lands mid-sentence: "…all done.**Notice:** Stop
|
||||
* says: …". Put it in its own blockquote paragraph, blank lines on both sides,
|
||||
* so it starts on a new line and Claude's next chunk does not continue the
|
||||
* quote. */
|
||||
export function transcriptBlock(text: string): string {
|
||||
const lines = text.trim().split(/\r?\n/);
|
||||
return `\n\n${lines.map((line) => (line ? `> ${line}` : ">")).join("\n")}\n\n`;
|
||||
}
|
||||
|
||||
const HOOK_SPEAKER = /^[^\n:]{1,80} says: /;
|
||||
|
||||
/** Claude Code prefixes every line of a hook's `systemMessage` with
|
||||
* "<HookEvent> says: ", so a two-line message reads "Stop says: a\nStop says:
|
||||
* b". Keep the prefix on the first line only when every line repeats it. */
|
||||
export function collapseHookSpeaker(text: string): string {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const prefix = lines[0].match(HOOK_SPEAKER)?.[0];
|
||||
if (!prefix || lines.length < 2 || !lines.every((line) => line.startsWith(prefix))) {
|
||||
return text;
|
||||
}
|
||||
return [lines[0], ...lines.slice(1).map((line) => line.slice(prefix.length))].join("\n");
|
||||
}
|
||||
|
||||
/** Fragments that read on after a bold label stand alone as a notice
|
||||
* description, so start them with a capital. */
|
||||
export function sentenceCase(text: string): string {
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
/** Collapses whitespace so a text shown as a notice can be recognized when
|
||||
* the SDK repeats it elsewhere (a hook-blocked turn's result, for one). */
|
||||
export function normalizeNoticeText(text: string): string {
|
||||
return text.trim().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
/** Notice fields are plain text. Free-form SDK/hook output may carry light
|
||||
* markdown that a transcript would render; drop the inline markers rather
|
||||
* than show literal asterisks and backticks in a toast. */
|
||||
export function noticePlainText(text: string): string {
|
||||
return text
|
||||
.replace(/^[ \t]*#{1,6}[ \t]+/gm, "")
|
||||
.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "$2")
|
||||
.replace(/(?<![\w`])`([^`\n]+)`(?![\w`])/g, "$1");
|
||||
}
|
||||
|
||||
/** Shapes free-form text into a notice title plus optional description: the
|
||||
* first line stands as the title when it is short enough, otherwise the whole
|
||||
* text becomes the description under `fallbackTitle`. */
|
||||
export function splitNoticeText(
|
||||
text: string,
|
||||
fallbackTitle: string,
|
||||
): Pick<SessionNotice, "title" | "description"> {
|
||||
const trimmed = noticePlainText(text).trim();
|
||||
if (!trimmed) return { title: fallbackTitle };
|
||||
const lineBreak = trimmed.search(/\r?\n/);
|
||||
const firstLine = lineBreak === -1 ? trimmed : trimmed.slice(0, lineBreak).trimEnd();
|
||||
const rest = lineBreak === -1 ? "" : trimmed.slice(lineBreak).trim();
|
||||
if (firstLine.length > MAX_NOTICE_TITLE_LENGTH) {
|
||||
return { title: fallbackTitle, description: trimmed };
|
||||
}
|
||||
return rest ? { title: firstLine, description: rest } : { title: firstLine };
|
||||
}
|
||||
|
||||
/** The notice of Claude Code's `informational` message (e.g. why a Stop hook
|
||||
* blocked continuation): a warning at level `warning`, else info. */
|
||||
export function informationalNotice(message: { level: string; content: string }): SessionNotice {
|
||||
const severity = message.level === "warning" ? "warning" : "info";
|
||||
return {
|
||||
severity,
|
||||
...splitNoticeText(
|
||||
message.content,
|
||||
severity === "warning" ? "Claude reported a warning" : "Claude reported a notice",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
export function mcpServerStartupNotice(
|
||||
server: { name: string; status: 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.",
|
||||
};
|
||||
}
|
||||
if (server.status === "needs-auth" && !oauthAvailable) {
|
||||
return {
|
||||
severity: "info",
|
||||
title: `MCP server "${server.name}" needs authentication`,
|
||||
description: "Its tools are unavailable until the server is authenticated.",
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* What Claude Code's `model_refusal_fallback` tells the user: the SDK retried
|
||||
* a refused turn on the fallback model.
|
||||
*
|
||||
* Current CLIs only emit direction "retry", a swap that lasts for the
|
||||
* session. "revert"/"sticky" are retained in the SDK enum for older CLIs,
|
||||
* where "revert" marked a turn-only fallback: the session stays on the
|
||||
* original model. `scope` (CLI 2.1.232+) "local" means a subagent,
|
||||
* side-question or background fork response fell back and the session model
|
||||
* is unchanged. Absent scope means an older CLI, where every retry was a
|
||||
* session-level swap. `persistent` is whether the session now runs
|
||||
* `fallback_model`, so its model option must follow.
|
||||
*/
|
||||
export function modelRefusalFallback(message: {
|
||||
original_model: string;
|
||||
fallback_model: string;
|
||||
direction?: string;
|
||||
scope?: string;
|
||||
api_refusal_category?: string | null;
|
||||
api_refusal_explanation?: string | null;
|
||||
}): {
|
||||
persistent: boolean;
|
||||
/** The one-line summary. */
|
||||
summary: string;
|
||||
explanation: string | undefined;
|
||||
/** The notice: the summary as its title when it is short enough, else a
|
||||
* generic title with everything in the description. */
|
||||
notice: SessionNotice;
|
||||
/** The transcript line for a client without `notice` updates. */
|
||||
transcript: string;
|
||||
} {
|
||||
const local = message.scope === "local";
|
||||
const persistent = message.direction !== "revert" && !local;
|
||||
const category = message.api_refusal_category ? ` (${message.api_refusal_category})` : "";
|
||||
const outcome = persistent
|
||||
? `The session will continue on ${message.fallback_model}.`
|
||||
: local
|
||||
? `Only that response came from ${message.fallback_model}; the session stays on ${message.original_model}.`
|
||||
: `The session stays on ${message.original_model}.`;
|
||||
const summary =
|
||||
`${message.original_model} declined this request${category}; ` +
|
||||
`retried with ${message.fallback_model}. ${outcome}`;
|
||||
const explanation = message.api_refusal_explanation || undefined;
|
||||
const full = explanation ? `${summary}\n\n${explanation}` : summary;
|
||||
return {
|
||||
persistent,
|
||||
summary,
|
||||
explanation,
|
||||
notice: {
|
||||
severity: "warning",
|
||||
...(summary.length > MAX_NOTICE_TITLE_LENGTH
|
||||
? { title: "Model fallback", description: full }
|
||||
: { title: summary, ...(explanation ? { description: explanation } : {}) }),
|
||||
},
|
||||
transcript: `**Model fallback:** ${full}`,
|
||||
};
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
type TimingLogger = {
|
||||
log: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
/** Small phase timer for session lifecycle diagnostics. */
|
||||
export class SessionTiming {
|
||||
private readonly startedAt: number;
|
||||
private phaseStartedAt: number;
|
||||
|
||||
constructor(
|
||||
private readonly logger: TimingLogger | undefined,
|
||||
private readonly operation: string,
|
||||
private readonly sessionId: string,
|
||||
startedAt = performance.now(),
|
||||
) {
|
||||
this.startedAt = startedAt;
|
||||
this.phaseStartedAt = startedAt;
|
||||
}
|
||||
|
||||
phase(name: string, detail = ""): void {
|
||||
const finishedAt = performance.now();
|
||||
this.logger?.log(
|
||||
`[session/${this.operation}] sessionId=${this.sessionId} phase=${name} durationMs=${Math.round(finishedAt - this.phaseStartedAt)} totalMs=${Math.round(finishedAt - this.startedAt)}${detail}`,
|
||||
);
|
||||
this.phaseStartedAt = finishedAt;
|
||||
}
|
||||
}
|
||||
@@ -1,466 +0,0 @@
|
||||
/**
|
||||
* AI-generated session titles.
|
||||
*
|
||||
* Claude Code titles a new SDK session itself: when it reads the first prompt,
|
||||
* it asks a small model for a title and stores it in the transcript as an
|
||||
* `ai-title` entry, a few seconds in. It sends no message when it does. This
|
||||
* module asks for the title with the `generate_session_title` control request,
|
||||
* which returns the stored title or waits for the one being generated, and
|
||||
* publishes it over ACP as a `session_info_update`. Where the CLI does not
|
||||
* title the session itself (a resumed session, or one with
|
||||
* `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or
|
||||
* `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` set), the same request generates it.
|
||||
*
|
||||
* {@link SessionTitles} holds the per-session state and is owned by the
|
||||
* session, in the v1 core (`v1/acp-agent.ts`) and the v2 core
|
||||
* (`v2/session.ts`). Each drives it from the same places:
|
||||
* {@link SessionTitles.onPrompt} and {@link SessionTitles.onAssistantText} to
|
||||
* collect text, {@link SessionTitles.onPromptQueued} once a prompt is sent to
|
||||
* the CLI, {@link SessionTitles.onTurnEnd} at `session_state_changed: idle`,
|
||||
* and, in v1, {@link SessionTitles.reset} on `conversation_reset`.
|
||||
*/
|
||||
|
||||
import type {
|
||||
ContentBlock,
|
||||
PromptRequest,
|
||||
SessionNotification,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import { getSessionInfo, type Query, type SDKSessionInfo } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ExplicitTitle } from "./session-index/explicit-title.js";
|
||||
|
||||
/** What titles read of their session. */
|
||||
export interface TitledSession {
|
||||
readonly query: Query;
|
||||
readonly queryClosed?: boolean;
|
||||
/** Whether a cancel stopped the session's work: no title is generated then. */
|
||||
readonly cancelled?: boolean;
|
||||
readonly cwd: string;
|
||||
}
|
||||
|
||||
/** What titles need of the core that serves the session (`ClaudeAcpAgent` in v1). */
|
||||
export interface TitleOwner {
|
||||
readonly client: { sessionUpdate(notification: SessionNotification): Promise<void> };
|
||||
readonly logger: { error: (...args: any[]) => void };
|
||||
/** The live sessions by id: a session replaced or closed meanwhile adopts no title. */
|
||||
readonly sessions: Readonly<Record<string, TitledSession | undefined>>;
|
||||
/** The title as the client shows it, such as with an archive prefix removed. */
|
||||
clientTitle?(title: string): string;
|
||||
}
|
||||
|
||||
const MAX_TITLE_LENGTH = 256;
|
||||
|
||||
/** How much session text the title is generated from. The CLI caps its own
|
||||
* title input at the same 1000 trailing characters. */
|
||||
const MAX_TITLE_CONTEXT_LENGTH = 1000;
|
||||
|
||||
/** Below this the generator returns null without calling the model, so there is
|
||||
* nothing to gain by asking yet. */
|
||||
const MIN_TITLE_CONTEXT_LENGTH = 10;
|
||||
|
||||
/** `generateSessionTitle` is present on the SDK's runtime `Query` class but is
|
||||
* not declared in `sdk.d.ts` (0.3.220), so it is reached through this optional
|
||||
* shape rather than the published interface. */
|
||||
type TitleCapableQuery = Query & {
|
||||
generateSessionTitle?: (
|
||||
description: string,
|
||||
options?: { persist?: boolean },
|
||||
) => Promise<string | null>;
|
||||
};
|
||||
|
||||
/** A title already stored for the session, published when generation is
|
||||
* unavailable or yields nothing. */
|
||||
type TitleFallback = { title: string; lastModified: number };
|
||||
|
||||
/** How much of a long text {@link sanitizeTitle} reads first. Collapsed, it
|
||||
* is longer than a title unless it is mostly whitespace. */
|
||||
const TITLE_SCAN_LENGTH = 4096;
|
||||
|
||||
export function sanitizeTitle(text: string): string {
|
||||
if (text.length > TITLE_SCAN_LENGTH) {
|
||||
// A stored summary can be a whole first prompt of megabytes. The title
|
||||
// depends only on the start of the text: collapsing the whitespace of a
|
||||
// prefix gives a prefix of the collapsed text. Two more characters than a
|
||||
// title hold at least one that is not a space (spaces are collapsed), so
|
||||
// the full text is longer than a title and gets the same cut.
|
||||
const head = text.slice(0, TITLE_SCAN_LENGTH).replace(/\s+/g, " ").trimStart();
|
||||
if (head.length >= MAX_TITLE_LENGTH + 2) {
|
||||
return head.slice(0, MAX_TITLE_LENGTH - 1) + "…";
|
||||
}
|
||||
}
|
||||
// Replace newlines and collapse whitespace
|
||||
const sanitized = text
|
||||
.replace(/[\r\n]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
if (sanitized.length <= MAX_TITLE_LENGTH) {
|
||||
return sanitized;
|
||||
}
|
||||
return sanitized.slice(0, MAX_TITLE_LENGTH - 1) + "…";
|
||||
}
|
||||
|
||||
/** Rolling text a title is generated from: `previous` plus `text`, keeping only
|
||||
* the trailing {@link MAX_TITLE_CONTEXT_LENGTH} characters. */
|
||||
export function appendTitleContext(previous: string | undefined, text: string): string {
|
||||
const next = (previous ?? "") + text;
|
||||
return next.length > MAX_TITLE_CONTEXT_LENGTH ? next.slice(-MAX_TITLE_CONTEXT_LENGTH) : next;
|
||||
}
|
||||
|
||||
/** The text chunks of a prompt, one per line. */
|
||||
function promptText(prompt: PromptRequest["prompt"]): string {
|
||||
return prompt.flatMap((chunk) => (chunk.type === "text" ? [chunk.text] : [])).join("\n");
|
||||
}
|
||||
|
||||
/** Whether this SDK still offers on-demand title generation. */
|
||||
function supportsTitleGeneration(query: Query): boolean {
|
||||
return typeof (query as TitleCapableQuery).generateSessionTitle === "function";
|
||||
}
|
||||
|
||||
/** One session's title: the text a generated title is derived from, whether a
|
||||
* title has been settled on, and the last one published. Created with the
|
||||
* session and reachable as `session.titles`. */
|
||||
export class SessionTitles {
|
||||
/** Last title pushed to the client via `session_info_update`, so an unchanged
|
||||
* title is never re-notified. Undefined until the first push. */
|
||||
private lastTitle?: string;
|
||||
|
||||
/** Rolling tail of this session's own user + assistant text, capped at
|
||||
* {@link MAX_TITLE_CONTEXT_LENGTH}. Dropped once a title exists. */
|
||||
private context?: string;
|
||||
|
||||
/** Set once this session has a title or has asked for one. A title is
|
||||
* generated at most once per session: the SDK reports a generated title in
|
||||
* the same field as a user `/rename`, so re-titling could silently overwrite
|
||||
* one. Released by {@link reset}, and when generation yields nothing. */
|
||||
private settled = false;
|
||||
|
||||
/** Whether {@link onPromptQueued} asked for a title from the latest prompt.
|
||||
* A turn end then does not ask again: like the CLI, a prompt that yields
|
||||
* no title gets one try, and the next prompt tries again. */
|
||||
private askedAtPrompt = false;
|
||||
|
||||
/** The title a client set, which no generated title replaces. */
|
||||
private readonly explicit = new ExplicitTitle();
|
||||
|
||||
/** The title last stored through {@link setExplicitTitle}, as stored
|
||||
* (with the archive prefix of an archived session): the title the CLI
|
||||
* holds. */
|
||||
private persistedTitle?: string;
|
||||
|
||||
/** Client title changes in flight, and the title state before the first. */
|
||||
private explicitChanges = 0;
|
||||
private beforeExplicit?: { settled: boolean; context: string | undefined };
|
||||
|
||||
get storedTitle(): string | undefined {
|
||||
return this.persistedTitle;
|
||||
}
|
||||
|
||||
/** The title last published, as the client shows it. */
|
||||
get shownTitle(): string | undefined {
|
||||
return this.lastTitle;
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly agent: TitleOwner,
|
||||
private readonly sessionId: string,
|
||||
) {}
|
||||
|
||||
/** Collect a prompt's own text for the title, skipping openers not worth
|
||||
* titling after. No-op once the title is settled. */
|
||||
onPrompt(prompt: PromptRequest["prompt"]): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.context = appendTitleContext(this.context, `\n${promptText(prompt)}\n`);
|
||||
}
|
||||
|
||||
/** Ask for the title as soon as a prompt is sent to the CLI, instead of
|
||||
* waiting for `idle`: `idle` comes only after the whole turn and its
|
||||
* background tasks, often minutes after the CLI stored its title. The CLI
|
||||
* answers `generate_session_title` while the turn runs, and with the title
|
||||
* it stored or is generating, so this makes no second model call. The
|
||||
* prompt alone is the description, because the CLI titles from the prompt
|
||||
* alone. When this yields no title, the stored summary is published and
|
||||
* the next prompt tries again. */
|
||||
onPromptQueued(session: TitledSession, prompt: PromptRequest["prompt"]): void {
|
||||
this.askedAtPrompt = false;
|
||||
// `session.cancelled` is not checked: after a cancelled turn it stays set
|
||||
// until the next turn starts, which is after this prompt is queued.
|
||||
if (this.settled || this.explicit.active || session.queryClosed) {
|
||||
return;
|
||||
}
|
||||
if (!supportsTitleGeneration(session.query)) {
|
||||
return;
|
||||
}
|
||||
const description = promptText(prompt).trim();
|
||||
if (description.length < MIN_TITLE_CONTEXT_LENGTH) {
|
||||
return;
|
||||
}
|
||||
this.askedAtPrompt = true;
|
||||
this.startGeneration(() => this.titleFromPrompt(session, description));
|
||||
}
|
||||
|
||||
/** Collect the assistant's own answer for the title. Chunks are appended
|
||||
* verbatim so streamed text reassembles. No-op once the title is settled. */
|
||||
onAssistantText(content: ContentBlock): void {
|
||||
if (this.settled || content.type !== "text") {
|
||||
return;
|
||||
}
|
||||
this.context = appendTitleContext(this.context, content.text);
|
||||
}
|
||||
|
||||
/** Drop the title state so the next turn re-evaluates. Used on
|
||||
* `conversation_reset`, which mounts a fresh transcript. */
|
||||
reset(): void {
|
||||
this.settled = false;
|
||||
this.askedAtPrompt = false;
|
||||
this.explicit.reset();
|
||||
this.context = undefined;
|
||||
this.lastTitle = undefined;
|
||||
this.persistedTitle = undefined;
|
||||
}
|
||||
|
||||
/** Turn-end title handling. `idle` is the SDK's turn-over signal, so it is
|
||||
* when a title may have landed or become generatable.
|
||||
*
|
||||
* `info.customTitle` is non-empty only once the session file holds a real
|
||||
* title — a user `/rename` or one generated earlier; the SDK folds both into
|
||||
* that one field. Adopt it and latch, so neither is ever titled over.
|
||||
*
|
||||
* With no title yet, and none asked for at the latest prompt (see
|
||||
* {@link onPromptQueued}), ask the SDK to generate one in the background
|
||||
* from the prompts and replies so far: it is a ~2s small-model call and
|
||||
* turn-end must not wait on it. That covers a prompt too short to title
|
||||
* from, such as "hi". Only when that is not possible do we fall back to
|
||||
* `summary`, which for an SDK-driven session is just the raw first prompt. */
|
||||
async onTurnEnd(session: TitledSession): Promise<void> {
|
||||
if (this.explicit.settledByClient) {
|
||||
// No title is generated over the one the client set, but a custom title
|
||||
// stored since by someone else (a `/rename`) is adopted, as before.
|
||||
const renames = this.explicit.renames;
|
||||
const info = await this.readSessionInfo(session);
|
||||
// No client change ran during the read, so the stored title is current;
|
||||
// an unchanged one is not published again.
|
||||
const stored = info?.customTitle;
|
||||
if (stored && this.explicit.settledByClient && this.explicit.renames === renames) {
|
||||
await this.publish(stored, info.lastModified);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// While a client title change is in flight, the session info read below
|
||||
// could still hold the previous title.
|
||||
if (this.explicit.active) return;
|
||||
const info = await this.readSessionInfo(session);
|
||||
if (this.explicit.active) return;
|
||||
|
||||
if (info?.customTitle) {
|
||||
this.settled = true;
|
||||
this.context = undefined;
|
||||
await this.publish(info.customTitle, info.lastModified);
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback = info?.summary
|
||||
? { title: info.summary, lastModified: info.lastModified }
|
||||
: undefined;
|
||||
|
||||
if (!this.askedAtPrompt && this.canRequest(session)) {
|
||||
const description = this.context?.trim() ?? "";
|
||||
this.startGeneration(() => this.requestGenerateTitle(session, description, fallback));
|
||||
return;
|
||||
}
|
||||
// Only while this session has no title of its own: `summary` degrades to the
|
||||
// raw first prompt, which must never overwrite a generated title if the
|
||||
// persisted one is slow to show up in `info`.
|
||||
if (fallback && !this.settled) {
|
||||
await this.publish(fallback.title, fallback.lastModified);
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies a title that the client chose (a rename, an archive or an
|
||||
* unarchive). Settles the title for good, waits for a generation in flight
|
||||
* so that its persisted title cannot land after this one, persists the
|
||||
* title with `persist`, which returns what it stored, if anything, and
|
||||
* publishes `title` unless it is undefined. A change that stored and
|
||||
* publishes nothing leaves the title state as it was. */
|
||||
async setExplicitTitle(
|
||||
publish: string | ((stored: string | undefined) => string) | undefined,
|
||||
persist: () => Promise<string | undefined | void>,
|
||||
): Promise<void> {
|
||||
// The state before the first of overlapping changes, which a change that
|
||||
// fails or names nothing puts back.
|
||||
if (this.explicitChanges++ === 0) {
|
||||
this.beforeExplicit = { settled: this.settled, context: this.context };
|
||||
}
|
||||
const previous = this.beforeExplicit!;
|
||||
this.settled = true;
|
||||
this.context = undefined;
|
||||
let stored: string | undefined;
|
||||
try {
|
||||
await this.explicit.apply(
|
||||
async () => {
|
||||
stored = (await persist()) ?? undefined;
|
||||
if (stored !== undefined) this.persistedTitle = stored;
|
||||
return stored !== undefined || publish !== undefined;
|
||||
},
|
||||
() => {
|
||||
this.settled = previous.settled;
|
||||
this.context ??= previous.context;
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
if (--this.explicitChanges === 0) this.beforeExplicit = undefined;
|
||||
}
|
||||
const title = typeof publish === "function" ? publish(stored) : publish;
|
||||
if (title === undefined) return;
|
||||
this.lastTitle = title;
|
||||
await this.agent.client.sessionUpdate({
|
||||
sessionId: this.sessionId,
|
||||
update: { sessionUpdate: "session_info_update", title },
|
||||
});
|
||||
}
|
||||
|
||||
/** Sends the session's current title and `updatedAt`, even when the client
|
||||
* was already sent that title: a client that resumes the session may not
|
||||
* have it. Both come from the session file, as `session/list` reports
|
||||
* them; a session with no file yet sends the last title published, if any,
|
||||
* without `updatedAt`. */
|
||||
async publishCurrent(session: TitledSession): Promise<void> {
|
||||
const info = await this.readSessionInfo(session);
|
||||
// A title published but not yet stored (a generated title still being
|
||||
// written) wins over `summary`, which is then only the raw first prompt.
|
||||
const stored =
|
||||
info?.customTitle || (this.settled && this.lastTitle ? undefined : info?.summary);
|
||||
const title = stored
|
||||
? sanitizeTitle(this.agent.clientTitle?.(stored) ?? stored)
|
||||
: this.lastTitle;
|
||||
if (!title) return;
|
||||
this.lastTitle = title;
|
||||
await this.agent.client.sessionUpdate({
|
||||
sessionId: this.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "session_info_update",
|
||||
title,
|
||||
...(info ? { updatedAt: new Date(info.lastModified).toISOString() } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Records a title the CLI took, as soon as it took it. */
|
||||
rememberStoredTitle(title: string): void {
|
||||
this.persistedTitle = title;
|
||||
}
|
||||
|
||||
/** Read the SDK's stored info for this session. A missing session file or read
|
||||
* error is non-fatal: the title is best-effort and another turn will retry. */
|
||||
private async readSessionInfo(session: TitledSession): Promise<SDKSessionInfo | undefined> {
|
||||
try {
|
||||
return await getSessionInfo(this.sessionId, { dir: session.cwd });
|
||||
} catch (error) {
|
||||
this.agent.logger.error(`Session ${this.sessionId}: failed to read session info: ${error}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Notify the client of a title, unless it is the one we last sent. */
|
||||
private async publish(rawTitle: string, lastModified: number): Promise<void> {
|
||||
const title = sanitizeTitle(this.agent.clientTitle?.(rawTitle) ?? rawTitle);
|
||||
if (title === this.lastTitle) {
|
||||
return;
|
||||
}
|
||||
this.lastTitle = title;
|
||||
await this.agent.client.sessionUpdate({
|
||||
sessionId: this.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "session_info_update",
|
||||
title,
|
||||
updatedAt: new Date(lastModified).toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether to ask the SDK for a generated title now: once per session, on a
|
||||
* live query, with enough collected text for the generator to work with. */
|
||||
private canRequest(session: TitledSession): boolean {
|
||||
if (this.settled || session.queryClosed || session.cancelled) {
|
||||
return false;
|
||||
}
|
||||
if (!supportsTitleGeneration(session.query)) {
|
||||
return false;
|
||||
}
|
||||
return (this.context?.trim().length ?? 0) >= MIN_TITLE_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
/** Latch the title and run `generation` in the background, so neither the
|
||||
* prompt nor turn-end waits on a model call. A client title change waits
|
||||
* for it to finish (see {@link ExplicitTitle.track}). */
|
||||
private startGeneration(generation: () => Promise<void>): void {
|
||||
this.settled = true;
|
||||
this.explicit.track(
|
||||
generation().catch((error) => {
|
||||
this.agent.logger.error(`Session ${this.sessionId}: session title update failed: ${error}`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The prompt-time title: the one the session file already holds (a resumed
|
||||
* session's title, or a `/rename`), else one generated from `description`.
|
||||
* The file is read first because the CLI checks only the titles it holds in
|
||||
* memory before generating one. */
|
||||
private async titleFromPrompt(session: TitledSession, description: string): Promise<void> {
|
||||
const info = await this.readSessionInfo(session);
|
||||
if (this.agent.sessions[this.sessionId] !== session || this.explicit.active) {
|
||||
return;
|
||||
}
|
||||
if (info?.customTitle) {
|
||||
this.context = undefined;
|
||||
await this.publish(info.customTitle, info.lastModified);
|
||||
return;
|
||||
}
|
||||
const fallback = info?.summary
|
||||
? { title: info.summary, lastModified: info.lastModified }
|
||||
: undefined;
|
||||
await this.requestGenerateTitle(session, description, fallback);
|
||||
}
|
||||
|
||||
/** Generate a title from `description` and publish it. `persist` writes it
|
||||
* to the session file, which is what carries it into `session/list` and
|
||||
* `session/load`. A null or failed generation releases the latch so a later
|
||||
* prompt or turn end retries, and publishes `fallback` (the stored summary)
|
||||
* so a backend that can't generate titles is no worse off than before. */
|
||||
private async requestGenerateTitle(
|
||||
session: TitledSession,
|
||||
description: string,
|
||||
fallback: TitleFallback | undefined,
|
||||
): Promise<void> {
|
||||
let title: string | null = null;
|
||||
|
||||
try {
|
||||
title =
|
||||
(await (session.query as TitleCapableQuery).generateSessionTitle?.(description, {
|
||||
persist: true,
|
||||
})) ?? null;
|
||||
} catch (error) {
|
||||
this.agent.logger.error(
|
||||
`Session ${this.sessionId}: failed to generate a session title: ${error}`,
|
||||
);
|
||||
}
|
||||
|
||||
// A session torn down or replaced while the title was in flight must not
|
||||
// adopt it, and a title the client set meanwhile wins.
|
||||
if (this.agent.sessions[this.sessionId] !== session || this.explicit.active) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!title) {
|
||||
this.settled = false;
|
||||
|
||||
if (fallback) {
|
||||
await this.publish(fallback.title, fallback.lastModified);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.context = undefined;
|
||||
await this.publish(title, Date.now());
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import type {
|
||||
SessionConfigOption,
|
||||
SetSessionConfigOptionRequest,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { ModelInfo, Query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ULTRACODE_CONFIG_ID } from "./session-config-ids.js";
|
||||
|
||||
export { ULTRACODE_CONFIG_ID } from "./session-config-ids.js";
|
||||
|
||||
/** Select-fallback values for clients without boolean config options. */
|
||||
export const ULTRACODE_ON = "on";
|
||||
export const ULTRACODE_OFF = "off";
|
||||
const ULTRACODE_DESCRIPTION = "Dynamic workflows on every task, at any effort level";
|
||||
|
||||
/** Ultracode state from the CLI's `get_settings` control response
|
||||
* (`applied.ultracodeAvailable` / `applied.ultracodeRequested`). Each field is
|
||||
* undefined when the CLI does not report it. */
|
||||
export type UltracodeSettingsReport = {
|
||||
/** Workflows are enabled and the current model supports ultracode. */
|
||||
available?: boolean;
|
||||
/** Ultracode is turned on for the session, whether or not it can take
|
||||
* effect on the current model. */
|
||||
requested?: boolean;
|
||||
};
|
||||
|
||||
// `Query.getSettings()` exists at runtime (sdk.mjs) but is missing from the
|
||||
// SDK's type declarations as of 0.3.319.
|
||||
type GetSettingsQuery = Query & {
|
||||
getSettings?: () => Promise<{
|
||||
applied?: { ultracodeAvailable?: unknown; ultracodeRequested?: unknown };
|
||||
}>;
|
||||
};
|
||||
|
||||
/** Ask the CLI whether ultracode is available and requested for the session.
|
||||
* Returns undefined when the SDK has no `getSettings` or the request fails;
|
||||
* callers then fall back to {@link modelSupportsUltracode}. */
|
||||
export async function readUltracodeSettings(
|
||||
query: Query,
|
||||
): Promise<UltracodeSettingsReport | undefined> {
|
||||
const getSettings = (query as GetSettingsQuery).getSettings;
|
||||
if (typeof getSettings !== "function") return undefined;
|
||||
try {
|
||||
const applied = (await getSettings.call(query))?.applied;
|
||||
return {
|
||||
available:
|
||||
typeof applied?.ultracodeAvailable === "boolean" ? applied.ultracodeAvailable : undefined,
|
||||
requested:
|
||||
typeof applied?.ultracodeRequested === "boolean" ? applied.ultracodeRequested : undefined,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The CLI supports ultracode on exactly the models that support `xhigh`
|
||||
* effort (both use the same capability check), and `supportedEffortLevels`
|
||||
* lists `xhigh` only for those models. E.g. Opus 4.7+, Sonnet 5+ and Haiku
|
||||
* 5.5 qualify; Opus 4.6 and Haiku 4.5 do not. */
|
||||
export function modelSupportsUltracode(modelInfo: ModelInfo | undefined): boolean {
|
||||
return (
|
||||
modelInfo?.supportsEffort === true &&
|
||||
modelInfo.supportedEffortLevels?.includes("xhigh") === true
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether dynamic workflows are enabled for the session, inferred from the
|
||||
* CLI's `ultracodeAvailable` for the model the session started on. This is
|
||||
* the part of availability that does not change with the model: the plan
|
||||
* default (off on Pro), `enableWorkflows`/`disableWorkflows` and org policy.
|
||||
* Undefined when the report can't tell, e.g. `ultracodeAvailable: false` on a
|
||||
* model that lacks ultracode support anyway. */
|
||||
export function ultracodeWorkflowsEnabled(
|
||||
report: UltracodeSettingsReport | undefined,
|
||||
modelInfo: ModelInfo | undefined,
|
||||
): boolean | undefined {
|
||||
if (report?.available === true) return true;
|
||||
if (report?.available === false && modelSupportsUltracode(modelInfo)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Whether to offer the ultracode toggle for `modelInfo`. An unknown workflows
|
||||
* state shows the toggle: the CLI keeps an unavailable request without
|
||||
* error, so the toggle is merely inert there. */
|
||||
export function ultracodeSupported(
|
||||
workflowsEnabled: boolean | undefined,
|
||||
modelInfo: ModelInfo | undefined,
|
||||
): boolean {
|
||||
return workflowsEnabled !== false && modelSupportsUltracode(modelInfo);
|
||||
}
|
||||
|
||||
/** Ultracode state threaded into `buildConfigOptions`. The option is only
|
||||
* surfaced while `supported`. */
|
||||
export type UltracodeOptionState = {
|
||||
supported: boolean;
|
||||
enabled: boolean;
|
||||
/** Whether the client opted into boolean config options. */
|
||||
useBooleanOption: boolean;
|
||||
};
|
||||
|
||||
/** Build the ultracode toggle: a native boolean for clients that opted into
|
||||
* boolean config options, otherwise an "on"/"off" select. */
|
||||
export function createUltracodeConfigOption(
|
||||
enabled: boolean,
|
||||
useBooleanOption: boolean,
|
||||
): SessionConfigOption {
|
||||
const base = {
|
||||
id: ULTRACODE_CONFIG_ID,
|
||||
name: "Ultracode",
|
||||
description: ULTRACODE_DESCRIPTION,
|
||||
category: "model_config",
|
||||
} as const;
|
||||
|
||||
if (useBooleanOption) {
|
||||
return { ...base, type: "boolean", currentValue: enabled };
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
type: "select",
|
||||
currentValue: enabled ? ULTRACODE_ON : ULTRACODE_OFF,
|
||||
options: [
|
||||
{ value: ULTRACODE_ON, name: "On" },
|
||||
{ value: ULTRACODE_OFF, name: "Off" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Read the requested ultracode value from a `session/set_config_option`
|
||||
* request: a boolean, or the "on"/"off" select-fallback strings. */
|
||||
export function resolveUltracodeEnabled(params: SetSessionConfigOptionRequest): boolean {
|
||||
const value = params.value;
|
||||
if (typeof value === "boolean") return value;
|
||||
if (value === ULTRACODE_ON) return true;
|
||||
if (value === ULTRACODE_OFF) return false;
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Invalid value for config option ${ULTRACODE_CONFIG_ID}: ${value}`,
|
||||
);
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
/**
|
||||
* Token usage as Claude Code reports it: the context window figures of
|
||||
* `usage_update` and the `_meta.quota` of a turn. Shared by the v1 core and
|
||||
* the v2 core.
|
||||
*/
|
||||
import type { ModelUsage } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
export type AccumulatedUsage = {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
cachedReadTokens: number;
|
||||
cachedWriteTokens: number;
|
||||
};
|
||||
|
||||
/** Per-model token tallies keyed by the model id the SDK reported them under
|
||||
* (its resolved spelling, e.g. "claude-opus-5[1m]"). */
|
||||
export type ModelTokenTally = Record<string, AccumulatedUsage>;
|
||||
|
||||
export type UsageSnapshot = {
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
cache_read_input_tokens: number;
|
||||
cache_creation_input_tokens: number;
|
||||
};
|
||||
|
||||
export const ZERO_USAGE = Object.freeze({
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cache_read_input_tokens: 0,
|
||||
cache_creation_input_tokens: 0,
|
||||
});
|
||||
|
||||
export const DEFAULT_CONTEXT_WINDOW = 200000;
|
||||
|
||||
/** `_meta.quota` for work that spent `usage` in its main agent loop and
|
||||
* `modelUsage` by model (see `turnQuotaMeta` in `v1/acp-agent.ts`). */
|
||||
export function quotaMeta(usage: AccumulatedUsage, modelUsage: ModelTokenTally | undefined) {
|
||||
return {
|
||||
quota: {
|
||||
token_count: quotaTokenCount(usage),
|
||||
model_usage: Object.entries(modelUsage ?? {}).map(([model, usage]) => ({
|
||||
model,
|
||||
token_count: quotaTokenCount(usage),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** One `token_count` object. `cachedInputTokens` is cache reads, matching
|
||||
* codex's field; Claude also reports cache writes, which codex has no slot
|
||||
* for, so those ride along in an extra sibling (the same name the ACP `usage`
|
||||
* field already uses) and are counted in `totalTokens`. `reasoningOutputTokens`
|
||||
* is always 0: Claude bills thinking inside its output tokens and never breaks
|
||||
* it out — the key is kept so the shape stays uniform across agents. */
|
||||
function quotaTokenCount(usage: AccumulatedUsage) {
|
||||
return {
|
||||
totalTokens: tallyTotal(usage),
|
||||
inputTokens: usage.inputTokens,
|
||||
cachedInputTokens: usage.cachedReadTokens,
|
||||
cachedWriteTokens: usage.cachedWriteTokens,
|
||||
outputTokens: usage.outputTokens,
|
||||
reasoningOutputTokens: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Sum a tally's four counters. Per the Anthropic API `inputTokens` excludes
|
||||
* the cache counters, so this is not double-counting (see `totalTokens`). */
|
||||
export function tallyTotal(usage: AccumulatedUsage): number {
|
||||
return usage.inputTokens + usage.outputTokens + usage.cachedReadTokens + usage.cachedWriteTokens;
|
||||
}
|
||||
|
||||
/** Project `result.modelUsage` into our tally shape. Counters are coerced the
|
||||
* way `snapshotFromUsage` coerces the stream's: third-party backends have been
|
||||
* observed omitting fields, and a missing or NaN counter must not reach the
|
||||
* wire as NaN (which `JSON.stringify` writes as `null`). */
|
||||
export function normalizeModelUsage(
|
||||
modelUsage: Record<string, ModelUsage> | undefined,
|
||||
): ModelTokenTally {
|
||||
const tally: ModelTokenTally = {};
|
||||
for (const [model, usage] of Object.entries(modelUsage ?? {})) {
|
||||
tally[model] = {
|
||||
inputTokens: finiteCount(usage?.inputTokens),
|
||||
outputTokens: finiteCount(usage?.outputTokens),
|
||||
cachedReadTokens: finiteCount(usage?.cacheReadInputTokens),
|
||||
cachedWriteTokens: finiteCount(usage?.cacheCreationInputTokens),
|
||||
};
|
||||
}
|
||||
return tally;
|
||||
}
|
||||
|
||||
function finiteCount(value: number | null | undefined): number {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
/** `current - previous` per model, dropping models with nothing to report so a
|
||||
* turn only lists the models it actually ran on. A reading that fell BELOW the
|
||||
* previous one means the running total restarted under us (a mid-session
|
||||
* /clear, a zeroed crash result): there is no usable reference left to
|
||||
* subtract, so the reading itself is the increment. */
|
||||
export function modelUsageIncrement(
|
||||
current: ModelTokenTally,
|
||||
previous: ModelTokenTally,
|
||||
): ModelTokenTally {
|
||||
const increment: ModelTokenTally = {};
|
||||
for (const [model, usage] of Object.entries(current)) {
|
||||
const base = previous[model];
|
||||
const subtracted: AccumulatedUsage = base
|
||||
? {
|
||||
inputTokens: usage.inputTokens - base.inputTokens,
|
||||
outputTokens: usage.outputTokens - base.outputTokens,
|
||||
cachedReadTokens: usage.cachedReadTokens - base.cachedReadTokens,
|
||||
cachedWriteTokens: usage.cachedWriteTokens - base.cachedWriteTokens,
|
||||
}
|
||||
: usage;
|
||||
const rewound = Object.values(subtracted).some((count) => count < 0);
|
||||
const resolved = rewound ? usage : subtracted;
|
||||
if (tallyTotal(resolved) > 0) {
|
||||
increment[model] = resolved;
|
||||
}
|
||||
}
|
||||
return increment;
|
||||
}
|
||||
|
||||
/** The per-model rows for the first result of a resumed session. Its
|
||||
* `modelUsage` reading continues from the totals the transcript saved (SDK
|
||||
* 0.3.277+; older transcripts may hold none), so there is no earlier reading
|
||||
* to subtract from, and taking the reading itself would charge the whole
|
||||
* pre-resume history to this one turn. The result's own `usage` is per-turn
|
||||
* (main agent loop only, like the response's `usage`), so it stands in under
|
||||
* the turn's top-level model — `key` is that model's `modelUsage` spelling
|
||||
* when the reading has one, else the assistant message's own. Any subagent
|
||||
* spend on this one turn goes unlisted rather than over-listed. */
|
||||
export function resumedFirstResultModelUsage(
|
||||
usage: {
|
||||
input_tokens?: number | null;
|
||||
output_tokens?: number | null;
|
||||
cache_read_input_tokens?: number | null;
|
||||
cache_creation_input_tokens?: number | null;
|
||||
},
|
||||
key: string | null,
|
||||
): ModelTokenTally {
|
||||
if (key === null) {
|
||||
return {};
|
||||
}
|
||||
const row: AccumulatedUsage = {
|
||||
inputTokens: finiteCount(usage.input_tokens),
|
||||
outputTokens: finiteCount(usage.output_tokens),
|
||||
cachedReadTokens: finiteCount(usage.cache_read_input_tokens),
|
||||
cachedWriteTokens: finiteCount(usage.cache_creation_input_tokens),
|
||||
};
|
||||
return tallyTotal(row) > 0 ? { [key]: row } : {};
|
||||
}
|
||||
|
||||
/** Fold `increment` into `base` per model — the per-model counterpart of the
|
||||
* `+=` the turn's flat accumulator uses. */
|
||||
export function addModelUsage(base: ModelTokenTally, increment: ModelTokenTally): ModelTokenTally {
|
||||
const merged: ModelTokenTally = { ...base };
|
||||
for (const [model, usage] of Object.entries(increment)) {
|
||||
const existing = merged[model];
|
||||
merged[model] = existing
|
||||
? {
|
||||
inputTokens: existing.inputTokens + usage.inputTokens,
|
||||
outputTokens: existing.outputTokens + usage.outputTokens,
|
||||
cachedReadTokens: existing.cachedReadTokens + usage.cachedReadTokens,
|
||||
cachedWriteTokens: existing.cachedWriteTokens + usage.cachedWriteTokens,
|
||||
}
|
||||
: usage;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Sum all four fields as a proxy for post-turn context occupancy: the current
|
||||
* turn's output becomes next turn's input. Per the Anthropic API, input_tokens
|
||||
* excludes cache tokens — cache_read and cache_creation are reported
|
||||
* separately — so summing all four is not double-counting. */
|
||||
export function totalTokens(usage: UsageSnapshot): number {
|
||||
return (
|
||||
usage.input_tokens +
|
||||
usage.output_tokens +
|
||||
usage.cache_read_input_tokens +
|
||||
usage.cache_creation_input_tokens
|
||||
);
|
||||
}
|
||||
|
||||
/** Project a nullable API usage object into our non-null snapshot shape.
|
||||
* Both SDK message_start and assistant message `usage` have `number | null`
|
||||
* cache fields; we coerce absent values to 0 so `totalTokens` never hits
|
||||
* NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
|
||||
* synthetic or third-party-backend stream events have been observed emitting
|
||||
* them as null/undefined — coerce those too so a malformed upstream event
|
||||
* can't leak NaN into the wire `used` field. Delta events have different
|
||||
* semantics (cumulative + prev fallback) and are handled inline. */
|
||||
export function snapshotFromUsage(usage: {
|
||||
input_tokens?: number | null;
|
||||
output_tokens?: number | null;
|
||||
cache_read_input_tokens?: number | null;
|
||||
cache_creation_input_tokens?: number | null;
|
||||
}): UsageSnapshot {
|
||||
return {
|
||||
input_tokens: usage.input_tokens ?? 0,
|
||||
output_tokens: usage.output_tokens ?? 0,
|
||||
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,
|
||||
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
function commonPrefixLength(a: string, b: string) {
|
||||
let i = 0;
|
||||
while (i < a.length && i < b.length && a[i] === b[i]) {
|
||||
i++;
|
||||
}
|
||||
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,
|
||||
) {
|
||||
let bestKey: string | null = null;
|
||||
let bestLen = 0;
|
||||
|
||||
for (const key of Object.keys(modelUsage)) {
|
||||
const len = commonPrefixLength(key, currentModel);
|
||||
if (len > bestLen) {
|
||||
bestLen = len;
|
||||
bestKey = key;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestKey) {
|
||||
// `bestKey` is the SDK's resolved model id (e.g. "claude-sonnet-5[1m]"),
|
||||
// the same spelling as ModelInfo.resolvedModel — the primary key the
|
||||
// window is cached under. `currentModel` (the assistant message's
|
||||
// `.model`) can be the bare form (e.g. "claude-sonnet-5"); the result
|
||||
// handler caches under that spelling too, for seed-time reads that fall
|
||||
// back to a bare id (rows without `resolvedModel`).
|
||||
return { key: bestKey, usage: modelUsage[bestKey] };
|
||||
}
|
||||
}
|
||||
242
src/settings.ts
242
src/settings.ts
@@ -1,242 +0,0 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
// resolveSettings and filterEscalatingDefaultMode are marked @alpha in the
|
||||
// SDK; API may shift in a future release.
|
||||
import {
|
||||
filterEscalatingDefaultMode,
|
||||
resolveSettings,
|
||||
type Settings,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { claudeConfigDir } from "./paths.js";
|
||||
|
||||
/**
|
||||
* Permission rule format examples:
|
||||
* - "Read" - matches all Read tool calls
|
||||
* - "Read(./.env)" - matches specific path
|
||||
* - "Read(./.env.*)" - glob pattern
|
||||
* - "Read(./secrets/**)" - recursive glob
|
||||
* - "Bash(npm run lint)" - exact command prefix
|
||||
* - "Bash(npm run:*)" - command prefix with wildcard
|
||||
*
|
||||
* Docs: https://code.claude.com/docs/en/iam#tool-specific-permission-rules
|
||||
*/
|
||||
|
||||
function getManagedSettingsPath(): string {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return "/Library/Application Support/ClaudeCode/managed-settings.json";
|
||||
case "win32":
|
||||
return "C:\\Program Files\\ClaudeCode\\managed-settings.json";
|
||||
default:
|
||||
return "/etc/claude-code/managed-settings.json";
|
||||
}
|
||||
}
|
||||
|
||||
export interface SettingsManagerOptions {
|
||||
onChange?: () => void;
|
||||
logger?: { log: (...args: any[]) => void; error: (...args: any[]) => void };
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages Claude Code settings using the SDK's `resolveSettings` merge engine
|
||||
* so the values we see match what `query()` would observe.
|
||||
*
|
||||
* Watches the user/project/local/managed settings files for changes and
|
||||
* re-resolves through the SDK on update. Escalating `permissions.defaultMode`
|
||||
* values from repo-committed sources are filtered out via
|
||||
* `filterEscalatingDefaultMode`, matching the CLI's trust policy.
|
||||
*/
|
||||
export class SettingsManager {
|
||||
private cwd: string;
|
||||
private effective: Settings = {};
|
||||
private managedDeniedModels: string[] = [];
|
||||
private managedApiKeyHelper?: string;
|
||||
private watchers: fs.FSWatcher[] = [];
|
||||
private onChange?: () => void;
|
||||
private logger: { log: (...args: any[]) => void; error: (...args: any[]) => void };
|
||||
private initialized = false;
|
||||
private disposed = false;
|
||||
private debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
|
||||
constructor(cwd: string, options?: SettingsManagerOptions) {
|
||||
this.cwd = cwd;
|
||||
this.onChange = options?.onChange;
|
||||
this.logger = options?.logger ?? console;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the settings manager by loading all settings and setting up file watchers
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
if (this.initPromise) {
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
this.disposed = false;
|
||||
this.initPromise = this.loadAllSettings().then(() => {
|
||||
if (!this.disposed) {
|
||||
this.setupWatchers();
|
||||
this.initialized = true;
|
||||
}
|
||||
this.initPromise = null;
|
||||
});
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths the SDK reads when resolving settings for this cwd. Watching the
|
||||
* containing directories means we pick up file creation as well as edits.
|
||||
*/
|
||||
private getWatchedPaths(): string[] {
|
||||
return [
|
||||
path.join(claudeConfigDir(), "settings.json"),
|
||||
path.join(this.cwd, ".claude", "settings.json"),
|
||||
path.join(this.cwd, ".claude", "settings.local.json"),
|
||||
getManagedSettingsPath(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the effective settings via the SDK and applies the CLI's trust
|
||||
* filter for escalating `permissions.defaultMode` values.
|
||||
*/
|
||||
private async loadAllSettings(): Promise<void> {
|
||||
try {
|
||||
const resolved = await resolveSettings({ cwd: this.cwd });
|
||||
this.effective = filterEscalatingDefaultMode(resolved);
|
||||
// The CLI reads `deniedModels` from managed settings only.
|
||||
this.managedDeniedModels = resolved.sources
|
||||
.filter((entry) => entry.source === "managed")
|
||||
.flatMap((entry) => entry.settings.deniedModels ?? []);
|
||||
this.managedApiKeyHelper =
|
||||
resolved.provenance.apiKeyHelper?.source === "managed"
|
||||
? resolved.effective.apiKeyHelper
|
||||
: undefined;
|
||||
} catch (error) {
|
||||
this.logger.error("Failed to resolve settings:", error);
|
||||
this.effective = {};
|
||||
this.managedDeniedModels = [];
|
||||
this.managedApiKeyHelper = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up file watchers for all settings files
|
||||
*/
|
||||
private setupWatchers(): void {
|
||||
for (const filePath of this.getWatchedPaths()) {
|
||||
try {
|
||||
const dir = path.dirname(filePath);
|
||||
const filename = path.basename(filePath);
|
||||
|
||||
if (fs.existsSync(dir)) {
|
||||
const watcher = fs.watch(dir, (eventType, changedFilename) => {
|
||||
if (changedFilename === filename) {
|
||||
this.handleSettingsChange();
|
||||
}
|
||||
});
|
||||
|
||||
watcher.on("error", (error) => {
|
||||
this.logger.error(`Settings watcher error for ${filePath}:`, error);
|
||||
});
|
||||
|
||||
this.watchers.push(watcher);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to set up watcher for ${filePath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles settings file changes with debouncing to avoid rapid reloads
|
||||
*/
|
||||
private handleSettingsChange(): void {
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer);
|
||||
}
|
||||
|
||||
this.debounceTimer = setTimeout(async () => {
|
||||
this.debounceTimer = null;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.loadAllSettings();
|
||||
if (!this.disposed) {
|
||||
this.onChange?.();
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error("Failed to reload settings:", error);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current merged settings
|
||||
*/
|
||||
getSettings(): Settings {
|
||||
return this.effective;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `apiKeyHelper` the CLI runs: managed settings outrank the `--settings`
|
||||
* override, which outranks the user/project/local files.
|
||||
*/
|
||||
getApiKeyHelper(settingsOverride?: Settings): string | undefined {
|
||||
return (
|
||||
this.managedApiKeyHelper ?? settingsOverride?.apiKeyHelper ?? this.effective.apiKeyHelper
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `deniedModels` entries from the managed tier, the only tier the CLI
|
||||
* honors them from.
|
||||
*/
|
||||
getManagedDeniedModels(): string[] {
|
||||
return this.managedDeniedModels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current working directory
|
||||
*/
|
||||
getCwd(): string {
|
||||
return this.cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the working directory and reloads project-specific settings
|
||||
*/
|
||||
async setCwd(cwd: string): Promise<void> {
|
||||
if (this.cwd === cwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dispose();
|
||||
this.cwd = cwd;
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disposes of file watchers and cleans up resources
|
||||
*/
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.initialized = false;
|
||||
this.initPromise = null;
|
||||
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer);
|
||||
this.debounceTimer = null;
|
||||
}
|
||||
|
||||
for (const watcher of this.watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
this.watchers = [];
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user