merge main

This commit is contained in:
Dallin Romney 2025-08-09 18:10:36 -07:00
commit e118375208
272 changed files with 17564 additions and 7600 deletions

87
.github/workflows/beta-release.yml vendored Normal file
View file

@ -0,0 +1,87 @@
name: Beta Release
on:
schedule:
# Run every day at 9am UTC
- cron: "0 9 * * *"
workflow_dispatch:
# Allow manual triggering
permissions:
contents: write
issues: write
pull-requests: write
jobs:
beta-release:
name: Beta Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Install dependencies
run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Get current version
id: get_version
run: |
# Get the latest version from package.json or npm registry
CURRENT_VERSION=$(node -p "require('./package.json').version")
if [[ "$CURRENT_VERSION" == "0.0.0-dev" ]]; then
# If it's dev version, get latest from npm registry
LATEST_VERSION=$(npm view @continuedev/cli version --silent 2>/dev/null || echo "0.0.0")
echo "Using latest npm version: $LATEST_VERSION"
CURRENT_VERSION=$LATEST_VERSION
fi
# Create beta version with current date
DATE_SUFFIX=$(date -u +%Y%m%d)
BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}"
echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT
- name: Update package.json for beta
run: |
# Update version in package.json
npm version ${{ steps.get_version.outputs.beta_version }} --no-git-tag-version
- name: Build
run: npm run build
- name: Publish beta to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag beta
echo "Published beta version: ${{ steps.get_version.outputs.beta_version }}"
- name: Create beta release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the beta
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.get_version.outputs.beta_version }}"
git push origin "v${{ steps.get_version.outputs.beta_version }}"
# Create GitHub release
gh release create "v${{ steps.get_version.outputs.beta_version }}" \
--title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \
--notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \
--prerelease

View file

@ -151,11 +151,10 @@ jobs:
if: inputs.prompt == '' && github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.event != 'pull_request')
run: |
cat > review_prompt.txt << 'EOF'
Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement.
Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. You do not need to acknowledge what was done well.
Format your response as a markdown code review.
Format your response as a markdown code review with each comment having only a short description about the problem and suggested solution, each being separated by "\n\n---\n\n".
Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
EOF
- name: Run Continue CLI Review
@ -167,7 +166,7 @@ jobs:
echo ""
# Run the CLI with the generated prompt and pipe output to code_review.md
cat review_prompt.txt | cn --config "${{ inputs.assistant }}" -p > code_review.md
cat review_prompt.txt | cn --auto --config "${{ inputs.assistant }}" -p > code_review.md
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}

View file

@ -10,6 +10,42 @@ permissions:
issues: write
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Run linting
run: npm run lint
format-check:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Check code formatting
run: npm run format:check
test:
strategy:
matrix:
@ -41,10 +77,7 @@ jobs:
- name: Run tests (excluding e2e on Windows)
if: matrix.os == 'windows-latest'
shell: bash
run: npm test -- --testPathIgnorePatterns='.*e2e.*'
- name: Run linting
run: npm run lint
run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
review:
uses: ./.github/workflows/continue-review.yaml
@ -65,6 +98,8 @@ jobs:
if: always()
runs-on: ubuntu-latest
needs:
- lint
- format-check
- test
steps:

View file

@ -1,11 +1,11 @@
name: Release
name: Legacy Release (Deprecated)
on:
schedule:
# Run every day at 9am UTC
- cron: "0 9 * * *"
# schedule:
# # Run every day at 9am UTC
# - cron: "0 9 * * *"
workflow_dispatch:
# Allow manual triggering
# Keep manual triggering for emergencies
permissions:
contents: write
@ -46,4 +46,4 @@ jobs:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release
run: npx semantic-release

View file

@ -0,0 +1,59 @@
name: Respond to @continuedev Comments
on:
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
respond-to-comment:
# Only run on pull request comments
if: github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Get comment content
if: steps.check-mention.outputs.contains_mention == 'true'
id: comment-content
run: |
# Store the comment body for debugging/logging
echo "Comment mentioning @continuedev from ${{ github.event.comment.user.login }}:"
echo "${{ github.event.comment.body }}"
- name: Respond to @continuedev mention
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v7
with:
script: |
const commentBody = `👋 Thanks for mentioning @continuedev, @${{ github.event.comment.user.login }}!
I've received your comment:
> ${{ github.event.comment.body }}
Your input has been acknowledged and will be reviewed by the team.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log acknowledgement
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully acknowledged comment mentioning @continuedev from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Original comment: ${{ github.event.comment.body }}"

137
.github/workflows/stable-release.yml vendored Normal file
View file

@ -0,0 +1,137 @@
name: Stable Release
on:
schedule:
# Run every Monday at 10am UTC (1 hour after beta release)
- cron: "0 10 * * 1"
workflow_dispatch:
inputs:
beta_version:
description: "Specific beta version to promote (e.g., 1.2.3-beta.20240115)"
required: false
type: string
permissions:
contents: write
issues: write
pull-requests: write
jobs:
stable-release:
name: Stable Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Find beta version to promote
id: find_beta
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [[ -n "${{ inputs.beta_version }}" ]]; then
# Manual input provided
BETA_VERSION="${{ inputs.beta_version }}"
echo "Using manually specified beta version: $BETA_VERSION"
else
# Find beta version that's at least 7 days old
SEVEN_DAYS_AGO=$(date -u -d '7 days ago' +%Y%m%d)
echo "Looking for beta versions from $SEVEN_DAYS_AGO or earlier"
# Get all beta versions from npm
BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' | sort -V)
CANDIDATE_VERSION=""
for version in $BETA_VERSIONS; do
# Extract date from beta version (format: x.y.z-beta.YYYYMMDD)
if [[ $version =~ -beta\.([0-9]{8}) ]]; then
BETA_DATE="${BASH_REMATCH[1]}"
if [[ $BETA_DATE -le $SEVEN_DAYS_AGO ]]; then
CANDIDATE_VERSION=$version
fi
fi
done
if [[ -z "$CANDIDATE_VERSION" ]]; then
echo "No beta version found that is at least 7 days old"
exit 1
fi
BETA_VERSION=$CANDIDATE_VERSION
echo "Selected beta version for promotion: $BETA_VERSION"
fi
# Extract base version (remove -beta.YYYYMMDD suffix)
STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//')
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
- name: Download and verify beta package
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
# Download the specific beta version
npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }}
# Extract and verify the package
PACKAGE_FILE=$(ls continuedev-cli-*.tgz)
tar -xzf "$PACKAGE_FILE"
echo "Beta package contents verified"
ls -la package/
- name: Update package.json for stable release
run: |
# Copy the beta package contents
cp -r package/* .
# Update version to stable (remove beta suffix)
npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
- name: Build (verification step)
run: npm run build
- name: Run tests (verification step)
run: npm test
- name: Publish stable to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag latest
echo "Published stable version: ${{ steps.find_beta.outputs.stable_version }}"
- name: Create stable release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the stable release
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.find_beta.outputs.stable_version }}"
git push origin "v${{ steps.find_beta.outputs.stable_version }}"
# Create GitHub release
gh release create "v${{ steps.find_beta.outputs.stable_version }}" \
--title "Stable Release v${{ steps.find_beta.outputs.stable_version }}" \
--notes "Stable release promoted from tested beta version ${{ steps.find_beta.outputs.beta_version }}. This version has been thoroughly tested in beta for at least 7 days." \
--latest
- name: Update GitHub release notes
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Mark the original beta release as superseded
gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \
--notes "This beta version has been promoted to stable as v${{ steps.find_beta.outputs.stable_version }}."

5
.gitignore vendored
View file

@ -5,4 +5,7 @@ dist
chat.log
*notes.md
*notes.md
# Local config files (users should not commit their personal configs)
config.yaml

40
.prettierignore Normal file
View file

@ -0,0 +1,40 @@
# Dependencies
node_modules/
# Build output
dist/
# Coverage
coverage/
# Logs
*.log
logs/
# OS files
.DS_Store
Thumbs.db
# IDE files
.vscode/
.idea/
*.swp
*.swo
# Lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
# Test files
*.test.ts
*.test.tsx
*.spec.ts
*.spec.tsx
# Config files that don't need formatting
.prettierrc
.prettierignore
# Generated files
*.generated.*

8
.prettierrc Normal file
View file

@ -0,0 +1,8 @@
{
"tabWidth": 2,
"useTabs": false,
"trailingComma": "all",
"semi": true,
"singleQuote": false,
"bracketSpacing": true
}

3
.vscode/launch.json vendored
View file

@ -21,7 +21,8 @@
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
]
],
"preLaunchTask": "watch-logs"
},
{

26
.vscode/tasks.json vendored
View file

@ -27,6 +27,30 @@
"showReuseMessage": true,
"clear": false
}
},
{
"label": "watch-logs",
"type": "shell",
"command": "npm run watch:logs",
"isBackground": true,
"problemMatcher": {
"pattern": {
"regexp": "^$",
"file": 1,
"location": 2,
"message": 3
},
"background": {
"activeOnStart": true,
"beginsPattern": "^.*$",
"endsPattern": "^.*$"
}
},
"presentation": {
"reveal": "always",
"panel": "new",
"focus": false
}
}
]
}
}

View file

@ -17,30 +17,25 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev
### Core Components
1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes:
- **Headless mode**: Non-interactive mode for automation/CI
- **TUI mode**: Terminal User Interface using Ink/React
- **Standard mode**: Traditional readline-based chat interface
2. **Authentication** (`src/auth/`): WorkOS-based authentication system
- `ensureAuth.ts`: Handles authentication flow
- `workos.ts`: WorkOS configuration and token management
3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with:
- API key authentication
- Assistant configuration (slug-based)
- Organization support
4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components
- `TUIChat.tsx`: Main chat interface component
- `UserInput.tsx`: Input handling with multi-line support
- `TextBuffer.ts`: Text display utilities
5. **Tools System** (`src/tools/`): Built-in development tools including:
- File operations (read, write, list)
- Code search functionality
- Terminal command execution

View file

@ -1,151 +1,134 @@
## [1.4.2](https://github.com/continuedev/cli/compare/v1.4.1...v1.4.2) (2025-07-17)
### Bug Fixes
* remove warning ([31b3f67](https://github.com/continuedev/cli/commit/31b3f6707b0f42180c8ae56faf9dfb2f566be5c1))
- remove warning ([31b3f67](https://github.com/continuedev/cli/commit/31b3f6707b0f42180c8ae56faf9dfb2f566be5c1))
## [1.4.1](https://github.com/continuedev/cli/compare/v1.4.0...v1.4.1) (2025-07-17)
### Bug Fixes
* update readme ([0d45e14](https://github.com/continuedev/cli/commit/0d45e14b1be6557ace027cfeadfbf418061a28b0))
- update readme ([0d45e14](https://github.com/continuedev/cli/commit/0d45e14b1be6557ace027cfeadfbf418061a28b0))
# [1.4.0](https://github.com/continuedev/cli/compare/v1.3.6...v1.4.0) (2025-07-17)
### Features
* dim user msg text color ([b22429b](https://github.com/continuedev/cli/commit/b22429ba0a101f99b14313345a8a8894caff3081))
- dim user msg text color ([b22429b](https://github.com/continuedev/cli/commit/b22429ba0a101f99b14313345a8a8894caff3081))
## [1.3.6](https://github.com/continuedev/cli/compare/v1.3.5...v1.3.6) (2025-07-16)
### Bug Fixes
* update readme ([01329e4](https://github.com/continuedev/cli/commit/01329e4b4f66d97c93c98e0342f100792f626126))
- update readme ([01329e4](https://github.com/continuedev/cli/commit/01329e4b4f66d97c93c98e0342f100792f626126))
## [1.3.5](https://github.com/continuedev/cli/compare/v1.3.4...v1.3.5) (2025-07-16)
### Bug Fixes
* package.json issues page ([91e1e2e](https://github.com/continuedev/cli/commit/91e1e2e004e86d6fb1df3bbfbbf94f6d46a4adb7))
* update review.yaml config ([b49ab0d](https://github.com/continuedev/cli/commit/b49ab0d9e54edf8374b113af4752e1c6fba15738))
- package.json issues page ([91e1e2e](https://github.com/continuedev/cli/commit/91e1e2e004e86d6fb1df3bbfbbf94f6d46a4adb7))
- update review.yaml config ([b49ab0d](https://github.com/continuedev/cli/commit/b49ab0d9e54edf8374b113af4752e1c6fba15738))
## [1.3.4](https://github.com/continuedev/cli/compare/v1.3.3...v1.3.4) (2025-07-16)
### Bug Fixes
* add /clear command to clear chat history ([3782732](https://github.com/continuedev/cli/commit/378273239b32fce735266cb4835512f5c547a86d))
- add /clear command to clear chat history ([3782732](https://github.com/continuedev/cli/commit/378273239b32fce735266cb4835512f5c547a86d))
## [1.3.3](https://github.com/continuedev/cli/compare/v1.3.2...v1.3.3) (2025-07-16)
### Bug Fixes
* update chat history state after streaming and save complete conversation ([936786a](https://github.com/continuedev/cli/commit/936786aee08fcbdde2484896730a0c67f1ebafee))
- update chat history state after streaming and save complete conversation ([936786a](https://github.com/continuedev/cli/commit/936786aee08fcbdde2484896730a0c67f1ebafee))
## [1.3.2](https://github.com/continuedev/cli/compare/v1.3.1...v1.3.2) (2025-07-16)
### Bug Fixes
* remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6))
- remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6))
## [1.3.1](https://github.com/continuedev/cli/compare/v1.3.0...v1.3.1) (2025-07-16)
### Bug Fixes
* type err ([f5f1bca](https://github.com/continuedev/cli/commit/f5f1bca7c6a9f2c4f2842605847d55b765fd3499))
- type err ([f5f1bca](https://github.com/continuedev/cli/commit/f5f1bca7c6a9f2c4f2842605847d55b765fd3499))
# [1.3.0](https://github.com/continuedev/cli/compare/v1.2.0...v1.3.0) (2025-07-15)
### Features
* add session management with --resume flag and cn alias ([0096fbc](https://github.com/continuedev/cli/commit/0096fbcc4934d7264d9a7a134908e016e037df1a))
- add session management with --resume flag and cn alias ([0096fbc](https://github.com/continuedev/cli/commit/0096fbcc4934d7264d9a7a134908e016e037df1a))
# [1.2.0](https://github.com/continuedev/cli/compare/v1.1.0...v1.2.0) (2025-07-14)
### Bug Fixes
* bg color for diff ([63c9ecf](https://github.com/continuedev/cli/commit/63c9ecf24fcf74f43d07244c963cef04f91baee8))
* display diff ([fde6098](https://github.com/continuedev/cli/commit/fde6098ef2c4d99a9b9b8d6ffc1299436e0f52c1))
* improve streaming message handling and display buffering ([d1372b3](https://github.com/continuedev/cli/commit/d1372b3aa2f79221957468fd1decbae2258becc0))
* remove part of the system message ([daae972](https://github.com/continuedev/cli/commit/daae97242f1fca92f42f8c979df8d9c3f912f69d))
* truncate diff at 16 lines ([cbb77e3](https://github.com/continuedev/cli/commit/cbb77e35ff19809c1c05760fbdf7c995d85dc72c))
- bg color for diff ([63c9ecf](https://github.com/continuedev/cli/commit/63c9ecf24fcf74f43d07244c963cef04f91baee8))
- display diff ([fde6098](https://github.com/continuedev/cli/commit/fde6098ef2c4d99a9b9b8d6ffc1299436e0f52c1))
- improve streaming message handling and display buffering ([d1372b3](https://github.com/continuedev/cli/commit/d1372b3aa2f79221957468fd1decbae2258becc0))
- remove part of the system message ([daae972](https://github.com/continuedev/cli/commit/daae97242f1fca92f42f8c979df8d9c3f912f69d))
- truncate diff at 16 lines ([cbb77e3](https://github.com/continuedev/cli/commit/cbb77e35ff19809c1c05760fbdf7c995d85dc72c))
### Features
* add /clear command to clear chat history ([c9c000c](https://github.com/continuedev/cli/commit/c9c000cfab6aa6efe156126f1eafc99349466413))
* convert absolute paths to relative paths in tool display ([2c722c4](https://github.com/continuedev/cli/commit/2c722c485eea4c3c283fb643193a4b1ffe14bf7f))
- add /clear command to clear chat history ([c9c000c](https://github.com/continuedev/cli/commit/c9c000cfab6aa6efe156126f1eafc99349466413))
- convert absolute paths to relative paths in tool display ([2c722c4](https://github.com/continuedev/cli/commit/2c722c485eea4c3c283fb643193a4b1ffe14bf7f))
# [1.1.0](https://github.com/continuedev/cli/compare/v1.0.1...v1.1.0) (2025-07-14)
### Bug Fixes
* improve streaming message handling and API endpoint ([b822b93](https://github.com/continuedev/cli/commit/b822b938f110af2de2c040f45cd3fca770d9a4a7))
* use ignore-walk for sys msg ([eb59dcc](https://github.com/continuedev/cli/commit/eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3))
- improve streaming message handling and API endpoint ([b822b93](https://github.com/continuedev/cli/commit/b822b938f110af2de2c040f45cd3fca770d9a4a7))
- use ignore-walk for sys msg ([eb59dcc](https://github.com/continuedev/cli/commit/eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3))
### Features
* base system message ([25a67cf](https://github.com/continuedev/cli/commit/25a67cf947f786d4cdc36c60e36e303a4e466c87))
- base system message ([25a67cf](https://github.com/continuedev/cli/commit/25a67cf947f786d4cdc36c60e36e303a4e466c87))
## [1.0.1](https://github.com/continuedev/cli/compare/v1.0.0...v1.0.1) (2025-07-14)
### Bug Fixes
* release index.js ([091cfa7](https://github.com/continuedev/cli/commit/091cfa7b64c1591f371e444e602d04fdcbca48d4))
- release index.js ([091cfa7](https://github.com/continuedev/cli/commit/091cfa7b64c1591f371e444e602d04fdcbca48d4))
# 1.0.0 (2025-07-14)
### Bug Fixes
* adjust placeholder ([94e6f12](https://github.com/continuedev/cli/commit/94e6f12924ff5ee429a43c53d1810d5519f026bb))
* adjust waiting message ([454df15](https://github.com/continuedev/cli/commit/454df1554500a530645ef5e7a6a80fea6a27f207))
* allow multiple consecutive new lines ([423dbdd](https://github.com/continuedev/cli/commit/423dbdd457683260f66eda9024f35dee9c49d5db))
* backspace on mac ([aa5606f](https://github.com/continuedev/cli/commit/aa5606f65f3284c9ff4d0a02cb1e4611b5cd080c))
* cursor position ([388eeeb](https://github.com/continuedev/cli/commit/388eeeb37afa7625b954e4dd44cbcd7cf0ab22bb))
* delete hallucinated tools ([2d4cf55](https://github.com/continuedev/cli/commit/2d4cf55c393121570ff2c4459c6942e124bc88dd))
* dot shade of green ([8f6ec39](https://github.com/continuedev/cli/commit/8f6ec398ff23ec1d59567cb5b2de92dabd58ab4b))
* empty assistant message ([5e773f5](https://github.com/continuedev/cli/commit/5e773f52684dc8b267fa33a94b0b707d292a6111))
* even nicer tool UI ([3716ebc](https://github.com/continuedev/cli/commit/3716ebcdd73a23e021e59a9d162d61915ce31184))
* more slashcommand UI ([daa4538](https://github.com/continuedev/cli/commit/daa45387725f6b0b9b247ebde63f1f3018052bc2))
* nicer tool display ([6749e10](https://github.com/continuedev/cli/commit/6749e10daad3fc9238dce6bf5c7309dd610cad2a))
* option + left/rght ([efa2c43](https://github.com/continuedev/cli/commit/efa2c434d0a5942e9aaf5171c2d1f03c5df3ca51))
* refactor display name for tools ([837ac2d](https://github.com/continuedev/cli/commit/837ac2d5c33ad0ef6482f8216dd7b3a8ec852fe3))
* round corners ([a08e217](https://github.com/continuedev/cli/commit/a08e2176a70f5a216f6e03657e9f6522eade99b8))
* shift+enter for newline ([fa30094](https://github.com/continuedev/cli/commit/fa30094e61dbb2b11f7940b875fc719d06ed3eec))
* slash command prefix matching ([0a40201](https://github.com/continuedev/cli/commit/0a402010d9ae98a6913b7ceb68b97dfd9772754e))
* slash command tab ([ee40d8b](https://github.com/continuedev/cli/commit/ee40d8bbb48d502055cad1e811e973598b0bf9bd))
* stream above input box ([c8945ad](https://github.com/continuedev/cli/commit/c8945adb85c99379039afa02ac4d63f114a6de6b))
* tool call custom UI ([fa4b98f](https://github.com/continuedev/cli/commit/fa4b98f455db6fe48b4c5810327d0222fade7902))
* tool name matching ([9792b14](https://github.com/continuedev/cli/commit/9792b1411f713c2615c0d3b82df2c7032d434205))
* tool ui again ([9c18d28](https://github.com/continuedev/cli/commit/9c18d28cbefed79f316a0b9d219f7ec585455eca))
* tool UI again ([9d4ea20](https://github.com/continuedev/cli/commit/9d4ea20deb278a7c8d427647b5c1d5cf4d333352))
* tui no longer completely broken ([8c0fd5e](https://github.com/continuedev/cli/commit/8c0fd5e87e7e8ce59b4b022669d4aba2ba1b8bcf))
- adjust placeholder ([94e6f12](https://github.com/continuedev/cli/commit/94e6f12924ff5ee429a43c53d1810d5519f026bb))
- adjust waiting message ([454df15](https://github.com/continuedev/cli/commit/454df1554500a530645ef5e7a6a80fea6a27f207))
- allow multiple consecutive new lines ([423dbdd](https://github.com/continuedev/cli/commit/423dbdd457683260f66eda9024f35dee9c49d5db))
- backspace on mac ([aa5606f](https://github.com/continuedev/cli/commit/aa5606f65f3284c9ff4d0a02cb1e4611b5cd080c))
- cursor position ([388eeeb](https://github.com/continuedev/cli/commit/388eeeb37afa7625b954e4dd44cbcd7cf0ab22bb))
- delete hallucinated tools ([2d4cf55](https://github.com/continuedev/cli/commit/2d4cf55c393121570ff2c4459c6942e124bc88dd))
- dot shade of green ([8f6ec39](https://github.com/continuedev/cli/commit/8f6ec398ff23ec1d59567cb5b2de92dabd58ab4b))
- empty assistant message ([5e773f5](https://github.com/continuedev/cli/commit/5e773f52684dc8b267fa33a94b0b707d292a6111))
- even nicer tool UI ([3716ebc](https://github.com/continuedev/cli/commit/3716ebcdd73a23e021e59a9d162d61915ce31184))
- more slashcommand UI ([daa4538](https://github.com/continuedev/cli/commit/daa45387725f6b0b9b247ebde63f1f3018052bc2))
- nicer tool display ([6749e10](https://github.com/continuedev/cli/commit/6749e10daad3fc9238dce6bf5c7309dd610cad2a))
- option + left/rght ([efa2c43](https://github.com/continuedev/cli/commit/efa2c434d0a5942e9aaf5171c2d1f03c5df3ca51))
- refactor display name for tools ([837ac2d](https://github.com/continuedev/cli/commit/837ac2d5c33ad0ef6482f8216dd7b3a8ec852fe3))
- round corners ([a08e217](https://github.com/continuedev/cli/commit/a08e2176a70f5a216f6e03657e9f6522eade99b8))
- shift+enter for newline ([fa30094](https://github.com/continuedev/cli/commit/fa30094e61dbb2b11f7940b875fc719d06ed3eec))
- slash command prefix matching ([0a40201](https://github.com/continuedev/cli/commit/0a402010d9ae98a6913b7ceb68b97dfd9772754e))
- slash command tab ([ee40d8b](https://github.com/continuedev/cli/commit/ee40d8bbb48d502055cad1e811e973598b0bf9bd))
- stream above input box ([c8945ad](https://github.com/continuedev/cli/commit/c8945adb85c99379039afa02ac4d63f114a6de6b))
- tool call custom UI ([fa4b98f](https://github.com/continuedev/cli/commit/fa4b98f455db6fe48b4c5810327d0222fade7902))
- tool name matching ([9792b14](https://github.com/continuedev/cli/commit/9792b1411f713c2615c0d3b82df2c7032d434205))
- tool ui again ([9c18d28](https://github.com/continuedev/cli/commit/9c18d28cbefed79f316a0b9d219f7ec585455eca))
- tool UI again ([9d4ea20](https://github.com/continuedev/cli/commit/9d4ea20deb278a7c8d427647b5c1d5cf4d333352))
- tui no longer completely broken ([8c0fd5e](https://github.com/continuedev/cli/commit/8c0fd5e87e7e8ce59b4b022669d4aba2ba1b8bcf))
### Features
* basic ink tui ([ed536d3](https://github.com/continuedev/cli/commit/ed536d3505167cd15e46ec4dee49847eb87b63a8))
* better slash command UI ([c62cbdc](https://github.com/continuedev/cli/commit/c62cbdc21e6e93788d8e01c0a97c17ef0c036261))
* disable PR description ([a5722ba](https://github.com/continuedev/cli/commit/a5722bab8bd7fb925806a767e9f76a4165f5f6b3))
* esc to interrupt ([5643a53](https://github.com/continuedev/cli/commit/5643a53b5a3440d1e3e2ee41df08524289ad94b2))
* integrate SDK into CLI ([#1](https://github.com/continuedev/cli/issues/1)) ([597e35b](https://github.com/continuedev/cli/commit/597e35b5be0ab1d1f62b6d9e2ac71e168d06e39c))
* more spinners ([dccb311](https://github.com/continuedev/cli/commit/dccb31106a43f2c295da3f8a4225a44969cb3ef7))
* new TextBuffer class for improved keystroke handling ([e7ab301](https://github.com/continuedev/cli/commit/e7ab301dbe3b7e27bd6bb15992f3cf1a3f9694d7))
* paste ([65f10a1](https://github.com/continuedev/cli/commit/65f10a1a4f2862bf1166d187e49fc732a503f9da))
* slash command UI and ASCII spinner ([7eefce2](https://github.com/continuedev/cli/commit/7eefce2de39fca9ab51b2d2fb1d0b24286c09404))
* suppress `console.info` in headless ([8177eef](https://github.com/continuedev/cli/commit/8177eef6a00a06f5c80d4b0ee4c84f00fd156cd5))
* TUI mode as default ([e73098b](https://github.com/continuedev/cli/commit/e73098b82ed5ea73f6d8d33eab24fdf6c67bb8ec))
- basic ink tui ([ed536d3](https://github.com/continuedev/cli/commit/ed536d3505167cd15e46ec4dee49847eb87b63a8))
- better slash command UI ([c62cbdc](https://github.com/continuedev/cli/commit/c62cbdc21e6e93788d8e01c0a97c17ef0c036261))
- disable PR description ([a5722ba](https://github.com/continuedev/cli/commit/a5722bab8bd7fb925806a767e9f76a4165f5f6b3))
- esc to interrupt ([5643a53](https://github.com/continuedev/cli/commit/5643a53b5a3440d1e3e2ee41df08524289ad94b2))
- integrate SDK into CLI ([#1](https://github.com/continuedev/cli/issues/1)) ([597e35b](https://github.com/continuedev/cli/commit/597e35b5be0ab1d1f62b6d9e2ac71e168d06e39c))
- more spinners ([dccb311](https://github.com/continuedev/cli/commit/dccb31106a43f2c295da3f8a4225a44969cb3ef7))
- new TextBuffer class for improved keystroke handling ([e7ab301](https://github.com/continuedev/cli/commit/e7ab301dbe3b7e27bd6bb15992f3cf1a3f9694d7))
- paste ([65f10a1](https://github.com/continuedev/cli/commit/65f10a1a4f2862bf1166d187e49fc732a503f9da))
- slash command UI and ASCII spinner ([7eefce2](https://github.com/continuedev/cli/commit/7eefce2de39fca9ab51b2d2fb1d0b24286c09404))
- suppress `console.info` in headless ([8177eef](https://github.com/continuedev/cli/commit/8177eef6a00a06f5c80d4b0ee4c84f00fd156cd5))
- TUI mode as default ([e73098b](https://github.com/continuedev/cli/commit/e73098b82ed5ea73f6d8d33eab24fdf6c67bb8ec))

150
README-sentry.md Normal file
View file

@ -0,0 +1,150 @@
# Sentry Integration
This document explains how to configure and use Sentry for error monitoring and performance tracking in the Continue CLI.
## Setup
### Environment Variables
To enable Sentry, set the following environment variables:
```bash
# Required: Sentry DSN (Data Source Name)
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
# Optional: Environment name (defaults to NODE_ENV or "development")
export SENTRY_ENVIRONMENT="production"
# Optional: Sample rates (defaults to 1.0 for all)
export SENTRY_SAMPLE_RATE="1.0" # Error sampling rate
export SENTRY_PROFILES_SAMPLE_RATE="1.0" # Performance profiling rate
export SENTRY_TRACES_SAMPLE_RATE="1.0" # Performance tracing rate
```
### Disabling Sentry
To completely disable Sentry, you can:
1. **Not set `SENTRY_DSN`** - Sentry will be disabled automatically
2. **Explicitly disable**: `export SENTRY_ENABLED="false"`
## What Gets Monitored
### Automatic Error Capture
- **Unhandled Promise Rejections**: Global promise rejections are captured
- **Uncaught Exceptions**: Global uncaught exceptions are captured
- **Logger Errors**: All `logger.error()` and `logger.warn()` calls are sent to Sentry
- **Command Errors**: Errors in chat commands and other CLI operations
### Performance Monitoring
- **Profiling**: CPU and memory profiling data (when enabled)
- **Performance Traces**: Request timing and performance metrics
### Context Information
Sentry automatically includes:
- Application version
- Environment (development/production)
- Node.js version and platform
- Error stack traces
- Custom context for each error (when available)
## Usage in Code
The Sentry service is automatically initialized and available throughout the application. You can use it directly:
```typescript
import { sentryService } from "./sentry.js";
// Capture an exception with context
try {
// some code
} catch (error) {
sentryService.captureException(error, {
context: "my_operation",
userId: "12345",
});
}
// Capture a message
sentryService.captureMessage("Something important happened", "info", {
customData: "value",
});
// Set user context
sentryService.setUser({
id: "user123",
email: "user@example.com",
});
// Add breadcrumbs for debugging
sentryService.addBreadcrumb({
message: "User performed action",
category: "user",
level: "info",
data: { action: "click_button" },
});
```
## Testing the Integration
### Test Error Capture
```bash
# Set up Sentry (replace with your actual DSN)
export SENTRY_DSN="https://your-dsn@sentry.io/project-id"
# Run the CLI and trigger an error to test
cn "this should work normally"
```
### Test Disabled State
```bash
# Disable Sentry
export SENTRY_ENABLED="false"
# or simply don't set SENTRY_DSN
# Run the CLI - no Sentry data should be sent
cn "this will run without Sentry"
```
### Verify Configuration
The application logs will show when Sentry is initialized:
```
DEBUG: Sentry initialized { environment: 'development', release: '0.0.0-dev' }
```
If Sentry is disabled, you won't see this log message.
## Privacy and Security
- Sentry only captures error information and performance metrics
- No user prompts or sensitive data are sent to Sentry by default
- All data transmission is encrypted (HTTPS)
- You control what environment and sampling rates to use
## Troubleshooting
### Sentry Not Working
1. **Check DSN**: Ensure `SENTRY_DSN` is set correctly
2. **Check Network**: Ensure your environment can reach sentry.io
3. **Check Logs**: Look for Sentry initialization messages in debug logs
4. **Check Sampling**: Ensure sample rates are > 0
### Too Much Data
1. **Reduce Sample Rates**: Lower `SENTRY_SAMPLE_RATE`, `SENTRY_PROFILES_SAMPLE_RATE`, or `SENTRY_TRACES_SAMPLE_RATE`
2. **Use Environment Filtering**: Set different configurations for dev vs prod
### No Data in Sentry Dashboard
1. **Check Project Settings**: Ensure the DSN matches your Sentry project
2. **Check Filters**: Verify no filters are blocking your data
3. **Wait**: It can take a few minutes for data to appear in Sentry

129
docs/command-line-flags.md Normal file
View file

@ -0,0 +1,129 @@
# Continue CLI Command Line Options
Quick reference for using `cn` command line options.
## Basic Usage
```bash
cn # Start interactive chat
cn "analyze my code" # Chat with prompt
cn -p "review this file" # Print response and exit (headless)
```
## Configuration
- `--config <path>` - Use specific config file
- `--verbose` - Show detailed logging
```bash
cn --config ./my-config.yaml
cn --verbose -p "debug this issue"
```
## Permission Modes
- `--readonly` - Only allow read operations (safe mode)
- `--auto` - Allow all tools without asking (careful!)
```bash
cn --readonly -p "analyze the codebase" # Safe: can't modify files
cn --auto -p "fix the failing tests" # Dangerous: will modify files
```
## Fine-grained Permissions
- `--allow <tool>` - Allow specific tools
- `--ask <tool>` - Ask before using tools
- `--exclude <tool>` - Block specific tools
```bash
cn --allow readFile --allow searchCode -p "find todos"
cn --exclude Write -p "help me understand this code" # Can't modify files
cn --ask writeFile -p "suggest fixes" # Will ask before writing
```
## Headless Mode (for scripts)
Use `-p` for non-interactive output:
```bash
cn -p "summarize the main function"
echo "error log" | cn -p "what caused this error?"
cn -p --format json "list main files" | jq '.response'
cn -p --silent "get summary" | grep -v "^$" # Clean output
```
## Server Mode
Run Continue as a server:
```bash
cn serve # Start server on port 8000
cn serve --port 3000 # Custom port
cn serve --timeout 600 # 10 minute timeout
```
## Remote Development
```bash
cn remote "help debug this" # Create new remote environment
cn remote --url https://my-server.com "work" # Connect to existing server
cn remote --idempotency-key my-session "work" # Resume or create idempotent session
```
### Idempotent Sessions
Use `--idempotency-key` to create resumable remote sessions:
```bash
# First time - creates new session
cn remote --idempotency-key "project-review" "start code review"
# Later - resumes same session if it exists
cn remote --idempotency-key "project-review" "continue where we left off"
# Different key - creates separate session
cn remote --idempotency-key "feature-dev" "work on new feature"
```
The backend manages session lifecycle based on the idempotency key:
- New key = new remote environment
- Existing key = connect to existing session
- Sessions may expire based on backend configuration
### Repository Detection
The `cn remote` command automatically detects your repository URL:
- **GitHub Actions**: Uses `GITHUB_REPOSITORY` and `GITHUB_SERVER_URL` environment variables
- **Git Repository**: Uses `git remote get-url origin`
- **Fallback**: Uses current working directory path
This ensures the remote environment is created with the correct repository context.
## Common Examples
```bash
# Safe code analysis
cn --readonly -p "review my git diff"
# Let AI fix tests (with permission)
cn --ask writeFile -p "fix failing tests"
# Scripted code review
git diff | cn -p "review this change" --format json
# Remote pair programming
cn remote "help me implement user auth"
# Run as code review server
cn serve --readonly --port 8080
```
## Notes
- Use `--readonly` when you want AI to analyze but not modify code
- Use `--auto` only when you trust the AI to make changes
- Pipe input works: `cat file.py | cn -p "explain this"`
- `--format json` and `--silent` only work with `-p`

112
eslint.config.js Normal file
View file

@ -0,0 +1,112 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
import importPlugin from "eslint-plugin-import";
import unusedImports from "eslint-plugin-unused-imports";
export default [
{
files: ["**/*.ts", "**/*.tsx"],
plugins: {
"@typescript-eslint": tsPlugin,
import: importPlugin,
"unused-imports": unusedImports,
},
languageOptions: {
parser: tsParser,
parserOptions: {
project: "./tsconfig.json",
ecmaVersion: "latest",
sourceType: "module",
},
},
rules: {
// Core rules - all as errors
"max-classes-per-file": ["error", 1],
"prefer-const": "error",
// TypeScript specific rules
"@typescript-eslint/no-floating-promises": "off",
// Import rules
"import/order": [
"error",
{
groups: [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
],
"newlines-between": "always",
alphabetize: {
order: "asc",
caseInsensitive: true,
},
},
],
"import/no-default-export": "error",
// Unused code detection
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"error",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
},
],
// Turn off rules that might be too strict
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-non-null-assertion": "off",
// Allow console for CLI tool
"no-console": "off",
},
settings: {
"import/resolver": {
typescript: {
project: "./tsconfig.json",
},
node: true,
},
},
},
{
// Allow default exports in specific files
files: ["src/index.ts", "*.config.js", "*.config.ts"],
rules: {
"import/no-default-export": "off",
},
},
{
// Test files can have different rules
files: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"],
rules: {
"@typescript-eslint/no-explicit-any": "off",
"unused-imports/no-unused-vars": "off",
"max-classes-per-file": "off",
},
},
{
ignores: [
"dist/**",
"node_modules/**",
"coverage/**",
"*.d.ts",
"src/__mocks__/**",
"jest.setup.ts",
"vitest.config.ts",
"*.config.js",
"*.config.ts",
],
},
];

View file

@ -3,21 +3,21 @@
# Tools that are automatically allowed without prompting
allow:
- Read # or read_file, read, READ - all normalized
- List # or list_files
- Search # or search_code
- Read # or read_file, read, READ - all normalized
- List # or list_files
- Search # or search_code
# Tools that require user confirmation before execution
ask:
- Write # or write_file
- Terminal # or run_terminal_command, Bash, bash
- Write # or write_file
- Terminal # or run_terminal_command, Bash, bash
# Tools that are completely excluded (model won't know they exist)
exclude:
- Exit # or exit
- Exit # or exit
# You can also use wildcards
# allow:
# - mcp__* # Allow all MCP tools
# exclude:
# - * # Exclude everything else
# - * # Exclude everything else

View file

@ -1,29 +1,29 @@
// Custom resolver for Jest to handle .js extensions in ESM project
const path = require('path');
const fs = require('fs');
const path = require("path");
const fs = require("fs");
module.exports = (request, options) => {
// Call the default resolver
const defaultResolver = options.defaultResolver;
// First try the default resolver
try {
return defaultResolver(request, options);
} catch (e) {
// Only continue if module not found
if (!e.message || !e.message.includes('Cannot find module')) {
if (!e.message || !e.message.includes("Cannot find module")) {
throw e;
}
}
// Handle relative imports
if (request.startsWith('.')) {
if (request.startsWith(".")) {
const basePath = options.basedir;
const fullPath = path.resolve(basePath, request);
// Try various extensions
const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
const extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
for (const ext of extensions) {
const testPath = fullPath + ext;
try {
@ -34,10 +34,10 @@ module.exports = (request, options) => {
// Continue to next extension
}
}
// Also try adding /index with various extensions
for (const ext of extensions) {
const testPath = path.join(fullPath, 'index' + ext);
const testPath = path.join(fullPath, "index" + ext);
try {
if (fs.existsSync(testPath)) {
return defaultResolver(testPath, options);
@ -47,7 +47,7 @@ module.exports = (request, options) => {
}
}
}
// If still not found, throw original error
throw new Error(`Cannot find module '${request}'`);
};
};

View file

@ -1,24 +1,24 @@
module.exports = (path, options) => {
// Call the default resolver
const resolver = options.defaultResolver;
try {
// Try to resolve the path as-is first
return resolver(path, options);
} catch (error) {
// If the path ends with .js and resolution fails, try without the extension
if (path.endsWith('.js')) {
if (path.endsWith(".js")) {
const pathWithoutJs = path.slice(0, -3);
try {
return resolver(pathWithoutJs, options);
} catch {
// If that also fails, try with .ts extension
try {
return resolver(pathWithoutJs + '.ts', options);
return resolver(pathWithoutJs + ".ts", options);
} catch {
// If that also fails, try with .tsx extension
try {
return resolver(pathWithoutJs + '.tsx', options);
return resolver(pathWithoutJs + ".tsx", options);
} catch {
// If all attempts fail, throw the original error
throw error;
@ -28,4 +28,4 @@ module.exports = (path, options) => {
}
throw error;
}
};
};

View file

@ -15,6 +15,12 @@ jest.mock("./src/auth/workos.js");
jest.mock("./src/commands/commands.js");
jest.mock("./src/services/index.js");
jest.mock("./src/services/ServiceContainerContext.js");
jest.mock("./src/config.js");
jest.mock("./src/configLoader.js");
jest.mock("./src/args.js");
jest.mock("./src/services/ServiceContainer.js");
jest.mock("./src/permissions/permissionsYamlLoader.js");
jest.mock("./src/permissions/precedenceResolver.js");
// Set up global afterEach hook to clear all timers and reset console
afterEach(() => {
@ -26,11 +32,11 @@ afterEach(() => {
// Ignore errors when clearing timers
}
}
// Reset console overrides to ensure clean state for each test
try {
resetConsoleOverrides();
} catch (e) {
// Ignore errors when resetting console
}
});
});

8791
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "@continuedev/cli",
"version": "0.0.0-dev",
"description": "",
"description": "Continue CLI",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
@ -9,15 +9,20 @@
"cn": "dist/index.js"
},
"scripts": {
"test": "npm run lint && cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"vitest": "vitest run",
"vitest:watch": "vitest watch",
"test": "npm run lint && vitest run",
"test:watch": "vitest watch",
"test:ui": "vitest --ui",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
"lint": "tsc --noEmit",
"lint": "tsc --noEmit && eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit",
"watch:logs": "tail -f ~/.continue/logs/cn.log",
"prepare": "npm run build",
"semantic-release": "semantic-release",
"semantic-release:dry-run": "semantic-release --dry-run"
@ -45,6 +50,8 @@
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@sentry/profiling-node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
@ -55,16 +62,19 @@
"dotenv": "^16.5.0",
"express": "^5.1.0",
"glob": "^11.0.3",
"gpt-tokenizer": "^3.0.1",
"ignore-walk": "^7.0.0",
"ink": "^6.0.1",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"swr": "^2.3.4",
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uuid": "^9.0.1",
@ -76,26 +86,34 @@
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@testing-library/react": "^16.3.0",
"@types/diff": "^7.0.2",
"@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jest": "^29.5.14",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"@types/supertest": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"conventional-changelog-conventionalcommits": "^9.1.0",
"cross-env": "^7.0.3",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"happy-dom": "^18.0.1",
"ink-testing-library": "^4.0.0",
"jest": "^29.7.0",
"jsdom": "^26.1.0",
"nock": "^14.0.5",
"prettier": "^3.6.2",
"semantic-release": "^24.2.7",
"supertest": "^7.1.3",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"tsx": "^4.20.3",
"vitest": "^3.2.4"

View file

@ -23,13 +23,11 @@ This document specifies the behavior of the CLI's configuration loading system,
**When CLI is invoked, config source is determined in this order:**
1. **CLI `--config` Flag** (highest priority)
- File path (starts with `.`, `/`, `~`): Loads local YAML file
- Assistant slug (`owner/package`): Fetches from Continue platform
- Overrides any saved preferences
2. **Saved Config URI** (if no `--config` flag)
- Retrieved from authentication config
- Converts `file://` URIs back to file paths
- Converts `slug://` URIs back to assistant slugs

49
spec/index.md Normal file
View file

@ -0,0 +1,49 @@
# `cn`
## Overall development goals
Fight to keep `cn` simple. This is an active process. The default is that `cn` will become disastrously complicated.
### Maintainability
Maintain minimal code (avoid new features unless there is overwhelming demand or they remove a clear blocker for many users). If someone offers up a feature you should seek to understand what they actually want and then decide as a maintainer of `cn` whether this can fit into some larger concept in a simple way. If someone asks to make something configurable, you should probably consider just changing the default.
### Don't write code by hand
Use `cn` for everything. You should very rarely need to write code by hand. If you find yourself doing this outside of small tweaks, you should ask what about the codebase is causing `cn` to be unable to make the change.
If we build a system that allows us to entrust all changes to `cn` then it will be more reliable than us writing the code. Not because we can't write better code, but because `cn` is consistently thorough + it will force us to build the right systems around the code.
### Do not test by hand
If you find yourself using `npm run start` to test that existing functionality is still working, this means that you are missing a test. A green check mark from `npm test` should be full proof that the code can be shipped. See our testing strategies [here](./testing-strategies.md).
For new features you obviously need to run them yourself to apply your taste. `cn` can't match that right now.
### Minimize the number of concepts
The spec for `cn` (if it were to be fully written out) should be relatively short. This helps keep the code / spec consistent. It also allows us to keep the docs short and makes it easier for users to understand.
### Low tolerance
Tolerance for the following should be very close to zero:
- Un-addressed code reviews
- Failing tests
- Flaky tests
- Sentry issues
If we are inundated then we should build a system to solve that. For example, if it is tiresome to address all AI code reviews, then set up a trigger to have `cn` automatically address them.
### Start with a spec
High level concepts / features should have a spec when possible. Good examples of this are [modes](./modes.md), [permissions](./permissions.md), [OTLP metrics](./otlp-metrics.md), and [wire format](./wire-format.md). Like code, the spec can and should be largely auto-generated.
## Codebase Design
- We intentionally write different implementations of the "loop" instead of trying to build a single engine that can be used across TUI, headless mode, `cn serve`, and more. So far, it would be more work than it is worth to add this abstraction.
- "Everything is a service." Nobody (human or AI) should need to re-invent a polling mechanism or way to store / update state. This decision has been made already so we can focus on the business logic. The service setup lets us easily keep reactive state and avoid React anti-patterns like `useEffect`.
- We use `ink` for UI, following the same usual React principles that we do elsewhere. Keep [components](../src/ui/components/) small, avoid `useEffect`, group logic into [hooks](../src/hooks).
- Always use the [logger](../src/util/logger.ts) instead of `console.log`.
- Use commander to define [commands](../src/commands/BaseCommandOptions.ts)
- `cn remote` is intended to act the same as `cn`'s TUI in almost every way. There is a test helper that allows us to run any e2e test in _both_ remote and normal modes to ensure this is true.

View file

@ -5,6 +5,7 @@ Modes are a system for managing tool permissions in the CLI. They can be set via
## Available Modes
### `normal` (default)
The default mode that follows configured permission policies from `permissions.yaml` and command-line overrides without any additional restrictions or mode-specific policies.
- **UI Indicator:** No indicator shown (clean interface for default behavior)
@ -13,6 +14,7 @@ The default mode that follows configured permission policies from `permissions.y
- **Backward compatibility:** Existing configurations work unchanged
### `plan`
Planning mode that **completely overrides all user permissions** to enforce read-only access. This mode absolutely prevents any write operations, file modifications, or command execution, regardless of user configuration.
- **Command-line flag:** `--readonly` (for backward compatibility)
@ -22,6 +24,7 @@ Planning mode that **completely overrides all user permissions** to enforce read
- **User config ignored:** Any user `--allow` flags for write tools are overridden
### `auto`
Auto mode that **completely overrides all user permissions** to allow everything without asking. This mode provides maximum automation by bypassing all permission policies and restrictions, regardless of user configuration.
- **Command-line flag:** `--auto` (starts in auto mode)
@ -33,7 +36,9 @@ Auto mode that **completely overrides all user permissions** to allow everything
## Usage
### Command-Line Initialization
Modes can be set when starting the CLI:
```bash
cn --readonly "Help me analyze this code" # Starts in plan mode
cn --auto "Fix all the linting errors" # Starts in auto mode
@ -41,14 +46,17 @@ cn "Let me implement this feature" # Starts in normal mode (default)
```
### Dynamic Mode Switching
Users can switch modes during chat sessions using:
**Keyboard Shortcut:**
- **Shift+Tab** - Cycle through modes: normal → plan → auto → (repeat)
## Implementation
Modes are implemented through the permission system:
- **ModeService**: Singleton service managing the current mode and initialization
- **ToolPermissionService**: Extended to support mode-specific policies with highest priority
- **ModeIndicator**: UI component showing current mode (hidden for normal mode)
@ -56,17 +64,21 @@ Modes are implemented through the permission system:
- **Backward compatibility**: Existing `--readonly` flag maps to plan mode
### Mode Policy Priority
**Mode policies completely override all other configurations** when in plan or auto mode:
**Plan and Auto modes:**
1. **Mode policies** (absolute override - ignores everything else)
**Normal mode only:**
1. Command-line overrides (`--allow`, `--ask`, `--exclude`)
2. Permission configuration from `permissions.yaml`
2. Permission configuration from `permissions.yaml`
3. Default tool policies
### Mode-Specific Behaviors
- **normal**: No mode policies applied, uses existing user configuration; shows current directory
- **plan**: **Absolute override** - excludes all write tools (Write, Edit, Bash), allows only read tools (Read, Grep, LS); hides current directory
- **auto**: **Absolute override** - allows all tools with `*: allow` policy; hides current directory

View file

@ -8,7 +8,6 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
1. If the --config flag is provided, load this config
2. Otherwise, we will present the user with two options:
- Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org
- Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model
@ -33,4 +32,4 @@ When something in the onboarding flow is done automatically, we should tell the
2. If the user is logged in, look for the first assistant in the selected org
3. If there are no assistants in that org, then look for a local ~/.continue/config.yaml
4. If there is no config.yaml, look for an ANTHROPIC_API_KEY in the environment and manually construct the config object to include just the claude-4-sonnet model with that API key
5. If none of the above, then bring the user to step 3 of the onboarding flow
5. If none of the above, then bring the user to step 3 of the onboarding flow

View file

@ -19,6 +19,7 @@ There is a default set of permissions for the builtin tools in [`src/permissions
5. Default policies
**Note:** Mode policies **completely override all other permission settings** in plan and auto modes. Available modes:
- `normal`: No mode policies (uses existing configuration)
- `plan`: **Absolute override** - excludes all write tools, allows only read tools (ignores user config)
- `auto`: **Absolute override** - allows all tools without asking (ignores user config)
@ -41,7 +42,7 @@ Each of the `--allow`, `--ask`, and `--exclude` flags allow you to set the permi
# Allow Read, Ask Write, and Exclude Bash
cn --allow Read --ask Write --exclude Bash
# Start in plan mode (read-only tools only)
# Start in plan mode (read-only tools only)
cn --readonly "Help me understand this codebase"
# Use mode switching during chat
@ -101,7 +102,7 @@ To use tools that normally require confirmation in headless mode, you must expli
# Headless mode with explicit permissions for write operations
cn -p --allow write_file "Write a hello world script"
# Headless mode with wildcard permission (allow all tools)
# Headless mode with wildcard permission (allow all tools)
cn -p --allow "*" "Write and run a script"
# Headless mode with specific restrictions

10
spec/telemtry.md Normal file
View file

@ -0,0 +1,10 @@
# Continue anonymous Posthog telemetry
## Behavior
- Used by Continue for product metrics (not used by customers)
- uses public posthog key in repo
- CONTINUE_CLI_ENABLE_TELEMETRY can be set to false to disable
- non-anonymous and private data like code is never sent to posthog
- Event user ids are the Continue user id is signed in, or a unique machine id if not
- Current events are slash command usage and chat calls

View file

@ -1,3 +1,6 @@
import * as fs from "node:fs";
import * as path from "node:path";
import {
FQSN,
PlatformClient,
@ -6,19 +9,18 @@ import {
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api";
import * as dotenv from "dotenv";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { env } from "./env.js";
export class CLIPlatformClient implements PlatformClient {
constructor(
private orgScopeId: string | null,
private readonly apiClient: DefaultApiInterface
private readonly apiClient: DefaultApiInterface,
) {}
private findSecretInEnvFile(
filePath: string,
secretName: string
secretName: string,
): string | undefined {
try {
if (!fs.existsSync(filePath)) return undefined;
@ -30,7 +32,7 @@ export class CLIPlatformClient implements PlatformClient {
console.warn(
`Error reading .env file at ${filePath}: ${
error instanceof Error ? error.message : String(error)
}`
}`,
);
return undefined;
}
@ -40,7 +42,7 @@ export class CLIPlatformClient implements PlatformClient {
// Check in priority order: ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
const workspaceDir = process.cwd();
const envPaths = [
path.join(os.homedir(), ".continue", ".env"),
path.join(env.continueHome, ".env"),
path.join(workspaceDir, ".continue", ".env"),
path.join(workspaceDir, ".env"),
];
@ -69,7 +71,7 @@ export class CLIPlatformClient implements PlatformClient {
}
const results: (SecretResult | undefined)[] = new Array(fqsns.length).fill(
undefined
undefined,
);
// Try to resolve secrets through the API client first
@ -91,7 +93,7 @@ export class CLIPlatformClient implements PlatformClient {
console.warn(
`Error resolving FQSNs through API: ${
error instanceof Error ? error.message : String(error)
}`
}`,
);
}

131
src/MCPConnection.ts Normal file
View file

@ -0,0 +1,131 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { logger } from "./util/logger.js";
export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
export class MCPConnection {
public prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
public tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
public status: MCPServerStatus = "idle";
public error?: Error;
public warnings: string[] = [];
public readonly command: string;
public readonly name: string;
constructor(
public readonly client: Client | null,
command: string,
name: string
) {
this.command = command;
this.name = name;
}
public static async create(
config: NonNullable<AssistantConfig["mcpServers"]>[number],
name: string
): Promise<MCPConnection> {
if (!config) {
throw new Error("MCP server config is null");
}
const connection = new MCPConnection(
null,
config.command || "unknown",
name
);
connection.status = "connecting";
try {
const client = new Client(
{
name: "continue-cli-client",
version: "1.0.0",
},
{ capabilities: {} }
);
// Construct transport
const env: Record<string, string> = config.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
if (!config.command) {
throw new Error("MCP server command is not specified");
}
const transport = new StdioClientTransport({
command: config.command,
args: config.args,
env,
});
// Connect
logger.debug("Connecting to MCP server", {
name,
command: config.command,
});
await client.connect(transport, {});
// Update connection with successful client
(connection as any).client = client;
connection.status = "connected";
const capabilities = client.getServerCapabilities();
logger.debug("MCP server capabilities", {
name,
hasPrompts: !!capabilities?.prompts,
hasTools: !!capabilities?.tools,
});
// Load prompts
if (capabilities?.prompts) {
try {
connection.prompts = (await client.listPrompts()).prompts;
logger.debug("Loaded MCP prompts", {
name,
count: connection.prompts.length,
});
} catch (error: any) {
connection.warnings.push(`Failed to load prompts: ${error.message}`);
logger.warn("Failed to load MCP prompts", {
name,
error: error.message,
});
}
}
// Load tools
if (capabilities?.tools) {
try {
connection.tools = (await client.listTools()).tools;
logger.debug("Loaded MCP tools", {
name,
count: connection.tools.length,
});
} catch (error: any) {
connection.warnings.push(`Failed to load tools: ${error.message}`);
logger.warn("Failed to load MCP tools", {
name,
error: error.message,
});
}
}
return connection;
} catch (error: any) {
connection.status = "error";
connection.error = error;
logger.error("Failed to connect to MCP server", {
name,
error: error.message,
});
throw error;
}
}
}

3
src/__mocks__/args.ts Normal file
View file

@ -0,0 +1,3 @@
import { vi } from "vitest";
export const processRule = vi.fn<(rule: string) => Promise<string>>();

View file

@ -1,5 +1,28 @@
import { jest } from '@jest/globals';
import { vi } from "vitest";
import type { AuthConfig } from "../../auth/workos.js";
export const isAuthenticated = jest.fn(() => false);
export const isAuthenticatedConfig = jest.fn(() => false);
export const loadAuthConfig = jest.fn(() => Promise.resolve(null));
export const isAuthenticated = vi.fn(() => false);
export const isAuthenticatedConfig = vi.fn(() => false);
export const isEnvironmentAuthConfig = vi.fn(() => false);
export const loadAuthConfig = vi.fn(() => null);
export const login = vi.fn();
export const logout = vi.fn();
export const ensureOrganization = vi.fn();
export const getOrganizationId = vi.fn(() => null);
export const saveAuthConfig = vi.fn();
export const listUserOrganizations = vi.fn();
export const hasMultipleOrganizations = vi.fn();
export const initWorkOS = vi.fn();
export const getModelName = vi.fn(() => null);
export const getAccessToken = vi.fn(() => null);
export const getConfigUri = vi.fn(() => null);
export const getAssistantSlug = vi.fn(() => null);
export const getLocalConfigPath = vi.fn(() => null);
export const pathToUri = vi.fn((path: string) => path);
export const slugToUri = vi.fn((slug: string) => slug);
export const uriToPath = vi.fn(() => null);
export const uriToSlug = vi.fn(() => null);
export const updateConfigUri = vi.fn();
export const updateModelName = vi.fn();
export const updateAssistantSlug = vi.fn();
export const updateLocalConfigPath = vi.fn();

View file

@ -1,6 +1,6 @@
import { jest } from '@jest/globals';
import { vi } from "vitest";
export const getAllSlashCommands = jest.fn(() => [
export const getAllSlashCommands = vi.fn(() => [
{ name: "help", description: "Show help", category: "system" },
{ name: "login", description: "Login to Continue", category: "system" },
]);
]);

17
src/__mocks__/config.ts Normal file
View file

@ -0,0 +1,17 @@
import { vi } from "vitest";
export const getApiClient = vi.fn<(accessToken: string | null) => any>(
() => null,
);
export const getLlmApi =
vi.fn<
(
config: any,
authConfig: any,
modelConfig?: any,
orgScopeId?: string,
) => [any, any]
>();
export const getModel = vi.fn<(config: any, modelName: string) => any>();
export const createLlmApi =
vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();

View file

@ -0,0 +1,3 @@
import { vi } from "vitest";
export const loadConfiguration = vi.fn<(options: any) => Promise<any>>();

View file

@ -1,13 +1,13 @@
import { jest } from "@jest/globals";
import { vi } from "vitest";
export const useService = jest.fn(() => ({
export const useService = vi.fn(() => ({
value: null,
state: "idle",
error: null,
reload: jest.fn(() => Promise.resolve()),
reload: vi.fn(() => Promise.resolve()),
}));
export const useServices = jest.fn(() => ({
export const useServices = vi.fn(() => ({
services: {
auth: { isAuthenticated: true },
config: { config: { name: "test-assistant" } },
@ -18,4 +18,4 @@ export const useServices = jest.fn(() => ({
loading: false,
error: null,
allReady: true,
}));
}));

View file

@ -1,14 +1,16 @@
export const log = jest.fn();
export const error = jest.fn();
export const info = jest.fn();
export const warn = jest.fn();
import { vi } from "vitest";
export const log = vi.fn();
export const error = vi.fn();
export const info = vi.fn();
export const warn = vi.fn();
export const loggers = {
blue: jest.fn(),
green: jest.fn(),
yellow: jest.fn(),
red: jest.fn(),
magenta: jest.fn(),
cyan: jest.fn(),
white: jest.fn(),
gray: jest.fn(),
};
blue: vi.fn(),
green: vi.fn(),
yellow: vi.fn(),
red: vi.fn(),
magenta: vi.fn(),
cyan: vi.fn(),
white: vi.fn(),
gray: vi.fn(),
};

View file

@ -0,0 +1,3 @@
import { vi } from "vitest";
export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null);

View file

@ -0,0 +1,5 @@
import { vi } from "vitest";
export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>(
() => [],
);

View file

@ -0,0 +1,9 @@
import { vi } from "vitest";
export const serviceContainer = {
get: vi.fn<(name: string) => any>(),
set: vi.fn<(name: string, state: any) => void>(),
has: vi.fn<(name: string) => boolean>(),
reset: vi.fn<() => void>(),
reload: vi.fn<(name: string) => Promise<void>>(),
};

View file

@ -1,25 +1,29 @@
import React from 'react';
import { jest } from "@jest/globals";
import { ServiceContainer } from '../../services/ServiceContainer.js';
import React from "react";
import { vi } from "vitest";
import { ServiceContainer } from "../../services/ServiceContainer.js";
// Create a mock service container
const mockServiceContainer = {
getSync: jest.fn((serviceName: string) => ({
getSync: vi.fn((serviceName: string) => ({
state: "ready",
value: {},
error: null,
})),
isReady: jest.fn(() => true),
on: jest.fn(),
off: jest.fn(),
load: jest.fn(() => Promise.resolve()),
reload: jest.fn(() => Promise.resolve()),
emit: jest.fn(),
setMaxListeners: jest.fn(),
isReady: vi.fn(() => true),
on: vi.fn(),
off: vi.fn(),
load: vi.fn(() => Promise.resolve()),
reload: vi.fn(() => Promise.resolve()),
emit: vi.fn(),
setMaxListeners: vi.fn(),
} as unknown as ServiceContainer;
export const ServiceContainerProvider = ({ children }: { children: React.ReactNode }) => {
export const ServiceContainerProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
return React.createElement(React.Fragment, null, children);
};
export const useServiceContainer = jest.fn(() => mockServiceContainer);
export const useServiceContainer = vi.fn(() => mockServiceContainer);

View file

@ -1,20 +1,20 @@
import { jest } from '@jest/globals';
import { vi } from "vitest";
export const services = {
auth: {
login: jest.fn(() => Promise.resolve({})),
logout: jest.fn(() => Promise.resolve({})),
switchOrganization: jest.fn(() => Promise.resolve({})),
getAvailableOrganizations: jest.fn(() => Promise.resolve([])),
login: vi.fn(() => Promise.resolve({})),
logout: vi.fn(() => Promise.resolve({})),
switchOrganization: vi.fn(() => Promise.resolve({})),
getAvailableOrganizations: vi.fn(() => Promise.resolve([])),
},
};
export const reloadService = jest.fn(() => Promise.resolve(undefined));
export const reloadService = vi.fn(() => Promise.resolve(undefined));
export const SERVICE_NAMES = {
AUTH: 'auth',
API_CLIENT: 'apiClient',
CONFIG: 'config',
MODEL: 'model',
MCP: 'mcp',
};
AUTH: "auth",
API_CLIENT: "apiClient",
CONFIG: "config",
MODEL: "model",
MCP: "mcp",
};

View file

@ -1,11 +1,13 @@
import { vi } from "vitest";
const mockLogger: any = {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
child: jest.fn((): any => mockLogger),
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
child: vi.fn((): any => mockLogger),
};
export default mockLogger;
export const getLogPath = jest.fn(() => "/mock/log/path");
export const getSessionId = jest.fn(() => "mock-session-id");
export const getLogPath = vi.fn(() => "/mock/log/path");
export const getSessionId = vi.fn(() => "mock-session-id");

View file

@ -1,4 +1,5 @@
import { jest } from '@jest/globals';
import { vi } from 'vitest';
import { parseArgs, processRule } from "./args.js";
describe("parseArgs", () => {
@ -16,22 +17,9 @@ describe("parseArgs", () => {
it("should return default values when no arguments provided", () => {
const result = parseArgs();
expect(result).toEqual({
isHeadless: false,
});
expect(result).toEqual({});
});
it("should set isHeadless to true when --print flag is present", () => {
process.argv = ["node", "script.js", "--print"];
const result = parseArgs();
expect(result.isHeadless).toBe(true);
});
it("should set isHeadless to true when -p flag is present", () => {
process.argv = ["node", "script.js", "-p"];
const result = parseArgs();
expect(result.isHeadless).toBe(true);
});
it("should set resume to true when --resume flag is present", () => {
process.argv = ["node", "script.js", "--resume"];
@ -74,7 +62,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js", "--print", "--readonly", "--resume"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: true,
readonly: true,
resume: true,
});
@ -84,7 +71,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js", "--config", "config.yaml", "--print"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: true,
configPath: "config.yaml",
});
});
@ -93,7 +79,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "--print"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: true,
rules: ["my-rule"],
});
});
@ -102,7 +87,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js", "--print", "What is the weather?"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: true,
prompt: "What is the weather?",
});
});
@ -117,7 +101,6 @@ describe("parseArgs", () => {
];
const result = parseArgs();
expect(result).toEqual({
isHeadless: false,
configPath: "config.yaml",
prompt: "Test prompt",
});
@ -127,7 +110,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: false,
rules: ["my-rule"],
prompt: "Test prompt",
});
@ -172,7 +154,6 @@ describe("parseArgs", () => {
];
const result = parseArgs();
expect(result).toEqual({
isHeadless: true,
configPath: "my-config.yaml",
rules: ["rule1", "rule2"],
readonly: true,
@ -196,14 +177,12 @@ describe("parseArgs", () => {
it("should handle config flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--config"];
const result = parseArgs();
expect(result.isHeadless).toBe(true);
expect(result.configPath).toBeUndefined();
});
it("should handle rule flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--rule"];
const result = parseArgs();
expect(result.isHeadless).toBe(true);
expect(result.rules).toEqual([]);
});
@ -211,7 +190,6 @@ describe("parseArgs", () => {
process.argv = ["node", "script.js"];
const result = parseArgs();
expect(result).toEqual({
isHeadless: false,
});
});
@ -245,7 +223,7 @@ describe("parseArgs", () => {
describe("processRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
const mockFetch = vi.fn() as any;
beforeAll(() => {
global.fetch = mockFetch;

View file

@ -1,16 +1,18 @@
import * as fs from "fs";
import JSZip from "jszip";
import * as path from "path";
import JSZip from "jszip";
import { env } from "./env.js";
export interface CommandLineArgs {
isHeadless: boolean;
configPath?: string;
organizationSlug?: string; // Organization slug to use for this session
prompt?: string; // Optional prompt argument
resume?: boolean; // Resume from last session
readonly?: boolean; // Start in plan mode (backward compatibility)
rules?: string[]; // Array of rule specifications
format?: 'json'; // Output format for headless mode
format?: "json"; // Output format for headless mode
}
/**
@ -39,14 +41,14 @@ async function loadRuleFromHub(slug: string): Promise<string> {
const parts = slug.split("/");
if (parts.length !== 2) {
throw new Error(
`Invalid hub slug format. Expected "owner/package", got: ${slug}`
`Invalid hub slug format. Expected "owner/package", got: ${slug}`,
);
}
const [ownerSlug, ruleSlug] = parts;
const downloadUrl = new URL(
`v0/${ownerSlug}/${ruleSlug}/latest/download`,
env.apiBase
env.apiBase,
);
try {
@ -63,7 +65,8 @@ async function loadRuleFromHub(slug: string): Promise<string> {
// Find the first .md or .txt file (rule content)
const ruleFiles = Object.keys(zipContents.files).filter(
(filename) => filename.endsWith(".md") && !zipContents.files[filename].dir
(filename) =>
filename.endsWith(".md") && !zipContents.files[filename].dir,
);
if (ruleFiles.length === 0) {
@ -108,21 +111,15 @@ export async function processRule(ruleSpec: string): Promise<string> {
}
/**
* Parse command line arguments
* Parse command line arguments for non-permission related flags
* @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
* @returns Parsed command line arguments
*/
export function parseArgs(): CommandLineArgs {
const args = process.argv.slice(2);
// Default values
const result: CommandLineArgs = {
isHeadless: false,
};
// Parse flags
if (args.includes("--print") || args.includes("-p")) {
result.isHeadless = true;
}
const result: CommandLineArgs = {};
if (args.includes("--resume")) {
result.resume = true;
@ -132,13 +129,12 @@ export function parseArgs(): CommandLineArgs {
result.readonly = true;
}
// Get format from --format flag
const formatIndex = args.indexOf("--format");
if (formatIndex !== -1 && formatIndex + 1 < args.length) {
const formatValue = args[formatIndex + 1];
if (formatValue === 'json') {
result.format = 'json';
if (formatValue === "json") {
result.format = "json";
}
}
@ -148,6 +144,15 @@ export function parseArgs(): CommandLineArgs {
result.configPath = args[configIndex + 1];
}
// Get organization slug from --org flag
const orgIndex = args.indexOf("--org");
if (orgIndex !== -1 && orgIndex + 1 < args.length) {
const orgValue = args[orgIndex + 1];
// Convert "personal" to undefined right away to simplify downstream logic
result.organizationSlug =
orgValue.toLowerCase() === "personal" ? undefined : orgValue;
}
// Get rules from --rule flags (can be specified multiple times)
const ruleIndices: number[] = [];
for (let i = 0; i < args.length; i++) {
@ -166,7 +171,7 @@ export function parseArgs(): CommandLineArgs {
}
// Find the last argument that's not a flag or a flag value
const flagsWithValues = ["--config", "--rule", "--format"];
const flagsWithValues = ["--config", "--org", "--rule", "--format"];
const nonFlagArgs = args.filter((arg, index) => {
// Skip flags (starting with --)
if (arg.startsWith("--") || arg === "-p") return false;

View file

@ -1,4 +1,5 @@
import chalk from "chalk";
import { getVersion } from "./version.js";
const b = chalk.bold.magenta;

View file

@ -1,4 +1,5 @@
import chalk from "chalk";
import { isAuthenticated, login } from "./workos.js";
/**
@ -6,7 +7,7 @@ import { isAuthenticated, login } from "./workos.js";
* Returns true if authentication is successful, false otherwise
*/
export async function ensureAuthenticated(
requireAuth: boolean = true
requireAuth: boolean = true,
): Promise<boolean> {
if (isAuthenticated()) {
return true;
@ -22,7 +23,7 @@ export async function ensureAuthenticated(
await login();
return true;
} catch (error) {
console.error(chalk.red("Failed to authenticate."));
console.error(chalk.red("Failed to authenticate."), error);
return false;
}
}

199
src/auth/workos-org.test.ts Normal file
View file

@ -0,0 +1,199 @@
import chalk from "chalk";
import { describe, expect, test, beforeEach, vi } from "vitest";
import { getApiClient } from "../config.js";
import { ensureOrganization } from "./workos.js";
import type { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos.js";
// Mock dependencies
vi.mock("../config.js", () => ({
getApiClient: vi.fn(() => ({
listOrganizations: vi.fn(),
})),
}));
vi.mock("fs", () => ({
default: {
existsSync: vi.fn(() => false),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
},
}));
describe("ensureOrganization with CLI organization slug", () => {
const mockAuthConfig: AuthenticatedConfig = {
userId: "user-123",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "refresh-token",
expiresAt: Date.now() + 3600000,
organizationId: null,
};
const mockEnvAuthConfig: EnvironmentAuthConfig = {
accessToken: "env-token",
organizationId: null,
};
const mockOrganizations = [
{ id: "org-1", name: "Organization One", slug: "org-one" },
{ id: "org-2", name: "Organization Two", slug: "org-two" },
{ id: "org-3", name: "Test Org", slug: "test-org" },
];
beforeEach(() => {
vi.clearAllMocks();
// Suppress console output during tests
vi.spyOn(console, "error").mockImplementation(() => {});
vi.spyOn(console, "info").mockImplementation(() => {});
});
describe("Organization resolution by slug", () => {
test("should resolve organization by exact slug match", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
expect(apiClient.listOrganizations).toHaveBeenCalled();
});
test("should show available organizations when slug not found", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const consoleInfoSpy = vi.spyOn(console, "info");
await expect(
ensureOrganization(mockAuthConfig, true, "invalid-org")
).rejects.toThrow('Organization "invalid-org" not found');
expect(consoleInfoSpy).toHaveBeenCalledWith(
chalk.yellow("Available organizations:"),
expect.stringContaining("personal")
);
});
});
describe("Mode restriction", () => {
test("should reject --org flag in interactive mode", async () => {
const consoleErrorSpy = vi.spyOn(console, "error");
const processExitSpy = vi
.spyOn(process, "exit")
.mockImplementation(() => {
throw new Error("Process exit");
});
await expect(
ensureOrganization(mockAuthConfig, false, "org-one")
).rejects.toThrow("Process exit");
expect(consoleErrorSpy).toHaveBeenCalledWith(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)"
)
);
expect(processExitSpy).toHaveBeenCalledWith(1);
processExitSpy.mockRestore();
});
});
describe("Auth type handling", () => {
test("should work with authenticated config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(mockAuthConfig, true, "test-org");
expect(result).toMatchObject({
userId: "user-123",
organizationId: "org-3",
});
});
test("should work with environment auth config and return updated organizationId", async () => {
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(
mockEnvAuthConfig,
true,
"org-two"
);
expect(result).toMatchObject({
accessToken: "env-token",
organizationId: "org-2",
});
});
test("should override existing organization with CLI slug", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const apiClient = {
listOrganizations: vi
.fn()
.mockResolvedValue({ organizations: mockOrganizations }),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
const result = await ensureOrganization(authWithOrg, true, "org-one");
expect(result).toMatchObject({
organizationId: "org-1",
});
});
test("should keep existing organization when no slug provided", async () => {
const authWithOrg = {
...mockAuthConfig,
organizationId: "existing-org",
};
const result = await ensureOrganization(authWithOrg, true);
expect(result).toMatchObject({
organizationId: "existing-org",
});
});
});
describe("Error handling", () => {
test("should handle API errors during organization fetch", async () => {
const apiClient = {
listOrganizations: vi.fn().mockRejectedValue(new Error("API Error")),
};
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
await expect(
ensureOrganization(mockAuthConfig, true, "org-one")
).rejects.toThrow("API Error");
});
});
});

View file

@ -1,20 +1,19 @@
import chalk from "chalk";
import * as fs from "fs";
import open from "open";
import * as os from "os";
import * as path from "path";
import { createInterface } from "readline";
import { env } from "../env.js";
import chalk from "chalk";
// Polyfill fetch for Node < 18
import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
// Config file path
const AUTH_CONFIG_PATH = path.join(os.homedir(), ".continue", "auth.json");
const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
// Represents an authenticated user's configuration
export interface AuthenticatedConfig {
@ -30,8 +29,15 @@ export interface AuthenticatedConfig {
// Represents configuration when using environment variable auth
export interface EnvironmentAuthConfig {
/**
* This userId?: undefined; field a trick to help TypeScript differentiate between
* AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
* a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
* type guards are involved.
*/
userId?: undefined;
accessToken: string;
organizationId: null; // Environment auth always uses personal organization
organizationId: string | null; // Can be set via --org flag in headless mode
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
@ -43,7 +49,7 @@ export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null;
* Type guard to check if config is authenticated via file-based auth
*/
export function isAuthenticatedConfig(
config: AuthConfig
config: AuthConfig,
): config is AuthenticatedConfig {
return config !== null && "userId" in config;
}
@ -52,7 +58,7 @@ export function isAuthenticatedConfig(
* Type guard to check if config is authenticated via environment variable
*/
export function isEnvironmentAuthConfig(
config: AuthConfig
config: AuthConfig,
): config is EnvironmentAuthConfig {
return config !== null && !("userId" in config);
}
@ -259,7 +265,11 @@ export function isAuthenticated(): boolean {
return true;
}
// Check if token is expired
/**
* THIS CODE DOESN'T WORK.
* .catch() will never return in a non-async function.
* It's a hallucination.
**/
if (Date.now() > config.expiresAt) {
// Try refreshing the token
refreshToken(config.refreshToken).catch(() => {
@ -271,23 +281,6 @@ export function isAuthenticated(): boolean {
return true;
}
/**
* Prompt the user for input
*/
function prompt(question: string): Promise<string> {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer);
});
});
}
/**
* Device authorization response from WorkOS
*/
@ -319,7 +312,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
"Content-Type": "application/x-www-form-urlencoded",
},
body: params,
}
},
);
if (!response.ok) {
@ -330,7 +323,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
} catch (error: any) {
console.error(
chalk.red("Device authorization error:"),
error.message || error
error.message || error,
);
throw error;
}
@ -342,7 +335,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
async function pollForDeviceToken(
deviceCode: string,
interval: number,
expiresIn: number
expiresIn: number,
): Promise<AuthenticatedConfig> {
const startTime = Date.now();
const expirationTime = startTime + expiresIn * 1000;
@ -367,7 +360,7 @@ async function pollForDeviceToken(
method: "POST",
headers,
body: params,
}
},
);
if (response.ok) {
@ -398,21 +391,21 @@ async function pollForDeviceToken(
// Log response details for debugging
if (response.status === 401) {
throw new Error(
"Oops! We had trouble authenticating. Please try again and reach out if the error persists."
"Oops! We had trouble authenticating. Please try again and reach out if the error persists.",
);
}
if (errorCode === "authorization_pending") {
// Continue polling
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000)
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "slow_down") {
// Increase polling interval
currentInterval += 5;
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000)
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "access_denied") {
@ -436,7 +429,7 @@ async function pollForDeviceToken(
* Refreshes the access token using a refresh token
*/
async function refreshToken(
refreshToken: string
refreshToken: string,
): Promise<AuthenticatedConfig> {
try {
// Load existing config to preserve organizationId and other fields
@ -499,7 +492,7 @@ export async function login(): Promise<AuthConfig> {
// If CONTINUE_API_KEY environment variable exists, use that instead
if (process.env.CONTINUE_API_KEY) {
console.info(
chalk.green("Using CONTINUE_API_KEY from environment variables")
chalk.green("Using CONTINUE_API_KEY from environment variables"),
);
return {
accessToken: process.env.CONTINUE_API_KEY,
@ -513,18 +506,20 @@ export async function login(): Promise<AuthConfig> {
const deviceAuth = await requestDeviceAuthorization();
console.info(
chalk.white(`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`)
chalk.white(
`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`,
),
);
console.info(
chalk.dim(
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`
)
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`,
),
);
// Try to open the complete verification URL in browser
try {
await open(deviceAuth.verification_uri_complete);
} catch (error) {
} catch {
console.info(chalk.yellow("Unable to open browser automatically"));
}
@ -534,7 +529,7 @@ export async function login(): Promise<AuthConfig> {
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in
deviceAuth.expires_in,
);
console.info(chalk.white("✅ Success!"));
@ -542,15 +537,75 @@ export async function login(): Promise<AuthConfig> {
return authConfig;
}
/**
* Helper function to resolve organization by slug
*/
async function resolveOrganizationBySlug(
apiClient: ReturnType<typeof getApiClient>,
organizationSlug: string,
): Promise<{ id: string; slug: string }> {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
// Find organization by slug (case-insensitive)
const matchedOrg = organizations.find(
(org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase(),
);
if (matchedOrg) {
return { id: matchedOrg.id, slug: matchedOrg.slug };
} else {
// Organization not found - show available options
const availableSlugs = organizations
.map((org) => org?.slug)
.filter(Boolean);
const availableOptions = ["personal", ...availableSlugs];
console.info(
chalk.yellow("Available organizations:"),
availableOptions.join(", "),
);
throw new Error(`Organization "${organizationSlug}" not found`);
}
}
/**
* Ensures the user has selected an organization, automatically selecting the first one if available
*/
export async function ensureOrganization(
authConfig: AuthConfig,
isHeadless: boolean = false
isHeadless: boolean = false,
cliOrganizationSlug?: string,
): Promise<AuthConfig> {
// If using CONTINUE_API_KEY environment variable, don't require organization selection
if (isEnvironmentAuthConfig(authConfig)) {
// Handle CLI organization slug if provided (undefined means no --org flag or --org personal)
if (cliOrganizationSlug) {
// Only allow --org flag in headless mode
if (!isHeadless) {
console.error(
chalk.red(
"The --org flag is only supported in headless mode (with -p/--print flag)",
),
);
process.exit(1);
}
// For environment auth configs
if (isEnvironmentAuthConfig(authConfig)) {
const apiClient = getApiClient(authConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
// Return modified environment auth config with organization ID
return {
...authConfig,
organizationId: resolvedOrg.id,
};
}
} else if (isEnvironmentAuthConfig(authConfig)) {
// No CLI organization slug (or "personal" was specified) - return as-is
return authConfig;
}
@ -560,7 +615,24 @@ export async function ensureOrganization(
}
// TypeScript now knows authConfig is AuthenticatedConfig
const authenticatedConfig = authConfig;
const authenticatedConfig: AuthenticatedConfig = authConfig;
// If a CLI organization slug is provided, try to use it (for authenticated configs)
if (cliOrganizationSlug) {
const apiClient = getApiClient(authenticatedConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
const updatedConfig: AuthenticatedConfig = {
...authenticatedConfig,
organizationId: resolvedOrg.id,
};
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// If already have organization ID (including null for personal), return as-is
if (authenticatedConfig.organizationId !== undefined) {
@ -625,7 +697,7 @@ export async function ensureOrganization(
} catch (error: any) {
console.error(
chalk.red("Error fetching organizations:"),
error.response?.data?.message || error.message || error
error.response?.data?.message || error.message || error,
);
console.info(chalk.yellow("Continuing without organization selection."));
const updatedConfig: AuthenticatedConfig = {
@ -647,7 +719,7 @@ export async function ensureOrganization(
* Gets the list of available organizations for the user
*/
export async function listUserOrganizations(): Promise<
{ id: string; name: string }[] | null
{ id: string; name: string; slug: string }[] | null
> {
const authConfig = loadAuthConfig();
@ -664,8 +736,15 @@ export async function listUserOrganizations(): Promise<
try {
const resp = await apiClient.listOrganizations();
return resp.organizations || [];
} catch (error) {
// Map the organizations to include slug field
return (
resp.organizations?.map((org) => ({
id: org.id,
name: org.name,
slug: org.slug,
})) || []
);
} catch {
return null;
}
}
@ -684,9 +763,8 @@ export async function hasMultipleOrganizations(): Promise<boolean> {
*/
export function logout(): void {
const onboardingFlagPath = path.join(
os.homedir(),
".continue",
".onboarding_complete"
env.continueHome,
".onboarding_complete",
);
// Remove onboarding completion flag so user will go through onboarding again
@ -697,8 +775,8 @@ export function logout(): void {
if (process.env.CONTINUE_API_KEY) {
console.info(
chalk.yellow(
"Using CONTINUE_API_KEY from environment variables, nothing to log out"
)
"Using CONTINUE_API_KEY from environment variables, nothing to log out",
),
);
return;
}

View file

@ -24,4 +24,4 @@ export interface ExtendedCommandOptions extends BaseCommandOptions {
readonly?: boolean;
/** Start in auto mode (all tools allowed) */
auto?: boolean;
}
}

View file

@ -1,11 +1,20 @@
import { ModelConfig } from "@continuedev/config-yaml";
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import { loadAuthConfig } from "../auth/workos.js";
import {
compactChatHistory,
findCompactionIndex,
getHistoryForLLM,
} from "../compaction.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { initializeWithOnboarding } from "../onboarding.js";
// initializeWithOnboarding is now handled internally by initializeServices
// import { initializeWithOnboarding } from "../onboarding.js";
import { sentryService } from "../sentry.js";
import { initializeServices } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
@ -13,11 +22,17 @@ import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
shouldAutoCompact,
} from "../util/tokenizer.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
/**
@ -33,7 +48,7 @@ function processJsonOutput(response: string): string {
JSON.parse(trimmedResponse);
// If it parses successfully, return as-is
return trimmedResponse;
} catch (error) {
} catch {
// If it's not valid JSON, wrap it in a JSON object
return JSON.stringify({
response: trimmedResponse,
@ -43,15 +58,35 @@ function processJsonOutput(response: string): string {
}
}
/**
* Strips <think></think> tags and excess whitespace from response
* @param response - The raw response from the LLM
* @returns Cleaned response
*/
function stripThinkTags(response: string): string {
// Remove <think></think> tags and their content
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
// Remove excess whitespace: multiple consecutive newlines become single newlines
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
// Trim leading and trailing whitespace
cleaned = cleaned.trim();
return cleaned;
}
export interface ChatOptions extends ExtendedCommandOptions {
headless?: boolean;
resume?: boolean;
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
silent?: boolean; // Strip <think></think> tags and excess whitespace
org?: string; // Organization slug to use for this session
}
export async function initializeChatHistory(
options: ChatOptions
options: ChatOptions,
): Promise<ChatCompletionMessageParam[]> {
let chatHistory: ChatCompletionMessageParam[] = [];
@ -73,7 +108,7 @@ export async function initializeChatHistory(
rulesSystemMessage,
options.rule,
options.format,
options.headless
options.headless,
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
@ -86,15 +121,130 @@ export async function initializeChatHistory(
async function processMessage(
userInput: string,
chatHistory: ChatCompletionMessageParam[],
model: any,
model: ModelConfig,
llmApi: any,
isHeadless: boolean,
format?: "json"
): Promise<void> {
format?: "json",
silent?: boolean,
compactionIndex?: number | null,
): Promise<{ compactionIndex?: number | null } | void> {
// Check for slash commands in headless mode
if (userInput.trim() === "/compact") {
if (!isHeadless) {
console.info(chalk.yellow("Compacting chat history..."));
}
try {
const result = await compactChatHistory(chatHistory, model, llmApi);
// Replace chat history with compacted version
chatHistory.length = 0;
chatHistory.push(...result.compactedHistory);
// Save the compacted session
saveSession(chatHistory);
if (!isHeadless) {
console.info(chalk.green("Chat history compacted successfully."));
} else {
safeStdout(
JSON.stringify({
status: "success",
message: "Chat history compacted",
historyLength: chatHistory.length,
}) + "\n",
);
}
return { compactionIndex: result.compactionIndex };
} catch (error) {
const errorMsg = `Compaction error: ${formatError(error)}`;
if (!isHeadless) {
console.error(chalk.red(errorMsg));
} else {
safeStdout(
JSON.stringify({ status: "error", message: errorMsg }) + "\n",
);
}
return;
}
}
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
// Add user message to history
// Check if auto-compacting is needed BEFORE adding user message
if (shouldAutoCompact(chatHistory, model)) {
logger.info("Auto-compacting triggered due to context limit");
if (!isHeadless) {
console.info(
chalk.yellow(
"\nApproaching context limit. Auto-compacting chat history...",
),
);
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "info",
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(chatHistory),
model,
) + "%",
}) + "\n",
);
}
try {
// Compact the history WITHOUT the current user message
const result = await compactChatHistory(chatHistory, model, llmApi);
// Replace chat history with compacted version
chatHistory.length = 0;
chatHistory.push(...result.compactedHistory);
// Save the compacted session
saveSession(chatHistory);
if (!isHeadless) {
console.info(
chalk.green("✓ Chat history auto-compacted successfully."),
);
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "success",
message: "Auto-compacted successfully",
historyLength: chatHistory.length,
}) + "\n",
);
}
// Update compaction index
compactionIndex = result.compactionIndex;
} catch (error) {
const errorMsg = `Auto-compaction error: ${formatError(error)}`;
logger.error(errorMsg);
if (!isHeadless) {
console.error(chalk.red(`Warning: ${errorMsg}`));
console.info(chalk.yellow("Continuing without compaction..."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "warning",
message: "Auto-compaction failed, continuing without compaction",
}) + "\n",
);
}
// Continue without compaction on error
}
}
// Add user message to history AFTER potential compaction
chatHistory.push({ role: "user", content: userInput });
// Get AI response with potential tool usage
@ -104,18 +254,48 @@ async function processMessage(
try {
const abortController = new AbortController();
const finalResponse = await streamChatResponse(
chatHistory,
model,
llmApi,
abortController
);
// Handle compaction properly - streamChatResponse modifies the array in place
let finalResponse;
if (compactionIndex !== null && compactionIndex !== undefined) {
// When using compaction, we need to send a subset but capture the full history
const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
const originalLength = historyForLLM.length;
finalResponse = await streamChatResponse(
historyForLLM,
model,
llmApi,
abortController,
);
// Append any new messages (assistant/tool) that were added by streamChatResponse
const newMessages = historyForLLM.slice(originalLength);
chatHistory.push(...newMessages);
} else {
// No compaction - just pass the full history directly
finalResponse = await streamChatResponse(
chatHistory,
model,
llmApi,
abortController,
);
}
// In headless mode, only print the final response using safe stdout
if (isHeadless && finalResponse && finalResponse.trim()) {
let processedResponse = finalResponse;
// Strip think tags if --silent flag is enabled
if (silent) {
processedResponse = stripThinkTags(processedResponse);
}
// Process output based on format
const outputResponse =
format === "json" ? processJsonOutput(finalResponse) : finalResponse;
format === "json"
? processJsonOutput(processedResponse)
: processedResponse;
safeStdout(outputResponse + "\n");
}
@ -123,10 +303,16 @@ async function processMessage(
// Save session after each successful response
saveSession(chatHistory);
} catch (e: any) {
logger.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`);
const error = e instanceof Error ? e : new Error(String(e));
logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
sentryService.captureException(error, {
context: "chat_response",
isHeadless,
chatHistoryLength: chatHistory.length,
});
if (!isHeadless) {
logger.info(
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`),
);
}
}
@ -134,38 +320,38 @@ async function processMessage(
async function runHeadlessMode(
prompt: string | undefined,
options: ChatOptions
options: ChatOptions,
): Promise<void> {
// Initialize services for headless mode
// Convert legacy flags to mode
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
} else if (options.auto) {
mode = "auto";
}
const { permissionOverrides } = processCommandFlags(options);
await initializeServices({
configPath: options.config,
organizationSlug: options.org,
rules: options.rule,
headless: true,
toolPermissionOverrides: {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
},
toolPermissionOverrides: permissionOverrides,
});
// Get required services from the service container
const modelState = await serviceContainer.get<ModelServiceState>(
SERVICE_NAMES.MODEL
SERVICE_NAMES.MODEL,
);
const { llmApi, model } = modelState;
if (!model) {
throw new Error("No models were found.");
}
// Initialize chat history
const chatHistory = await initializeChatHistory(options);
// Track compaction index if resuming with compacted history
let compactionIndex: number | null = null;
if (options.resume) {
compactionIndex = findCompactionIndex(chatHistory);
}
let isFirstMessage = true;
while (true) {
// When in headless mode, don't ask for user input
@ -181,14 +367,21 @@ async function runHeadlessMode(
isFirstMessage = false;
await processMessage(
const result = await processMessage(
userInput,
chatHistory,
model,
llmApi,
true,
options.format
options.format,
options.silent,
compactionIndex,
);
// Update compaction index if compaction occurred
if (result && result.compactionIndex !== undefined) {
compactionIndex = result.compactionIndex;
}
}
}
@ -207,49 +400,51 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// Start active time tracking
telemetryService.startActiveTime();
// If not in headless mode, check for onboarding first
// If not in headless mode, use unified initialization with TUI
if (!options.headless) {
// Load auth config to check for onboarding
const authConfig = loadAuthConfig();
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
// Run onboarding check - this will handle first-time setup
const onboardingResult = await initializeWithOnboarding(
authConfig,
options.config,
options.rule
);
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
configPath: options.config,
organizationSlug: options.org,
rules: options.rule,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
// If onboarding was completed (user just went through setup), show success message
if (onboardingResult.wasOnboarded) {
// If onboarding was completed, show success message
if (initResult.wasOnboarded) {
console.log(chalk.green("✓ Setup complete! Starting chat..."));
}
// Show ASCII art and version for TUI mode
console.log(CONTINUE_ASCII_ART);
// Convert legacy flags to mode for TUI
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
} else if (options.auto) {
mode = "auto";
}
// Start TUI immediately - it will handle service loading
await startTUIChat(prompt, options.resume, options.config, options.rule, {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
});
// Start TUI with skipOnboarding since we already handled it
await startTUIChat(
prompt,
options.resume,
options.config,
options.org,
options.rule,
permissionOverrides,
true,
);
return;
}
// Run headless mode
await runHeadlessMode(prompt, options);
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error));
// Use headless-aware error logging to ensure fatal errors are shown in headless mode
logging.error(chalk.red(`Fatal error: ${formatError(error)}`));
logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
process.exit(1);
} finally {
// Stop active time tracking

View file

@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it } from '@jest/globals';
import type { AssistantConfig } from '@continuedev/sdk';
import { describe, expect, it } from 'vitest';
import { getAllSlashCommands } from './commands.js';
describe('Slash Commands Integration', () => {

View file

@ -22,11 +22,6 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Clear the chat history",
category: "system",
},
{
name: "exit",
description: "Exit the chat",
category: "system",
},
{
name: "login",
description: "Authenticate with your account",
@ -42,11 +37,6 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Check who you're currently logged in as",
category: "system",
},
{
name: "org",
description: "Switch organization",
category: "system",
},
{
name: "model",
description: "Switch between available chat models",
@ -58,8 +48,23 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
category: "system",
},
{
<<<<<<< HEAD
name: "mcp",
description: "Manage MCP server connections",
=======
name: "org",
description: "Switch organization",
category: "system",
},
{
name: "compact",
description: "Summarize chat history into a compact form",
category: "system",
},
{
name: "exit",
description: "Exit the chat",
>>>>>>> 4effd5de05497ea750ede3957b3213e657746cd8
category: "system",
},
];
@ -78,7 +83,7 @@ export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
*/
export function getAllSlashCommands(
assistant: AssistantConfig,
options: { isRemoteMode?: boolean } = {}
options: { isRemoteMode?: boolean } = {},
): SlashCommand[] {
const { isRemoteMode = false } = options;
@ -105,7 +110,7 @@ export function getAllSlashCommands(
* Get assistant prompt commands only
*/
export function getAssistantSlashCommands(
assistant: AssistantConfig
assistant: AssistantConfig,
): SlashCommand[] {
return (
assistant?.prompts?.map((prompt) => ({
@ -114,4 +119,4 @@ export function getAssistantSlashCommands(
category: "assistant" as const,
})) || []
);
}
}

View file

@ -1,4 +1,5 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
export async function login() {

View file

@ -1,11 +1,12 @@
import chalk from "chalk";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
prompt?: string,
url: string = "http://localhost:8000"
url: string = "http://localhost:8000",
) {
console.info(chalk.white(`Connecting to remote environment at ${url}...`));
@ -22,7 +23,7 @@ export async function remoteTest(
}
} catch (error: any) {
logger.error(
chalk.red(`Failed to connect to remote environment: ${error.message}`)
chalk.red(`Failed to connect to remote environment: ${error.message}`),
);
process.exit(1);
}

171
src/commands/remote.test.ts Normal file
View file

@ -0,0 +1,171 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { remote } from "./remote.js";
// Mock dependencies
vi.mock("../auth/workos.js");
vi.mock("../env.js");
vi.mock("../telemetry/telemetryService.js");
vi.mock("../ui/index.js");
vi.mock("../util/git.js");
vi.mock("../util/logger.js");
const mockWorkos = vi.mocked(
await import("../auth/workos.js")
);
const mockEnv = vi.mocked(await import("../env.js"));
const mockGit = vi.mocked(await import("../util/git.js"));
const mockStartRemoteTUIChat = vi.mocked(
await import("../ui/index.js")
);
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch as any;
// Mock console methods
const mockConsoleInfo = vi.fn();
const mockConsoleError = vi.fn();
global.console = {
...global.console,
info: mockConsoleInfo,
error: mockConsoleError,
};
describe("remote command", () => {
beforeEach(() => {
vi.clearAllMocks();
// Clear GitHub Actions environment variables
delete process.env.GITHUB_ACTIONS;
delete process.env.GITHUB_REPOSITORY;
delete process.env.GITHUB_SERVER_URL;
// Setup default mocks
mockWorkos.loadAuthConfig.mockReturnValue({
userId: "test-user-id",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh-token",
expiresAt: Date.now() + 3600000,
organizationId: null,
});
mockWorkos.isAuthenticatedConfig.mockReturnValue(true);
mockWorkos.getAccessToken.mockReturnValue("test-token");
mockEnv.env = {
apiBase: "https://api.example.com",
workOsClientId: "test-client-id",
appUrl: "https://test.example.com",
continueHome: "/tmp/test-continue-home",
};
mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git");
mockFetch.mockResolvedValue({
ok: true,
json: async () => ({
url: "ws://test-url.com",
port: 8080,
}),
});
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
});
it("should include idempotency key in request body when provided", async () => {
const testIdempotencyKey = "test-idempotency-key-123";
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
expect(mockFetch).toHaveBeenCalledWith(
new URL("agents/devboxes", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-token",
},
body: expect.stringContaining(`"idempotencyKey":"${testIdempotencyKey}"`),
})
);
});
it("should not include idempotency key in request body when not provided", async () => {
await remote("test prompt", {});
expect(mockFetch).toHaveBeenCalledWith(
new URL("agents/devboxes", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-token",
},
body: expect.not.stringContaining("idempotencyKey"),
})
);
});
it("should work with direct URL connection and idempotency key", async () => {
const testUrl = "ws://direct-url.com";
const testIdempotencyKey = "direct-key-789";
await remote("test prompt", {
url: testUrl,
idempotencyKey: testIdempotencyKey
});
// Should not make POST request when connecting directly to URL
expect(mockFetch).not.toHaveBeenCalled();
// Should connect directly to the provided URL
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
testUrl,
"test prompt"
);
});
it("should handle proper request body structure with all fields", async () => {
const testIdempotencyKey = "structured-test-key";
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
const fetchCall = mockFetch.mock.calls[0];
const requestBody = JSON.parse(fetchCall[1].body);
expect(requestBody).toEqual({
cUserId: "test-user-id",
repoUrl: "https://github.com/user/test-repo.git",
name: expect.stringMatching(/^devbox-\d+$/),
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
});
});
it("should call getRepoUrl to get the current repository URL", async () => {
await remote("test prompt", {});
expect(mockGit.getRepoUrl).toHaveBeenCalled();
});
it("should work correctly in GitHub Actions environment", async () => {
// Simulate GitHub Actions environment
process.env.GITHUB_ACTIONS = "true";
process.env.GITHUB_REPOSITORY = "myorg/myrepo";
// Mock getRepoUrl to return the GitHub Actions URL
mockGit.getRepoUrl.mockReturnValue("https://github.com/myorg/myrepo.git");
await remote("test prompt", { idempotencyKey: "github-actions-key" });
const fetchCall = mockFetch.mock.calls[0];
const requestBody = JSON.parse(fetchCall[1].body);
expect(requestBody.repoUrl).toBe("https://github.com/myorg/myrepo.git");
expect(requestBody.idempotencyKey).toBe("github-actions-key");
});
});

View file

@ -1,22 +1,24 @@
import chalk from "chalk";
import {
getAccessToken,
isAuthenticatedConfig,
loadAuthConfig,
} from "../auth/workos.js";
import { env } from "../env.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import logger from "../util/logger.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
export async function remote(
prompt: string | undefined,
options: { url?: string } = {}
options: { url?: string; idempotencyKey?: string } = {},
) {
// If --url is provided, connect directly to that URL
if (options.url) {
console.info(
chalk.white(`Connecting to remote environment at: ${options.url}`)
chalk.white(`Connecting to remote environment at: ${options.url}`),
);
// Record session start
@ -39,44 +41,47 @@ export async function remote(
if (!isAuthenticatedConfig(authConfig)) {
console.error(
chalk.red("Not authenticated. Please run 'cn login' first.")
chalk.red("Not authenticated. Please run 'cn login' first."),
);
process.exit(1);
}
const accessToken = getAccessToken(authConfig);
const requestBody: any = {
cUserId: authConfig.userId,
repoUrl: getRepoUrl(),
name: `devbox-${Date.now()}`,
prompt: prompt,
idempotencyKey: options.idempotencyKey,
};
const response = await fetch(new URL("agents/devboxes", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
cUserId: authConfig.userId,
repoUrl: "https://github.com/continuedev/amplified.dev", // getRepoUrl(),
name: `devbox-${Date.now()}`,
prompt: prompt,
}),
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Failed to create remote environment: ${response.status} ${errorText}`
`Failed to create remote environment: ${response.status} ${errorText}`,
);
}
const result = await response.json();
console.info(
chalk.green("✅ Remote development environment created successfully!")
chalk.green("✅ Remote development environment created successfully!"),
);
if (result.url && result.port) {
const remoteUrl = result.url;
console.info(
chalk.white(`Connecting to remote environment at: ${remoteUrl}`)
chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
);
// Record session start
@ -91,12 +96,12 @@ export async function remote(
}
} else {
throw new Error(
"No URL or port returned from remote environment creation"
"No URL or port returned from remote environment creation",
);
}
} catch (error: any) {
logger.error(
chalk.red(`Failed to create remote environment: ${error.message}`)
chalk.red(`Failed to create remote environment: ${error.message}`),
);
process.exit(1);
}

View file

@ -1,18 +1,19 @@
import type { Server } from "http";
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
import type { Server } from "http";
vi,
} from "vitest";
import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
describe("serve command", () => {
let context: any;
let originalProcessExit: typeof process.exit;
let serverPromise: Promise<void>;
let serverRef: Server | null = null;
beforeEach(() => {
@ -20,66 +21,66 @@ describe("serve command", () => {
// Mock process.exit to prevent actual exit during tests
originalProcessExit = process.exit;
process.exit = jest.fn() as any;
process.exit = vi.fn() as any;
// Mock console.log to prevent output during tests
jest.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "log").mockImplementation(() => {});
// Mock all required modules at test level with correct relative paths
jest.mock("fs", () => ({
...(jest.requireActual("fs") as any),
existsSync: jest.fn(() => false),
vi.mock("fs", () => ({
...(vi.importActual("fs") as any),
existsSync: vi.fn(() => false),
}));
jest.mock("../auth/workos.js", () => ({
loadAuthConfig: jest.fn(() => null),
ensureOrganization: jest.fn(),
getOrganizationId: jest.fn(),
isAuthenticated: jest.fn(() => false),
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn(() => null),
ensureOrganization: vi.fn(),
getOrganizationId: vi.fn(),
isAuthenticated: vi.fn(() => false),
}));
jest.mock("../onboarding.js", () => ({
runNormalFlow: jest.fn(() =>
vi.mock("../onboarding.js", () => ({
runNormalFlow: vi.fn(() =>
Promise.resolve({
config: { models: [] },
llmApi: { chat: jest.fn() },
llmApi: { chat: vi.fn() },
model: { name: "test-model" },
})
),
runOnboardingFlow: jest.fn(() =>
runOnboardingFlow: vi.fn(() =>
Promise.resolve({
config: { models: [] },
llmApi: { chat: jest.fn() },
llmApi: { chat: vi.fn() },
model: { name: "test-model" },
})
),
}));
jest.mock("../session.js", () => ({
saveSession: jest.fn(),
vi.mock("../session.js", () => ({
saveSession: vi.fn(),
}));
jest.mock("../systemMessage.js", () => ({
constructSystemMessage: jest.fn(() => Promise.resolve("System message")),
vi.mock("../systemMessage.js", () => ({
constructSystemMessage: vi.fn(() => Promise.resolve("System message")),
}));
jest.mock("../telemetry/telemetryService.js", () => ({
vi.mock("../telemetry/telemetryService.js", () => ({
default: {
recordSessionStart: jest.fn(),
startActiveTime: jest.fn(),
stopActiveTime: jest.fn(),
updateOrganization: jest.fn(),
recordSessionStart: vi.fn(),
startActiveTime: vi.fn(),
stopActiveTime: vi.fn(),
updateOrganization: vi.fn(),
},
}));
jest.mock("../util/logger.js", () => ({
vi.mock("../util/logger.js", () => ({
default: {
error: jest.fn(),
debug: jest.fn(),
error: vi.fn(),
debug: vi.fn(),
},
}));
jest.mock("chalk", () => ({
vi.mock("chalk", () => ({
default: {
green: (str: string) => str,
dim: (str: string) => str,
@ -96,7 +97,7 @@ describe("serve command", () => {
process.exit = originalProcessExit;
// Restore console.log
jest.restoreAllMocks();
vi.restoreAllMocks();
// Clean up server if it's still running
if (serverRef) {
@ -106,7 +107,7 @@ describe("serve command", () => {
serverRef = null;
}
jest.clearAllMocks();
vi.clearAllMocks();
});
it.skip("should have /exit endpoint that returns success response", async () => {

View file

@ -1,12 +1,14 @@
import chalk from "chalk";
import { exec } from "child_process";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import path from "path";
import { promisify } from "util";
import chalk from "chalk";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import { saveSession } from "../session.js";
import {
getService,
initializeServices,
@ -17,17 +19,19 @@ import {
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import { saveSession } from "../session.js";
import {
streamChatResponse,
type StreamCallbacks,
} from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { getToolDisplayName } from "../tools/index.js";
import { DisplayMessage } from "../ui/types.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import { getToolDisplayName } from "../tools/index.js";
const execAsync = promisify(exec);
@ -63,19 +67,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const port = parseInt(options.port || "8000", 10);
// Initialize services with tool permission overrides
// Convert legacy flags to mode
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
}
const { permissionOverrides } = processCommandFlags(options);
await initializeServices({
toolPermissionOverrides: {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
},
toolPermissionOverrides: permissionOverrides,
configPath: options.config,
rules: options.rule,
headless: true, // Skip onboarding in serve mode
@ -116,8 +111,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
chalk.dim(
` Assistant: ${assistantName}${
assistantSlug ? ` (${assistantSlug})` : ""
}`
)
}`,
),
);
console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
if (options.config) {
@ -125,8 +120,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Initialize chat history
let chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = await constructSystemMessage("", options.rule, undefined, true);
const chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = await constructSystemMessage(
"",
options.rule,
undefined,
true,
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
}
@ -271,7 +271,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// POST /exit - Gracefully shut down the server
app.post("/exit", async (_req: Request, res: Response) => {
console.log(
chalk.yellow("\nReceived exit request, shutting down server...")
chalk.yellow("\nReceived exit request, shutting down server..."),
);
// Respond immediately before shutting down
@ -312,24 +312,24 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
console.log(chalk.dim(" GET /state - Get current agent state"));
console.log(
chalk.dim(
" POST /message - Send a message (body: { message: string })"
)
" POST /message - Send a message (body: { message: string })",
),
);
console.log(
chalk.dim(
" POST /permission - Approve/reject tool (body: { requestId, approved })"
)
" POST /permission - Approve/reject tool (body: { requestId, approved })",
),
);
console.log(
chalk.dim(" GET /diff - Get git diff against main branch")
chalk.dim(" GET /diff - Get git diff against main branch"),
);
console.log(
chalk.dim(" POST /exit - Gracefully shut down the server")
chalk.dim(" POST /exit - Gracefully shut down the server"),
);
console.log(
chalk.dim(
`\nServer will shut down after ${timeoutSeconds} seconds of inactivity`
)
`\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
),
);
// If initial prompt provided, queue it for processing
@ -361,7 +361,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state,
llmApi,
state.currentAbortController,
() => state.shouldInterrupt
() => state.shouldInterrupt,
);
// Save session after successful response
@ -411,8 +411,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
console.log(
chalk.yellow(
`\nShutting down due to ${timeoutSeconds} seconds of inactivity`
)
`\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
),
);
state.serverRunning = false;
server.close(() => {
@ -446,7 +446,7 @@ async function streamChatResponseWithInterruption(
state: ServerState,
llmApi: any,
abortController: AbortController,
shouldInterrupt: () => boolean
shouldInterrupt: () => boolean,
): Promise<string> {
// Import the original streamChatResponse logic but add interruption checks
// Create a wrapper that checks for interruption
@ -561,7 +561,7 @@ async function streamChatResponseWithInterruption(
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
requestId: string
requestId: string,
) => {
// Set pending permission state
state.pendingPermission = {
@ -589,7 +589,7 @@ async function streamChatResponseWithInterruption(
state.model,
llmApi,
abortController,
callbacks
callbacks,
);
return response || "";
} finally {

View file

@ -0,0 +1,160 @@
// Unit tests for the stripThinkTags function
// Since stripThinkTags is currently a private function in chat.ts,
// we'll extract it for testing purposes. This follows the same pattern
// as other utility functions in the codebase.
/**
* Strips <think></think> tags and excess whitespace from response
* @param response - The raw response from the LLM
* @returns Cleaned response
*/
function stripThinkTags(response: string): string {
// Remove <think></think> tags and their content
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, '');
// Remove excess whitespace: multiple consecutive newlines become single newlines
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
// Trim leading and trailing whitespace
cleaned = cleaned.trim();
return cleaned;
}
describe("stripThinkTags", () => {
it("should remove simple think tags", () => {
const input = `<think>
This is a thought
</think>
This is the actual content`;
const expected = "This is the actual content";
expect(stripThinkTags(input)).toBe(expected);
});
it("should remove multiple think tag blocks", () => {
const input = `<think>First thought</think>
Content 1
<think>Second thought</think>
Content 2`;
const expected = "Content 1\n\nContent 2";
expect(stripThinkTags(input)).toBe(expected);
});
it("should handle think tags with nested content", () => {
const input = `<think>
I need to think about:
1. Step one
2. Step two
- Sub step
</think>
Final result`;
const expected = "Final result";
expect(stripThinkTags(input)).toBe(expected);
});
it("should reduce excess whitespace", () => {
const input = `<think>Remove this</think>
Content with lots of space
More content`;
const expected = "Content with lots of space\n\nMore content";
expect(stripThinkTags(input)).toBe(expected);
});
it("should handle content without think tags", () => {
const input = `#!/bin/bash
echo "Hello World"
This has no think tags.`;
// Should return the same content (trimmed)
expect(stripThinkTags(input)).toBe(input.trim());
});
it("should handle empty think tags", () => {
const input = `<think></think>
Content after empty think tag`;
const expected = "Content after empty think tag";
expect(stripThinkTags(input)).toBe(expected);
});
it("should handle think tags at the end", () => {
const input = `Content at the beginning
<think>
This thought is at the end
</think>`;
const expected = "Content at the beginning";
expect(stripThinkTags(input)).toBe(expected);
});
it("should handle complex whitespace patterns", () => {
const input = `<think>Remove</think>
Content with indented whitespace
More content`;
const result = stripThinkTags(input);
// Should reduce triple+ newlines to double newlines
expect(result).not.toMatch(/\n\s*\n\s*\n/);
expect(result).toContain("Content with indented whitespace");
expect(result).toContain("More content");
});
it("should handle think tags with special characters", () => {
const input = `<think>
Special chars: !@#$%^&*()
Code: const x = () => { return "test"; }
</think>
Actual content`;
const expected = "Actual content";
expect(stripThinkTags(input)).toBe(expected);
});
it("should be case sensitive for think tags", () => {
const input = `<THINK>This should not be removed</THINK>
<Think>This should not be removed</Think>
<think>This should be removed</think>
Content`;
const result = stripThinkTags(input);
expect(result).toContain("<THINK>This should not be removed</THINK>");
expect(result).toContain("<Think>This should not be removed</Think>");
expect(result).not.toContain("<think>This should be removed</think>");
expect(result).toContain("Content");
});
it("should handle malformed think tags gracefully", () => {
const input = `<think>Unclosed think tag
Content should remain`;
// Should not remove unclosed tags
expect(stripThinkTags(input)).toContain("<think>Unclosed think tag");
expect(stripThinkTags(input)).toContain("Content should remain");
});
});

616
src/compaction.test.ts Normal file
View file

@ -0,0 +1,616 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { describe, it, expect, vi } from "vitest";
import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
import { streamChatResponse } from "./streamChatResponse.js";
// Mock the streamChatResponse function
vi.mock("./streamChatResponse.js", () => ({
streamChatResponse: vi.fn()
}));
describe("compaction", () => {
const mockModel: ModelConfig = {
name: "test-model",
provider: "test",
model: "test-model",
} as ModelConfig;
const mockLlmApi = {} as BaseLlmApi;
describe("findCompactionIndex", () => {
it("should find compaction marker in chat history", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
{ role: "user", content: "Another message" },
];
const index = findCompactionIndex(history);
expect(index).toBe(3);
});
it("should return null if no compaction marker found", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
];
const index = findCompactionIndex(history);
expect(index).toBeNull();
});
it("should return first compaction marker when multiple exist", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nFirst summary` },
{ role: "user", content: "Hello" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSecond summary` },
];
const index = findCompactionIndex(history);
expect(index).toBe(1);
});
it("should return null for empty chat history", () => {
const history: ChatCompletionMessageParam[] = [];
const index = findCompactionIndex(history);
expect(index).toBeNull();
});
it("should not match marker in middle of content", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "assistant", content: `Some text ${COMPACTION_MARKER} in the middle` },
{ role: "user", content: "Hello" },
];
const index = findCompactionIndex(history);
expect(index).toBeNull();
});
it("should handle non-string content", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "assistant", content: null as any },
{ role: "assistant", content: undefined as any },
{ role: "assistant", content: 123 as any },
];
const index = findCompactionIndex(history);
expect(index).toBeNull();
});
it("should only match assistant role messages", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: `${COMPACTION_MARKER}\nSystem compaction?` },
{ role: "user", content: `${COMPACTION_MARKER}\nUser compaction?` },
{ role: "assistant", content: `${COMPACTION_MARKER}\nReal compaction` },
];
const index = findCompactionIndex(history);
expect(index).toBe(2);
});
});
describe("getHistoryForLLM", () => {
it("should return full history when no compaction index", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
];
const result = getHistoryForLLM(history, null);
expect(result).toEqual(history);
});
it("should return compacted history with system message", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
{ role: "user", content: "Another message" },
];
const result = getHistoryForLLM(history, 3);
expect(result).toEqual([
{ role: "system", content: "System message" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
{ role: "user", content: "Another message" },
]);
});
it("should return compacted history without system message when compaction is at index 0", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
{ role: "user", content: "Another message" },
];
const result = getHistoryForLLM(history, 0);
expect(result).toEqual(history);
});
it("should return full history when compactionIndex is out of bounds", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
];
const result = getHistoryForLLM(history, 10);
expect(result).toEqual(history);
});
it("should handle negative compactionIndex", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
];
const result = getHistoryForLLM(history, -1);
// Negative index with slice means "from the end", so -1 gives us only the last message
// Since compactionIndex is not > 0, system message is not included
expect(result).toEqual([
{ role: "user", content: "Hello" },
]);
});
it("should handle empty history", () => {
const history: ChatCompletionMessageParam[] = [];
const result = getHistoryForLLM(history, 0);
expect(result).toEqual([]);
});
it("should handle history with only system message", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
];
const result = getHistoryForLLM(history, 0);
expect(result).toEqual(history);
});
it("should handle history without system message but with compaction", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New message" },
];
const result = getHistoryForLLM(history, 1);
expect(result).toEqual([
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New message" },
]);
});
it("should include system message when first message is not system", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "First user message" },
{ role: "system", content: "System message in wrong position" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New message" },
];
// Since system message is not at index 0, it's not included
const result = getHistoryForLLM(history, 2);
expect(result).toEqual([
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New message" },
]);
});
it("should preserve message order from compaction point", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
{ role: "user", content: "Old 1" },
{ role: "assistant", content: "Old 2" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New 1" },
{ role: "assistant", content: "New 2" },
{ role: "user", content: "New 3" },
];
const result = getHistoryForLLM(history, 3);
expect(result).toEqual([
{ role: "system", content: "System" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
{ role: "user", content: "New 1" },
{ role: "assistant", content: "New 2" },
{ role: "user", content: "New 3" },
]);
});
});
describe("compactChatHistory", () => {
it("should compact chat history successfully", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockContent = "This is a summary of the conversation";
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.(mockContent);
callbacks?.onContentComplete?.(mockContent);
return mockContent;
});
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System message" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toHaveLength(2);
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "System message" });
expect(result.compactedHistory[1]).toEqual({
role: "assistant",
content: `${COMPACTION_MARKER}\n${mockContent}`
});
expect(result.compactionIndex).toBe(1);
expect(result.compactionContent).toBe(mockContent);
});
it("should handle callbacks correctly", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockContent = "Summary content";
const onStreamContent = vi.fn();
const onStreamComplete = vi.fn();
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary ");
callbacks?.onContent?.("content");
callbacks?.onContentComplete?.(mockContent);
return mockContent;
});
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
];
await compactChatHistory(history, mockModel, mockLlmApi, {
onStreamContent,
onStreamComplete
});
expect(onStreamContent).toHaveBeenCalledWith("Summary ");
expect(onStreamContent).toHaveBeenCalledWith("content");
expect(onStreamComplete).toHaveBeenCalled();
});
it("should handle errors correctly", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockError = new Error("Stream failed");
const onError = vi.fn();
mockStreamResponse.mockRejectedValue(mockError);
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
];
await expect(
compactChatHistory(history, mockModel, mockLlmApi, { onError })
).rejects.toThrow("Stream failed");
expect(onError).toHaveBeenCalledWith(mockError);
});
it("should handle history with only system message", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockContent = "Summary of system setup";
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.(mockContent);
callbacks?.onContentComplete?.(mockContent);
return mockContent;
});
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "You are a helpful assistant" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toHaveLength(2);
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "You are a helpful assistant" });
expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER);
});
it("should handle empty content from stream", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("");
callbacks?.onContentComplete?.("");
return "";
});
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactionContent).toBe("");
expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`);
});
it("should correctly construct prompt for compaction", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
let capturedHistory: ChatCompletionMessageParam[] = [];
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
capturedHistory = [...history];
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.("Summary");
return "Summary";
});
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi" },
];
await compactChatHistory(history, mockModel, mockLlmApi);
// Should have original history plus the compaction prompt
expect(capturedHistory).toHaveLength(4);
expect(capturedHistory[3]).toEqual({
role: "user",
content: expect.stringContaining("provide a concise summary")
});
});
it("should handle history with tool calls and mixed message types", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockContent = "Summary including tool usage";
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.(mockContent);
callbacks?.onContentComplete?.(mockContent);
return mockContent;
});
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
{ role: "user", content: "Do something" },
{ role: "assistant", content: "I'll help", tool_calls: [{} as any] },
{ role: "tool", content: "Tool result", tool_call_id: "123" },
{ role: "assistant", content: "Done" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toHaveLength(2);
expect(result.compactionContent).toBe(mockContent);
});
it("should handle very long chat histories", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Long summary");
callbacks?.onContentComplete?.("Long summary");
return "Long summary";
});
// Create a very long history
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
];
for (let i = 0; i < 100; i++) {
history.push({ role: "user", content: `User message ${i}` });
history.push({ role: "assistant", content: `Assistant response ${i}` });
}
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toHaveLength(2); // System + compaction
expect(result.compactionIndex).toBe(1);
});
it("should handle history without system message", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockContent = "Summary without system";
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.(mockContent);
callbacks?.onContentComplete?.(mockContent);
return mockContent;
});
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toHaveLength(1); // Only compaction
expect(result.compactedHistory[0].role).toBe("assistant");
expect(result.compactionIndex).toBe(0);
});
});
describe("property-based tests", () => {
it("getHistoryForLLM should always return a subset of the original history", () => {
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
{
history: [
{ role: "system", content: "System" },
{ role: "user", content: "User 1" },
{ role: "assistant", content: "Assistant 1" },
],
compactionIndex: 1
},
{
history: [
{ role: "user", content: "User 1" },
{ role: "assistant", content: "Assistant 1" },
{ role: "user", content: "User 2" },
],
compactionIndex: 2
},
{
history: [],
compactionIndex: null
}
];
testCases.forEach(({ history, compactionIndex }) => {
const result = getHistoryForLLM(history, compactionIndex);
// Every message in result should exist in original history
result.forEach(msg => {
expect(history).toContainEqual(msg);
});
// Result length should be <= original length
expect(result.length).toBeLessThanOrEqual(history.length);
});
});
it("getHistoryForLLM should always include system message if it exists at index 0", () => {
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "System" };
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
{
history: [
systemMessage,
{ role: "user", content: "User 1" },
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
],
compactionIndex: 2
},
{
history: [
systemMessage,
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
],
compactionIndex: 1
}
];
testCases.forEach(({ history, compactionIndex }) => {
const result = getHistoryForLLM(history, compactionIndex);
if (history[0]?.role === "system" && compactionIndex !== null && compactionIndex > 0) {
expect(result[0]).toEqual(systemMessage);
}
});
});
it("compaction should always reduce message count for non-trivial histories", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.("Summary");
return "Summary";
});
const testHistories: ChatCompletionMessageParam[][] = [
[
{ role: "system", content: "System" },
{ role: "user", content: "User 1" },
{ role: "assistant", content: "Assistant 1" },
{ role: "user", content: "User 2" },
{ role: "assistant", content: "Assistant 2" },
],
[
{ role: "user", content: "User 1" },
{ role: "assistant", content: "Assistant 1" },
{ role: "user", content: "User 2" },
]
];
for (const history of testHistories) {
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// Compacted history should be shorter than original
// (system + compaction) or just compaction
expect(result.compactedHistory.length).toBeLessThanOrEqual(2);
expect(result.compactedHistory.length).toBeLessThan(history.length);
}
});
});
describe("invariant tests", () => {
it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary content");
callbacks?.onContentComplete?.("Summary content");
return "Summary content";
});
const histories: ChatCompletionMessageParam[][] = [
[{ role: "system", content: "System" }, { role: "user", content: "Hello" }],
[{ role: "user", content: "Hello" }, { role: "assistant", content: "Hi" }],
[{ role: "system", content: "System" }],
];
for (const history of histories) {
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// The message at compactionIndex should contain the marker
const compactionMessage = result.compactedHistory[result.compactionIndex];
expect(compactionMessage.role).toBe("assistant");
expect(typeof compactionMessage.content === "string" && compactionMessage.content.startsWith(COMPACTION_MARKER)).toBe(true);
}
});
it("system message should always be preserved in the same position", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.("Summary");
return "Summary";
});
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "You are helpful" };
const history: ChatCompletionMessageParam[] = [
systemMessage,
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// System message should still be at index 0
expect(result.compactedHistory[0]).toEqual(systemMessage);
});
it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
const mockStreamResponse = vi.mocked(streamChatResponse);
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.("Summary");
return "Summary";
});
const history: ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi" },
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// findCompactionIndex should find the same index
const foundIndex = findCompactionIndex(result.compactedHistory);
expect(foundIndex).toBe(result.compactionIndex);
});
});
});

139
src/compaction.ts Normal file
View file

@ -0,0 +1,139 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { StreamCallbacks, streamChatResponse } from "./streamChatResponse.js";
import { logger } from "./util/logger.js";
export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
export interface CompactionResult {
compactedHistory: ChatCompletionMessageParam[];
compactionIndex: number;
compactionContent: string;
}
export interface CompactionCallbacks {
onStreamContent?: (content: string) => void;
onStreamComplete?: () => void;
onError?: (error: Error) => void;
}
/**
* Compacts a chat history into a summarized form
* @param chatHistory The current chat history to compact
* @param model The model configuration
* @param llmApi The LLM API instance
* @param callbacks Optional callbacks for streaming updates
* @returns The compacted history with compaction index
*/
export async function compactChatHistory(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
llmApi: BaseLlmApi,
callbacks?: CompactionCallbacks,
): Promise<CompactionResult> {
// Create a prompt to summarize the conversation
const compactionPrompt: ChatCompletionMessageParam = {
role: "user",
content:
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
};
// Get the current history for compaction
const historyForCompaction = [...chatHistory, compactionPrompt];
// Stream the compaction response
const controller = new AbortController();
let compactionContent = "";
const streamCallbacks: StreamCallbacks = {
onContent: (content: string) => {
compactionContent += content;
callbacks?.onStreamContent?.(content);
},
onContentComplete: () => {
callbacks?.onStreamComplete?.();
},
};
try {
await streamChatResponse(
historyForCompaction,
model,
llmApi,
controller,
streamCallbacks,
);
// Create the compacted history with a special marker
const systemMessage = chatHistory.find((msg) => msg.role === "system");
const compactedMessage: ChatCompletionMessageParam = {
role: "assistant",
content: `${COMPACTION_MARKER}\n${compactionContent}`,
};
// Set new chat history with only system message and compaction
const compactedHistory = systemMessage
? [systemMessage, compactedMessage]
: [compactedMessage];
const compactionIndex = compactedHistory.length - 1;
logger.debug("Chat history compacted", {
originalLength: chatHistory.length,
compactedLength: compactedHistory.length,
compactionIndex,
});
return {
compactedHistory,
compactionIndex,
compactionContent,
};
} catch (error) {
logger.error("Compaction failed", error);
callbacks?.onError?.(error as Error);
throw error;
}
}
/**
* Finds the compaction index in a chat history
* @param chatHistory The chat history to search
* @returns The index of the compaction message, or null if not found
*/
export function findCompactionIndex(
chatHistory: ChatCompletionMessageParam[],
): number | null {
const compactedIndex = chatHistory.findIndex(
(msg) =>
msg.role === "assistant" &&
typeof msg.content === "string" &&
msg.content.startsWith(COMPACTION_MARKER),
);
return compactedIndex !== -1 ? compactedIndex : null;
}
/**
* Gets the history to send to the LLM, taking compaction into account
* @param fullHistory The complete chat history
* @param compactionIndex The index of the compaction message, if any
* @returns The history to send to the LLM
*/
export function getHistoryForLLM(
fullHistory: ChatCompletionMessageParam[],
compactionIndex: number | null,
): ChatCompletionMessageParam[] {
if (compactionIndex === null || compactionIndex >= fullHistory.length) {
return fullHistory;
}
// Include system message (if at index 0) and everything from compaction index forward
const systemMessage =
fullHistory[0]?.role === "system" ? fullHistory[0] : null;
const messagesFromCompaction = fullHistory.slice(compactionIndex);
return systemMessage && compactionIndex > 0
? [systemMessage, ...messagesFromCompaction]
: messagesFromCompaction;
}

View file

@ -1,9 +1,4 @@
import {
AssistantUnrolled,
ModelConfig,
RegistryClient,
unrollAssistant,
} from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import {
BaseLlmApi,
constructLlmApi,
@ -14,30 +9,28 @@ import {
DefaultApi,
DefaultApiInterface,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { dirname } from "node:path";
import {
AuthConfig,
getAccessToken,
getOrganizationId,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./mcp.js";
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig
authConfig: AuthConfig,
): [BaseLlmApi, ModelConfig] {
const model = assistant.models?.find(
(model) =>
model?.roles?.includes("chat") || (model && model.roles === undefined)
model?.roles?.includes("chat") || (model && model.roles === undefined),
);
if (!model) {
throw new Error(
"No models with the chat role found in the configured assistant"
"No models with the chat role found in the configured assistant",
);
}
@ -70,64 +63,27 @@ export function getLlmApi(
if (!llmApi) {
throw new Error(
"Failed to initialize LLM. Please check your configuration."
"Failed to initialize LLM. Please check your configuration.",
);
}
return [llmApi, model];
}
async function loadConfigYaml(
accessToken: string | null,
filePath: string,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const unrollResult = await unrollAssistant(
{ filePath, uriType: "file" },
new RegistryClient({
accessToken: accessToken ?? undefined,
apiBase: env.apiBase,
rootPath: dirname(filePath),
}),
{
currentUserSlug: "",
alwaysUseProxy: false,
orgScopeId: organizationId,
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
}
);
const errorDetails = unrollResult.errors;
if (!unrollResult.config) {
throw new Error(`Failed to load config file:\n${errorDetails}`);
} else if (errorDetails?.length) {
const warnings =
errorDetails?.length > 1
? errorDetails.map((d) => `\n- ${d.message}`)
: errorDetails[0].message;
console.warn(chalk.dim(`Warning: ${warnings}`));
}
return unrollResult.config;
}
export function getApiClient(
accessToken: string | undefined | null
accessToken: string | undefined | null,
): DefaultApi {
return new DefaultApi(
new Configuration({
basePath: env.apiBase.replace(/\/$/, ""),
accessToken: accessToken ?? undefined,
})
}),
);
}
export async function initialize(
authConfig: AuthConfig,
configPath: string | undefined
configPath: string | undefined,
): Promise<{
config: AssistantUnrolled;
llmApi: BaseLlmApi;

View file

@ -1,3 +1,7 @@
import * as fs from "fs";
import { dirname } from "node:path";
import * as path from "path";
import {
AssistantUnrolled,
RegistryClient,
@ -5,10 +9,7 @@ import {
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import { dirname } from "node:path";
import * as os from "os";
import * as path from "path";
import {
AuthConfig,
getAccessToken,
@ -27,7 +28,7 @@ export interface ConfigLoadResult {
source: ConfigSource;
}
export type ConfigSource =
export type ConfigSource =
| { type: "cli-flag"; path: string }
| { type: "saved-uri"; uri: string }
| { type: "user-assistant"; slug: string }
@ -41,17 +42,22 @@ export type ConfigSource =
export async function loadConfiguration(
authConfig: AuthConfig,
cliConfigPath: string | undefined,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<ConfigLoadResult> {
const organizationId = getOrganizationId(authConfig);
const accessToken = getAccessToken(authConfig);
// Step 1: Determine config source using precedence rules
const configSource = determineConfigSource(authConfig, cliConfigPath);
// Step 2: Load configuration from the determined source
const config = await loadFromSource(configSource, accessToken, organizationId, apiClient);
const config = await loadFromSource(
configSource,
accessToken,
organizationId,
apiClient,
);
// Step 3: Save config URI for session continuity (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const uri = getUriFromSource(configSource);
@ -71,7 +77,7 @@ export async function loadConfiguration(
*/
function determineConfigSource(
authConfig: AuthConfig,
cliConfigPath: string | undefined
cliConfigPath: string | undefined,
): ConfigSource {
// Priority 1: CLI --config flag
if (cliConfigPath) {
@ -92,7 +98,7 @@ function determineConfigSource(
return { type: "user-assistant", slug: "" }; // Empty slug means "first available"
} else {
// Unauthenticated: check for default config.yaml, then fallback to default agent
const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml");
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
if (fs.existsSync(defaultConfigPath)) {
return { type: "default-config-yaml" };
}
@ -107,32 +113,50 @@ async function loadFromSource(
source: ConfigSource,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
try {
switch (source.type) {
case "cli-flag":
return await loadFromCliFlag(source.path, accessToken, organizationId, apiClient);
return await loadFromCliFlag(
source.path,
accessToken,
organizationId,
apiClient,
);
case "saved-uri":
return await loadFromSavedUri(source.uri, accessToken, organizationId, apiClient);
return await loadFromSavedUri(
source.uri,
accessToken,
organizationId,
apiClient,
);
case "user-assistant":
return await loadUserAssistantWithFallback(organizationId, apiClient);
case "default-config-yaml":
return await loadDefaultConfigYaml(accessToken, organizationId, apiClient);
return await loadDefaultConfigYaml(
accessToken,
organizationId,
apiClient,
);
case "default-agent":
return await loadDefaultAgent(organizationId, apiClient);
default:
throw new Error(`Unknown config source type: ${(source as any).type}`);
}
} catch (error) {
// If we're trying user assistants and it fails, fall back to default agent
if (source.type === "user-assistant") {
console.warn(chalk.yellow("Failed to load user assistants, falling back to default agent"));
console.warn(
chalk.yellow(
"Failed to load user assistants, falling back to default agent",
),
);
return await loadDefaultAgent(organizationId, apiClient);
}
throw error;
@ -147,11 +171,16 @@ async function loadFromCliFlag(
configPath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
if (isFilePath(configPath)) {
// Load local YAML file
return await loadConfigYaml(configPath, accessToken, organizationId, apiClient);
return await loadConfigYaml(
configPath,
accessToken,
organizationId,
apiClient,
);
} else {
// Load assistant slug
return await loadAssistantSlug(configPath, organizationId, apiClient);
@ -165,18 +194,23 @@ async function loadFromSavedUri(
uri: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const filePath = uriToPath(uri);
if (filePath) {
return await loadConfigYaml(filePath, accessToken, organizationId, apiClient);
return await loadConfigYaml(
filePath,
accessToken,
organizationId,
apiClient,
);
}
const slug = uriToSlug(uri);
if (slug) {
return await loadAssistantSlug(slug, organizationId, apiClient);
}
throw new Error(`Invalid saved config URI: ${uri}`);
}
@ -185,7 +219,7 @@ async function loadFromSavedUri(
*/
async function loadUserAssistantWithFallback(
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
@ -210,10 +244,15 @@ async function loadUserAssistantWithFallback(
async function loadDefaultConfigYaml(
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml");
return await loadConfigYaml(defaultConfigPath, accessToken, organizationId, apiClient);
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
return await loadConfigYaml(
defaultConfigPath,
accessToken,
organizationId,
apiClient,
);
}
/**
@ -221,7 +260,7 @@ async function loadDefaultConfigYaml(
*/
async function loadDefaultAgent(
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const resp = await apiClient.getAssistant({
ownerSlug: "continuedev",
@ -232,7 +271,7 @@ async function loadDefaultAgent(
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
}
return resp.configResult.config as AssistantUnrolled;
}
@ -243,7 +282,7 @@ async function loadConfigYaml(
filePath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const unrollResult = await unrollAssistant(
{ filePath, uriType: "file" },
@ -259,7 +298,7 @@ async function loadConfigYaml(
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
}
},
);
const errorDetails = unrollResult.errors;
@ -282,11 +321,13 @@ async function loadConfigYaml(
async function loadAssistantSlug(
slug: string,
organizationId: string | null,
apiClient: DefaultApiInterface
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const [ownerSlug, packageSlug] = slug.split("/");
if (!ownerSlug || !packageSlug) {
throw new Error(`Invalid assistant slug format. Expected "owner/package", got: ${slug}`);
throw new Error(
`Invalid assistant slug format. Expected "owner/package", got: ${slug}`,
);
}
const resp = await apiClient.getAssistant({
@ -311,7 +352,15 @@ function isFilePath(configPath: string): boolean {
return (
configPath.startsWith(".") ||
configPath.startsWith("/") ||
configPath.startsWith("~")
configPath.startsWith("~") ||
// Windows absolute paths (C:\, D:\, etc.)
/^[A-Za-z]:[/\\]/.test(configPath) ||
// UNC paths (\\server\share)
configPath.startsWith("\\\\") ||
// Contains file extension
configPath.includes(".yaml") ||
configPath.includes(".yml") ||
configPath.includes(".json")
);
}
@ -321,14 +370,14 @@ function isFilePath(configPath: string): boolean {
function getUriFromSource(source: ConfigSource): string | null {
switch (source.type) {
case "cli-flag":
return isFilePath(source.path)
? `file://${source.path}`
return isFilePath(source.path)
? `file://${source.path}`
: `slug://${source.path}`;
case "saved-uri":
return source.uri;
case "default-config-yaml":
return `file://${path.join(os.homedir(), ".continue", "config.yaml")}`;
return `file://${path.join(env.continueHome, "config.yaml")}`;
default:
return null;
}
}
}

View file

@ -1,7 +1,8 @@
import { Continue, ContinueClient } from "@continuedev/sdk";
import { env } from "./env.js";
import chalk from "chalk";
import { env } from "./env.js";
/**
* Initialize the Continue SDK with the given parameters
* @param apiKey - API key to use for authentication
@ -12,7 +13,7 @@ import chalk from "chalk";
export async function initializeContinueSDK(
apiKey: string | undefined,
assistantSlug: string,
organizationId?: string
organizationId?: string,
): Promise<ContinueClient> {
if (!apiKey) {
console.error(chalk.red("Error: No API key provided for Continue SDK"));
@ -29,7 +30,7 @@ export async function initializeContinueSDK(
} catch (error) {
console.error(
chalk.red("Error initializing Continue SDK:"),
error instanceof Error ? error.message : String(error)
error instanceof Error ? error.message : String(error),
);
throw error;
}

View file

@ -1,5 +1,6 @@
import fs from "fs/promises";
import path from "path";
import {
cleanupTestContext,
createTestContext,

View file

@ -1,4 +1,4 @@
import { describe, expect, test } from '@jest/globals';
import { describe, expect, test } from 'vitest';
describe('Config Switching Implementation Test', () => {
test('ConfigService updateConfigPath method exists with correct signature', async () => {

View file

@ -1,3 +1,6 @@
import * as fs from "fs/promises";
import * as path from "path";
import {
cleanupTestContext,
createTestContext,
@ -10,8 +13,6 @@ import {
createMockLLMConfig,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
import * as fs from "fs/promises";
import * as path from "path";
describe("E2E: Headless Mode with Dynamic Responses", () => {
let context: any;

View file

@ -1,5 +1,6 @@
import fs from "fs/promises";
import path from "path";
import {
cleanupTestContext,
createTestContext,

View file

@ -0,0 +1,105 @@
import {
createTestContext,
cleanupTestContext,
runCLI,
createTestConfig,
} from "../test-helpers/cli-helpers.js";
describe("E2E: Headless Mode with --org flag", () => {
let context: any;
const testConfig = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`;
const testEnv = {
OPENAI_API_KEY: "test-key",
CONTINUE_API_KEY: "test-api-key",
};
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
describe("--org flag mode restriction", () => {
it("should fail when --org is used without -p flag (interactive mode)", async () => {
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: [
"--config",
context.configPath,
"--org",
"my-org",
"Test prompt",
],
env: testEnv,
expectError: true,
});
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain(
"--org flag is only supported in headless mode"
);
});
it("should accept --org flag with -p flag (headless mode)", async () => {
await createTestConfig(context, testConfig);
// This will fail due to missing actual auth, but should get past the flag validation
const result = await runCLI(context, {
args: [
"-p",
"--config",
context.configPath,
"--org",
"my-org",
"Test prompt",
],
env: testEnv,
expectError: true,
});
// Should fail for a different reason (no actual auth/API), not because of flag validation
expect(result.stderr).not.toContain(
"--org flag is only supported in headless mode"
);
});
});
describe("--org flag inheritance", () => {
it("should inherit --org flag from parent command", async () => {
await createTestConfig(context, testConfig);
// Test with chat subcommand
const result = await runCLI(context, {
args: [
"--org",
"test-org",
"chat",
"-p",
"--config",
context.configPath,
"Test prompt",
],
env: testEnv,
expectError: true,
});
// The org flag should be inherited and work in headless mode
expect(result.stderr).not.toContain(
"--org flag is only supported in headless mode"
);
});
});
});

View file

@ -0,0 +1,217 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with --silent Flag", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should strip <think></think> tags from response with --silent flag", async () => {
const responseWithThinkTags = `<think>
I need to write a shell script. Let me think about this.
The user wants a simple Hello World script.
</think>
#!/bin/bash
echo "Hello World"`;
mockServer = await setupMockLLMTest(context, {
response: responseWithThinkTags,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
timeout: 15000,
});
// Verify think tags are stripped
expect(result.stdout).not.toContain("<think>");
expect(result.stdout).not.toContain("</think>");
expect(result.stdout).not.toContain("I need to write a shell script");
// Verify the actual content remains
expect(result.stdout).toContain("#!/bin/bash");
expect(result.stdout).toContain('echo "Hello World"');
expect(result.exitCode).toBe(0);
}, 20000);
it("should strip multiple <think></think> blocks with --silent flag", async () => {
const responseWithMultipleThinkTags = `<think>
First thought block
</think>
Some content here
<think>
Second thought block
More thinking...
</think>
Final content`;
mockServer = await setupMockLLMTest(context, {
response: responseWithMultipleThinkTags,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify all think tags are stripped
expect(result.stdout).not.toContain("<think>");
expect(result.stdout).not.toContain("</think>");
expect(result.stdout).not.toContain("First thought block");
expect(result.stdout).not.toContain("Second thought block");
expect(result.stdout).not.toContain("More thinking...");
// Verify the actual content remains
expect(result.stdout).toContain("Some content here");
expect(result.stdout).toContain("Final content");
expect(result.exitCode).toBe(0);
}, 20000);
it("should reduce excess whitespace with --silent flag", async () => {
const responseWithExcessWhitespace = `<think>
This will be removed
</think>
Content with lots of whitespace
More content`;
mockServer = await setupMockLLMTest(context, {
response: responseWithExcessWhitespace,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify think tags are stripped and excess whitespace is reduced
expect(result.stdout).not.toContain("<think>");
expect(result.stdout).not.toContain("This will be removed");
expect(result.stdout).toContain("Content with lots of whitespace");
expect(result.stdout).toContain("More content");
// Verify no triple newlines exist (excess whitespace reduced)
expect(result.stdout).not.toMatch(/\n\s*\n\s*\n/);
expect(result.exitCode).toBe(0);
}, 20000);
it("should work normally without --silent flag (baseline test)", async () => {
const responseWithThinkTags = `<think>
I need to write a shell script. Let me think about this.
</think>
#!/bin/bash
echo "Hello World"`;
mockServer = await setupMockLLMTest(context, {
response: responseWithThinkTags,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Write a shell script"],
timeout: 15000,
});
// Verify think tags are NOT stripped without --silent flag
expect(result.stdout).toContain("<think>");
expect(result.stdout).toContain("</think>");
expect(result.stdout).toContain("I need to write a shell script");
expect(result.stdout).toContain("#!/bin/bash");
expect(result.stdout).toContain('echo "Hello World"');
expect(result.exitCode).toBe(0);
}, 20000);
it("should handle response with no think tags using --silent flag", async () => {
const responseWithoutThinkTags = `#!/bin/bash
echo "Hello World"
This is a simple script.`;
mockServer = await setupMockLLMTest(context, {
response: responseWithoutThinkTags,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
timeout: 15000,
});
// Verify content is preserved when no think tags exist
expect(result.stdout).toContain("#!/bin/bash");
expect(result.stdout).toContain('echo "Hello World"');
expect(result.stdout).toContain("This is a simple script.");
expect(result.exitCode).toBe(0);
}, 20000);
it("should fail validation when --silent is used without -p flag", async () => {
const result = await runCLI(context, {
args: ["--silent", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--silent flag can only be used with -p/--print flag");
expect(result.exitCode).toBe(1);
}, 10000);
it("should work with both --silent and --format json flags", async () => {
const responseWithThinkTags = `<think>
I should respond with JSON
</think>
{"message": "Hello World", "status": "success"}`;
mockServer = await setupMockLLMTest(context, {
response: responseWithThinkTags,
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--silent", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify think tags are stripped and JSON is valid
expect(result.stdout).not.toContain("<think>");
expect(result.stdout).not.toContain("I should respond with JSON");
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput.message).toBe("Hello World");
expect(parsedOutput.status).toBe("success");
expect(result.exitCode).toBe(0);
}, 20000);
});

View file

@ -1,4 +1,5 @@
import * as http from "http";
import {
cleanupTestContext,
createTestContext,

View file

@ -1,4 +1,4 @@
import { describe, expect, test } from '@jest/globals';
import { describe, expect, test } from 'vitest';
describe('Local Config Switching Investigation', () => {
test('understands local vs remote config paths', () => {

View file

@ -1,3 +1,6 @@
import * as fs from "fs/promises";
import * as path from "path";
import {
cleanupTestContext,
createTestContext,
@ -8,8 +11,6 @@ import {
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
import * as fs from "fs/promises";
import * as path from "path";
describe("E2E: Resume Flag", () => {
let context: any;
@ -130,7 +131,7 @@ describe("E2E: Resume Flag", () => {
expect(firstResult.stdout).toContain("First response");
// Verify the first session was saved correctly
let sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
const sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
let sessionFiles = await fs.readdir(sessionDir);
expect(sessionFiles).toHaveLength(1);

View file

@ -21,20 +21,20 @@ A typical E2E test follows this structure:
```typescript
describe("E2E: Feature", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
it("should do something", async () => {
const result = await runCLI(context, {
args: ["command", "--flag"],
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Expected output");
});
@ -78,9 +78,10 @@ const result = await runCLI(context, {
```typescript
// For complex interactive flows
const result = await withInteractiveInput(context,
["chat"],
["First input", "Second input"]
const result = await withInteractiveInput(
context,
["chat"],
["First input", "Second input"],
);
```
@ -120,7 +121,7 @@ it("should get response from mock LLM", async () => {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hi"],
});
expect(result.stdout).toContain("Hello World!");
});
```
@ -128,15 +129,16 @@ it("should get response from mock LLM", async () => {
### Advanced Mock LLM Features
- **Dynamic responses** based on prompts:
```typescript
mockServer = await setupMockLLMTest(context, {
response: (prompt) => prompt.includes("weather")
? "It's sunny!"
: "I don't know",
response: (prompt) =>
prompt.includes("weather") ? "It's sunny!" : "I don't know",
});
```
- **Non-streaming responses**:
```typescript
mockServer = await setupMockLLMTest(context, {
response: "All at once response",
@ -166,7 +168,7 @@ const configPath = await createTestConfig(context, {
// Create a mock session
await createMockSession(context, [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" }
{ role: "assistant", content: "Hi there!" },
]);
// Read the session
@ -199,7 +201,7 @@ const result = await runCLI(context, {
const result = await withInteractiveInput(
context,
["chat"],
["User input", "/exit"]
["User input", "/exit"],
);
```
@ -216,4 +218,4 @@ const result = await runCLI(context, {
- Set longer timeouts for complex tests: `}, 30000);` (30 seconds)
- Examine the full output: `console.log(result.stdout, result.stderr)`
- Check the test directory: `console.log(context.testDir)`
- For intermittent failures, try running the test in isolation
- For intermittent failures, try running the test in isolation

View file

@ -1,3 +1,6 @@
import * as os from "os";
import * as path from "path";
import dotenv from "dotenv";
dotenv.config();
@ -7,4 +10,6 @@ export const env = {
workOsClientId:
process.env.WORKOS_CLIENT_ID ?? "client_01J0FW6XN8N2XJAECF7NE0Y65J",
appUrl: process.env.HUB_URL || "https://hub.continue.dev",
continueHome:
process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"),
};

View file

@ -100,4 +100,4 @@ export function listFiles(dirPath: string): ToolResult {
error: error instanceof Error ? error.message : String(error),
};
}
}
}

View file

@ -0,0 +1,145 @@
import {
convertLegacyModeFlags,
buildPermissionOverrides,
processCommandFlags,
} from "./flagProcessor.js";
describe("convertLegacyModeFlags", () => {
test("should return 'plan' when readonly is true", () => {
expect(convertLegacyModeFlags(true, false)).toBe("plan");
});
test("should return 'auto' when auto is true", () => {
expect(convertLegacyModeFlags(false, true)).toBe("auto");
});
test("should return undefined when both flags are false", () => {
expect(convertLegacyModeFlags(false, false)).toBeUndefined();
});
test("should return undefined when no flags provided", () => {
expect(convertLegacyModeFlags()).toBeUndefined();
});
test("should throw error when both readonly and auto are true", () => {
expect(() => convertLegacyModeFlags(true, true)).toThrow(
"Cannot use both --readonly and --auto flags together"
);
});
});
describe("buildPermissionOverrides", () => {
test("should build permission overrides with all parameters", () => {
const result = buildPermissionOverrides(
["readFile"],
["writeFile"],
["runTerminalCommand"],
"plan"
);
expect(result).toEqual({
allow: ["readFile"],
ask: ["writeFile"],
exclude: ["runTerminalCommand"],
mode: "plan",
});
});
test("should handle undefined parameters", () => {
const result = buildPermissionOverrides();
expect(result).toEqual({
allow: undefined,
ask: undefined,
exclude: undefined,
mode: undefined,
});
});
test("should handle partial parameters", () => {
const result = buildPermissionOverrides(["readFile"], undefined, ["Write"]);
expect(result).toEqual({
allow: ["readFile"],
ask: undefined,
exclude: ["Write"],
mode: undefined,
});
});
});
describe("processCommandFlags", () => {
test("should process readonly flag correctly", () => {
const result = processCommandFlags({
readonly: true,
allow: ["readFile"],
exclude: ["Write"],
});
expect(result).toEqual({
mode: "plan",
permissionOverrides: {
allow: ["readFile"],
ask: undefined,
exclude: ["Write"],
mode: "plan",
},
});
});
test("should process auto flag correctly", () => {
const result = processCommandFlags({
auto: true,
ask: ["writeFile"],
});
expect(result).toEqual({
mode: "auto",
permissionOverrides: {
allow: undefined,
ask: ["writeFile"],
exclude: undefined,
mode: "auto",
},
});
});
test("should handle no mode flags", () => {
const result = processCommandFlags({
allow: ["readFile", "searchCode"],
});
expect(result).toEqual({
mode: undefined,
permissionOverrides: {
allow: ["readFile", "searchCode"],
ask: undefined,
exclude: undefined,
mode: undefined,
},
});
});
test("should throw error for conflicting flags", () => {
expect(() =>
processCommandFlags({
readonly: true,
auto: true,
})
).toThrow("Cannot use both --readonly and --auto flags together");
});
test("should handle empty options", () => {
const result = processCommandFlags({});
expect(result).toEqual({
mode: undefined,
permissionOverrides: {
allow: undefined,
ask: undefined,
exclude: undefined,
mode: undefined,
},
});
});
});

View file

@ -0,0 +1,86 @@
/**
* Shared flag processing utilities to eliminate duplication between TUI and headless modes
*/
import { PermissionMode } from "../permissions/types.js";
export interface PermissionOverrides {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
}
export interface ProcessedFlags {
mode?: PermissionMode;
permissionOverrides: PermissionOverrides;
}
/**
* Converts legacy readonly/auto flags to the new mode system
* This logic was previously duplicated in chat.ts lines 168-173 and 259-264
*/
export function convertLegacyModeFlags(
readonly?: boolean,
auto?: boolean,
): PermissionMode | undefined {
if (readonly && auto) {
throw new Error("Cannot use both --readonly and --auto flags together");
}
if (readonly) {
return "plan";
}
if (auto) {
return "auto";
}
return undefined;
}
/**
* Structures permission overrides for service initialization
* This logic was previously duplicated between TUI and headless paths
*/
export function buildPermissionOverrides(
allow?: string[],
ask?: string[],
exclude?: string[],
mode?: PermissionMode,
): PermissionOverrides {
return {
allow,
ask,
exclude,
mode,
};
}
/**
* Processes all command line flags into a consistent structure
* Eliminates duplication and provides single source of truth for flag processing
*/
export function processCommandFlags(options: {
readonly?: boolean;
auto?: boolean;
allow?: string[];
ask?: string[];
exclude?: string[];
}): ProcessedFlags {
// Convert legacy flags to mode
const mode = convertLegacyModeFlags(options.readonly, options.auto);
// Build permission overrides
const permissionOverrides = buildPermissionOverrides(
options.allow,
options.ask,
options.exclude,
mode,
);
return {
mode,
permissionOverrides,
};
}

View file

@ -0,0 +1,209 @@
import { validateFlags, handleValidationErrors } from './flagValidator.js';
describe('validateFlags', () => {
describe('format flag validation', () => {
test('should pass when format is used with print', () => {
const result = validateFlags({
format: 'json',
print: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when format is used without print', () => {
const result = validateFlags({
format: 'json',
print: false,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('FORMAT_REQUIRES_PRINT');
expect(result.errors[0].message).toContain('--format flag can only be used with -p/--print');
});
test('should fail when format value is invalid', () => {
const result = validateFlags({
format: 'xml',
print: true,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('INVALID_FORMAT_VALUE');
expect(result.errors[0].message).toContain("--format currently only supports 'json'");
});
});
describe('silent flag validation', () => {
test('should pass when silent is used with print', () => {
const result = validateFlags({
silent: true,
print: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when silent is used without print', () => {
const result = validateFlags({
silent: true,
print: false,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('SILENT_REQUIRES_PRINT');
expect(result.errors[0].message).toContain('--silent flag can only be used with -p/--print');
});
});
describe('mode flags validation', () => {
test('should pass with readonly only', () => {
const result = validateFlags({
readonly: true,
auto: false,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should pass with auto only', () => {
const result = validateFlags({
readonly: false,
auto: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when both readonly and auto are used', () => {
const result = validateFlags({
readonly: true,
auto: true,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('CONFLICTING_MODE_FLAGS');
expect(result.errors[0].message).toContain('Cannot use both --readonly and --auto');
});
});
describe('permission flags validation', () => {
test('should pass with valid permission flags', () => {
const result = validateFlags({
allow: ['readFile', 'searchCode'],
ask: ['writeFile'],
exclude: ['Write', 'Bash'],
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail with empty tool names in allow', () => {
const result = validateFlags({
allow: ['readFile', '', 'searchCode'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_ALLOW_TOOL');
expect(result.errors[0].message).toContain('--allow requires a tool name');
});
test('should fail with empty tool names in ask', () => {
const result = validateFlags({
ask: ['writeFile', ' ', 'editFile'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_ASK_TOOL');
expect(result.errors[0].message).toContain('--ask requires a tool name');
});
test('should fail with empty tool names in exclude', () => {
const result = validateFlags({
exclude: ['Write', '', 'Bash'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_EXCLUDE_TOOL');
expect(result.errors[0].message).toContain('--exclude requires a tool name');
});
});
describe('multiple errors', () => {
test('should return all validation errors', () => {
const result = validateFlags({
format: 'xml',
print: false,
silent: true,
readonly: true,
auto: true,
allow: ['readFile', ''],
});
expect(result.isValid).toBe(false);
expect(result.errors.length).toBeGreaterThan(1);
const errorCodes = result.errors.map(e => e.code);
expect(errorCodes).toContain('FORMAT_REQUIRES_PRINT');
expect(errorCodes).toContain('INVALID_FORMAT_VALUE');
expect(errorCodes).toContain('SILENT_REQUIRES_PRINT');
expect(errorCodes).toContain('CONFLICTING_MODE_FLAGS');
expect(errorCodes).toContain('EMPTY_ALLOW_TOOL');
});
});
describe('config path validation', () => {
test('should pass with valid config path', () => {
const result = validateFlags({
config: './my-config.yaml',
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should pass with undefined config', () => {
const result = validateFlags({
config: undefined,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
});
});
describe('handleValidationErrors', () => {
test('should be a function that accepts validation errors', () => {
// Test function signature without calling it (since it calls process.exit)
expect(typeof handleValidationErrors).toBe('function');
expect(handleValidationErrors.length).toBe(1);
});
test('should accept proper error format', () => {
const validErrors = [
{ code: 'TEST_ERROR', message: 'Test message' },
{ code: 'ANOTHER_ERROR', message: 'Another message' }
];
// Verify the function exists and would accept this format
// We don't call it since it would exit the process
expect(() => {
const errorArray = validErrors;
expect(Array.isArray(errorArray)).toBe(true);
expect(errorArray.every(e => e.code && e.message)).toBe(true);
}).not.toThrow();
});
});

193
src/flags/flagValidator.ts Normal file
View file

@ -0,0 +1,193 @@
/**
* Centralized command line flag validation
* Provides consistent validation across all commands and proper error reporting
*/
export interface ValidationOptions {
// Root command specific flags
print?: boolean;
format?: string;
silent?: boolean;
// Common flags
readonly?: boolean;
auto?: boolean;
config?: string;
// Permission flags
allow?: string[];
ask?: string[];
exclude?: string[];
// Command context
isRootCommand?: boolean;
commandName?: string;
}
export interface ValidationError {
message: string;
code: string;
}
export interface ValidationResult {
isValid: boolean;
errors: ValidationError[];
}
/**
* Validate that --format flag only works with -p/--print
*/
function validateFormatFlag(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.format && !options.print) {
errors.push({
code: "FORMAT_REQUIRES_PRINT",
message: "Error: --format flag can only be used with -p/--print flag",
});
}
return errors;
}
/**
* Validate that --silent flag only works with -p/--print
*/
function validateSilentFlag(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.silent && !options.print) {
errors.push({
code: "SILENT_REQUIRES_PRINT",
message: "Error: --silent flag can only be used with -p/--print flag",
});
}
return errors;
}
/**
* Validate format value is supported
*/
function validateFormatValue(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.format && options.format !== "json") {
errors.push({
code: "INVALID_FORMAT_VALUE",
message: "Error: --format currently only supports 'json'",
});
}
return errors;
}
/**
* Validate that --readonly and --auto are mutually exclusive
* This validation is now handled in flagProcessor.ts, but we keep it here for completeness
*/
function validateModeFlags(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.readonly && options.auto) {
errors.push({
code: "CONFLICTING_MODE_FLAGS",
message: "Error: Cannot use both --readonly and --auto flags together",
});
}
return errors;
}
/**
* Validate config path exists (basic check)
*/
function validateConfigPath(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
// Note: We don't check file existence here since the config loader handles that
// and provides better error messages. This is just for basic validation.
if (options.config && typeof options.config !== "string") {
errors.push({
code: "INVALID_CONFIG_PATH",
message: "Error: --config must be a valid path",
});
}
return errors;
}
/**
* Validate permission flag combinations
*/
function validatePermissionFlags(
options: ValidationOptions,
): ValidationError[] {
const errors: ValidationError[] = [];
// Check for empty permission arrays (likely user error)
if (options.allow?.some((tool) => !tool.trim())) {
errors.push({
code: "EMPTY_ALLOW_TOOL",
message: "Error: --allow requires a tool name (e.g., --allow readFile)",
});
}
if (options.ask?.some((tool) => !tool.trim())) {
errors.push({
code: "EMPTY_ASK_TOOL",
message: "Error: --ask requires a tool name (e.g., --ask writeFile)",
});
}
if (options.exclude?.some((tool) => !tool.trim())) {
errors.push({
code: "EMPTY_EXCLUDE_TOOL",
message: "Error: --exclude requires a tool name (e.g., --exclude Write)",
});
}
return errors;
}
/**
* Run all validation checks on the provided options
*/
export function validateFlags(options: ValidationOptions): ValidationResult {
const allErrors: ValidationError[] = [];
// Run all validation functions
const validators = [
validateFormatFlag,
validateSilentFlag,
validateFormatValue,
validateModeFlags,
validateConfigPath,
validatePermissionFlags,
];
for (const validator of validators) {
allErrors.push(...validator(options));
}
return {
isValid: allErrors.length === 0,
errors: allErrors,
};
}
/**
* Display validation errors and exit process
* Provides consistent error formatting across all commands
*/
export function handleValidationErrors(errors: ValidationError[]): never {
for (const error of errors) {
console.error(error.message);
}
if (errors.length > 1) {
console.error(`\nFound ${errors.length} validation errors.`);
}
process.exit(1);
}

View file

@ -1,15 +1,19 @@
import chalk from "chalk";
import { spawn } from "child_process";
import * as fs from "fs";
import open from "open";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import { env } from "./env.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
import chalk from "chalk";
import open from "open";
import * as readlineSync from "readline-sync";
import { env } from "./env.js";
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
} from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
/**
* Creates or updates the local config with Anthropic API key
@ -21,10 +25,10 @@ async function createOrUpdateConfig(apiKey: string): Promise<void> {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
@ -36,7 +40,9 @@ async function createOrUpdateConfig(apiKey: string): Promise<void> {
* 2. Provides two specific options for continuing
* 3. Returns to the chat without restarting the entire CLI
*/
export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): Promise<void> {
export async function handleMaxedOutFreeTrial(
onReload?: () => Promise<void>,
): Promise<void> {
// Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
console.clear();
@ -60,16 +66,16 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
console.log(chalk.green("\n✓ Browser opened successfully!"));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
"After setting up your models subscription, restart the CLI to continue.",
),
);
} catch (error) {
} catch {
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
console.log(chalk.white(`Please visit: ${modelsUrl}`));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
"After setting up your models subscription, restart the CLI to continue.",
),
);
}
@ -82,13 +88,11 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
chalk.white("\nEnter your Anthropic API key: "),
{
hideEchoBack: true,
}
},
);
if (!isValidAnthropicApiKey(apiKey)) {
console.log(
chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`)
);
console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`));
process.exit(1);
}
@ -96,7 +100,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
await createOrUpdateConfig(apiKey);
console.log(chalk.green(`✓ API key saved successfully!`));
console.log(chalk.green("✓ Switching to local configuration..."));
// If a reload callback is provided, use it instead of restarting
if (onReload) {
await onReload();
@ -110,7 +114,9 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
// Fallback: restart the CLI if no reload callback was provided
console.log(
chalk.green("\n🔄 Restarting Continue CLI to resume your conversation...\n")
chalk.green(
"\n🔄 Restarting Continue CLI to resume your conversation...\n",
),
);
// Get the path to the current script
@ -124,7 +130,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
{
stdio: "inherit",
detached: true,
}
},
);
// Unref the child to allow the parent process to exit

View file

@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { useServiceContainer } from '../services/ServiceContainerContext.js';
import { ServiceResult } from '../services/types.js';
import { useEffect, useState } from "react";
import { useServiceContainer } from "../services/ServiceContainerContext.js";
import { ServiceResult } from "../services/types.js";
/**
* React hook for consuming services reactively
@ -10,8 +11,8 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
reload: () => Promise<void>;
} {
const container = useServiceContainer();
const [result, setResult] = useState<ServiceResult<T>>(() =>
container.getSync<T>(serviceName)
const [result, setResult] = useState<ServiceResult<T>>(() =>
container.getSync<T>(serviceName),
);
useEffect(() => {
@ -20,7 +21,7 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
setResult(initialResult);
// Auto-load if idle
if (initialResult.state === 'idle') {
if (initialResult.state === "idle") {
container.load<T>(serviceName).catch(() => {
// Error is handled by the service container and will trigger the error event
});
@ -28,33 +29,33 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
// Set up event listeners
const onLoading = () => {
setResult(prev => ({ ...prev, state: 'loading', error: null }));
setResult((prev) => ({ ...prev, state: "loading", error: null }));
};
const onReady = (value: T) => {
setResult({
value,
state: 'ready',
state: "ready",
error: null,
lastUpdated: new Date()
lastUpdated: new Date(),
});
};
const onError = (error: Error) => {
setResult(prev => ({
setResult((prev) => ({
...prev,
state: 'error',
state: "error",
error,
lastUpdated: new Date()
lastUpdated: new Date(),
}));
};
const onChanged = (value: T) => {
setResult(prev => ({
setResult((prev) => ({
...prev,
value,
error: null,
lastUpdated: new Date()
lastUpdated: new Date(),
}));
};
@ -79,7 +80,7 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
return {
...result,
reload
reload,
};
}
@ -87,10 +88,10 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
* Hook for consuming multiple services
*/
export function useServices<T extends Record<string, any>>(
serviceNames: (keyof T)[]
): {
services: Partial<T>;
loading: boolean;
serviceNames: (keyof T)[],
): {
services: Partial<T>;
loading: boolean;
error: Error | null;
allReady: boolean;
} {
@ -104,25 +105,20 @@ export function useServices<T extends Record<string, any>>(
const newServices: Partial<T> = {};
let hasLoading = false;
let hasError: Error | null = null;
let allReady = true;
for (const serviceName of serviceNames) {
const result = container.getSync(serviceName as string);
if (result.state === 'loading') {
if (result.state === "loading") {
hasLoading = true;
allReady = false;
} else if (result.state === 'error') {
} else if (result.state === "error") {
hasError = result.error;
allReady = false;
} else if (result.state === 'idle') {
allReady = false;
} else if (result.state === "idle") {
// Auto-load idle services
container.load(serviceName as string).catch(() => {});
} else if (result.state === 'ready' && result.value !== null) {
} else if (result.state === "ready" && result.value !== null) {
newServices[serviceName] = result.value as T[keyof T];
} else {
allReady = false;
}
}
@ -136,17 +132,17 @@ export function useServices<T extends Record<string, any>>(
// Set up listeners for all services
const listeners: Array<() => void> = [];
for (const serviceName of serviceNames) {
const name = serviceName as string;
const onAnyChange = () => updateState();
container.on(`${name}:loading`, onAnyChange);
container.on(`${name}:ready`, onAnyChange);
container.on(`${name}:error`, onAnyChange);
container.on(`${name}:changed`, onAnyChange);
listeners.push(() => {
container.off(`${name}:loading`, onAnyChange);
container.off(`${name}:ready`, onAnyChange);
@ -157,13 +153,13 @@ export function useServices<T extends Record<string, any>>(
// Cleanup
return () => {
listeners.forEach(cleanup => cleanup());
listeners.forEach((cleanup) => cleanup());
};
}, [serviceNames.join(','), container]);
}, [serviceNames.join(","), container]);
const allReady = serviceNames.every(name =>
container.isReady(name as string)
const allReady = serviceNames.every((name) =>
container.isReady(name as string),
);
return { services, loading, error, allReady };
}
}

View file

@ -1,26 +1,39 @@
#!/usr/bin/env node
import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { serve } from "./commands/serve.js";
import {
validateFlags,
handleValidationErrors,
} from "./flags/flagValidator.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import logger from "./util/logger.js";
import { logger } from "./util/logger.js";
import { readStdinSync } from "./util/stdin.js";
import { getVersion } from "./version.js";
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled Rejection at:", { promise, reason });
sentryService.captureException(
reason instanceof Error ? reason : new Error(String(reason)),
{
promise: String(promise),
},
);
// Don't exit the process, just log the error
});
process.on("uncaughtException", (error) => {
logger.error("Uncaught Exception:", error);
sentryService.captureException(error);
// Don't exit the process, just log the error
});
@ -29,7 +42,7 @@ const program = new Command();
program
.name("cn")
.description(
"Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output."
"Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.",
)
.version(getVersion());
@ -40,26 +53,36 @@ addCommonOptions(program)
.option("-p, --print", "Print response and exit (useful for pipes)")
.option(
"--format <format>",
"Output format for headless mode (json). Only works with -p/--print flag."
"Output format for headless mode (json). Only works with -p/--print flag.",
)
.option(
"--silent",
"Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.",
)
.option("--resume", "Resume from last session")
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
const isHeadless = options.print;
configureConsoleForHeadless(isHeadless);
logger.configureHeadlessMode(isHeadless);
// Validate --format flag only works with -p/--print
if (options.format && !options.print) {
console.error(
"Error: --format flag can only be used with -p/--print flag"
);
process.exit(1);
}
// Validate all command line flags
const validation = validateFlags({
print: options.print,
format: options.format,
silent: options.silent,
readonly: options.readonly,
auto: options.auto,
config: options.config,
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
isRootCommand: true,
commandName: "cn",
});
// Validate format value
if (options.format && options.format !== "json") {
console.error("Error: --format currently only supports 'json'");
process.exit(1);
if (!validation.isValid) {
handleValidationErrors(validation.errors);
}
if (options.verbose) {
@ -71,7 +94,7 @@ addCommonOptions(program)
console.log(`Verbose logging enabled (session: ${sessionId})`);
console.log(`Logs: ${logPath}`);
console.log(
`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`
`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`,
);
}
logger.debug("Verbose logging enabled");
@ -93,7 +116,9 @@ addCommonOptions(program)
// In headless mode, ensure we have a prompt
if (options.print && !prompt) {
console.error("Error: A prompt is required when using the -p/--print flag.\n");
console.error(
"Error: A prompt is required when using the -p/--print flag.\n",
);
console.error("Usage examples:");
console.error(' cn -p "please review my current git diff"');
console.error(' echo "hello" | cn -p');
@ -129,7 +154,11 @@ program
.description("Launch a remote instance of the cn agent")
.option(
"--url <url>",
"Connect directly to the specified URL instead of creating a new remote environment"
"Connect directly to the specified URL instead of creating a new remote environment",
)
.option(
"--idempotency-key <key>",
"Idempotency key for session management - allows resuming existing sessions",
)
.action(async (prompt: string | undefined, options) => {
await remote(prompt, options);
@ -142,7 +171,7 @@ program
.option(
"--timeout <seconds>",
"Inactivity timeout in seconds (default: 300)",
"300"
"300",
)
.option("--port <port>", "Port to run the server on (default: 8000)", "8000")
.action(async (prompt, options) => {
@ -178,5 +207,19 @@ try {
program.parse();
} catch (error) {
console.error(error);
sentryService.captureException(
error instanceof Error ? error : new Error(String(error)),
);
process.exit(1);
}
}
// Graceful shutdown - flush Sentry data
process.on("SIGINT", async () => {
await sentryService.flush();
process.exit(0);
});
process.on("SIGTERM", async () => {
await sentryService.flush();
process.exit(0);
});

View file

@ -6,15 +6,15 @@ export function configureLogger(isHeadless: boolean): void {
if (isHeadless) {
// Save the original console.info function
const originalConsoleInfo = console.info;
// Override console.info to be a no-op in headless mode
console.info = function() {
console.info = function () {
// Do nothing in headless mode
};
// Add a method to restore original behavior if needed
(console as any).restoreInfo = function() {
(console as any).restoreInfo = function () {
console.info = originalConsoleInfo;
};
}
}
}

View file

@ -1,3 +1,6 @@
import chalk from 'chalk';
import { vi } from 'vitest';
import {
configureLogger,
isLoggingEnabled,
@ -7,26 +10,24 @@ import {
warn,
loggers
} from './logging.js';
import { jest } from '@jest/globals';
import chalk from 'chalk';
describe('logging utilities', () => {
let consoleInfoSpy: jest.SpiedFunction<typeof console.info>;
let consoleErrorSpy: jest.SpiedFunction<typeof console.error>;
let consoleWarnSpy: jest.SpiedFunction<typeof console.warn>;
let consoleInfoSpy: ReturnType<typeof vi.spyOn>;
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// Reset logger state
configureLogger({ headless: false });
// Mock console methods
consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {});
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe('configureLogger', () => {

View file

@ -1,10 +1,8 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import logger from "./util/logger.js";
import {logger} from "./util/logger.js";
import { MCPServiceState } from "./services/types.js";
import { MCPConnection, MCPServerStatus } from "./MCPConnection.js";
export type MCPServerStatus = "idle" | "connecting" | "connected" | "error";
export interface MCPConnectionInfo {
name: string;
@ -16,6 +14,7 @@ export interface MCPConnectionInfo {
warnings: string[];
}
export class MCPService {
private connections: Map<string, MCPConnection> = new Map();
private currentState: MCPServiceState;
@ -397,125 +396,3 @@ export class MCPService {
}
}
export class MCPConnection {
public prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
public tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
public status: MCPServerStatus = "idle";
public error?: Error;
public warnings: string[] = [];
public readonly command: string;
public readonly name: string;
constructor(
public readonly client: Client | null,
command: string,
name: string
) {
this.command = command;
this.name = name;
}
public static async create(
config: NonNullable<AssistantConfig["mcpServers"]>[number],
name: string
): Promise<MCPConnection> {
if (!config) {
throw new Error("MCP server config is null");
}
const connection = new MCPConnection(
null,
config.command || "unknown",
name
);
connection.status = "connecting";
try {
const client = new Client(
{
name: "continue-cli-client",
version: "1.0.0",
},
{ capabilities: {} }
);
// Construct transport
const env: Record<string, string> = config.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
if (!config.command) {
throw new Error("MCP server command is not specified");
}
const transport = new StdioClientTransport({
command: config.command,
args: config.args,
env,
});
// Connect
logger.debug("Connecting to MCP server", {
name,
command: config.command,
});
await client.connect(transport, {});
// Update connection with successful client
(connection as any).client = client;
connection.status = "connected";
const capabilities = client.getServerCapabilities();
logger.debug("MCP server capabilities", {
name,
hasPrompts: !!capabilities?.prompts,
hasTools: !!capabilities?.tools,
});
// Load prompts
if (capabilities?.prompts) {
try {
connection.prompts = (await client.listPrompts()).prompts;
logger.debug("Loaded MCP prompts", {
name,
count: connection.prompts.length,
});
} catch (error: any) {
connection.warnings.push(`Failed to load prompts: ${error.message}`);
logger.warn("Failed to load MCP prompts", {
name,
error: error.message,
});
}
}
// Load tools
if (capabilities?.tools) {
try {
connection.tools = (await client.listTools()).tools;
logger.debug("Loaded MCP tools", {
name,
count: connection.tools.length,
});
} catch (error: any) {
connection.warnings.push(`Failed to load tools: ${error.message}`);
logger.warn("Failed to load MCP tools", {
name,
error: error.message,
});
}
}
return connection;
} catch (error: any) {
connection.status = "error";
connection.error = error;
logger.error("Failed to connect to MCP server", {
name,
error: error.message,
});
throw error;
}
}
}

155
src/onboarding.test.ts Normal file
View file

@ -0,0 +1,155 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { describe, expect, test, beforeEach, afterEach } from 'vitest';
import type { AuthConfig } from './auth/workos.js';
import { runNormalFlow } from './onboarding.js';
describe('onboarding config flag handling', () => {
let tempDir: string;
let mockAuthConfig: AuthConfig;
beforeEach(() => {
// Create a temporary directory for test config files
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'continue-test-'));
// Create a minimal auth config for testing
mockAuthConfig = {
userId: 'test-user',
userEmail: 'test@example.com',
accessToken: 'test-token',
refreshToken: 'test-refresh',
expiresAt: Date.now() + 3600000,
organizationId: 'test-org',
};
});
afterEach(() => {
// Clean up temporary directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
test('should fail loudly when --config points to non-existent file', async () => {
const configPath = path.join(tempDir, 'non-existent.yaml');
// Verify the file doesn't exist
expect(fs.existsSync(configPath)).toBe(false);
// Should throw an error that mentions both the path and the failure
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*non-existent\.yaml": .*ENOENT/
);
});
test('should fail loudly when --config points to malformed YAML file', async () => {
const configPath = path.join(tempDir, 'malformed.yaml');
// Create a malformed YAML file
fs.writeFileSync(configPath, `
name: "Test Config"
models:
- name: "GPT-4"
provider: "openai"
invalid_yaml_syntax: [unclosed array
`);
// Verify the file exists
expect(fs.existsSync(configPath)).toBe(true);
// Should throw an error mentioning the path and failure to load
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*malformed\.yaml": .+/
);
});
test('should fail loudly when --config points to file with missing required fields', async () => {
const configPath = path.join(tempDir, 'incomplete.yaml');
// Create a config file missing required fields
fs.writeFileSync(configPath, `
name: "Incomplete Config"
# Missing models array and other required fields
`);
// Verify the file exists
expect(fs.existsSync(configPath)).toBe(true);
// Should throw with our specific error format and include path
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/^Failed to load config from ".*": .+/
);
});
test('should handle different config path formats with proper error messages', async () => {
const testPaths = [
'./non-existent.yaml',
'/absolute/path/config.yaml',
'../relative/config.yaml',
'simple-name.yaml'
];
for (const configPath of testPaths) {
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
/Failed to load config from ".*": .+/
);
}
});
test('should handle empty string config path', async () => {
// Empty string should be treated differently from undefined
// Note: empty string triggers onboarding flow, but should still fail in our error format
await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow();
});
test('should not fall back to default config when explicit config fails', async () => {
const configPath = path.join(tempDir, 'bad-config.yaml');
// Create a bad config file
fs.writeFileSync(configPath, 'invalid: yaml: content: [');
const promise = runNormalFlow(mockAuthConfig, configPath);
await expect(promise).rejects.toThrow();
try {
await promise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
// CRITICAL: Must have our specific error format from the fix
expect(message).toMatch(/^Failed to load config from ".*": .+/);
// Error should be about the specific config file we provided
expect(message).toContain(configPath);
// Should NOT mention falling back to default config (this was the bug!)
expect(message).not.toContain('~/.continue/config.yaml');
expect(message).not.toContain('default config');
expect(message).not.toContain('fallback');
}
});
test('demonstrates the fix: explicit config failure vs no config provided', async () => {
const badConfigPath = path.join(tempDir, 'bad.yaml');
fs.writeFileSync(badConfigPath, 'invalid yaml [');
// Case 1: Explicit --config that fails should throw our specific error
await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow(
/^Failed to load config from "/
);
// Case 2: No explicit config should follow different logic
try {
await runNormalFlow(mockAuthConfig, undefined);
// If it succeeds, that's fine - the point is it's different behavior
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// This should NOT have our "Failed to load config from" prefix
expect(errorMessage).not.toMatch(/^Failed to load config from "/);
}
});
});

View file

@ -1,18 +1,24 @@
import * as fs from "fs";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { env } from "./env.js";
import { MCPService } from "./mcp.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
export interface OnboardingResult {
config: AssistantUnrolled;
@ -24,7 +30,7 @@ export interface OnboardingResult {
}
export async function checkHasAcceptableModel(
configPath: string
configPath: string,
): Promise<boolean> {
try {
if (!fs.existsSync(configPath)) {
@ -33,13 +39,11 @@ export async function checkHasAcceptableModel(
const content = fs.readFileSync(configPath, "utf8");
return content.includes("claude");
} catch (error) {
} catch {
return false;
}
}
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
export async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
@ -47,25 +51,39 @@ export async function createOrUpdateConfig(apiKey: string): Promise<void> {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
export async function runOnboardingFlow(
configPath: string | undefined,
authConfig: AuthConfig
authConfig: AuthConfig,
): Promise<OnboardingResult> {
// Step 1: Check if --config flag is provided
if (configPath) {
if (configPath !== undefined) {
const result = await initialize(authConfig, configPath);
return { ...result, wasOnboarded: false };
}
// Step 2: Present user with two options
// Step 2: Check if we're in a test/CI environment - if so, skip interactive prompts
const isTestEnv =
process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
process.env.VITEST === "true" ||
process.env.GITHUB_ACTIONS === "true" ||
!process.stdin.isTTY;
if (isTestEnv) {
// In test/CI environment, return a minimal working configuration
const result = await initialize(authConfig, undefined);
return { ...result, wasOnboarded: false };
}
// Step 3: Present user with two options
console.log(chalk.yellow("How do you want to get started?"));
console.log(chalk.white("1. ⏩ Log in with Continue"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
@ -85,7 +103,7 @@ export async function runOnboardingFlow(
chalk.white("\nEnter your Anthropic API key: "),
{
hideEchoBack: true,
}
},
);
if (!isValidAnthropicApiKey(apiKey)) {
@ -94,7 +112,7 @@ export async function runOnboardingFlow(
await createOrUpdateConfig(apiKey);
console.log(
chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`)
chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`),
);
const result = await initialize(authConfig, CONFIG_PATH);
@ -107,40 +125,58 @@ export async function runOnboardingFlow(
export async function runNormalFlow(
authConfig: AuthConfig,
configPath?: string,
rules?: string[]
rules?: string[],
): Promise<OnboardingResult> {
// Step 1: Check if --config flag is provided
if (configPath) {
let result = await initialize(authConfig, configPath);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
if (configPath !== undefined) {
// Empty string is invalid and should be treated as an error
if (configPath === "") {
throw new Error(
`Failed to load config from "": Config path cannot be empty`,
);
}
return { ...result, wasOnboarded: false };
}
// Step 2: If user is logged in, look for first assistant in selected org
if (isAuthenticated()) {
try {
let result = await initialize(authConfig, undefined);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch (error) {}
}
// Step 3: Look for local ~/.continue/config.yaml
if (fs.existsSync(CONFIG_PATH)) {
try {
let result = await initialize(authConfig, CONFIG_PATH);
const result = await initialize(authConfig, configPath);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch (error) {
// If user explicitly provided --config flag, fail loudly instead of falling back
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to load config from "${configPath}": ${errorMessage}`,
);
}
}
// Step 2: If user is logged in, look for first assistant in selected org
if (isAuthenticated()) {
try {
const result = await initialize(authConfig, undefined);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch {
// Silently ignore errors when loading default assistant
}
}
// Step 3: Look for local ~/.continue/config.yaml
if (fs.existsSync(CONFIG_PATH)) {
try {
const result = await initialize(authConfig, CONFIG_PATH);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch {
console.log(chalk.yellow("⚠ Invalid config file found"));
}
}
@ -150,7 +186,7 @@ export async function runNormalFlow(
console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment"));
await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`));
let result = await initialize(authConfig, CONFIG_PATH);
const result = await initialize(authConfig, CONFIG_PATH);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
@ -163,13 +199,11 @@ export async function runNormalFlow(
}
export async function isFirstTime(): Promise<boolean> {
return !fs.existsSync(
path.join(os.homedir(), ".continue", ".onboarding_complete")
);
return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete"));
}
export async function markOnboardingComplete(): Promise<void> {
const flagPath = path.join(os.homedir(), ".continue", ".onboarding_complete");
const flagPath = path.join(env.continueHome, ".onboarding_complete");
const flagDir = path.dirname(flagPath);
if (!fs.existsSync(flagDir)) {
@ -187,13 +221,13 @@ export async function markOnboardingComplete(): Promise<void> {
*/
async function injectRulesIntoConfig(
config: AssistantUnrolled,
rules: string[]
rules: string[],
): Promise<AssistantUnrolled> {
if (!rules || rules.length === 0) {
return config;
}
let processedRules: string[] = [];
const processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
const processedRule = await processRule(ruleSpec);
@ -201,8 +235,8 @@ async function injectRulesIntoConfig(
} catch (error: any) {
console.warn(
chalk.yellow(
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
)
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`,
),
);
}
}
@ -219,9 +253,8 @@ async function injectRulesIntoConfig(
const rulesSection = processedRules.join("\n\n");
if (existingSystemMessage) {
(
modifiedConfig as any
).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`;
(modifiedConfig as any).systemMessage =
`${existingSystemMessage}\n\n${rulesSection}`;
} else {
(modifiedConfig as any).systemMessage = rulesSection;
}
@ -232,7 +265,7 @@ async function injectRulesIntoConfig(
export async function initializeWithOnboarding(
authConfig: AuthConfig,
configPath: string | undefined,
rules?: string[]
rules?: string[],
): Promise<OnboardingResult> {
const firstTime = await isFirstTime();
@ -253,4 +286,4 @@ export async function initializeWithOnboarding(
}
return result;
}
}

View file

@ -6,26 +6,26 @@ import { ToolPermissionPolicy } from "./types.js";
*/
export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [
// Read-only tools are generally safe to allow
{ tool: "read_file", permission: "allow" },
{ tool: "list_files", permission: "allow" },
{ tool: "search_code", permission: "allow" },
{ tool: "fetch", permission: "allow" },
{ tool: "Read", permission: "allow" },
{ tool: "List", permission: "allow" },
{ tool: "Search", permission: "allow" },
{ tool: "Fetch", permission: "allow" },
// Write operations should require confirmation
{ tool: "write_file", permission: "ask" },
{ tool: "edit_file", permission: "ask" },
{ tool: "Write", permission: "ask" },
{ tool: "Edit", permission: "ask" },
// Write to a checklist
{ tool: "write_checklist", permission: "allow" },
{ tool: "Checklist", permission: "allow" },
// Terminal commands should require confirmation by default
{ tool: "run_terminal_command", permission: "ask" },
{ tool: "Bash", permission: "ask" },
// Exit tool is generally safe (headless mode only)
{ tool: "exit", permission: "allow" },
{ tool: "Exit", permission: "allow" },
// View diff is read-only
{ tool: "view_diff", permission: "allow" },
{ tool: "Diff", permission: "allow" },
// Default fallback - ask for any unmatched tools
{ tool: "*", permission: "ask" },

View file

@ -1,6 +1,6 @@
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import { checkToolPermission } from "./permissionChecker.js";
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
describe("Headless Permissions Integration", () => {
describe("precedence resolution", () => {
@ -34,13 +34,13 @@ describe("Headless Permissions Integration", () => {
const permissions = { policies: DEFAULT_TOOL_POLICIES };
// Read-only tools should be allowed
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "list_files", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "search_code", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "List", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Search", arguments: {} }, permissions).permission).toBe("allow");
// Write operations should require permission
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask");
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("ask");
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("ask");
// Unknown tools should default to ask
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
@ -61,8 +61,8 @@ describe("Headless Permissions Integration", () => {
expect(excludedResult.permission).toBe("exclude");
// Default tools should follow their normal rules
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask");
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
});
});
@ -74,7 +74,7 @@ describe("Headless Permissions Integration", () => {
// Still exclude truly dangerous operations
exclude: ["rm", "sudo"],
// Allow specific tools that would normally require confirmation
allow: ["write_file", "run_terminal_command"],
allow: ["Write", "Bash"],
},
useDefaults: true,
personalSettings: false,
@ -87,11 +87,11 @@ describe("Headless Permissions Integration", () => {
expect(checkToolPermission({ name: "sudo", arguments: {} }, permissions).permission).toBe("exclude");
// Explicitly allowed tools should be allowed
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
// Read-only tools should still be allowed by default
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
// Unknown tools should default to ask (since no wildcard allow override was provided)
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
@ -109,8 +109,8 @@ describe("Headless Permissions Integration", () => {
const permissions = { policies };
// All tools should be allowed due to wildcard override
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow");
});
});

View file

@ -0,0 +1,114 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { ToolPermissionService } from '../services/ToolPermissionService.js';
import { checkToolPermission } from './permissionChecker.js';
describe('Permission Integration Tests', () => {
let service: ToolPermissionService;
beforeEach(() => {
service = new ToolPermissionService();
});
describe('Headless mode with --allow flags', () => {
it('should allow Edit tool when --allow Edit is specified in headless mode', () => {
// Initialize service with headless mode and --allow Edit
service.initializeSync({
allow: ['Edit'],
isHeadless: true
});
const state = service.getState();
// Check that the service is in headless mode
expect(state.isHeadless).toBe(true);
// Check permission for Edit tool
const result = checkToolPermission(
{ name: 'Edit', arguments: {} },
state.permissions
);
// Should be allowed because --allow Edit is specified
expect(result.permission).toBe('allow');
});
it('should allow multiple tools with --allow in headless mode', () => {
// Initialize service with headless mode and multiple --allow flags
service.initializeSync({
allow: ['Edit', 'Write', 'Bash'],
isHeadless: true
});
const state = service.getState();
// Check Edit
const editResult = checkToolPermission(
{ name: 'Edit', arguments: {} },
state.permissions
);
expect(editResult.permission).toBe('allow');
// Check Write
const writeResult = checkToolPermission(
{ name: 'Write', arguments: {} },
state.permissions
);
expect(writeResult.permission).toBe('allow');
// Check Bash
const bashResult = checkToolPermission(
{ name: 'Bash', arguments: {} },
state.permissions
);
expect(bashResult.permission).toBe('allow');
});
it('should respect --exclude in headless mode', () => {
service.initializeSync({
allow: ['Read'],
exclude: ['Edit'],
isHeadless: true
});
const state = service.getState();
// Check that Read is allowed
const readResult = checkToolPermission(
{ name: 'Read', arguments: {} },
state.permissions
);
expect(readResult.permission).toBe('allow');
// Check that Edit is excluded
const editResult = checkToolPermission(
{ name: 'Edit', arguments: {} },
state.permissions
);
expect(editResult.permission).toBe('exclude');
});
it('should work with plan mode and --allow overrides', () => {
// Plan mode normally excludes write operations
service.initializeSync({
mode: 'plan',
allow: ['Edit'], // But we explicitly allow Edit
isHeadless: true
});
const state = service.getState();
// In plan mode with --allow Edit override
const editResult = checkToolPermission(
{ name: 'Edit', arguments: {} },
state.permissions
);
// Currently this fails because plan mode ignores --allow flags
// After fix, this should be 'allow'
expect(editResult.permission).toBe('exclude'); // Current behavior
// TODO: After fix, change to: expect(editResult.permission).toBe('allow');
});
});
});

View file

@ -1,8 +1,8 @@
import {
checkToolPermission,
filterExcludedTools,
matchesToolPattern,
matchesArguments,
matchesToolPattern,
} from "./permissionChecker.js";
import { ToolPermissions } from "./types.js";
@ -20,7 +20,9 @@ describe("Permission Checker", () => {
});
it("should match prefix wildcards", () => {
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(true);
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
true
);
expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
});
@ -55,7 +57,9 @@ describe("Permission Checker", () => {
expect(matchesToolPattern("test$dollar", "test$dollar")).toBe(true);
expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(true);
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
true
);
});
it("should handle wildcard patterns with special regex characters", () => {
@ -68,37 +72,67 @@ describe("Permission Checker", () => {
});
describe("Bash command patterns", () => {
it("should match Bash command patterns with run_terminal_command", () => {
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls" })).toBe(true);
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls -la" })).toBe(true);
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "pwd" })).toBe(false);
it("should match Bash command patterns with Bash tool", () => {
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
true
);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })
).toBe(false);
});
it("should match Bash command patterns with Bash display name", () => {
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })).toBe(true);
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })).toBe(false);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })
).toBe(false);
});
it("should match exact Bash commands", () => {
expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls" })).toBe(true);
expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls -la" })).toBe(false);
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
true
);
expect(
matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })
).toBe(false);
});
it("should not match Bash patterns for non-bash tools", () => {
expect(matchesToolPattern("read_file", "Bash(ls*)", { command: "ls" })).toBe(false);
expect(matchesToolPattern("write_file", "Bash(git*)", { command: "git status" })).toBe(false);
expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
false
);
expect(
matchesToolPattern("Write", "Bash(git*)", { command: "git status" })
).toBe(false);
});
it("should not match Bash patterns without command argument", () => {
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", {})).toBe(false);
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { other: "value" })).toBe(false);
expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
expect(
matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })
).toBe(false);
});
it("should handle complex Bash command patterns", () => {
expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm install" })).toBe(true);
expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm run build" })).toBe(true);
expect(matchesToolPattern("run_terminal_command", "Bash(git*commit*)", { command: "git commit -m 'test'" })).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })
).toBe(true);
expect(
matchesToolPattern("Bash", "Bash(git*commit*)", {
command: "git commit -m 'test'",
})
).toBe(true);
});
});
});
@ -114,7 +148,7 @@ describe("Permission Checker", () => {
const args = { path: "/test.txt", mode: "read" };
const patterns = { path: "/test.txt" };
expect(matchesArguments(args, patterns)).toBe(true);
const nonMatchingPatterns = { path: "/other.txt" };
expect(matchesArguments(args, nonMatchingPatterns)).toBe(false);
});
@ -123,7 +157,7 @@ describe("Permission Checker", () => {
const args = { path: "/any/file.txt", mode: "write" };
const patterns = { path: "*", mode: "write" };
expect(matchesArguments(args, patterns)).toBe(true);
const wildcardOnlyPatterns = { path: "*" };
expect(matchesArguments(args, wildcardOnlyPatterns)).toBe(true);
});
@ -132,7 +166,7 @@ describe("Permission Checker", () => {
const args = { path: "/test.txt", mode: "read", format: "json" };
const allMatchingPatterns = { path: "/test.txt", mode: "read" };
expect(matchesArguments(args, allMatchingPatterns)).toBe(true);
const partialMatchingPatterns = { path: "/test.txt", mode: "write" };
expect(matchesArguments(args, partialMatchingPatterns)).toBe(false);
});
@ -147,7 +181,7 @@ describe("Permission Checker", () => {
const args = { count: 42, enabled: true, data: null, list: [1, 2, 3] };
const patterns = { count: 42, enabled: true };
expect(matchesArguments(args, patterns)).toBe(true);
const mismatchedPatterns = { count: "42" }; // string vs number
expect(matchesArguments(args, mismatchedPatterns)).toBe(false);
});
@ -155,38 +189,43 @@ describe("Permission Checker", () => {
it("should handle complex object arguments with reference equality", () => {
const configObj = { host: "localhost", port: 3000 };
const optionsArray = ["verbose", "debug"];
const args = {
const args = {
config: configObj,
options: optionsArray
options: optionsArray,
};
const patterns = {
const patterns = {
config: configObj, // Same reference
options: optionsArray // Same reference
options: optionsArray, // Same reference
};
expect(matchesArguments(args, patterns)).toBe(true);
const differentObjectPatterns = {
config: { host: "localhost", port: 8080 } // Different object
const differentObjectPatterns = {
config: { host: "localhost", port: 8080 }, // Different object
};
expect(matchesArguments(args, differentObjectPatterns)).toBe(false);
const differentButEqualObjectPatterns = {
config: { host: "localhost", port: 3000 } // Different reference, same content
const differentButEqualObjectPatterns = {
config: { host: "localhost", port: 3000 }, // Different reference, same content
};
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(false);
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
false
);
});
describe("glob pattern matching", () => {
it("should match glob patterns with asterisk wildcards", () => {
const args = { command: "cd ../projects && ls", file_path: "/src/file.ts" };
const args = {
command: "cd ../projects && ls",
file_path: "/src/file.ts",
};
// Test command patterns
expect(matchesArguments(args, { command: "cd*" })).toBe(true);
expect(matchesArguments(args, { command: "*ls" })).toBe(true);
expect(matchesArguments(args, { command: "*&&*" })).toBe(true);
expect(matchesArguments(args, { command: "pwd*" })).toBe(false);
// Test file path patterns
expect(matchesArguments(args, { file_path: "*.ts" })).toBe(true);
expect(matchesArguments(args, { file_path: "/src/*" })).toBe(true);
@ -196,7 +235,7 @@ describe("Permission Checker", () => {
it("should match glob patterns with question mark wildcards", () => {
const args = { command: "git add", file: "test1.js" };
expect(matchesArguments(args, { command: "git a?d" })).toBe(true);
expect(matchesArguments(args, { command: "git a??d" })).toBe(false);
expect(matchesArguments(args, { file: "test?.js" })).toBe(true);
@ -204,87 +243,99 @@ describe("Permission Checker", () => {
});
it("should match complex glob patterns", () => {
const args = {
const args = {
command: "npm run test:unit",
path: "/home/user/projects/myapp/src/utils/helper.ts"
path: "/home/user/projects/myapp/src/utils/helper.ts",
};
expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(true);
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
true
);
expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
expect(matchesArguments(args, { path: "/home/*/projects/*/src/**" })).toBe(true);
expect(
matchesArguments(args, { path: "/home/*/projects/*/src/**" })
).toBe(true);
expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
});
it("should escape special regex characters in glob patterns", () => {
const args = {
const args = {
command: "echo 'test.pattern'",
regex: "test[0-9]+",
special: "file(1).txt"
special: "file(1).txt",
};
// Literal dots, brackets, parentheses should match exactly
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(true);
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
true
);
expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
expect(matchesArguments(args, { special: "file(*).txt" })).toBe(true);
// These should not match due to regex escaping
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(false);
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
false
);
expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
});
it("should handle mixed exact and glob patterns", () => {
const args = {
tool: "bash",
const args = {
tool: "bash",
command: "cd projects && npm install",
flag: "--verbose"
flag: "--verbose",
};
// Mix of exact and glob matching
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*install", // glob match
flag: "--verbose" // exact match
})).toBe(true);
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*test", // glob no match
flag: "--verbose" // exact match
})).toBe(false);
expect(
matchesArguments(args, {
tool: "bash", // exact match
command: "cd*install", // glob match
flag: "--verbose", // exact match
})
).toBe(true);
expect(
matchesArguments(args, {
tool: "bash", // exact match
command: "cd*test", // glob no match
flag: "--verbose", // exact match
})
).toBe(false);
});
it("should convert non-string values to strings for pattern matching", () => {
const args = {
const args = {
port: 3000,
enabled: true,
count: null,
items: [1, 2, 3]
items: [1, 2, 3],
};
expect(matchesArguments(args, { port: "30*" })).toBe(true);
expect(matchesArguments(args, { enabled: "tr*" })).toBe(true);
expect(matchesArguments(args, { count: "*" })).toBe(true); // null -> ""
expect(matchesArguments(args, { items: "*,*,*" })).toBe(true); // array toString
expect(matchesArguments(args, { port: "40*" })).toBe(false);
expect(matchesArguments(args, { enabled: "fa*" })).toBe(false);
});
it("should handle empty and undefined argument values", () => {
const args = {
const args = {
empty: "",
undef: undefined,
zero: 0,
false_val: false
false_val: false,
};
expect(matchesArguments(args, { empty: "*" })).toBe(true);
expect(matchesArguments(args, { undef: "*" })).toBe(true); // undefined -> ""
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
expect(matchesArguments(args, { false_val: "*" })).toBe(true); // false -> "false"
expect(matchesArguments(args, { empty: "nonempty*" })).toBe(false);
expect(matchesArguments(args, { zero: "1*" })).toBe(false);
});
@ -393,11 +444,11 @@ describe("Permission Checker", () => {
it("should use default policies when no custom permissions provided", () => {
const result = checkToolPermission({
name: "read_file",
name: "Read",
arguments: { path: "/test.txt" },
});
// Should match the default policies (read_file should be "allow")
// Should match the default policies (Read should be "allow")
expect(result.permission).toBe("allow");
});
@ -419,13 +470,13 @@ describe("Permission Checker", () => {
policies: [
{ tool: "Bash(ls*)", permission: "allow" },
{ tool: "Bash(git*)", permission: "ask" },
{ tool: "run_terminal_command", permission: "ask" }, // Fallback for other commands
{ tool: "Bash", permission: "ask" }, // Fallback for other commands
],
};
// Should match "Bash(ls*)" pattern and allow
const lsResult = checkToolPermission(
{ name: "run_terminal_command", arguments: { command: "ls -la" } },
{ name: "Bash", arguments: { command: "ls -la" } },
permissions
);
expect(lsResult.permission).toBe("allow");
@ -433,7 +484,7 @@ describe("Permission Checker", () => {
// Should match "Bash(git*)" pattern and ask
const gitResult = checkToolPermission(
{ name: "run_terminal_command", arguments: { command: "git status" } },
{ name: "Bash", arguments: { command: "git status" } },
permissions
);
expect(gitResult.permission).toBe("ask");
@ -441,36 +492,36 @@ describe("Permission Checker", () => {
// Should match general fallback for other commands
const npmResult = checkToolPermission(
{ name: "run_terminal_command", arguments: { command: "npm install" } },
{ name: "Bash", arguments: { command: "npm install" } },
permissions
);
expect(npmResult.permission).toBe("ask");
expect(npmResult.matchedPolicy?.tool).toBe("run_terminal_command");
expect(npmResult.matchedPolicy?.tool).toBe("Bash");
});
it("should match argument patterns with glob patterns", () => {
const permissions: ToolPermissions = {
policies: [
{
tool: "run_terminal_command",
permission: "exclude",
argumentMatches: { command: "rm*" }
tool: "Bash",
permission: "exclude",
argumentMatches: { command: "rm*" },
},
{
tool: "write_file",
tool: "Write",
permission: "ask",
argumentMatches: { file_path: "**/*.ts" }
argumentMatches: { file_path: "**/*.ts" },
},
{
tool: "write_file",
permission: "allow"
}
tool: "Write",
permission: "allow",
},
],
};
// Should exclude dangerous rm commands
const rmResult = checkToolPermission(
{ name: "run_terminal_command", arguments: { command: "rm -rf /" } },
{ name: "Bash", arguments: { command: "rm -rf /" } },
permissions
);
expect(rmResult.permission).toBe("exclude");
@ -478,15 +529,20 @@ describe("Permission Checker", () => {
// Should ask for TypeScript files
const tsResult = checkToolPermission(
{ name: "write_file", arguments: { file_path: "/src/components/Button.ts" } },
{
name: "Write",
arguments: { file_path: "/src/components/Button.ts" },
},
permissions
);
expect(tsResult.permission).toBe("ask");
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe("**/*.ts");
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
"**/*.ts"
);
// Should allow other file writes
const jsResult = checkToolPermission(
{ name: "write_file", arguments: { file_path: "/src/utils/helper.js" } },
{ name: "Write", arguments: { file_path: "/src/utils/helper.js" } },
permissions
);
expect(jsResult.permission).toBe("allow");

View file

@ -1,6 +1,7 @@
import { getServiceSync } from "../services/index.js";
import { SERVICE_NAMES } from "../services/types.js";
import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import {
PermissionCheckResult,
@ -14,9 +15,9 @@ import {
* Also handles special Bash command patterns like "Bash(ls*)"
*/
export function matchesToolPattern(
toolName: string,
pattern: string,
toolArguments?: Record<string, any>
toolName: string,
pattern: string,
toolArguments?: Record<string, any>,
): boolean {
if (pattern === "*") return true;
if (pattern === toolName) return true;
@ -24,12 +25,12 @@ export function matchesToolPattern(
// Handle special Bash command patterns like "Bash(ls*)"
const bashCommandMatch = pattern.match(/^Bash\((.+)\)$/);
if (bashCommandMatch) {
// Check if this is a bash/terminal tool (either normalized name or display name)
const isBashTool = toolName === "run_terminal_command" || toolName === "Bash";
// Check if this is a bash/terminal tool
const isBashTool = toolName === "Bash";
if (isBashTool && toolArguments?.command) {
const commandPattern = bashCommandMatch[1];
const command = toolArguments.command;
// Handle command patterns with wildcards
if (commandPattern.includes("*") || commandPattern.includes("?")) {
// Escape all regex metacharacters except * and ?
@ -39,7 +40,7 @@ export function matchesToolPattern(
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(command);
}
// Exact command match
return command === commandPattern;
}
@ -65,7 +66,7 @@ export function matchesToolPattern(
*/
export function matchesArguments(
args: Record<string, any>,
patterns?: Record<string, any>
patterns?: Record<string, any>,
): boolean {
if (!patterns) return true;
@ -75,16 +76,19 @@ export function matchesArguments(
if (pattern === "*") continue; // Wildcard matches anything
// Handle glob patterns with wildcards (only for string patterns)
if (typeof pattern === "string" && (pattern.includes("*") || pattern.includes("?"))) {
if (
typeof pattern === "string" &&
(pattern.includes("*") || pattern.includes("?"))
) {
// Convert argValue to string for pattern matching
const stringValue = String(argValue ?? "");
// Escape all regex metacharacters except * and ?
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
// Convert * and ? to their regex equivalents
const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
const regex = new RegExp(`^${regexPattern}$`);
if (!regex.test(stringValue)) {
return false;
}
@ -105,22 +109,23 @@ export function matchesArguments(
*/
export function checkToolPermission(
toolCall: ToolCallRequest,
permissions?: ToolPermissions
permissions?: ToolPermissions,
): PermissionCheckResult {
// Get permissions from service if not provided
let policies = permissions?.policies;
if (!policies) {
const serviceResult = getServiceSync<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS
SERVICE_NAMES.TOOL_PERMISSIONS,
);
// Only use defaults if service is not ready, not registered, or has no value
// This allows critical runtime errors to propagate properly
if (serviceResult.state !== 'ready' || !serviceResult.value) {
if (serviceResult.state !== "ready" || !serviceResult.value) {
policies = DEFAULT_TOOL_POLICIES;
} else {
policies = serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
policies =
serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
}
}
@ -147,12 +152,12 @@ export function checkToolPermission(
*/
export function filterExcludedTools(
toolNames: string[],
permissions?: ToolPermissions
permissions?: ToolPermissions,
): string[] {
return toolNames.filter((toolName) => {
const result = checkToolPermission(
{ name: toolName, arguments: {} },
permissions
permissions,
);
return result.permission !== "exclude";
});

View file

@ -15,8 +15,14 @@ describe("ToolPermissionManager", () => {
describe("Request Management", () => {
it("should generate unique request IDs", async () => {
const toolCall1: ToolCallRequest = { name: "readFile", arguments: { path: "/test1.txt" } };
const toolCall2: ToolCallRequest = { name: "readFile", arguments: { path: "/test2.txt" } };
const toolCall1: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test1.txt" },
};
const toolCall2: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test2.txt" },
};
// Start requests but don't await them
const promise1 = manager.requestPermission(toolCall1);
@ -33,13 +39,16 @@ describe("ToolPermissionManager", () => {
});
it("should store pending request details correctly", async () => {
const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt", content: "data" } };
const toolCall: ToolCallRequest = {
name: "writeFile",
arguments: { path: "/test.txt", content: "data" },
};
const promise = manager.requestPermission(toolCall);
const pendingIds = manager.getPendingRequestIds();
expect(pendingIds).toHaveLength(1);
const requestDetails = manager.getPendingRequest(pendingIds[0]);
expect(requestDetails).toBeDefined();
expect(requestDetails?.toolCall).toEqual(toolCall);
@ -50,17 +59,20 @@ describe("ToolPermissionManager", () => {
});
it("should remove request after approval", async () => {
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
const toolCall: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test.txt" },
};
const promise = manager.requestPermission(toolCall);
const pendingIds = manager.getPendingRequestIds();
const requestId = pendingIds[0];
expect(manager.getPendingRequest(requestId)).toBeDefined();
const approved = manager.approveRequest(requestId);
expect(approved).toBe(true);
const result = await promise;
expect(result.approved).toBe(true);
expect(manager.getPendingRequest(requestId)).toBeUndefined();
@ -68,15 +80,18 @@ describe("ToolPermissionManager", () => {
});
it("should remove request after rejection", async () => {
const toolCall: ToolCallRequest = { name: "runTerminalCommand", arguments: { command: "rm -rf /" } };
const toolCall: ToolCallRequest = {
name: "runTerminalCommand",
arguments: { command: "rm -rf /" },
};
const promise = manager.requestPermission(toolCall);
const pendingIds = manager.getPendingRequestIds();
const requestId = pendingIds[0];
const rejected = manager.rejectRequest(requestId);
expect(rejected).toBe(true);
const result = await promise;
expect(result.approved).toBe(false);
expect(manager.getPendingRequest(requestId)).toBeUndefined();
@ -93,13 +108,16 @@ describe("ToolPermissionManager", () => {
});
it("should support remember option for approval", async () => {
const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt" } };
const toolCall: ToolCallRequest = {
name: "writeFile",
arguments: { path: "/test.txt" },
};
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.approveRequest(requestId, true); // Remember = true
const result = await promise;
expect(result.approved).toBe(true);
expect(result.remember).toBe(true);
@ -107,54 +125,71 @@ describe("ToolPermissionManager", () => {
});
describe("Event Emission", () => {
it("should emit permissionRequested event", (done) => {
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
manager.on("permissionRequested", (event) => {
expect(event.requestId).toBeDefined();
expect(event.toolCall).toEqual(toolCall);
done();
it("should emit permissionRequested event", () => {
const toolCall: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test.txt" },
};
return new Promise<void>((resolve) => {
manager.on("permissionRequested", (event) => {
expect(event.requestId).toBeDefined();
expect(event.toolCall).toEqual(toolCall);
resolve();
});
manager.requestPermission(toolCall);
});
manager.requestPermission(toolCall);
});
it("should emit permissionResponse event on approval", (done) => {
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(true);
expect(event.requestId).toBeDefined();
done();
it("should emit permissionResponse event on approval", () => {
const toolCall: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test.txt" },
};
return new Promise<void>((resolve) => {
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(true);
expect(event.requestId).toBeDefined();
resolve();
});
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.approveRequest(requestId);
});
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.approveRequest(requestId);
});
it("should emit permissionResponse event on rejection", (done) => {
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(false);
expect(event.requestId).toBeDefined();
done();
it("should emit permissionResponse event on rejection", () => {
const toolCall: ToolCallRequest = {
name: "readFile",
arguments: { path: "/test.txt" },
};
return new Promise<void>((resolve) => {
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(false);
expect(event.requestId).toBeDefined();
resolve();
});
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.rejectRequest(requestId);
});
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.rejectRequest(requestId);
});
it("should emit permissionResponse even for non-existent requests", (done) => {
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(true);
expect(event.requestId).toBe("fake-id");
done();
it("should emit permissionResponse even for non-existent requests", () => {
return new Promise<void>((resolve) => {
manager.on("permissionResponse", (event) => {
expect(event.approved).toBe(true);
expect(event.requestId).toBe("fake-id");
resolve();
});
manager.approveRequest("fake-id");
});
manager.approveRequest("fake-id");
});
});
@ -162,13 +197,18 @@ describe("ToolPermissionManager", () => {
it("should handle multiple concurrent requests", async () => {
const toolCalls = [
{ name: "readFile", arguments: { path: "/file1.txt" } },
{ name: "writeFile", arguments: { path: "/file2.txt", content: "data1" } },
{
name: "writeFile",
arguments: { path: "/file2.txt", content: "data1" },
},
{ name: "runTerminalCommand", arguments: { command: "ls" } },
];
// Start all requests
const promises = toolCalls.map(toolCall => manager.requestPermission(toolCall));
const promises = toolCalls.map((toolCall) =>
manager.requestPermission(toolCall)
);
// Get all pending request IDs
const pendingIds = manager.getPendingRequestIds();
expect(pendingIds).toHaveLength(3);
@ -180,11 +220,11 @@ describe("ToolPermissionManager", () => {
// Wait for all to complete
const results = await Promise.all(promises);
expect(results[0].approved).toBe(true);
expect(results[1].approved).toBe(false);
expect(results[2].approved).toBe(true);
// All requests should be cleared
expect(manager.getPendingRequestIds()).toHaveLength(0);
});
@ -193,13 +233,13 @@ describe("ToolPermissionManager", () => {
describe("Edge Cases", () => {
it("should handle empty tool call arguments", async () => {
const toolCall: ToolCallRequest = { name: "exit", arguments: {} };
const promise = manager.requestPermission(toolCall);
const requestId = manager.getPendingRequestIds()[0];
manager.approveRequest(requestId);
const result = await promise;
expect(result.approved).toBe(true);
});
@ -209,17 +249,19 @@ describe("ToolPermissionManager", () => {
arguments: {
config: { host: "localhost", port: 3000 },
options: ["verbose", "debug"],
metadata: { created: new Date(), version: "1.0.0" }
}
metadata: { created: new Date(), version: "1.0.0" },
},
};
const promise = manager.requestPermission(toolCall);
const requestDetails = manager.getPendingRequest(manager.getPendingRequestIds()[0]);
const requestDetails = manager.getPendingRequest(
manager.getPendingRequestIds()[0]
);
expect(requestDetails?.toolCall.arguments).toEqual(toolCall.arguments);
manager.approveRequest(manager.getPendingRequestIds()[0]);
await promise;
});
});
});
});

View file

@ -1,4 +1,5 @@
import { EventEmitter } from "events";
import { ToolCallRequest } from "./types.js";
export interface PermissionRequestResult {
@ -22,7 +23,7 @@ export class ToolPermissionManager extends EventEmitter {
* when the user approves or rejects the request.
*/
async requestPermission(
toolCall: ToolCallRequest
toolCall: ToolCallRequest,
): Promise<PermissionRequestResult> {
const requestId = `tool-request-${++this.requestCounter}`;

View file

@ -12,24 +12,24 @@ describe("permissionsYamlLoader", () => {
const policies = yamlConfigToPolicies(config);
expect(policies).toEqual([
{ tool: "run_terminal_command", permission: "exclude" },
{ tool: "write_file", permission: "ask" },
{ tool: "read_file", permission: "allow" },
{ tool: "list_files", permission: "allow" },
{ tool: "Bash", permission: "exclude" },
{ tool: "Write", permission: "ask" },
{ tool: "Read", permission: "allow" },
{ tool: "List", permission: "allow" },
]);
});
it("should normalize tool names", () => {
const config = {
allow: ["read", "READ", "read_file"],
allow: ["read", "READ", "Read"],
};
const policies = yamlConfigToPolicies(config);
expect(policies).toEqual([
{ tool: "read_file", permission: "allow" },
{ tool: "read_file", permission: "allow" },
{ tool: "read_file", permission: "allow" },
{ tool: "Read", permission: "allow" },
{ tool: "Read", permission: "allow" },
{ tool: "Read", permission: "allow" },
]);
});
@ -63,7 +63,7 @@ describe("permissionsYamlLoader", () => {
const policies = yamlConfigToPolicies(config);
expect(policies).toEqual([{ tool: "read_file", permission: "allow" }]);
expect(policies).toEqual([{ tool: "Read", permission: "allow" }]);
});
it("should handle all permission types", () => {
@ -76,12 +76,12 @@ describe("permissionsYamlLoader", () => {
const policies = yamlConfigToPolicies(config);
expect(policies).toEqual([
{ tool: "fetch", permission: "exclude" },
{ tool: "exit", permission: "exclude" },
{ tool: "write_file", permission: "ask" },
{ tool: "run_terminal_command", permission: "ask" },
{ tool: "read_file", permission: "allow" },
{ tool: "list_files", permission: "allow" },
{ tool: "Fetch", permission: "exclude" },
{ tool: "Exit", permission: "exclude" },
{ tool: "Write", permission: "ask" },
{ tool: "Bash", permission: "ask" },
{ tool: "Read", permission: "allow" },
{ tool: "List", permission: "allow" },
]);
});
});
@ -91,7 +91,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("Write", "allow");
expect(policy).toEqual({
tool: "write_file",
tool: "Write",
permission: "allow"
});
});
@ -100,7 +100,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("Write(**/*.ts)", "exclude");
expect(policy).toEqual({
tool: "write_file",
tool: "Write",
permission: "exclude",
argumentMatches: {
file_path: "**/*.ts"
@ -112,7 +112,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("Bash(npm install)", "ask");
expect(policy).toEqual({
tool: "run_terminal_command",
tool: "Bash",
permission: "ask",
argumentMatches: {
command: "npm install"
@ -124,19 +124,19 @@ describe("permissionsYamlLoader", () => {
const testCases = [
{
pattern: "Read(src/**/*.js)",
expected: { tool: "read_file", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
expected: { tool: "Read", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
},
{
pattern: "List(/home/user)",
expected: { tool: "list_files", permission: "allow", argumentMatches: { path: "/home/user" } }
expected: { tool: "List", permission: "allow", argumentMatches: { path: "/home/user" } }
},
{
pattern: "Search(TODO)",
expected: { tool: "search_code", permission: "allow", argumentMatches: { query: "TODO" } }
expected: { tool: "Search", permission: "allow", argumentMatches: { query: "TODO" } }
},
{
pattern: "Fetch(https://api.example.com)",
expected: { tool: "fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
expected: { tool: "Fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
}
];
@ -150,7 +150,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("Write()", "allow");
expect(policy).toEqual({
tool: "write_file",
tool: "Write",
permission: "allow"
});
});
@ -159,7 +159,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("Bash( npm run test )", "ask");
expect(policy).toEqual({
tool: "run_terminal_command",
tool: "Bash",
permission: "ask",
argumentMatches: {
command: "npm run test"
@ -187,7 +187,7 @@ describe("permissionsYamlLoader", () => {
const policy = parseToolPattern("write(**/*.ts)", "allow");
expect(policy).toEqual({
tool: "write_file",
tool: "Write",
permission: "allow",
argumentMatches: {
file_path: "**/*.ts"

View file

@ -1,15 +1,16 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as yaml from "yaml";
import logger from "../util/logger.js";
import { env } from "../env.js";
import { logger } from "../util/logger.js";
import { normalizeToolName } from "./toolNameMapping.js";
import { PermissionPolicy, ToolPermissionPolicy } from "./types.js";
export const PERMISSIONS_YAML_PATH = path.join(
os.homedir(),
".continue",
"permissions.yaml"
export const PERMISSIONS_YAML_PATH = path.resolve(
path.join(env.continueHome, "permissions.yaml"),
);
export interface PermissionsYamlConfig {
@ -41,7 +42,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
(key) =>
validKeys.includes(key) &&
(!parsed[key as keyof PermissionsYamlConfig] ||
Array.isArray(parsed[key as keyof PermissionsYamlConfig]))
Array.isArray(parsed[key as keyof PermissionsYamlConfig])),
);
if (hasValidStructure) {
@ -70,13 +71,13 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
/**
* Parses a pattern string into a ToolPermissionPolicy
* Supports formats like:
* - "Write" -> { tool: "write_file", permission }
* - "Write(pattern)" -> { tool: "write_file", permission, argumentMatches: { file_path: "pattern" } }
* - "Bash(npm install)" -> { tool: "run_terminal_command", permission, argumentMatches: { command: "npm install" } }
* - "Write" -> { tool: "Write", permission }
* - "Write(pattern)" -> { tool: "Write", permission, argumentMatches: { file_path: "pattern" } }
* - "Bash(npm install)" -> { tool: "Bash", permission, argumentMatches: { command: "npm install" } }
*/
export function parseToolPattern(
pattern: string,
permission: PermissionPolicy
permission: PermissionPolicy,
): ToolPermissionPolicy {
const match = pattern.match(/^([^(]+)(?:\(([^)]*)\))?$/);
if (!match) {
@ -96,14 +97,14 @@ export function parseToolPattern(
if (trimmedArgs) {
// Map tool names to their primary argument parameter
const toolArgMappings: Record<string, string> = {
write_file: "file_path",
edit_file: "file_path",
read_file: "file_path",
list_files: "path",
search_code: "query",
run_terminal_command: "command",
fetch: "url",
view_diff: "file_path",
Write: "file_path",
Edit: "file_path",
Read: "file_path",
List: "path",
Search: "query",
Bash: "command",
Fetch: "url",
Diff: "file_path",
};
const argKey = toolArgMappings[normalizedName] || "pattern";
@ -120,7 +121,7 @@ export function parseToolPattern(
* Converts permissions YAML config to ToolPermissionPolicy array
*/
export function yamlConfigToPolicies(
config: PermissionsYamlConfig
config: PermissionsYamlConfig,
): ToolPermissionPolicy[] {
const policies: ToolPermissionPolicy[] = [];

View file

@ -1,8 +1,15 @@
import * as fs from "fs";
import * as yaml from "yaml";
import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js";
import { logger } from "../util/logger.js";
import {
PERMISSIONS_YAML_PATH,
PermissionsYamlConfig,
loadPermissionsYaml,
} from "./permissionsYamlLoader.js";
import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
import logger from "../util/logger.js";
/**
* Generates a policy rule for a given tool call
@ -11,9 +18,9 @@ import logger from "../util/logger.js";
*/
export function generatePolicyRule(toolName: string, toolArgs: any): string {
const normalizedName = normalizeToolName(toolName);
// For Bash tool (run_terminal_command), create command-specific policies
if (normalizedName === "run_terminal_command" && toolArgs?.command) {
// For Bash tool, create command-specific policies
if (normalizedName === "Bash" && toolArgs?.command) {
const command = toolArgs.command.trim();
// Extract the first command (before pipes, &&, ||, etc.)
const firstCommand = command.split(/[;&|]|&&|\|\|/)[0]?.trim();
@ -23,7 +30,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string {
return `Bash(${commandName}*)`;
}
}
// For all other tools, return the display name
return getDisplayName(normalizedName);
}
@ -34,34 +41,37 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string {
export async function addPolicyToYaml(policyRule: string): Promise<void> {
try {
// Load existing config or create empty one
let config: PermissionsYamlConfig = loadPermissionsYaml() || {};
const config: PermissionsYamlConfig = loadPermissionsYaml() || {};
// Ensure allow array exists
if (!config.allow) {
config.allow = [];
}
// Add the policy if it doesn't already exist
if (!config.allow.includes(policyRule)) {
config.allow.push(policyRule);
// Write the updated config back to the file
const yamlContent = yaml.stringify(config);
// Add header comment
const finalContent = `# Continue CLI Permissions Configuration
# This file is managed by the Continue CLI and should not be edited manually.
# Use the TUI to modify permissions interactively.
${yamlContent}`;
await fs.promises.writeFile(PERMISSIONS_YAML_PATH, finalContent, "utf-8");
logger.info(`Added policy rule to permissions.yaml: ${policyRule}`);
} else {
logger.debug(`Policy rule already exists: ${policyRule}`);
}
} catch (error) {
logger.error("Failed to add policy to permissions.yaml", { error, policyRule });
logger.error("Failed to add policy to permissions.yaml", {
error,
policyRule,
});
throw error;
}
}
}

View file

@ -0,0 +1,23 @@
import { generatePolicyRule } from "./policyWriter.js";
describe("policyWriter verification", () => {
it("should return display names for all tools", () => {
// Test Edit tool
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
// Test Write tool
expect(generatePolicyRule("Write", { filepath: "test.txt" })).toBe("Write");
// Test Read tool
expect(generatePolicyRule("Read", { filepath: "test.txt" })).toBe("Read");
// Test Bash tool with commands
expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)");
});
it("should handle mixed case tool names", () => {
expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("Edit");
expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("Edit");
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
});
});

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