Merge branch 'main' into idempotency-key
This commit is contained in:
commit
57eded4787
156 changed files with 2588 additions and 1715 deletions
8
.github/workflows/beta-release.yml
vendored
8
.github/workflows/beta-release.yml
vendored
|
|
@ -46,11 +46,11 @@ jobs:
|
|||
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
|
||||
|
|
@ -79,9 +79,9 @@ jobs:
|
|||
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
|
||||
--prerelease
|
||||
|
|
|
|||
41
.github/workflows/pr_checks.yml
vendored
41
.github/workflows/pr_checks.yml
vendored
|
|
@ -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:
|
||||
|
|
@ -43,9 +79,6 @@ jobs:
|
|||
shell: bash
|
||||
run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
|
||||
|
||||
- name: Run linting
|
||||
run: npm run lint
|
||||
|
||||
review:
|
||||
uses: ./.github/workflows/continue-review.yaml
|
||||
secrets:
|
||||
|
|
@ -65,6 +98,8 @@ jobs:
|
|||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- lint
|
||||
- format-check
|
||||
- test
|
||||
|
||||
steps:
|
||||
|
|
|
|||
30
.github/workflows/respond-to-cubic-dev-ai.yml
vendored
30
.github/workflows/respond-to-cubic-dev-ai.yml
vendored
|
|
@ -1,4 +1,4 @@
|
|||
name: Respond to cubic-dev-ai Comments
|
||||
name: Respond to @continuedev Comments
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
|
|
@ -14,31 +14,31 @@ jobs:
|
|||
# Only run on pull request comments
|
||||
if: github.event.issue.pull_request
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
steps:
|
||||
- name: Check if comment is from cubic-dev-ai
|
||||
id: check-author
|
||||
- name: Check if comment contains @continuedev
|
||||
id: check-mention
|
||||
run: |
|
||||
if [ "${{ github.event.comment.user.login }}" = "cubic-dev-ai" ]; then
|
||||
echo "is_cubic_dev_ai=true" >> $GITHUB_OUTPUT
|
||||
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
|
||||
echo "contains_mention=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "is_cubic_dev_ai=false" >> $GITHUB_OUTPUT
|
||||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Get comment content
|
||||
if: steps.check-author.outputs.is_cubic_dev_ai == 'true'
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: comment-content
|
||||
run: |
|
||||
# Store the comment body for debugging/logging
|
||||
echo "Comment from cubic-dev-ai:"
|
||||
echo "Comment mentioning @continuedev from ${{ github.event.comment.user.login }}:"
|
||||
echo "${{ github.event.comment.body }}"
|
||||
|
||||
- name: Respond to cubic-dev-ai comment
|
||||
if: steps.check-author.outputs.is_cubic_dev_ai == 'true'
|
||||
- name: Respond to @continuedev mention
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `👋 Thanks for the feedback, @cubic-dev-ai!
|
||||
const commentBody = `👋 Thanks for mentioning @continuedev, @${{ github.event.comment.user.login }}!
|
||||
|
||||
I've received your comment:
|
||||
> ${{ github.event.comment.body }}
|
||||
|
|
@ -53,7 +53,7 @@ jobs:
|
|||
});
|
||||
|
||||
- name: Log acknowledgement
|
||||
if: steps.check-author.outputs.is_cubic_dev_ai == 'true'
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
echo "✅ Successfully acknowledged comment from cubic-dev-ai on PR #${{ github.event.issue.number }}"
|
||||
echo "Original comment: ${{ github.event.comment.body }}"
|
||||
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 }}"
|
||||
|
|
|
|||
16
.github/workflows/stable-release.yml
vendored
16
.github/workflows/stable-release.yml
vendored
|
|
@ -7,7 +7,7 @@ on:
|
|||
workflow_dispatch:
|
||||
inputs:
|
||||
beta_version:
|
||||
description: 'Specific beta version to promote (e.g., 1.2.3-beta.20240115)'
|
||||
description: "Specific beta version to promote (e.g., 1.2.3-beta.20240115)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
|
|
@ -70,10 +70,10 @@ jobs:
|
|||
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
|
||||
|
||||
|
|
@ -83,11 +83,11 @@ jobs:
|
|||
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/
|
||||
|
||||
|
|
@ -95,7 +95,7 @@ jobs:
|
|||
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
|
||||
|
||||
|
|
@ -121,7 +121,7 @@ jobs:
|
|||
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 }}" \
|
||||
|
|
@ -134,4 +134,4 @@ jobs:
|
|||
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 }}."
|
||||
--notes "This beta version has been promoted to stable as v${{ steps.find_beta.outputs.stable_version }}."
|
||||
|
|
|
|||
40
.prettierignore
Normal file
40
.prettierignore
Normal 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
8
.prettierrc
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"trailingComma": "all",
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"bracketSpacing": true
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
129
CHANGELOG.md
129
CHANGELOG.md
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ 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
|
||||
- `--ask <tool>` - Ask before using tools
|
||||
- `--exclude <tool>` - Block specific tools
|
||||
|
||||
```bash
|
||||
|
|
@ -66,7 +66,7 @@ cn serve --timeout 600 # 10 minute timeout
|
|||
## Remote Development
|
||||
|
||||
```bash
|
||||
cn remote "help debug this" # Create new remote environment
|
||||
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
|
||||
```
|
||||
|
|
@ -125,4 +125,4 @@ cn serve --readonly --port 8080
|
|||
- 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`
|
||||
- `--format json` and `--silent` only work with `-p`
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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}'`);
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -32,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
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
17
package-lock.json
generated
17
package-lock.json
generated
|
|
@ -84,6 +84,7 @@
|
|||
"ink-testing-library": "^4.0.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"nock": "^14.0.5",
|
||||
"prettier": "^3.6.2",
|
||||
"semantic-release": "^24.2.7",
|
||||
"supertest": "^7.1.3",
|
||||
"ts-node": "^10.9.2",
|
||||
|
|
@ -16145,6 +16146,22 @@
|
|||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
|
||||
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/pretty-format": {
|
||||
"version": "27.5.1",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@
|
|||
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
|
||||
"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",
|
||||
|
|
@ -108,6 +110,7 @@
|
|||
"ink-testing-library": "^4.0.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"nock": "^14.0.5",
|
||||
"prettier": "^3.6.2",
|
||||
"semantic-release": "^24.2.7",
|
||||
"supertest": "^7.1.3",
|
||||
"ts-node": "^10.9.2",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -14,12 +14,12 @@ import * as dotenv from "dotenv";
|
|||
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;
|
||||
|
|
@ -31,7 +31,7 @@ export class CLIPlatformClient implements PlatformClient {
|
|||
console.warn(
|
||||
`Error reading .env file at ${filePath}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -70,7 +70,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
|
||||
|
|
@ -92,7 +92,7 @@ export class CLIPlatformClient implements PlatformClient {
|
|||
console.warn(
|
||||
`Error resolving FQSNs through API: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,14 +11,14 @@ export class MCPConnection {
|
|||
private constructor(public readonly client: Client) {}
|
||||
|
||||
public static async create(
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number]
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number],
|
||||
) {
|
||||
const client = new Client(
|
||||
{
|
||||
name: "continue-cli-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{ capabilities: {} }
|
||||
{ capabilities: {} },
|
||||
);
|
||||
|
||||
// Construct transport
|
||||
|
|
@ -39,10 +39,13 @@ export class MCPConnection {
|
|||
|
||||
// Connect and get all prompts and tools
|
||||
const connection = new MCPConnection(client);
|
||||
logger.debug('Connecting to MCP server', { command: config.command });
|
||||
logger.debug("Connecting to MCP server", { command: config.command });
|
||||
await client.connect(transport);
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools });
|
||||
logger.debug("MCP server capabilities", {
|
||||
hasPrompts: !!capabilities?.prompts,
|
||||
hasTools: !!capabilities?.tools,
|
||||
});
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
connection.prompts = (await client.listPrompts()).prompts;
|
||||
|
|
@ -54,4 +57,4 @@ export class MCPConnection {
|
|||
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const processRule = vi.fn<(rule: string) => Promise<string>>();
|
||||
export const processRule = vi.fn<(rule: string) => Promise<string>>();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { vi } from 'vitest';
|
||||
import type { AuthConfig } from '../../auth/workos.js';
|
||||
import { vi } from "vitest";
|
||||
import type { AuthConfig } from "../../auth/workos.js";
|
||||
|
||||
export const isAuthenticated = vi.fn(() => false);
|
||||
export const isAuthenticatedConfig = vi.fn(() => false);
|
||||
|
|
@ -25,4 +25,4 @@ 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();
|
||||
export const updateLocalConfigPath = vi.fn();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,17 @@
|
|||
import { vi } from 'vitest';
|
||||
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 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>();
|
||||
export const createLlmApi =
|
||||
vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const loadConfiguration = vi.fn<(options: any) => Promise<any>>();
|
||||
export const loadConfiguration = vi.fn<(options: any) => Promise<any>>();
|
||||
|
|
|
|||
|
|
@ -18,4 +18,4 @@ export const useServices = vi.fn(() => ({
|
|||
loading: false,
|
||||
error: null,
|
||||
allReady: true,
|
||||
}));
|
||||
}));
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const log = vi.fn();
|
||||
export const error = vi.fn();
|
||||
|
|
@ -13,4 +13,4 @@ export const loggers = {
|
|||
cyan: vi.fn(),
|
||||
white: vi.fn(),
|
||||
gray: vi.fn(),
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null);
|
||||
export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>(() => []);
|
||||
export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>(
|
||||
() => [],
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const serviceContainer = {
|
||||
get: vi.fn<(name: string) => any>(),
|
||||
|
|
@ -6,4 +6,4 @@ export const serviceContainer = {
|
|||
has: vi.fn<(name: string) => boolean>(),
|
||||
reset: vi.fn<() => void>(),
|
||||
reload: vi.fn<(name: string) => Promise<void>>(),
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import React from 'react';
|
||||
import React from "react";
|
||||
import { vi } from "vitest";
|
||||
import { ServiceContainer } from '../../services/ServiceContainer.js';
|
||||
import { ServiceContainer } from "../../services/ServiceContainer.js";
|
||||
|
||||
// Create a mock service container
|
||||
const mockServiceContainer = {
|
||||
|
|
@ -18,8 +18,12 @@ const mockServiceContainer = {
|
|||
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 = vi.fn(() => mockServiceContainer);
|
||||
export const useServiceContainer = vi.fn(() => mockServiceContainer);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const services = {
|
||||
auth: {
|
||||
|
|
@ -12,9 +12,9 @@ export const services = {
|
|||
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",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
const mockLogger: any = {
|
||||
debug: vi.fn(),
|
||||
|
|
@ -10,4 +10,4 @@ const mockLogger: any = {
|
|||
|
||||
export default mockLogger;
|
||||
export const getLogPath = vi.fn(() => "/mock/log/path");
|
||||
export const getSessionId = vi.fn(() => "mock-session-id");
|
||||
export const getSessionId = vi.fn(() => "mock-session-id");
|
||||
|
|
|
|||
26
src/args.ts
26
src/args.ts
|
|
@ -7,11 +7,12 @@ import { env } from "./env.js";
|
|||
|
||||
export interface CommandLineArgs {
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -40,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 {
|
||||
|
|
@ -64,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) {
|
||||
|
|
@ -127,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";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -143,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++) {
|
||||
|
|
@ -161,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;
|
||||
|
|
|
|||
|
|
@ -7,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;
|
||||
|
|
|
|||
199
src/auth/workos-org.test.ts
Normal file
199
src/auth/workos-org.test.ts
Normal 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");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -30,8 +30,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 +50,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 +59,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 +266,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(() => {
|
||||
|
|
@ -302,7 +313,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
|
|||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: params,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -313,7 +324,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
|
|||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Device authorization error:"),
|
||||
error.message || error
|
||||
error.message || error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
|
@ -325,7 +336,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;
|
||||
|
|
@ -350,7 +361,7 @@ async function pollForDeviceToken(
|
|||
method: "POST",
|
||||
headers,
|
||||
body: params,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
|
|
@ -381,21 +392,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") {
|
||||
|
|
@ -419,7 +430,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
|
||||
|
|
@ -482,7 +493,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,
|
||||
|
|
@ -496,12 +507,14 @@ 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
|
||||
|
|
@ -517,7 +530,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!"));
|
||||
|
|
@ -525,15 +538,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;
|
||||
}
|
||||
|
||||
|
|
@ -543,7 +616,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) {
|
||||
|
|
@ -608,7 +698,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 = {
|
||||
|
|
@ -630,7 +720,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();
|
||||
|
||||
|
|
@ -647,7 +737,14 @@ export async function listUserOrganizations(): Promise<
|
|||
|
||||
try {
|
||||
const resp = await apiClient.listOrganizations();
|
||||
return resp.organizations || [];
|
||||
// Map the organizations to include slug field
|
||||
return (
|
||||
resp.organizations?.map((org) => ({
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
slug: org.slug,
|
||||
})) || []
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
|
@ -669,7 +766,7 @@ export function logout(): void {
|
|||
const onboardingFlagPath = path.join(
|
||||
os.homedir(),
|
||||
".continue",
|
||||
".onboarding_complete"
|
||||
".onboarding_complete",
|
||||
);
|
||||
|
||||
// Remove onboarding completion flag so user will go through onboarding again
|
||||
|
|
@ -680,8 +777,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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,4 +24,4 @@ export interface ExtendedCommandOptions extends BaseCommandOptions {
|
|||
readonly?: boolean;
|
||||
/** Start in auto mode (all tools allowed) */
|
||||
auto?: boolean;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,10 +82,11 @@ export interface ChatOptions extends ExtendedCommandOptions {
|
|||
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[] = [];
|
||||
|
||||
|
|
@ -107,7 +108,7 @@ export async function initializeChatHistory(
|
|||
rulesSystemMessage,
|
||||
options.rule,
|
||||
options.format,
|
||||
options.headless
|
||||
options.headless,
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
|
|
@ -125,7 +126,7 @@ async function processMessage(
|
|||
isHeadless: boolean,
|
||||
format?: "json",
|
||||
silent?: boolean,
|
||||
compactionIndex?: number | null
|
||||
compactionIndex?: number | null,
|
||||
): Promise<{ compactionIndex?: number | null } | void> {
|
||||
// Check for slash commands in headless mode
|
||||
if (userInput.trim() === "/compact") {
|
||||
|
|
@ -151,7 +152,7 @@ async function processMessage(
|
|||
status: "success",
|
||||
message: "Chat history compacted",
|
||||
historyLength: chatHistory.length,
|
||||
}) + "\n"
|
||||
}) + "\n",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -162,7 +163,7 @@ async function processMessage(
|
|||
console.error(chalk.red(errorMsg));
|
||||
} else {
|
||||
safeStdout(
|
||||
JSON.stringify({ status: "error", message: errorMsg }) + "\n"
|
||||
JSON.stringify({ status: "error", message: errorMsg }) + "\n",
|
||||
);
|
||||
}
|
||||
return;
|
||||
|
|
@ -179,8 +180,8 @@ async function processMessage(
|
|||
if (!isHeadless) {
|
||||
console.info(
|
||||
chalk.yellow(
|
||||
"\nApproaching context limit. Auto-compacting chat history..."
|
||||
)
|
||||
"\nApproaching context limit. Auto-compacting chat history...",
|
||||
),
|
||||
);
|
||||
} else if (format === "json") {
|
||||
safeStdout(
|
||||
|
|
@ -190,9 +191,9 @@ async function processMessage(
|
|||
contextUsage:
|
||||
calculateContextUsagePercentage(
|
||||
countChatHistoryTokens(chatHistory),
|
||||
model
|
||||
model,
|
||||
) + "%",
|
||||
}) + "\n"
|
||||
}) + "\n",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -209,7 +210,7 @@ async function processMessage(
|
|||
|
||||
if (!isHeadless) {
|
||||
console.info(
|
||||
chalk.green("✓ Chat history auto-compacted successfully.")
|
||||
chalk.green("✓ Chat history auto-compacted successfully."),
|
||||
);
|
||||
} else if (format === "json") {
|
||||
safeStdout(
|
||||
|
|
@ -217,7 +218,7 @@ async function processMessage(
|
|||
status: "success",
|
||||
message: "Auto-compacted successfully",
|
||||
historyLength: chatHistory.length,
|
||||
}) + "\n"
|
||||
}) + "\n",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -235,7 +236,7 @@ async function processMessage(
|
|||
JSON.stringify({
|
||||
status: "warning",
|
||||
message: "Auto-compaction failed, continuing without compaction",
|
||||
}) + "\n"
|
||||
}) + "\n",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -265,7 +266,7 @@ async function processMessage(
|
|||
historyForLLM,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
abortController,
|
||||
);
|
||||
|
||||
// Append any new messages (assistant/tool) that were added by streamChatResponse
|
||||
|
|
@ -277,7 +278,7 @@ async function processMessage(
|
|||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
abortController,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -311,7 +312,7 @@ async function processMessage(
|
|||
});
|
||||
if (!isHeadless) {
|
||||
logger.info(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -319,13 +320,14 @@ async function processMessage(
|
|||
|
||||
async function runHeadlessMode(
|
||||
prompt: string | undefined,
|
||||
options: ChatOptions
|
||||
options: ChatOptions,
|
||||
): Promise<void> {
|
||||
// Initialize services for headless mode
|
||||
const { permissionOverrides } = processCommandFlags(options);
|
||||
|
||||
await initializeServices({
|
||||
configPath: options.config,
|
||||
organizationSlug: options.org,
|
||||
rules: options.rule,
|
||||
headless: true,
|
||||
toolPermissionOverrides: permissionOverrides,
|
||||
|
|
@ -333,7 +335,7 @@ async function runHeadlessMode(
|
|||
|
||||
// Get required services from the service container
|
||||
const modelState = await serviceContainer.get<ModelServiceState>(
|
||||
SERVICE_NAMES.MODEL
|
||||
SERVICE_NAMES.MODEL,
|
||||
);
|
||||
const { llmApi, model } = modelState;
|
||||
|
||||
|
|
@ -373,7 +375,7 @@ async function runHeadlessMode(
|
|||
true,
|
||||
options.format,
|
||||
options.silent,
|
||||
compactionIndex
|
||||
compactionIndex,
|
||||
);
|
||||
|
||||
// Update compaction index if compaction occurred
|
||||
|
|
@ -406,6 +408,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
// Initialize services with onboarding handled internally
|
||||
const initResult = await initializeServices({
|
||||
configPath: options.config,
|
||||
organizationSlug: options.org,
|
||||
rules: options.rule,
|
||||
headless: false,
|
||||
toolPermissionOverrides: permissionOverrides,
|
||||
|
|
@ -424,9 +427,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
prompt,
|
||||
options.resume,
|
||||
options.config,
|
||||
options.org,
|
||||
options.rule,
|
||||
permissionOverrides,
|
||||
true
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -78,7 +78,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 +105,7 @@ export function getAllSlashCommands(
|
|||
* Get assistant prompt commands only
|
||||
*/
|
||||
export function getAssistantSlashCommands(
|
||||
assistant: AssistantConfig
|
||||
assistant: AssistantConfig,
|
||||
): SlashCommand[] {
|
||||
return (
|
||||
assistant?.prompts?.map((prompt) => ({
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ 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}...`));
|
||||
|
||||
|
|
@ -23,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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export async function remote(
|
|||
// 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
|
||||
|
|
@ -41,7 +41,7 @@ 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);
|
||||
}
|
||||
|
|
@ -68,20 +68,20 @@ export async function remote(
|
|||
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
|
||||
|
|
@ -96,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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ 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";
|
||||
|
|
@ -112,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) {
|
||||
|
|
@ -122,7 +121,12 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
|
||||
// Initialize chat history
|
||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
||||
const systemMessage = await constructSystemMessage("", options.rule, undefined, true);
|
||||
const systemMessage = await constructSystemMessage(
|
||||
"",
|
||||
options.rule,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
@ -267,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
|
||||
|
|
@ -308,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
|
||||
|
|
@ -357,7 +361,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
state,
|
||||
llmApi,
|
||||
state.currentAbortController,
|
||||
() => state.shouldInterrupt
|
||||
() => state.shouldInterrupt,
|
||||
);
|
||||
|
||||
// Save session after successful response
|
||||
|
|
@ -407,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(() => {
|
||||
|
|
@ -442,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
|
||||
|
|
@ -557,7 +561,7 @@ async function streamChatResponseWithInterruption(
|
|||
onToolPermissionRequest: (
|
||||
toolName: string,
|
||||
toolArgs: any,
|
||||
requestId: string
|
||||
requestId: string,
|
||||
) => {
|
||||
// Set pending permission state
|
||||
state.pendingPermission = {
|
||||
|
|
@ -585,7 +589,7 @@ async function streamChatResponseWithInterruption(
|
|||
state.model,
|
||||
llmApi,
|
||||
abortController,
|
||||
callbacks
|
||||
callbacks,
|
||||
);
|
||||
return response || "";
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ export async function compactChatHistory(
|
|||
chatHistory: ChatCompletionMessageParam[],
|
||||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
callbacks?: CompactionCallbacks
|
||||
callbacks?: CompactionCallbacks,
|
||||
): Promise<CompactionResult> {
|
||||
// Create a prompt to summarize the conversation
|
||||
const compactionPrompt: ChatCompletionMessageParam = {
|
||||
|
|
@ -63,7 +63,7 @@ export async function compactChatHistory(
|
|||
model,
|
||||
llmApi,
|
||||
controller,
|
||||
streamCallbacks
|
||||
streamCallbacks,
|
||||
);
|
||||
|
||||
// Create the compacted history with a special marker
|
||||
|
|
@ -103,13 +103,13 @@ export async function compactChatHistory(
|
|||
* @returns The index of the compaction message, or null if not found
|
||||
*/
|
||||
export function findCompactionIndex(
|
||||
chatHistory: ChatCompletionMessageParam[]
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
): number | null {
|
||||
const compactedIndex = chatHistory.findIndex(
|
||||
(msg) =>
|
||||
msg.role === "assistant" &&
|
||||
typeof msg.content === "string" &&
|
||||
msg.content.startsWith(COMPACTION_MARKER)
|
||||
msg.content.startsWith(COMPACTION_MARKER),
|
||||
);
|
||||
return compactedIndex !== -1 ? compactedIndex : null;
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ export function findCompactionIndex(
|
|||
*/
|
||||
export function getHistoryForLLM(
|
||||
fullHistory: ChatCompletionMessageParam[],
|
||||
compactionIndex: number | null
|
||||
compactionIndex: number | null,
|
||||
): ChatCompletionMessageParam[] {
|
||||
if (compactionIndex === null || compactionIndex >= fullHistory.length) {
|
||||
return fullHistory;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,4 @@
|
|||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ModelConfig,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import {
|
||||
BaseLlmApi,
|
||||
constructLlmApi,
|
||||
|
|
@ -25,16 +21,16 @@ 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",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -67,7 +63,7 @@ export function getLlmApi(
|
|||
|
||||
if (!llmApi) {
|
||||
throw new Error(
|
||||
"Failed to initialize LLM. Please check your configuration."
|
||||
"Failed to initialize LLM. Please check your configuration.",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -75,19 +71,19 @@ export function getLlmApi(
|
|||
}
|
||||
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -29,7 +29,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 }
|
||||
|
|
@ -43,17 +43,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);
|
||||
|
|
@ -73,7 +78,7 @@ export async function loadConfiguration(
|
|||
*/
|
||||
function determineConfigSource(
|
||||
authConfig: AuthConfig,
|
||||
cliConfigPath: string | undefined
|
||||
cliConfigPath: string | undefined,
|
||||
): ConfigSource {
|
||||
// Priority 1: CLI --config flag
|
||||
if (cliConfigPath) {
|
||||
|
|
@ -94,7 +99,11 @@ 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(
|
||||
os.homedir(),
|
||||
".continue",
|
||||
"config.yaml",
|
||||
);
|
||||
if (fs.existsSync(defaultConfigPath)) {
|
||||
return { type: "default-config-yaml" };
|
||||
}
|
||||
|
|
@ -109,32 +118,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;
|
||||
|
|
@ -149,11 +176,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);
|
||||
|
|
@ -167,18 +199,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}`);
|
||||
}
|
||||
|
||||
|
|
@ -187,7 +224,7 @@ async function loadFromSavedUri(
|
|||
*/
|
||||
async function loadUserAssistantWithFallback(
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface
|
||||
apiClient: DefaultApiInterface,
|
||||
): Promise<AssistantUnrolled> {
|
||||
const assistants = await apiClient.listAssistants({
|
||||
alwaysUseProxy: "false",
|
||||
|
|
@ -212,10 +249,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);
|
||||
return await loadConfigYaml(
|
||||
defaultConfigPath,
|
||||
accessToken,
|
||||
organizationId,
|
||||
apiClient,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -223,7 +265,7 @@ async function loadDefaultConfigYaml(
|
|||
*/
|
||||
async function loadDefaultAgent(
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface
|
||||
apiClient: DefaultApiInterface,
|
||||
): Promise<AssistantUnrolled> {
|
||||
const resp = await apiClient.getAssistant({
|
||||
ownerSlug: "continuedev",
|
||||
|
|
@ -234,7 +276,7 @@ async function loadDefaultAgent(
|
|||
if (!resp.configResult.config) {
|
||||
throw new Error("Failed to load default agent.");
|
||||
}
|
||||
|
||||
|
||||
return resp.configResult.config as AssistantUnrolled;
|
||||
}
|
||||
|
||||
|
|
@ -245,7 +287,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" },
|
||||
|
|
@ -261,7 +303,7 @@ async function loadConfigYaml(
|
|||
renderSecrets: true,
|
||||
platformClient: new CLIPlatformClient(organizationId, apiClient),
|
||||
onPremProxyUrl: null,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const errorDetails = unrollResult.errors;
|
||||
|
|
@ -284,11 +326,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({
|
||||
|
|
@ -331,8 +375,8 @@ 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;
|
||||
|
|
@ -341,4 +385,4 @@ function getUriFromSource(source: ConfigSource): string | null {
|
|||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import { env } from "./env.js";
|
|||
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"));
|
||||
|
|
@ -30,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;
|
||||
}
|
||||
|
|
|
|||
105
src/e2e/headless-org-flag.test.ts
Normal file
105
src/e2e/headless-org-flag.test.ts
Normal 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"
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -100,4 +100,4 @@ export function listFiles(dirPath: string): ToolResult {
|
|||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,19 +20,22 @@ export interface ProcessedFlags {
|
|||
* 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 {
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
@ -44,7 +47,7 @@ export function buildPermissionOverrides(
|
|||
allow?: string[],
|
||||
ask?: string[],
|
||||
exclude?: string[],
|
||||
mode?: PermissionMode
|
||||
mode?: PermissionMode,
|
||||
): PermissionOverrides {
|
||||
return {
|
||||
allow,
|
||||
|
|
@ -67,17 +70,17 @@ export function processCommandFlags(options: {
|
|||
}): 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
|
||||
mode,
|
||||
);
|
||||
|
||||
|
||||
return {
|
||||
mode,
|
||||
permissionOverrides,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,17 +8,17 @@ export interface ValidationOptions {
|
|||
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;
|
||||
|
|
@ -39,14 +39,14 @@ export interface ValidationResult {
|
|||
*/
|
||||
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'
|
||||
code: "FORMAT_REQUIRES_PRINT",
|
||||
message: "Error: --format flag can only be used with -p/--print flag",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
|
@ -55,14 +55,14 @@ function validateFormatFlag(options: ValidationOptions): ValidationError[] {
|
|||
*/
|
||||
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'
|
||||
code: "SILENT_REQUIRES_PRINT",
|
||||
message: "Error: --silent flag can only be used with -p/--print flag",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
|
@ -71,14 +71,14 @@ function validateSilentFlag(options: ValidationOptions): ValidationError[] {
|
|||
*/
|
||||
function validateFormatValue(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
if (options.format && options.format !== 'json') {
|
||||
|
||||
if (options.format && options.format !== "json") {
|
||||
errors.push({
|
||||
code: 'INVALID_FORMAT_VALUE',
|
||||
message: "Error: --format currently only supports 'json'"
|
||||
code: "INVALID_FORMAT_VALUE",
|
||||
message: "Error: --format currently only supports 'json'",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
|
@ -88,14 +88,14 @@ function validateFormatValue(options: ValidationOptions): ValidationError[] {
|
|||
*/
|
||||
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'
|
||||
code: "CONFLICTING_MODE_FLAGS",
|
||||
message: "Error: Cannot use both --readonly and --auto flags together",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
|
@ -104,47 +104,49 @@ function validateModeFlags(options: ValidationOptions): ValidationError[] {
|
|||
*/
|
||||
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') {
|
||||
if (options.config && typeof options.config !== "string") {
|
||||
errors.push({
|
||||
code: 'INVALID_CONFIG_PATH',
|
||||
message: 'Error: --config must be a valid path'
|
||||
code: "INVALID_CONFIG_PATH",
|
||||
message: "Error: --config must be a valid path",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate permission flag combinations
|
||||
*/
|
||||
function validatePermissionFlags(options: ValidationOptions): ValidationError[] {
|
||||
function validatePermissionFlags(
|
||||
options: ValidationOptions,
|
||||
): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
|
||||
// Check for empty permission arrays (likely user error)
|
||||
if (options.allow?.some(tool => !tool.trim())) {
|
||||
if (options.allow?.some((tool) => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_ALLOW_TOOL',
|
||||
message: 'Error: --allow requires a tool name (e.g., --allow readFile)'
|
||||
code: "EMPTY_ALLOW_TOOL",
|
||||
message: "Error: --allow requires a tool name (e.g., --allow readFile)",
|
||||
});
|
||||
}
|
||||
|
||||
if (options.ask?.some(tool => !tool.trim())) {
|
||||
|
||||
if (options.ask?.some((tool) => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_ASK_TOOL',
|
||||
message: 'Error: --ask requires a tool name (e.g., --ask writeFile)'
|
||||
code: "EMPTY_ASK_TOOL",
|
||||
message: "Error: --ask requires a tool name (e.g., --ask writeFile)",
|
||||
});
|
||||
}
|
||||
|
||||
if (options.exclude?.some(tool => !tool.trim())) {
|
||||
|
||||
if (options.exclude?.some((tool) => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_EXCLUDE_TOOL',
|
||||
message: 'Error: --exclude requires a tool name (e.g., --exclude Write)'
|
||||
code: "EMPTY_EXCLUDE_TOOL",
|
||||
message: "Error: --exclude requires a tool name (e.g., --exclude Write)",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
|
@ -153,7 +155,7 @@ function validatePermissionFlags(options: ValidationOptions): ValidationError[]
|
|||
*/
|
||||
export function validateFlags(options: ValidationOptions): ValidationResult {
|
||||
const allErrors: ValidationError[] = [];
|
||||
|
||||
|
||||
// Run all validation functions
|
||||
const validators = [
|
||||
validateFormatFlag,
|
||||
|
|
@ -163,11 +165,11 @@ export function validateFlags(options: ValidationOptions): ValidationResult {
|
|||
validateConfigPath,
|
||||
validatePermissionFlags,
|
||||
];
|
||||
|
||||
|
||||
for (const validator of validators) {
|
||||
allErrors.push(...validator(options));
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
isValid: allErrors.length === 0,
|
||||
errors: allErrors,
|
||||
|
|
@ -182,10 +184,10 @@ 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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,10 @@ import open from "open";
|
|||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { env } from "./env.js";
|
||||
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
|
||||
import {
|
||||
isValidAnthropicApiKey,
|
||||
getApiKeyValidationError,
|
||||
} from "./util/apiKeyValidation.js";
|
||||
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
|
||||
|
|
@ -23,10 +26,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);
|
||||
}
|
||||
|
|
@ -38,7 +41,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();
|
||||
|
||||
|
|
@ -62,16 +67,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 {
|
||||
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.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -84,13 +89,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);
|
||||
}
|
||||
|
||||
|
|
@ -98,7 +101,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();
|
||||
|
|
@ -112,7 +115,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
|
||||
|
|
@ -126,7 +131,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
|
|||
{
|
||||
stdio: "inherit",
|
||||
detached: true,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Unref the child to allow the parent process to exit
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useServiceContainer } from '../services/ServiceContainerContext.js';
|
||||
import { ServiceResult } from '../services/types.js';
|
||||
import { useServiceContainer } from "../services/ServiceContainerContext.js";
|
||||
import { ServiceResult } from "../services/types.js";
|
||||
|
||||
/**
|
||||
* React hook for consuming services reactively
|
||||
|
|
@ -11,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(() => {
|
||||
|
|
@ -21,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
|
||||
});
|
||||
|
|
@ -29,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(),
|
||||
}));
|
||||
};
|
||||
|
||||
|
|
@ -80,7 +80,7 @@ export function useService<T>(serviceName: string): ServiceResult<T> & {
|
|||
|
||||
return {
|
||||
...result,
|
||||
reload
|
||||
reload,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -88,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;
|
||||
} {
|
||||
|
|
@ -108,15 +108,15 @@ export function useServices<T extends Record<string, any>>(
|
|||
|
||||
for (const serviceName of serviceNames) {
|
||||
const result = container.getSync(serviceName as string);
|
||||
|
||||
if (result.state === 'loading') {
|
||||
|
||||
if (result.state === "loading") {
|
||||
hasLoading = true;
|
||||
} else if (result.state === 'error') {
|
||||
} else if (result.state === "error") {
|
||||
hasError = result.error;
|
||||
} else if (result.state === 'idle') {
|
||||
} 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 {
|
||||
}
|
||||
|
|
@ -132,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);
|
||||
|
|
@ -153,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 };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
18
src/index.ts
18
src/index.ts
|
|
@ -26,7 +26,7 @@ process.on("unhandledRejection", (reason, promise) => {
|
|||
reason instanceof Error ? reason : new Error(String(reason)),
|
||||
{
|
||||
promise: String(promise),
|
||||
}
|
||||
},
|
||||
);
|
||||
// Don't exit the process, just log the error
|
||||
});
|
||||
|
|
@ -42,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());
|
||||
|
||||
|
|
@ -53,11 +53,11 @@ 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."
|
||||
"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) => {
|
||||
|
|
@ -94,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");
|
||||
|
|
@ -117,7 +117,7 @@ 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"
|
||||
"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"');
|
||||
|
|
@ -154,7 +154,7 @@ 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>",
|
||||
|
|
@ -171,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) => {
|
||||
|
|
@ -208,7 +208,7 @@ try {
|
|||
} catch (error) {
|
||||
console.error(error);
|
||||
sentryService.captureException(
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
10
src/mcp.ts
10
src/mcp.ts
|
|
@ -21,13 +21,17 @@ export class MCPService {
|
|||
const service = new MCPService(assistant);
|
||||
|
||||
if (assistant.mcpServers?.length) {
|
||||
logger.debug('Creating MCP connections', { serverCount: assistant.mcpServers.length });
|
||||
logger.debug("Creating MCP connections", {
|
||||
serverCount: assistant.mcpServers.length,
|
||||
});
|
||||
const connectionPromises = assistant.mcpServers.map((server) =>
|
||||
MCPConnection.create(server)
|
||||
MCPConnection.create(server),
|
||||
);
|
||||
const connections = await Promise.all(connectionPromises);
|
||||
service.connections.push(...connections);
|
||||
logger.debug('MCP connections established', { connectionCount: connections.length });
|
||||
logger.debug("MCP connections established", {
|
||||
connectionCount: connections.length,
|
||||
});
|
||||
}
|
||||
|
||||
// Store the instance and return it
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export interface OnboardingResult {
|
|||
}
|
||||
|
||||
export async function checkHasAcceptableModel(
|
||||
configPath: string
|
||||
configPath: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
|
|
@ -61,7 +61,7 @@ export async function createOrUpdateConfig(apiKey: string): Promise<void> {
|
|||
|
||||
export async function runOnboardingFlow(
|
||||
configPath: string | undefined,
|
||||
authConfig: AuthConfig
|
||||
authConfig: AuthConfig,
|
||||
): Promise<OnboardingResult> {
|
||||
// Step 1: Check if --config flag is provided
|
||||
if (configPath) {
|
||||
|
|
@ -103,7 +103,7 @@ export async function runOnboardingFlow(
|
|||
chalk.white("\nEnter your Anthropic API key: "),
|
||||
{
|
||||
hideEchoBack: true,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!isValidAnthropicApiKey(apiKey)) {
|
||||
|
|
@ -112,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);
|
||||
|
|
@ -125,7 +125,7 @@ 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) {
|
||||
|
|
@ -141,7 +141,7 @@ export async function runNormalFlow(
|
|||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
throw new Error(
|
||||
`Failed to load config from "${configPath}": ${errorMessage}`
|
||||
`Failed to load config from "${configPath}": ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -193,7 +193,7 @@ export async function runNormalFlow(
|
|||
|
||||
export async function isFirstTime(): Promise<boolean> {
|
||||
return !fs.existsSync(
|
||||
path.join(os.homedir(), ".continue", ".onboarding_complete")
|
||||
path.join(os.homedir(), ".continue", ".onboarding_complete"),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -216,7 +216,7 @@ export async function markOnboardingComplete(): Promise<void> {
|
|||
*/
|
||||
async function injectRulesIntoConfig(
|
||||
config: AssistantUnrolled,
|
||||
rules: string[]
|
||||
rules: string[],
|
||||
): Promise<AssistantUnrolled> {
|
||||
if (!rules || rules.length === 0) {
|
||||
return config;
|
||||
|
|
@ -230,8 +230,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}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -248,9 +248,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;
|
||||
}
|
||||
|
|
@ -261,7 +260,7 @@ async function injectRulesIntoConfig(
|
|||
export async function initializeWithOnboarding(
|
||||
authConfig: AuthConfig,
|
||||
configPath: string | undefined,
|
||||
rules?: string[]
|
||||
rules?: string[],
|
||||
): Promise<OnboardingResult> {
|
||||
const firstTime = await isFirstTime();
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
export function matchesToolPattern(
|
||||
toolName: string,
|
||||
pattern: string,
|
||||
toolArguments?: Record<string, any>
|
||||
toolArguments?: Record<string, any>,
|
||||
): boolean {
|
||||
if (pattern === "*") return true;
|
||||
if (pattern === toolName) return true;
|
||||
|
|
@ -66,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;
|
||||
|
||||
|
|
@ -109,14 +109,14 @@ 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
|
||||
|
|
@ -152,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";
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,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}`;
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { PermissionPolicy, ToolPermissionPolicy } from "./types.js";
|
|||
export const PERMISSIONS_YAML_PATH = path.join(
|
||||
os.homedir(),
|
||||
".continue",
|
||||
"permissions.yaml"
|
||||
"permissions.yaml",
|
||||
);
|
||||
|
||||
export interface PermissionsYamlConfig {
|
||||
|
|
@ -44,7 +44,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) {
|
||||
|
|
@ -79,7 +79,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
|
|||
*/
|
||||
export function parseToolPattern(
|
||||
pattern: string,
|
||||
permission: PermissionPolicy
|
||||
permission: PermissionPolicy,
|
||||
): ToolPermissionPolicy {
|
||||
const match = pattern.match(/^([^(]+)(?:\(([^)]*)\))?$/);
|
||||
if (!match) {
|
||||
|
|
@ -123,7 +123,7 @@ export function parseToolPattern(
|
|||
* Converts permissions YAML config to ToolPermissionPolicy array
|
||||
*/
|
||||
export function yamlConfigToPolicies(
|
||||
config: PermissionsYamlConfig
|
||||
config: PermissionsYamlConfig,
|
||||
): ToolPermissionPolicy[] {
|
||||
const policies: ToolPermissionPolicy[] = [];
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,11 @@ import * as yaml from "yaml";
|
|||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js";
|
||||
import {
|
||||
PERMISSIONS_YAML_PATH,
|
||||
PermissionsYamlConfig,
|
||||
loadPermissionsYaml,
|
||||
} from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
|
||||
|
||||
/**
|
||||
|
|
@ -14,7 +18,7 @@ import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
|
|||
*/
|
||||
export function generatePolicyRule(toolName: string, toolArgs: any): string {
|
||||
const normalizedName = normalizeToolName(toolName);
|
||||
|
||||
|
||||
// For Bash tool, create command-specific policies
|
||||
if (normalizedName === "Bash" && toolArgs?.command) {
|
||||
const command = toolArgs.command.trim();
|
||||
|
|
@ -26,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);
|
||||
}
|
||||
|
|
@ -38,33 +42,36 @@ export async function addPolicyToYaml(policyRule: string): Promise<void> {
|
|||
try {
|
||||
// Load existing config or create empty one
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js";
|
||||
import {
|
||||
loadPermissionsYaml,
|
||||
yamlConfigToPolicies,
|
||||
} from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { ToolPermissionPolicy } from "./types.js";
|
||||
|
||||
|
|
@ -23,15 +26,17 @@ export interface PermissionSources {
|
|||
/**
|
||||
* Resolves permission policies from all sources according to precedence rules.
|
||||
* This function implements the clean precedence logic from the specification:
|
||||
*
|
||||
*
|
||||
* 1. Command line flags (highest)
|
||||
* 2. Permissions in config.yaml (when implemented)
|
||||
* 3. Permissions in ~/.continue/permissions.yaml
|
||||
* 4. Default policies (lowest)
|
||||
*
|
||||
*
|
||||
* Earlier sources completely override later ones on a per-tool basis.
|
||||
*/
|
||||
export function resolvePermissionPrecedence(sources: PermissionSources): ToolPermissionPolicy[] {
|
||||
export function resolvePermissionPrecedence(
|
||||
sources: PermissionSources,
|
||||
): ToolPermissionPolicy[] {
|
||||
const layers: {
|
||||
name: string;
|
||||
policies: ToolPermissionPolicy[];
|
||||
|
|
@ -41,7 +46,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer
|
|||
if (sources.useDefaults !== false) {
|
||||
layers.push({
|
||||
name: "defaults",
|
||||
policies: [...DEFAULT_TOOL_POLICIES]
|
||||
policies: [...DEFAULT_TOOL_POLICIES],
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -53,7 +58,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer
|
|||
if (yamlPolicies.length > 0) {
|
||||
layers.push({
|
||||
name: "personal-settings",
|
||||
policies: yamlPolicies
|
||||
policies: yamlPolicies,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -63,7 +68,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer
|
|||
if (sources.configPermissions) {
|
||||
layers.push({
|
||||
name: "config",
|
||||
policies: sources.configPermissions
|
||||
policies: sources.configPermissions,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -73,7 +78,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer
|
|||
if (cliPolicies.length > 0) {
|
||||
layers.push({
|
||||
name: "cli-flags",
|
||||
policies: cliPolicies
|
||||
policies: cliPolicies,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -82,8 +87,8 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer
|
|||
const combinedPolicies = combineLayersWithPrecedence(layers);
|
||||
|
||||
logger.debug("Resolved permission precedence", {
|
||||
layers: layers.map(l => ({ name: l.name, count: l.policies.length })),
|
||||
totalPolicies: combinedPolicies.length
|
||||
layers: layers.map((l) => ({ name: l.name, count: l.policies.length })),
|
||||
totalPolicies: combinedPolicies.length,
|
||||
});
|
||||
|
||||
return combinedPolicies;
|
||||
|
|
@ -128,7 +133,9 @@ function commandLineFlagsToPolicies(flags: {
|
|||
* Combines permission layers with proper precedence.
|
||||
* Higher precedence layers come later in the array and are prepended to the result.
|
||||
*/
|
||||
function combineLayersWithPrecedence(layers: Array<{ name: string; policies: ToolPermissionPolicy[] }>): ToolPermissionPolicy[] {
|
||||
function combineLayersWithPrecedence(
|
||||
layers: Array<{ name: string; policies: ToolPermissionPolicy[] }>,
|
||||
): ToolPermissionPolicy[] {
|
||||
// Start with empty array
|
||||
let combined: ToolPermissionPolicy[] = [];
|
||||
|
||||
|
|
@ -141,4 +148,4 @@ function combineLayersWithPrecedence(layers: Array<{ name: string; policies: Too
|
|||
}
|
||||
|
||||
return combined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,4 +47,4 @@ export function setRuntimePermissionOverrides(overrides: {
|
|||
|
||||
export function getRuntimePermissionOverrides(): ToolPermissionPolicy[] | null {
|
||||
return runtimeOverrides;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,10 +37,10 @@ class SentryService {
|
|||
release: getVersion(),
|
||||
sampleRate: parseFloat(process.env.SENTRY_SAMPLE_RATE || "1.0"),
|
||||
profilesSampleRate: parseFloat(
|
||||
process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0"
|
||||
process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0",
|
||||
),
|
||||
tracesSampleRate: parseFloat(
|
||||
process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0"
|
||||
process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
@ -98,7 +98,7 @@ class SentryService {
|
|||
public captureMessage(
|
||||
message: string,
|
||||
level: "info" | "warning" | "error" | "debug" | "fatal" = "info",
|
||||
context?: Record<string, any>
|
||||
context?: Record<string, any>,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -9,9 +9,12 @@ import { ApiClientServiceState } from "./types.js";
|
|||
* Service for managing API client state
|
||||
* Provides access to the Continue SDK API client
|
||||
*/
|
||||
export class ApiClientService extends BaseService<ApiClientServiceState> implements ServiceWithDependencies {
|
||||
export class ApiClientService
|
||||
extends BaseService<ApiClientServiceState>
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
constructor() {
|
||||
super('ApiClientService', {
|
||||
super("ApiClientService", {
|
||||
apiClient: null,
|
||||
});
|
||||
}
|
||||
|
|
@ -20,7 +23,7 @@ export class ApiClientService extends BaseService<ApiClientServiceState> impleme
|
|||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth'];
|
||||
return ["auth"];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -51,7 +54,7 @@ export class ApiClientService extends BaseService<ApiClientServiceState> impleme
|
|||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update ApiClientService:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -62,4 +65,4 @@ export class ApiClientService extends BaseService<ApiClientServiceState> impleme
|
|||
override isReady(): boolean {
|
||||
return super.isReady() && this.currentState.apiClient !== null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import { AuthServiceState } from "./types.js";
|
|||
*/
|
||||
export class AuthService extends BaseService<AuthServiceState> {
|
||||
constructor() {
|
||||
super('AuthService', {
|
||||
super("AuthService", {
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
});
|
||||
|
|
@ -69,7 +69,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Login failed:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -96,7 +96,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
* Ensure organization is selected, prompting if necessary
|
||||
*/
|
||||
async ensureOrganization(
|
||||
isHeadless: boolean = false
|
||||
isHeadless: boolean = false,
|
||||
): Promise<AuthServiceState> {
|
||||
if (!this.currentState.authConfig) {
|
||||
throw new Error("Not authenticated - cannot ensure organization");
|
||||
|
|
@ -109,7 +109,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
|
||||
const updatedConfig = await ensureOrganization(
|
||||
this.currentState.authConfig,
|
||||
isHeadless
|
||||
isHeadless,
|
||||
);
|
||||
|
||||
this.setState({
|
||||
|
|
@ -129,14 +129,14 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
* Switch to a different organization
|
||||
*/
|
||||
async switchOrganization(
|
||||
organizationId: string | null
|
||||
organizationId: string | null,
|
||||
): Promise<AuthServiceState> {
|
||||
if (
|
||||
!this.currentState.authConfig ||
|
||||
!("userId" in this.currentState.authConfig)
|
||||
) {
|
||||
throw new Error(
|
||||
"Not authenticated with file-based auth - cannot switch organizations"
|
||||
"Not authenticated with file-based auth - cannot switch organizations",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -182,7 +182,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
return await listUserOrganizations();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to list organizations:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -202,4 +202,4 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
logger.debug("Refreshing auth state from disk");
|
||||
return this.reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -136,6 +136,59 @@ describe('AuthService', () => {
|
|||
'Not authenticated - cannot ensure organization'
|
||||
);
|
||||
});
|
||||
|
||||
test('should pass organization slug to ensureOrganization in headless mode', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' };
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig);
|
||||
|
||||
const state = await service.ensureOrganization(true, 'org-slug');
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug');
|
||||
expect(state).toEqual({
|
||||
authConfig: updatedConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-456'
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle personal organization slug', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const personalConfig = { ...mockAuthConfig, organizationId: null };
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(personalConfig);
|
||||
|
||||
const state = await service.ensureOrganization(true, 'personal');
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal');
|
||||
expect(state).toEqual({
|
||||
authConfig: personalConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: undefined
|
||||
});
|
||||
});
|
||||
|
||||
test('should work without organization slug parameter', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
|
||||
|
||||
const state = await service.ensureOrganization(false);
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined);
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchOrganization()', () => {
|
||||
|
|
@ -189,8 +242,8 @@ describe('AuthService', () => {
|
|||
await service.initialize();
|
||||
|
||||
const mockOrgs = [
|
||||
{ id: 'org-1', name: 'Org 1' },
|
||||
{ id: 'org-2', name: 'Org 2' }
|
||||
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
|
||||
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
|
||||
];
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
|
||||
|
||||
|
|
@ -234,8 +287,8 @@ describe('AuthService', () => {
|
|||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([
|
||||
{ id: 'org-1', name: 'Org 1' },
|
||||
{ id: 'org-2', name: 'Org 2' }
|
||||
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
|
||||
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
|
||||
]);
|
||||
|
||||
const hasMultiple = await service.hasMultipleOrganizations();
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import { AuthServiceState } from "./types.js";
|
|||
*/
|
||||
export class AuthService extends BaseService<AuthServiceState> {
|
||||
constructor() {
|
||||
super('AuthService', {
|
||||
super("AuthService", {
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
});
|
||||
|
|
@ -69,7 +69,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Login failed:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -96,7 +96,8 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
* Ensure organization is selected, prompting if necessary
|
||||
*/
|
||||
async ensureOrganization(
|
||||
isHeadless: boolean = false
|
||||
isHeadless: boolean = false,
|
||||
cliOrganizationSlug?: string,
|
||||
): Promise<AuthServiceState> {
|
||||
if (!this.currentState.authConfig) {
|
||||
throw new Error("Not authenticated - cannot ensure organization");
|
||||
|
|
@ -105,11 +106,13 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
logger.debug("Ensuring organization is selected", {
|
||||
currentOrgId: this.currentState.organizationId,
|
||||
isHeadless,
|
||||
cliOrganizationSlug,
|
||||
});
|
||||
|
||||
const updatedConfig = await ensureOrganization(
|
||||
this.currentState.authConfig,
|
||||
isHeadless
|
||||
isHeadless,
|
||||
cliOrganizationSlug,
|
||||
);
|
||||
|
||||
this.setState({
|
||||
|
|
@ -129,14 +132,14 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
* Switch to a different organization
|
||||
*/
|
||||
async switchOrganization(
|
||||
organizationId: string | null
|
||||
organizationId: string | null,
|
||||
): Promise<AuthServiceState> {
|
||||
if (
|
||||
!this.currentState.authConfig ||
|
||||
!("userId" in this.currentState.authConfig)
|
||||
) {
|
||||
throw new Error(
|
||||
"Not authenticated with file-based auth - cannot switch organizations"
|
||||
"Not authenticated with file-based auth - cannot switch organizations",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -182,7 +185,7 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
return await listUserOrganizations();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to list organizations:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -202,4 +205,4 @@ export class AuthService extends BaseService<AuthServiceState> {
|
|||
logger.debug("Refreshing auth state from disk");
|
||||
return this.reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export abstract class BaseService<TState> extends EventEmitter {
|
|||
const previousState = this.currentState;
|
||||
this.currentState = { ...this.currentState, ...newState };
|
||||
// Only log state updates if not in production to avoid circular reference issues
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
logger.debug(`${this.serviceName} state updated`);
|
||||
}
|
||||
this.emit("stateChanged", this.currentState, previousState);
|
||||
|
|
@ -103,7 +103,7 @@ export interface ServiceWithDependencies {
|
|||
* Helper to check if a service has dependencies
|
||||
*/
|
||||
export function hasDependencies(
|
||||
service: any
|
||||
service: any,
|
||||
): service is ServiceWithDependencies {
|
||||
return !!service && typeof service.getDependencies === "function";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,10 +2,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
|
|||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
|
||||
import { processRule } from "../args.js";
|
||||
import {
|
||||
AuthConfig,
|
||||
loadAuthConfig,
|
||||
} from "../auth/workos.js";
|
||||
import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
|
|
@ -20,9 +17,12 @@ import {
|
|||
* Service for managing configuration state and operations
|
||||
* Handles loading configs from files or assistant slugs
|
||||
*/
|
||||
export class ConfigService extends BaseService<ConfigServiceState> implements ServiceWithDependencies {
|
||||
export class ConfigService
|
||||
extends BaseService<ConfigServiceState>
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
constructor() {
|
||||
super('ConfigService', {
|
||||
super("ConfigService", {
|
||||
config: null,
|
||||
configPath: undefined,
|
||||
});
|
||||
|
|
@ -43,12 +43,12 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
configPath: string | undefined,
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface,
|
||||
rules?: string[]
|
||||
rules?: string[],
|
||||
): Promise<ConfigServiceState> {
|
||||
// Use the new streamlined config loader
|
||||
const { loadConfiguration } = await import("../configLoader.js");
|
||||
const result = await loadConfiguration(authConfig, configPath, apiClient);
|
||||
|
||||
|
||||
let config = result.config;
|
||||
|
||||
// Inject rules if provided
|
||||
|
|
@ -59,7 +59,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
// Config URI persistence is now handled by the streamlined loader
|
||||
|
||||
logger.debug("ConfigService initialized successfully");
|
||||
|
||||
|
||||
return {
|
||||
config,
|
||||
configPath,
|
||||
|
|
@ -74,7 +74,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
authConfig: AuthConfig,
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface,
|
||||
rules?: string[]
|
||||
rules?: string[],
|
||||
): Promise<ConfigServiceState> {
|
||||
logger.debug("Switching configuration", {
|
||||
from: this.currentState.configPath,
|
||||
|
|
@ -84,8 +84,12 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
try {
|
||||
// Use the new streamlined config loader
|
||||
const { loadConfiguration } = await import("../configLoader.js");
|
||||
const result = await loadConfiguration(authConfig, newConfigPath, apiClient);
|
||||
|
||||
const result = await loadConfiguration(
|
||||
authConfig,
|
||||
newConfigPath,
|
||||
apiClient,
|
||||
);
|
||||
|
||||
let config = result.config;
|
||||
|
||||
// Inject rules if provided
|
||||
|
|
@ -107,7 +111,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to switch configuration:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -119,7 +123,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
authConfig: AuthConfig,
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface,
|
||||
rules?: string[]
|
||||
rules?: string[],
|
||||
): Promise<ConfigServiceState> {
|
||||
if (!this.currentState.configPath) {
|
||||
throw new Error("No configuration path available for reload");
|
||||
|
|
@ -132,7 +136,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
authConfig,
|
||||
organizationId,
|
||||
apiClient,
|
||||
rules
|
||||
rules,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -141,7 +145,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
*/
|
||||
private async injectRulesIntoConfig(
|
||||
config: AssistantUnrolled,
|
||||
rules: string[]
|
||||
rules: string[],
|
||||
): Promise<AssistantUnrolled> {
|
||||
if (!rules || rules.length === 0) {
|
||||
return config;
|
||||
|
|
@ -170,9 +174,8 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
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;
|
||||
}
|
||||
|
|
@ -194,7 +197,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
// Get current auth and API client state needed for config loading
|
||||
const authConfig = loadAuthConfig();
|
||||
const apiClientState = await serviceContainer.get<ApiClientServiceState>(
|
||||
SERVICE_NAMES.API_CLIENT
|
||||
SERVICE_NAMES.API_CLIENT,
|
||||
);
|
||||
|
||||
if (!apiClientState.apiClient) {
|
||||
|
|
@ -204,9 +207,9 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
// Load the new configuration using streamlined loader
|
||||
const { loadConfiguration } = await import("../configLoader.js");
|
||||
const result = await loadConfiguration(
|
||||
authConfig,
|
||||
newConfigPath,
|
||||
apiClientState.apiClient
|
||||
authConfig,
|
||||
newConfigPath,
|
||||
apiClientState.apiClient,
|
||||
);
|
||||
|
||||
// Update internal state
|
||||
|
|
@ -230,9 +233,8 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
|
|||
});
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update configuration path:", error);
|
||||
this.emit('error', error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
|
||||
import { MCPService } from '../mcp.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
import { MCPService } from "../mcp.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { MCPServiceState } from './types.js';
|
||||
import { MCPServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service wrapper for managing MCP service state
|
||||
|
|
@ -11,30 +11,30 @@ import { MCPServiceState } from './types.js';
|
|||
*/
|
||||
export class MCPServiceWrapper {
|
||||
private currentState: MCPServiceState = {
|
||||
mcpService: null
|
||||
mcpService: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize the MCP service wrapper
|
||||
*/
|
||||
async initialize(assistant: AssistantUnrolled): Promise<MCPServiceState> {
|
||||
logger.debug('Initializing MCPServiceWrapper');
|
||||
|
||||
logger.debug("Initializing MCPServiceWrapper");
|
||||
|
||||
try {
|
||||
const mcpService = await MCPService.create(assistant);
|
||||
|
||||
this.currentState = {
|
||||
mcpService
|
||||
mcpService,
|
||||
};
|
||||
|
||||
logger.debug('MCPServiceWrapper initialized successfully', {
|
||||
logger.debug("MCPServiceWrapper initialized successfully", {
|
||||
toolCount: mcpService.getTools().length,
|
||||
promptCount: mcpService.getPrompts().length
|
||||
promptCount: mcpService.getPrompts().length,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to initialize MCPServiceWrapper:', error);
|
||||
logger.error("Failed to initialize MCPServiceWrapper:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -51,26 +51,26 @@ export class MCPServiceWrapper {
|
|||
* Note: This creates a new MCP service since the original is a singleton
|
||||
*/
|
||||
async update(assistant: AssistantUnrolled): Promise<MCPServiceState> {
|
||||
logger.debug('Updating MCPServiceWrapper');
|
||||
|
||||
logger.debug("Updating MCPServiceWrapper");
|
||||
|
||||
try {
|
||||
// Clear the existing singleton instance to force recreation
|
||||
(MCPService as any).instance = null;
|
||||
|
||||
|
||||
const mcpService = await MCPService.create(assistant);
|
||||
|
||||
this.currentState = {
|
||||
mcpService
|
||||
mcpService,
|
||||
};
|
||||
|
||||
logger.debug('MCPServiceWrapper updated successfully', {
|
||||
logger.debug("MCPServiceWrapper updated successfully", {
|
||||
toolCount: mcpService.getTools().length,
|
||||
promptCount: mcpService.getPrompts().length
|
||||
promptCount: mcpService.getPrompts().length,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to update MCPServiceWrapper:', error);
|
||||
logger.error("Failed to update MCPServiceWrapper:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -92,7 +92,7 @@ export class MCPServiceWrapper {
|
|||
|
||||
return {
|
||||
toolCount: this.currentState.mcpService.getTools().length,
|
||||
promptCount: this.currentState.mcpService.getPrompts().length
|
||||
promptCount: this.currentState.mcpService.getPrompts().length,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,11 +18,11 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
|
||||
private constructor() {
|
||||
const toolPermissionService = new ToolPermissionService();
|
||||
super('ModeService', {
|
||||
super("ModeService", {
|
||||
mode: "normal",
|
||||
toolPermissionService
|
||||
toolPermissionService,
|
||||
});
|
||||
|
||||
|
||||
// Increase max listeners since ModeService is a singleton that can have
|
||||
// multiple subscribers (UI components, tests, etc.)
|
||||
this.setMaxListeners(100);
|
||||
|
|
@ -49,9 +49,9 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
// Convert legacy flags to mode
|
||||
let mode: PermissionMode = "normal";
|
||||
if (args.readonly) {
|
||||
mode = "plan"; // Legacy flag maps directly to plan mode
|
||||
mode = "plan"; // Legacy flag maps directly to plan mode
|
||||
} else if (args.auto) {
|
||||
mode = "auto"; // Auto flag maps to auto mode
|
||||
mode = "auto"; // Auto flag maps to auto mode
|
||||
}
|
||||
|
||||
this.currentState.toolPermissionService.initializeSync({
|
||||
|
|
@ -59,14 +59,14 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
ask: args.ask,
|
||||
exclude: args.exclude,
|
||||
mode,
|
||||
isHeadless: args.isHeadless
|
||||
isHeadless: args.isHeadless,
|
||||
});
|
||||
|
||||
logger.debug(`ModeService initialized with mode: ${mode}`);
|
||||
|
||||
return {
|
||||
mode,
|
||||
toolPermissionService: this.currentState.toolPermissionService
|
||||
toolPermissionService: this.currentState.toolPermissionService,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -76,14 +76,14 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
public switchMode(mode: PermissionMode): void {
|
||||
const previousMode = this.currentState.mode;
|
||||
this.currentState.toolPermissionService.switchMode(mode);
|
||||
|
||||
|
||||
this.setState({ mode });
|
||||
|
||||
|
||||
logger.info(`Switched to ${mode} mode`);
|
||||
|
||||
|
||||
// Emit mode change event for immediate UI updates
|
||||
if (previousMode !== mode) {
|
||||
this.emit('modeChanged', mode, previousMode);
|
||||
this.emit("modeChanged", mode, previousMode);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -104,11 +104,23 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
/**
|
||||
* Get available modes with descriptions
|
||||
*/
|
||||
public getAvailableModes(): Array<{ mode: PermissionMode; description: string }> {
|
||||
public getAvailableModes(): Array<{
|
||||
mode: PermissionMode;
|
||||
description: string;
|
||||
}> {
|
||||
return [
|
||||
{ mode: "normal", description: "Default mode - follows configured permission policies" },
|
||||
{ mode: "plan", description: "Planning mode - only allow read-only tools for analysis" },
|
||||
{ mode: "auto", description: "Automatically allow all tools without asking" }
|
||||
{
|
||||
mode: "normal",
|
||||
description: "Default mode - follows configured permission policies",
|
||||
},
|
||||
{
|
||||
mode: "plan",
|
||||
description: "Planning mode - only allow read-only tools for analysis",
|
||||
},
|
||||
{
|
||||
mode: "auto",
|
||||
description: "Automatically allow all tools without asking",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
|
@ -129,4 +141,4 @@ export class ModeService extends BaseService<ModeServiceState> {
|
|||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const modeService = ModeService.getInstance();
|
||||
export const modeService = ModeService.getInstance();
|
||||
|
|
|
|||
|
|
@ -1,26 +1,34 @@
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
|
||||
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
|
||||
import { getLlmApi } from '../config.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
import {
|
||||
AuthConfig,
|
||||
getAccessToken,
|
||||
getOrganizationId,
|
||||
getModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { getLlmApi } from "../config.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from './BaseService.js';
|
||||
import { ModelServiceState } from './types.js';
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { ModelServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service for managing LLM and model state
|
||||
* Extends BaseService and implements ServiceWithDependencies
|
||||
*/
|
||||
export class ModelService extends BaseService<ModelServiceState> implements ServiceWithDependencies {
|
||||
export class ModelService
|
||||
extends BaseService<ModelServiceState>
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
private availableModels: ModelConfig[] = [];
|
||||
private assistant: AssistantUnrolled | null = null;
|
||||
private authConfig: AuthConfig | null = null;
|
||||
|
||||
constructor() {
|
||||
super('ModelService', {
|
||||
super("ModelService", {
|
||||
llmApi: null,
|
||||
model: null
|
||||
model: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +36,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
return ["auth", "config"];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -36,14 +44,14 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) => model && model.roles?.includes("chat"),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
|
|
@ -57,7 +65,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
|
|
@ -65,7 +73,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -75,34 +83,34 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async update(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug('Updating ModelService');
|
||||
|
||||
logger.debug("Updating ModelService");
|
||||
|
||||
try {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) => model && model.roles?.includes("chat"),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
});
|
||||
|
||||
logger.debug('ModelService updated successfully', {
|
||||
logger.debug("ModelService updated successfully", {
|
||||
modelProvider: model.provider,
|
||||
modelName: (model as any).name || 'unnamed',
|
||||
availableModels: this.availableModels.length
|
||||
modelName: (model as any).name || "unnamed",
|
||||
availableModels: this.availableModels.length,
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to update ModelService:', error);
|
||||
this.emit('error', error);
|
||||
logger.error("Failed to update ModelService:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -111,9 +119,11 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Override isReady to check for required state
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null;
|
||||
return (
|
||||
super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -126,18 +136,22 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
|
||||
return {
|
||||
provider: this.currentState.model.provider,
|
||||
name: (this.currentState.model as any).name || 'unnamed'
|
||||
name: (this.currentState.model as any).name || "unnamed",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available chat models
|
||||
*/
|
||||
getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> {
|
||||
getAvailableChatModels(): Array<{
|
||||
provider: string;
|
||||
name: string;
|
||||
index: number;
|
||||
}> {
|
||||
return this.availableModels.map((model, index) => ({
|
||||
provider: model.provider,
|
||||
name: (model as any).name || (model as any).model || 'unnamed',
|
||||
index
|
||||
name: (model as any).name || (model as any).model || "unnamed",
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -146,18 +160,20 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async switchModel(modelIndex: number): Promise<ModelServiceState> {
|
||||
if (!this.assistant || !this.authConfig) {
|
||||
throw new Error('ModelService not initialized');
|
||||
throw new Error("ModelService not initialized");
|
||||
}
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
|
||||
throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`);
|
||||
throw new Error(
|
||||
`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
logger.debug('Switching to model', {
|
||||
logger.debug("Switching to model", {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
name: (selectedModel as any).name || 'unnamed'
|
||||
name: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
try {
|
||||
|
|
@ -188,23 +204,23 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const llmApi = constructLlmApi(config);
|
||||
|
||||
if (!llmApi) {
|
||||
throw new Error('Failed to initialize LLM with selected model');
|
||||
throw new Error("Failed to initialize LLM with selected model");
|
||||
}
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel
|
||||
model: selectedModel,
|
||||
});
|
||||
|
||||
logger.debug('Model switched successfully', {
|
||||
logger.debug("Model switched successfully", {
|
||||
modelProvider: selectedModel.provider,
|
||||
modelName: (selectedModel as any).name || 'unnamed'
|
||||
modelName: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to switch model:', error);
|
||||
this.emit('error', error);
|
||||
logger.error("Failed to switch model:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -217,9 +233,10 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
return -1;
|
||||
}
|
||||
|
||||
return this.availableModels.findIndex(model =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name
|
||||
return this.availableModels.findIndex(
|
||||
(model) =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -227,15 +244,15 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Get model index by name and provider
|
||||
*/
|
||||
getModelIndexByName(modelName: string, provider?: string): number {
|
||||
return this.availableModels.findIndex(model => {
|
||||
return this.availableModels.findIndex((model) => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
const nameMatches = name === modelName;
|
||||
|
||||
|
||||
if (provider) {
|
||||
return nameMatches && model.provider === provider;
|
||||
}
|
||||
|
||||
|
||||
return nameMatches;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,34 @@
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
|
||||
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
|
||||
import { getLlmApi } from '../config.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
import {
|
||||
AuthConfig,
|
||||
getAccessToken,
|
||||
getOrganizationId,
|
||||
getModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { getLlmApi } from "../config.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from './BaseService.js';
|
||||
import { ModelServiceState } from './types.js';
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { ModelServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service for managing LLM and model state
|
||||
* Depends on auth config and assistant config
|
||||
*/
|
||||
export class ModelService extends BaseService<ModelServiceState> implements ServiceWithDependencies {
|
||||
export class ModelService
|
||||
extends BaseService<ModelServiceState>
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
private availableModels: ModelConfig[] = [];
|
||||
private assistant: AssistantUnrolled | null = null;
|
||||
private authConfig: AuthConfig | null = null;
|
||||
|
||||
constructor() {
|
||||
super('ModelService', {
|
||||
super("ModelService", {
|
||||
llmApi: null,
|
||||
model: null
|
||||
model: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +36,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
return ["auth", "config"];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -36,14 +44,14 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) => model && model.roles?.includes("chat"),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
|
|
@ -57,7 +65,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
|
|
@ -65,7 +73,7 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -75,34 +83,34 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async update(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug('Updating ModelService');
|
||||
|
||||
logger.debug("Updating ModelService");
|
||||
|
||||
try {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) => model && model.roles?.includes("chat"),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model
|
||||
model,
|
||||
});
|
||||
|
||||
logger.debug('ModelService updated successfully', {
|
||||
logger.debug("ModelService updated successfully", {
|
||||
modelProvider: model.provider,
|
||||
modelName: (model as any).name || 'unnamed',
|
||||
availableModels: this.availableModels.length
|
||||
modelName: (model as any).name || "unnamed",
|
||||
availableModels: this.availableModels.length,
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to update ModelService:', error);
|
||||
this.emit('error', error);
|
||||
logger.error("Failed to update ModelService:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -111,9 +119,11 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Override isReady to check for required state
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null;
|
||||
return (
|
||||
super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -126,18 +136,22 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
|
||||
return {
|
||||
provider: this.currentState.model.provider,
|
||||
name: (this.currentState.model as any).name || 'unnamed'
|
||||
name: (this.currentState.model as any).name || "unnamed",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available chat models
|
||||
*/
|
||||
getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> {
|
||||
getAvailableChatModels(): Array<{
|
||||
provider: string;
|
||||
name: string;
|
||||
index: number;
|
||||
}> {
|
||||
return this.availableModels.map((model, index) => ({
|
||||
provider: model.provider,
|
||||
name: (model as any).name || (model as any).model || 'unnamed',
|
||||
index
|
||||
name: (model as any).name || (model as any).model || "unnamed",
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -146,18 +160,20 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
*/
|
||||
async switchModel(modelIndex: number): Promise<ModelServiceState> {
|
||||
if (!this.assistant || !this.authConfig) {
|
||||
throw new Error('ModelService not initialized');
|
||||
throw new Error("ModelService not initialized");
|
||||
}
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
|
||||
throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`);
|
||||
throw new Error(
|
||||
`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`,
|
||||
);
|
||||
}
|
||||
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
logger.debug('Switching to model', {
|
||||
logger.debug("Switching to model", {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
name: (selectedModel as any).name || 'unnamed'
|
||||
name: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
try {
|
||||
|
|
@ -188,23 +204,23 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
const llmApi = constructLlmApi(config);
|
||||
|
||||
if (!llmApi) {
|
||||
throw new Error('Failed to initialize LLM with selected model');
|
||||
throw new Error("Failed to initialize LLM with selected model");
|
||||
}
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel
|
||||
model: selectedModel,
|
||||
});
|
||||
|
||||
logger.debug('Model switched successfully', {
|
||||
logger.debug("Model switched successfully", {
|
||||
modelProvider: selectedModel.provider,
|
||||
modelName: (selectedModel as any).name || 'unnamed'
|
||||
modelName: (selectedModel as any).name || "unnamed",
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to switch model:', error);
|
||||
this.emit('error', error);
|
||||
logger.error("Failed to switch model:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -217,9 +233,10 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
return -1;
|
||||
}
|
||||
|
||||
return this.availableModels.findIndex(model =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name
|
||||
return this.availableModels.findIndex(
|
||||
(model) =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -227,15 +244,15 @@ export class ModelService extends BaseService<ModelServiceState> implements Serv
|
|||
* Get model index by name and provider
|
||||
*/
|
||||
getModelIndexByName(modelName: string, provider?: string): number {
|
||||
return this.availableModels.findIndex(model => {
|
||||
return this.availableModels.findIndex((model) => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
const nameMatches = name === modelName;
|
||||
|
||||
|
||||
if (provider) {
|
||||
return nameMatches && model.provider === provider;
|
||||
}
|
||||
|
||||
|
||||
return nameMatches;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { EventEmitter } from "events";
|
||||
|
||||
import { logger } from '../util/logger.js';
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { ServiceResult, ServiceState } from './types.js';
|
||||
import { ServiceResult, ServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Central service container that manages service lifecycle and dependencies
|
||||
|
|
@ -23,20 +23,20 @@ export class ServiceContainer extends EventEmitter {
|
|||
* Register a service factory with optional dependencies
|
||||
*/
|
||||
register<T>(
|
||||
serviceName: string,
|
||||
serviceName: string,
|
||||
factory: () => Promise<T>,
|
||||
deps: string[] = []
|
||||
deps: string[] = [],
|
||||
): void {
|
||||
this.factories.set(serviceName, factory);
|
||||
this.dependencies.set(serviceName, deps);
|
||||
|
||||
|
||||
// Only initialize with idle state if the service doesn't already exist
|
||||
// This prevents overwriting services that were registered with registerValue
|
||||
if (!this.services.has(serviceName)) {
|
||||
this.services.set(serviceName, {
|
||||
value: null,
|
||||
state: 'idle',
|
||||
error: null
|
||||
state: "idle",
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -47,25 +47,22 @@ export class ServiceContainer extends EventEmitter {
|
|||
* Register a service with an immediate value (no factory needed)
|
||||
* Used when the service is already initialized
|
||||
*/
|
||||
registerValue<T>(
|
||||
serviceName: string,
|
||||
value: T
|
||||
): void {
|
||||
registerValue<T>(serviceName: string, value: T): void {
|
||||
// Set the service as ready with the provided value
|
||||
this.services.set(serviceName, {
|
||||
value,
|
||||
state: 'ready',
|
||||
state: "ready",
|
||||
error: null,
|
||||
lastUpdated: new Date()
|
||||
lastUpdated: new Date(),
|
||||
});
|
||||
|
||||
// Emit ready event
|
||||
this.emit(`${serviceName}:ready`, value);
|
||||
|
||||
logger.debug(`Registered service with immediate value: ${serviceName}`, {
|
||||
state: 'ready',
|
||||
state: "ready",
|
||||
hasValue: value !== null,
|
||||
serviceMapSize: this.services.size
|
||||
serviceMapSize: this.services.size,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -78,8 +75,8 @@ export class ServiceContainer extends EventEmitter {
|
|||
logger.warn(`Service not found: ${serviceName}`);
|
||||
return {
|
||||
value: null,
|
||||
state: 'error',
|
||||
error: new Error(`Service '${serviceName}' not registered`)
|
||||
state: "error",
|
||||
error: new Error(`Service '${serviceName}' not registered`),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
|
|
@ -90,12 +87,12 @@ export class ServiceContainer extends EventEmitter {
|
|||
*/
|
||||
async get<T>(serviceName: string): Promise<T> {
|
||||
const current = this.getSync<T>(serviceName);
|
||||
|
||||
if (current.state === 'ready' && current.value !== null) {
|
||||
|
||||
if (current.state === "ready" && current.value !== null) {
|
||||
return current.value;
|
||||
}
|
||||
|
||||
if (current.state === 'loading') {
|
||||
if (current.state === "loading") {
|
||||
// Wait for loading to complete
|
||||
return new Promise((resolve, reject) => {
|
||||
const onReady = (value: T) => {
|
||||
|
|
@ -103,7 +100,7 @@ export class ServiceContainer extends EventEmitter {
|
|||
this.off(`${serviceName}:error`, onError);
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
|
||||
const onError = (error: Error) => {
|
||||
this.off(`${serviceName}:ready`, onReady);
|
||||
this.off(`${serviceName}:error`, onError);
|
||||
|
|
@ -125,31 +122,33 @@ export class ServiceContainer extends EventEmitter {
|
|||
async load<T>(serviceName: string): Promise<T> {
|
||||
const factory = this.factories.get(serviceName);
|
||||
if (!factory) {
|
||||
const error = new Error(`No factory registered for service '${serviceName}'`);
|
||||
const error = new Error(
|
||||
`No factory registered for service '${serviceName}'`,
|
||||
);
|
||||
this.setServiceError(serviceName, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Check if already loading
|
||||
const current = this.services.get(serviceName);
|
||||
if (current?.state === 'loading') {
|
||||
if (current?.state === "loading") {
|
||||
return this.get<T>(serviceName);
|
||||
}
|
||||
|
||||
logger.debug(`Loading service: ${serviceName}`);
|
||||
this.setServiceState(serviceName, 'loading');
|
||||
this.setServiceState(serviceName, "loading");
|
||||
|
||||
try {
|
||||
// Load dependencies first
|
||||
const deps = this.dependencies.get(serviceName) || [];
|
||||
await Promise.all(deps.map(dep => this.load(dep)));
|
||||
await Promise.all(deps.map((dep) => this.load(dep)));
|
||||
|
||||
// Load the service
|
||||
const value = await factory();
|
||||
|
||||
|
||||
this.setServiceValue(serviceName, value);
|
||||
logger.debug(`Service loaded successfully: ${serviceName}`);
|
||||
|
||||
|
||||
return value;
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to load service '${serviceName}':`, error);
|
||||
|
|
@ -163,27 +162,27 @@ export class ServiceContainer extends EventEmitter {
|
|||
*/
|
||||
async reload<T>(serviceName: string): Promise<T> {
|
||||
logger.debug(`Reloading service: ${serviceName}`);
|
||||
|
||||
|
||||
// Find all services that depend on this one (recursively)
|
||||
const dependents = this.findAllDependents(serviceName);
|
||||
|
||||
|
||||
logger.debug(`Found dependents for ${serviceName}:`, dependents);
|
||||
|
||||
// Reset this service and all dependents to ensure fresh reload
|
||||
this.resetService(serviceName);
|
||||
dependents.forEach(dep => this.resetService(dep));
|
||||
dependents.forEach((dep) => this.resetService(dep));
|
||||
|
||||
// Now reload ALL services that were reset, starting with the root service
|
||||
// This ensures proper dependency order and that all dependents get reloaded
|
||||
const allToReload = [serviceName, ...dependents];
|
||||
|
||||
|
||||
// Reset ALL services first to ensure clean state
|
||||
allToReload.forEach(name => this.resetService(name));
|
||||
|
||||
allToReload.forEach((name) => this.resetService(name));
|
||||
|
||||
// Load all services in dependency order - starting with the root service
|
||||
// will naturally load its dependents when they're requested
|
||||
const results = await Promise.all(
|
||||
allToReload.map(name => this.load(name))
|
||||
allToReload.map((name) => this.load(name)),
|
||||
);
|
||||
|
||||
// Return the value of the primary service that was reloaded
|
||||
|
|
@ -228,7 +227,7 @@ export class ServiceContainer extends EventEmitter {
|
|||
*/
|
||||
isReady(serviceName: string): boolean {
|
||||
const result = this.services.get(serviceName);
|
||||
return result?.state === 'ready' && result.value !== null;
|
||||
return result?.state === "ready" && result.value !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -236,7 +235,7 @@ export class ServiceContainer extends EventEmitter {
|
|||
*/
|
||||
isLoading(serviceName: string): boolean {
|
||||
const result = this.services.get(serviceName);
|
||||
return result?.state === 'loading';
|
||||
return result?.state === "loading";
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -244,22 +243,25 @@ export class ServiceContainer extends EventEmitter {
|
|||
* This eagerly loads all services rather than waiting for them to be requested
|
||||
*/
|
||||
async initializeAll(): Promise<void> {
|
||||
logger.debug('Initializing all registered services');
|
||||
|
||||
logger.debug("Initializing all registered services");
|
||||
|
||||
// Get all registered service names
|
||||
const serviceNames = Array.from(this.factories.keys());
|
||||
|
||||
|
||||
// Load all services in parallel (dependencies will be handled by load())
|
||||
await Promise.all(
|
||||
serviceNames.map(name =>
|
||||
this.load(name).catch(error => {
|
||||
serviceNames.map((name) =>
|
||||
this.load(name).catch((error) => {
|
||||
logger.error(`Failed to initialize service ${name}:`, error);
|
||||
// Don't throw - let individual services fail without breaking others
|
||||
})
|
||||
)
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
logger.debug(
|
||||
"All services initialization complete",
|
||||
this.getServiceStates(),
|
||||
);
|
||||
|
||||
logger.debug('All services initialization complete', this.getServiceStates());
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -277,7 +279,11 @@ export class ServiceContainer extends EventEmitter {
|
|||
* Private helper methods
|
||||
*/
|
||||
private setServiceState(serviceName: string, state: ServiceState): void {
|
||||
const current = this.services.get(serviceName) || { value: null, state: 'idle', error: null };
|
||||
const current = this.services.get(serviceName) || {
|
||||
value: null,
|
||||
state: "idle",
|
||||
error: null,
|
||||
};
|
||||
const updated = { ...current, state, lastUpdated: new Date() };
|
||||
this.services.set(serviceName, updated);
|
||||
this.emit(`${serviceName}:${state}`);
|
||||
|
|
@ -286,11 +292,11 @@ export class ServiceContainer extends EventEmitter {
|
|||
private setServiceValue<T>(serviceName: string, value: T): void {
|
||||
const result: ServiceResult<T> = {
|
||||
value,
|
||||
state: 'ready',
|
||||
state: "ready",
|
||||
error: null,
|
||||
lastUpdated: new Date()
|
||||
lastUpdated: new Date(),
|
||||
};
|
||||
|
||||
|
||||
this.services.set(serviceName, result);
|
||||
this.emit(`${serviceName}:ready`, value);
|
||||
this.emit(`${serviceName}:changed`, value);
|
||||
|
|
@ -299,11 +305,11 @@ export class ServiceContainer extends EventEmitter {
|
|||
private setServiceError(serviceName: string, error: Error): void {
|
||||
const result: ServiceResult<any> = {
|
||||
value: null,
|
||||
state: 'error',
|
||||
state: "error",
|
||||
error,
|
||||
lastUpdated: new Date()
|
||||
lastUpdated: new Date(),
|
||||
};
|
||||
|
||||
|
||||
this.services.set(serviceName, result);
|
||||
this.emit(`${serviceName}:error`, error);
|
||||
}
|
||||
|
|
@ -311,13 +317,13 @@ export class ServiceContainer extends EventEmitter {
|
|||
private resetService(serviceName: string): void {
|
||||
const result: ServiceResult<any> = {
|
||||
value: null,
|
||||
state: 'idle',
|
||||
error: null
|
||||
state: "idle",
|
||||
error: null,
|
||||
};
|
||||
|
||||
|
||||
this.services.set(serviceName, result);
|
||||
}
|
||||
}
|
||||
|
||||
// Global singleton instance
|
||||
export const serviceContainer = new ServiceContainer();
|
||||
export const serviceContainer = new ServiceContainer();
|
||||
|
|
|
|||
|
|
@ -1,15 +1,16 @@
|
|||
import React, { createContext, useContext } from 'react';
|
||||
import React, { createContext, useContext } from "react";
|
||||
|
||||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
import { ServiceContainer } from "./ServiceContainer.js";
|
||||
|
||||
import { serviceContainer as defaultContainer } from './index.js';
|
||||
import { serviceContainer as defaultContainer } from "./index.js";
|
||||
|
||||
const ServiceContainerContext = createContext<ServiceContainer>(defaultContainer);
|
||||
const ServiceContainerContext =
|
||||
createContext<ServiceContainer>(defaultContainer);
|
||||
|
||||
export function ServiceContainerProvider({
|
||||
children,
|
||||
container = defaultContainer
|
||||
}: {
|
||||
export function ServiceContainerProvider({
|
||||
children,
|
||||
container = defaultContainer,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
container?: ServiceContainer;
|
||||
}) {
|
||||
|
|
@ -22,4 +23,4 @@ export function ServiceContainerProvider({
|
|||
|
||||
export function useServiceContainer() {
|
||||
return useContext(ServiceContainerContext);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -165,7 +165,7 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
|
|||
modePolicyCount: 0, // Reset since we're replacing all policies
|
||||
});
|
||||
logger.debug(
|
||||
`Updated tool permissions with ${newPolicies.length} policies`
|
||||
`Updated tool permissions with ${newPolicies.length} policies`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -174,7 +174,7 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
|
|||
*/
|
||||
switchMode(newMode: PermissionMode): ToolPermissionServiceState {
|
||||
logger.debug(
|
||||
`Switching from mode '${this.currentState.currentMode}' to '${newMode}'`
|
||||
`Switching from mode '${this.currentState.currentMode}' to '${newMode}'`,
|
||||
);
|
||||
|
||||
// Store original policies when leaving normal mode for the first time
|
||||
|
|
@ -190,7 +190,7 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
|
|||
},
|
||||
});
|
||||
logger.debug(
|
||||
`Stored ${this.currentState.permissions.policies.length} original policies`
|
||||
`Stored ${this.currentState.permissions.policies.length} original policies`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -214,11 +214,11 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
|
|||
const originalModePolicyCount = 0; // Normal mode has no mode policies
|
||||
const originalNonModePolicies =
|
||||
this.currentState.originalPolicies.policies.slice(
|
||||
originalModePolicyCount
|
||||
originalModePolicyCount,
|
||||
);
|
||||
allPolicies = [...modePolicies, ...originalNonModePolicies];
|
||||
logger.debug(
|
||||
`Restored ${originalNonModePolicies.length} original user policies`
|
||||
`Restored ${originalNonModePolicies.length} original user policies`,
|
||||
);
|
||||
} else {
|
||||
// Fallback to existing behavior if no original policies stored
|
||||
|
|
@ -239,7 +239,7 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
|
|||
});
|
||||
|
||||
logger.debug(
|
||||
`Mode switched to '${newMode}' with ${allPolicies.length} total policies`
|
||||
`Mode switched to '${newMode}' with ${allPolicies.length} total policies`,
|
||||
);
|
||||
return this.getState();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,18 +29,20 @@ const mcpServiceWrapper = new MCPServiceWrapper();
|
|||
* Initialize all services and register them with the service container
|
||||
* Handles onboarding internally for TUI mode unless skipOnboarding is true
|
||||
*/
|
||||
export async function initializeServices(options: ServiceInitOptions = {}): Promise<ServiceInitResult> {
|
||||
export async function initializeServices(
|
||||
options: ServiceInitOptions = {},
|
||||
): Promise<ServiceInitResult> {
|
||||
logger.debug("Initializing service registry");
|
||||
|
||||
|
||||
let wasOnboarded = false;
|
||||
|
||||
|
||||
// Handle onboarding for TUI mode (headless: false) unless explicitly skipped
|
||||
if (!options.headless && !options.skipOnboarding) {
|
||||
const authConfig = loadAuthConfig();
|
||||
const onboardingResult = await initializeWithOnboarding(
|
||||
authConfig,
|
||||
options.configPath,
|
||||
options.rules
|
||||
options.rules,
|
||||
);
|
||||
wasOnboarded = onboardingResult.wasOnboarded;
|
||||
}
|
||||
|
|
@ -48,15 +50,15 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
// Initialize mode service with tool permission overrides
|
||||
if (options.toolPermissionOverrides) {
|
||||
const overrides = { ...options.toolPermissionOverrides };
|
||||
|
||||
|
||||
// Convert mode to boolean flags for ModeService
|
||||
const initArgs: Parameters<typeof modeService.initialize>[0] = {
|
||||
allow: overrides.allow,
|
||||
ask: overrides.ask,
|
||||
exclude: overrides.exclude,
|
||||
isHeadless: options.headless
|
||||
isHeadless: options.headless,
|
||||
};
|
||||
|
||||
|
||||
// Only set the boolean flag that corresponds to the mode
|
||||
if (overrides.mode === "plan") {
|
||||
initArgs.readonly = true;
|
||||
|
|
@ -64,15 +66,15 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
initArgs.auto = true;
|
||||
}
|
||||
// If mode is "normal" or undefined, no flags are set
|
||||
|
||||
|
||||
await modeService.initialize(initArgs);
|
||||
} else {
|
||||
// Even if no overrides, we need to initialize with defaults
|
||||
await modeService.initialize({
|
||||
isHeadless: options.headless
|
||||
isHeadless: options.headless,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Register the TOOL_PERMISSIONS service with immediate value
|
||||
// Since ToolPermissionService is already initialized synchronously in ModeService,
|
||||
// we can register it as a ready value instead of a factory
|
||||
|
|
@ -80,28 +82,28 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
logger.debug("Registering TOOL_PERMISSIONS with state:", {
|
||||
currentMode: toolPermissionState.currentMode,
|
||||
isHeadless: toolPermissionState.isHeadless,
|
||||
policyCount: toolPermissionState.permissions.policies.length
|
||||
policyCount: toolPermissionState.permissions.policies.length,
|
||||
});
|
||||
serviceContainer.registerValue(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
toolPermissionState
|
||||
toolPermissionState,
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.AUTH,
|
||||
() => authService.initialize(),
|
||||
[] // No dependencies
|
||||
[], // No dependencies
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.API_CLIENT,
|
||||
async () => {
|
||||
const authState = await serviceContainer.get<AuthServiceState>(
|
||||
SERVICE_NAMES.AUTH
|
||||
SERVICE_NAMES.AUTH,
|
||||
);
|
||||
return apiClientService.initialize(authState.authConfig);
|
||||
},
|
||||
[SERVICE_NAMES.AUTH] // Depends on auth
|
||||
[SERVICE_NAMES.AUTH], // Depends on auth
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
|
|
@ -112,11 +114,12 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
serviceContainer.get<ApiClientServiceState>(SERVICE_NAMES.API_CLIENT),
|
||||
]);
|
||||
|
||||
// Ensure organization is selected if authenticated and not headless
|
||||
// Ensure organization is selected if authenticated
|
||||
let finalAuthState = authState;
|
||||
if (authState.authConfig && !options.headless) {
|
||||
if (authState.authConfig) {
|
||||
finalAuthState = await authService.ensureOrganization(
|
||||
options.headless ?? false
|
||||
options.headless ?? false,
|
||||
options.organizationSlug,
|
||||
);
|
||||
// Update the auth service state in container
|
||||
serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState);
|
||||
|
|
@ -130,8 +133,11 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
// otherwise use initial options.configPath (for first initialization)
|
||||
// IMPORTANT: Always prefer explicit --config flag over saved state
|
||||
const currentState = configService.getState();
|
||||
let configPath = options.configPath ||
|
||||
(currentState.configPath !== undefined ? currentState.configPath : undefined);
|
||||
let configPath =
|
||||
options.configPath ||
|
||||
(currentState.configPath !== undefined
|
||||
? currentState.configPath
|
||||
: undefined);
|
||||
|
||||
// If no config path is available, check for saved config URI in auth config
|
||||
if (!configPath) {
|
||||
|
|
@ -151,10 +157,10 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
configPath,
|
||||
finalAuthState.organizationId || null,
|
||||
apiClientState.apiClient,
|
||||
options.rules
|
||||
options.rules,
|
||||
);
|
||||
},
|
||||
[SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT] // Depends on auth and API client
|
||||
[SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
|
|
@ -171,14 +177,14 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
|
||||
return modelService.initialize(configState.config, authState.authConfig);
|
||||
},
|
||||
[SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH] // Depends on config and auth
|
||||
[SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.MCP,
|
||||
async () => {
|
||||
const configState = await serviceContainer.get<ConfigServiceState>(
|
||||
SERVICE_NAMES.CONFIG
|
||||
SERVICE_NAMES.CONFIG,
|
||||
);
|
||||
|
||||
if (!configState.config) {
|
||||
|
|
@ -187,7 +193,7 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
|
||||
return mcpServiceWrapper.initialize(configState.config);
|
||||
},
|
||||
[SERVICE_NAMES.CONFIG] // Depends on config
|
||||
[SERVICE_NAMES.CONFIG], // Depends on config
|
||||
);
|
||||
|
||||
// Eagerly initialize all services to ensure they're ready when needed
|
||||
|
|
@ -195,7 +201,7 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom
|
|||
await serviceContainer.initializeAll();
|
||||
|
||||
logger.debug("Service registry initialized");
|
||||
|
||||
|
||||
return { wasOnboarded };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { PermissionMode, ToolPermissions } from "../permissions/types.js";
|
|||
/**
|
||||
* Service lifecycle states
|
||||
*/
|
||||
export type ServiceState = 'idle' | 'loading' | 'ready' | 'error';
|
||||
export type ServiceState = "idle" | "loading" | "ready" | "error";
|
||||
|
||||
/**
|
||||
* Generic service result with state tracking
|
||||
|
|
@ -69,12 +69,12 @@ export interface ToolPermissionServiceState {
|
|||
* Service names as constants to prevent typos
|
||||
*/
|
||||
export const SERVICE_NAMES = {
|
||||
AUTH: 'auth',
|
||||
CONFIG: 'config',
|
||||
MODEL: 'model',
|
||||
MCP: 'mcp',
|
||||
API_CLIENT: 'apiClient',
|
||||
TOOL_PERMISSIONS: 'toolPermissions'
|
||||
AUTH: "auth",
|
||||
CONFIG: "config",
|
||||
MODEL: "model",
|
||||
MCP: "mcp",
|
||||
API_CLIENT: "apiClient",
|
||||
TOOL_PERMISSIONS: "toolPermissions",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
@ -82,6 +82,7 @@ export const SERVICE_NAMES = {
|
|||
*/
|
||||
export interface ServiceInitOptions {
|
||||
configPath?: string;
|
||||
organizationSlug?: string; // Organization slug to use for this session
|
||||
rules?: string[];
|
||||
headless?: boolean;
|
||||
skipOnboarding?: boolean; // Skip onboarding check even in TUI mode
|
||||
|
|
@ -98,4 +99,4 @@ export interface ServiceInitOptions {
|
|||
*/
|
||||
export interface ServiceInitResult {
|
||||
wasOnboarded?: boolean;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@ import { Command } from "commander";
|
|||
export function addCommonOptions(command: Command): Command {
|
||||
return command
|
||||
.option("--config <path>", "Path to configuration file")
|
||||
.option(
|
||||
"--org <slug>",
|
||||
"Organization slug to use for this session (supported only in headless mode)",
|
||||
)
|
||||
.option("--readonly", "Start in plan mode (read-only tools)")
|
||||
.option("--auto", "Start in auto mode (all tools allowed)")
|
||||
.option("-v, --verbose", "Enable verbose logging")
|
||||
|
|
@ -15,7 +19,7 @@ export function addCommonOptions(command: Command): Command {
|
|||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
[] as string[],
|
||||
)
|
||||
.option(
|
||||
"--allow <tool>",
|
||||
|
|
@ -25,7 +29,7 @@ export function addCommonOptions(command: Command): Command {
|
|||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
[] as string[],
|
||||
)
|
||||
.option(
|
||||
"--ask <tool>",
|
||||
|
|
@ -35,7 +39,7 @@ export function addCommonOptions(command: Command): Command {
|
|||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
[] as string[],
|
||||
)
|
||||
.option(
|
||||
"--exclude <tool>",
|
||||
|
|
@ -45,7 +49,7 @@ export function addCommonOptions(command: Command): Command {
|
|||
array.push(value);
|
||||
return array;
|
||||
},
|
||||
[] as string[]
|
||||
[] as string[],
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -56,22 +60,26 @@ export function mergeParentOptions(parentCommand: Command, options: any): any {
|
|||
|
||||
// List of options to inherit from parent if not present in subcommand
|
||||
const inheritableOptions = [
|
||||
'config',
|
||||
'readonly',
|
||||
'auto',
|
||||
'tools',
|
||||
'verbose',
|
||||
'rule',
|
||||
'allow',
|
||||
'ask',
|
||||
'exclude'
|
||||
"config",
|
||||
"org",
|
||||
"readonly",
|
||||
"auto",
|
||||
"tools",
|
||||
"verbose",
|
||||
"rule",
|
||||
"allow",
|
||||
"ask",
|
||||
"exclude",
|
||||
];
|
||||
|
||||
for (const optName of inheritableOptions) {
|
||||
if (parentOpts[optName] !== undefined && mergedOptions[optName] === undefined) {
|
||||
if (
|
||||
parentOpts[optName] !== undefined &&
|
||||
mergedOptions[optName] === undefined
|
||||
) {
|
||||
mergedOptions[optName] = parentOpts[optName];
|
||||
}
|
||||
}
|
||||
|
||||
return mergedOptions;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { posthogService } from "./telemetry/posthogService.js";
|
|||
|
||||
export async function handleSlashCommands(
|
||||
input: string,
|
||||
assistant: AssistantConfig
|
||||
assistant: AssistantConfig,
|
||||
): Promise<{
|
||||
output?: string;
|
||||
exit?: boolean;
|
||||
|
|
@ -30,7 +30,10 @@ export async function handleSlashCommands(
|
|||
const allCommands = getAllSlashCommands(assistant);
|
||||
const helpMessage = [
|
||||
chalk.cyan("Slash commands:"),
|
||||
...allCommands.map((cmd) => `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`),
|
||||
...allCommands.map(
|
||||
(cmd) =>
|
||||
`- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`,
|
||||
),
|
||||
].join("\n");
|
||||
posthogService.capture("useSlashCommand", {
|
||||
name: "help",
|
||||
|
|
@ -195,7 +198,7 @@ export async function handleSlashCommands(
|
|||
}
|
||||
default:
|
||||
const assistantPrompt = assistant.prompts?.find(
|
||||
(prompt) => prompt?.name === command
|
||||
(prompt) => prompt?.name === command,
|
||||
);
|
||||
if (assistantPrompt) {
|
||||
const newInput = assistantPrompt.prompt + args.join(" ");
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ export function getAllTools() {
|
|||
|
||||
// Check if the ToolPermissionService is ready
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
|
||||
let allowedToolNames: string[];
|
||||
|
|
@ -57,16 +57,16 @@ export function getAllTools() {
|
|||
// Filter out excluded tools based on permissions
|
||||
allowedToolNames = filterExcludedTools(
|
||||
allToolNames,
|
||||
serviceResult.value.permissions
|
||||
serviceResult.value.permissions,
|
||||
);
|
||||
} else {
|
||||
// Service not ready - this is a critical error since tools should only be
|
||||
// requested after services are properly initialized
|
||||
logger.error(
|
||||
"ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue"
|
||||
"ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
|
||||
);
|
||||
throw new Error(
|
||||
"ToolPermissionService not initialized. Services must be initialized before requesting tools."
|
||||
"ToolPermissionService not initialized. Services must be initialized before requesting tools.",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ export function getAllTools() {
|
|||
|
||||
// Filter builtin tools
|
||||
const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name)
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
|
||||
|
|
@ -92,7 +92,7 @@ export function getAllTools() {
|
|||
description: param.description,
|
||||
items: param.items,
|
||||
},
|
||||
])
|
||||
]),
|
||||
),
|
||||
required: Object.entries(tool.parameters)
|
||||
.filter(([_, param]) => param.required)
|
||||
|
|
@ -104,7 +104,7 @@ export function getAllTools() {
|
|||
// Add filtered MCP tools
|
||||
const mcpTools = MCPService.getInstance()?.getTools() ?? [];
|
||||
const allowedMcpTools = mcpTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name)
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
allTools.push(
|
||||
|
|
@ -115,7 +115,7 @@ export function getAllTools() {
|
|||
description: tool.description,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
}))
|
||||
})),
|
||||
);
|
||||
|
||||
return allTools;
|
||||
|
|
@ -131,11 +131,11 @@ export interface StreamCallbacks {
|
|||
toolName: string,
|
||||
toolArgs: any,
|
||||
requestId: string,
|
||||
preview?: ToolCallPreview[]
|
||||
preview?: ToolCallPreview[],
|
||||
) => void;
|
||||
}
|
||||
function getDefaultCompletionOptions(
|
||||
opts?: CompletionOptions
|
||||
opts?: CompletionOptions,
|
||||
): Partial<ChatCompletionCreateParamsStreaming> {
|
||||
if (!opts) return {};
|
||||
return {
|
||||
|
|
@ -155,7 +155,7 @@ export async function processStreamingResponse(
|
|||
abortController: AbortController,
|
||||
callbacks?: StreamCallbacks,
|
||||
isHeadless?: boolean,
|
||||
tools?: ChatCompletionTool[]
|
||||
tools?: ChatCompletionTool[],
|
||||
): Promise<{
|
||||
content: string;
|
||||
finalContent: string; // Added field for final content only
|
||||
|
|
@ -179,7 +179,7 @@ export async function processStreamingResponse(
|
|||
tools,
|
||||
...getDefaultCompletionOptions(model.defaultCompletionOptions),
|
||||
},
|
||||
abortController.signal
|
||||
abortController.signal,
|
||||
);
|
||||
};
|
||||
|
||||
|
|
@ -194,7 +194,7 @@ export async function processStreamingResponse(
|
|||
try {
|
||||
const streamWithBackoff = withExponentialBackoff(
|
||||
streamFactory,
|
||||
abortController.signal
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
let chunkCount = 0;
|
||||
|
|
@ -213,7 +213,7 @@ export async function processStreamingResponse(
|
|||
firstTokenTime - requestStartTime,
|
||||
model.model,
|
||||
"time_to_first_token",
|
||||
(tools?.length || 0) > 0
|
||||
(tools?.length || 0) > 0,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -332,7 +332,7 @@ export async function processStreamingResponse(
|
|||
totalDuration,
|
||||
model.model,
|
||||
"total_response_time",
|
||||
(tools?.length || 0) > 0
|
||||
(tools?.length || 0) > 0,
|
||||
);
|
||||
|
||||
// Log API request event
|
||||
|
|
@ -343,7 +343,7 @@ export async function processStreamingResponse(
|
|||
undefined, // no error
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cost
|
||||
cost,
|
||||
);
|
||||
|
||||
logger.debug("Stream complete", {
|
||||
|
|
@ -363,7 +363,7 @@ export async function processStreamingResponse(
|
|||
model.model,
|
||||
errorDuration,
|
||||
false, // failed
|
||||
error.message || String(error)
|
||||
error.message || String(error),
|
||||
);
|
||||
|
||||
if (error.name === "AbortError" || abortController?.signal.aborted) {
|
||||
|
|
@ -413,7 +413,7 @@ export async function processStreamingResponse(
|
|||
*/
|
||||
export async function preprocessStreamedToolCalls(
|
||||
toolCalls: ToolCall[],
|
||||
callbacks?: StreamCallbacks
|
||||
callbacks?: StreamCallbacks,
|
||||
): Promise<{
|
||||
preprocessedCalls: PreprocessedToolCall[];
|
||||
errorChatEntries: ChatCompletionToolMessageParam[];
|
||||
|
|
@ -468,7 +468,7 @@ export async function preprocessStreamedToolCalls(
|
|||
toolCall.name,
|
||||
false,
|
||||
duration,
|
||||
errorMessage
|
||||
errorMessage,
|
||||
);
|
||||
|
||||
// Add error to chat history
|
||||
|
|
@ -495,7 +495,7 @@ export async function preprocessStreamedToolCalls(
|
|||
export async function executeStreamedToolCalls(
|
||||
preprocessedCalls: PreprocessedToolCall[],
|
||||
callbacks?: StreamCallbacks,
|
||||
isHeadless?: boolean
|
||||
isHeadless?: boolean,
|
||||
): Promise<{
|
||||
hasRejection: boolean;
|
||||
chatHistoryEntries: ChatCompletionToolMessageParam[];
|
||||
|
|
@ -541,13 +541,13 @@ export async function executeStreamedToolCalls(
|
|||
const tool = allBuiltinTools.find((t) => t.name === toolCall.name);
|
||||
const toolName = tool?.displayName || toolCall.name;
|
||||
console.error(
|
||||
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.`
|
||||
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.`,
|
||||
);
|
||||
console.error(
|
||||
`If you want to allow this tool, use --allow ${toolName}.`
|
||||
`If you want to allow this tool, use --allow ${toolName}.`,
|
||||
);
|
||||
console.error(
|
||||
`If you don't want the tool to be included, use --exclude ${toolName}.`
|
||||
`If you don't want the tool to be included, use --exclude ${toolName}.`,
|
||||
);
|
||||
|
||||
process.exit(1);
|
||||
|
|
@ -570,21 +570,21 @@ export async function executeStreamedToolCalls(
|
|||
if (event.toolCall.name === toolCall.name) {
|
||||
toolPermissionManager.off(
|
||||
"permissionRequested",
|
||||
handlePermissionRequested
|
||||
handlePermissionRequested,
|
||||
);
|
||||
// Notify UI about permission request
|
||||
callbacks.onToolPermissionRequest!(
|
||||
event.toolCall.name,
|
||||
event.toolCall.arguments,
|
||||
event.requestId,
|
||||
event.toolCall.preview
|
||||
event.toolCall.preview,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
toolPermissionManager.on(
|
||||
"permissionRequested",
|
||||
handlePermissionRequested
|
||||
handlePermissionRequested,
|
||||
);
|
||||
|
||||
// Request permission using the proper API
|
||||
|
|
@ -667,7 +667,7 @@ export async function streamChatResponse(
|
|||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
abortController: AbortController,
|
||||
callbacks?: StreamCallbacks
|
||||
callbacks?: StreamCallbacks,
|
||||
) {
|
||||
logger.debug("streamChatResponse called", {
|
||||
model,
|
||||
|
|
@ -676,7 +676,7 @@ export async function streamChatResponse(
|
|||
});
|
||||
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
const isHeadless = serviceResult.value?.isHeadless ?? false;
|
||||
const tools = getAllTools();
|
||||
|
|
@ -701,7 +701,7 @@ export async function streamChatResponse(
|
|||
abortController,
|
||||
callbacks,
|
||||
isHeadless,
|
||||
tools
|
||||
tools,
|
||||
);
|
||||
|
||||
fullResponse += content;
|
||||
|
|
@ -756,12 +756,12 @@ export async function streamChatResponse(
|
|||
await executeStreamedToolCalls(
|
||||
preprocessedCalls,
|
||||
callbacks,
|
||||
isHeadless
|
||||
isHeadless,
|
||||
);
|
||||
|
||||
if (isHeadless && hasRejection) {
|
||||
logger.debug(
|
||||
"Tool call rejected in headless mode - returning current content"
|
||||
"Tool call rejected in headless mode - returning current content",
|
||||
);
|
||||
return finalResponse || content || fullResponse;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ export async function constructSystemMessage(
|
|||
rulesSystemMessage: string,
|
||||
additionalRules?: string[],
|
||||
format?: "json",
|
||||
headless?: boolean
|
||||
headless?: boolean,
|
||||
): Promise<string> {
|
||||
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
|
||||
|
||||
|
|
@ -136,7 +136,7 @@ export async function constructSystemMessage(
|
|||
processedRules.push(processedRule);
|
||||
} catch (error: any) {
|
||||
console.warn(
|
||||
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
|
||||
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ export class PosthogService {
|
|||
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
|
||||
{
|
||||
host: "https://app.posthog.com",
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -110,13 +110,13 @@ class TelemetryService {
|
|||
`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
|
||||
"http://localhost:4318/v1/metrics",
|
||||
headers: this.parseHeaders(
|
||||
process.env.OTEL_EXPORTER_OTLP_HEADERS || ""
|
||||
process.env.OTEL_EXPORTER_OTLP_HEADERS || "",
|
||||
),
|
||||
}),
|
||||
exportIntervalMillis: parseInt(
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000",
|
||||
),
|
||||
})
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "console":
|
||||
|
|
@ -124,9 +124,9 @@ class TelemetryService {
|
|||
new PeriodicExportingMetricReader({
|
||||
exporter: new ConsoleMetricExporter(),
|
||||
exportIntervalMillis: parseInt(
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
|
||||
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000",
|
||||
),
|
||||
})
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
|
@ -175,7 +175,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Count of CLI sessions started",
|
||||
unit: "count",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.linesOfCodeCounter = this.meter.createCounter(
|
||||
|
|
@ -183,7 +183,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Count of lines of code modified",
|
||||
unit: "count",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.pullRequestCounter = this.meter.createCounter(
|
||||
|
|
@ -191,7 +191,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Number of pull requests created",
|
||||
unit: "count",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.commitCounter = this.meter.createCounter("continue.cli.commit.count", {
|
||||
|
|
@ -214,7 +214,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Count of code editing tool permission decisions",
|
||||
unit: "count",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.activeTimeCounter = this.meter.createCounter(
|
||||
|
|
@ -222,7 +222,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Total active time in seconds",
|
||||
unit: "s",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Additional Continue CLI specific metrics
|
||||
|
|
@ -231,7 +231,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Authentication attempts",
|
||||
unit: "{attempt}",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.mcpConnectionsGauge = this.meter.createObservableGauge(
|
||||
|
|
@ -239,7 +239,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Active MCP connections",
|
||||
unit: "{connection}",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.startupTimeHistogram = this.meter.createHistogram(
|
||||
|
|
@ -247,7 +247,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "Time from CLI start to ready state",
|
||||
unit: "ms",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.responseTimeHistogram = this.meter.createHistogram(
|
||||
|
|
@ -255,7 +255,7 @@ class TelemetryService {
|
|||
{
|
||||
description: "LLM response time metrics",
|
||||
unit: "ms",
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -265,7 +265,7 @@ class TelemetryService {
|
|||
}
|
||||
|
||||
private getStandardAttributes(
|
||||
additionalAttributes: Record<string, string> = {}
|
||||
additionalAttributes: Record<string, string> = {},
|
||||
) {
|
||||
const attributes: Record<string, string> = { ...additionalAttributes };
|
||||
|
||||
|
|
@ -319,7 +319,7 @@ class TelemetryService {
|
|||
public recordLinesOfCodeModified(
|
||||
type: "added" | "removed",
|
||||
count: number,
|
||||
language?: string
|
||||
language?: string,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -352,7 +352,7 @@ class TelemetryService {
|
|||
public recordTokenUsage(
|
||||
tokens: number,
|
||||
type: "input" | "output" | "cacheRead" | "cacheCreation",
|
||||
model: string
|
||||
model: string,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -362,7 +362,7 @@ class TelemetryService {
|
|||
public recordCodeEditDecision(
|
||||
tool: string,
|
||||
decision: "accept" | "reject",
|
||||
language?: string
|
||||
language?: string,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -391,26 +391,26 @@ class TelemetryService {
|
|||
|
||||
this.activeTimeCounter.add(
|
||||
this.totalActiveTime / 1000,
|
||||
this.getStandardAttributes()
|
||||
this.getStandardAttributes(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public recordAuthAttempt(
|
||||
result: "success" | "failure" | "cancelled",
|
||||
method: "workos" | "token"
|
||||
method: "workos" | "token",
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
this.authAttemptsCounter.add(
|
||||
1,
|
||||
this.getStandardAttributes({ result, method })
|
||||
this.getStandardAttributes({ result, method }),
|
||||
);
|
||||
}
|
||||
|
||||
public recordMCPConnection(
|
||||
serverName: string,
|
||||
status: "connected" | "disconnected" | "error"
|
||||
status: "connected" | "disconnected" | "error",
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -425,7 +425,7 @@ class TelemetryService {
|
|||
public recordStartupTime(
|
||||
timeMs: number,
|
||||
mode?: "tui" | "headless" | "standard",
|
||||
coldStart?: boolean
|
||||
coldStart?: boolean,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -440,7 +440,7 @@ class TelemetryService {
|
|||
timeMs: number,
|
||||
model: string,
|
||||
metricType: "time_to_first_token" | "total_response_time",
|
||||
hasTools?: boolean
|
||||
hasTools?: boolean,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -478,7 +478,7 @@ class TelemetryService {
|
|||
error?: string,
|
||||
decision?: "accept" | "reject",
|
||||
source?: string,
|
||||
toolParameters?: string
|
||||
toolParameters?: string,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
@ -506,7 +506,7 @@ class TelemetryService {
|
|||
error?: string,
|
||||
inputTokens?: number,
|
||||
outputTokens?: number,
|
||||
costUsd?: number
|
||||
costUsd?: number,
|
||||
) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { diffLines } from "diff";
|
|||
*/
|
||||
export function calculateLinesOfCodeDiff(
|
||||
oldContent: string,
|
||||
newContent: string
|
||||
newContent: string,
|
||||
): { added: number; removed: number } {
|
||||
const diff = diffLines(oldContent, newContent);
|
||||
let added = 0;
|
||||
|
|
@ -119,7 +119,7 @@ export function isPullRequestCommand(command: string): boolean {
|
|||
export function calculateTokenCost(
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
model: string
|
||||
model: string,
|
||||
): number {
|
||||
// Pricing per 1K tokens (these are approximate and should be updated)
|
||||
const pricingMap: Record<string, { input: number; output: number }> = {
|
||||
|
|
@ -134,7 +134,7 @@ export function calculateTokenCost(
|
|||
|
||||
// Find pricing for model (case insensitive partial match)
|
||||
const modelKey = Object.keys(pricingMap).find((key) =>
|
||||
model.toLowerCase().includes(key.toLowerCase())
|
||||
model.toLowerCase().includes(key.toLowerCase()),
|
||||
);
|
||||
|
||||
if (!modelKey) {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,10 @@ The `mock-llm-server.ts` module provides utilities for creating mock LLM servers
|
|||
### Basic Usage
|
||||
|
||||
```typescript
|
||||
import { setupMockLLMTest, cleanupMockLLMServer } from "../test-helpers/mock-llm-server.js";
|
||||
import {
|
||||
setupMockLLMTest,
|
||||
cleanupMockLLMServer,
|
||||
} from "../test-helpers/mock-llm-server.js";
|
||||
|
||||
describe("My Test", () => {
|
||||
let context: any;
|
||||
|
|
@ -87,13 +90,17 @@ expect(mockServer.requests[0].body.messages[0].content).toBe("User prompt");
|
|||
### API Reference
|
||||
|
||||
#### `setupMockLLMTest(context, options)`
|
||||
|
||||
Sets up a complete test environment with mock LLM server, config file, and skips onboarding.
|
||||
|
||||
#### `createMockLLMServer(options)`
|
||||
|
||||
Creates just the mock server without test environment setup.
|
||||
|
||||
#### `createMockLLMConfig(mockServer, modelName)`
|
||||
|
||||
Generates a config YAML string for the mock server.
|
||||
|
||||
#### `cleanupMockLLMServer(mockServer)`
|
||||
Properly shuts down the mock server.
|
||||
|
||||
Properly shuts down the mock server.
|
||||
|
|
|
|||
|
|
@ -13,38 +13,42 @@ export function mockLLMResponse(response: string) {
|
|||
const words = response.split(" ");
|
||||
for (const word of words) {
|
||||
yield {
|
||||
choices: [{
|
||||
delta: {
|
||||
content: word + " "
|
||||
}
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
delta: {
|
||||
content: word + " ",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
chatCompletion: async () => ({
|
||||
choices: [{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: response
|
||||
}
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: response,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
|
||||
// Add any other methods that might be used
|
||||
completionStream: async function* () {
|
||||
yield response;
|
||||
},
|
||||
|
||||
|
||||
completion: async () => response,
|
||||
};
|
||||
|
||||
vi.doMock("@continuedev/openai-adapters", () => ({
|
||||
constructLlmApi: () => mockApi,
|
||||
BaseLlmApi: MockBaseLlmApi,
|
||||
LLMConfig: {}
|
||||
LLMConfig: {},
|
||||
}));
|
||||
|
||||
|
||||
return mockApi;
|
||||
}
|
||||
|
||||
|
|
@ -56,39 +60,43 @@ export function mockLLMStreamResponse(chunks: string[]) {
|
|||
chatCompletionStream: async function* () {
|
||||
for (const chunk of chunks) {
|
||||
yield {
|
||||
choices: [{
|
||||
delta: {
|
||||
content: chunk
|
||||
}
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
delta: {
|
||||
content: chunk,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
chatCompletion: async () => ({
|
||||
choices: [{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: chunks.join("")
|
||||
}
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: chunks.join(""),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
|
||||
completionStream: async function* () {
|
||||
for (const chunk of chunks) {
|
||||
yield chunk;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
completion: async () => chunks.join(""),
|
||||
};
|
||||
|
||||
vi.doMock("@continuedev/openai-adapters", () => ({
|
||||
constructLlmApi: () => mockApi,
|
||||
BaseLlmApi: MockBaseLlmApi,
|
||||
LLMConfig: {}
|
||||
LLMConfig: {},
|
||||
}));
|
||||
|
||||
|
||||
return mockApi;
|
||||
}
|
||||
|
||||
|
|
@ -100,15 +108,15 @@ export function mockLLMError(errorMessage: string) {
|
|||
chatCompletionStream: async function* () {
|
||||
throw new Error(errorMessage);
|
||||
},
|
||||
|
||||
|
||||
chatCompletion: async () => {
|
||||
throw new Error(errorMessage);
|
||||
},
|
||||
|
||||
|
||||
completionStream: async function* () {
|
||||
throw new Error(errorMessage);
|
||||
},
|
||||
|
||||
|
||||
completion: async () => {
|
||||
throw new Error(errorMessage);
|
||||
},
|
||||
|
|
@ -117,9 +125,9 @@ export function mockLLMError(errorMessage: string) {
|
|||
vi.doMock("@continuedev/openai-adapters", () => ({
|
||||
constructLlmApi: () => mockApi,
|
||||
BaseLlmApi: MockBaseLlmApi,
|
||||
LLMConfig: {}
|
||||
LLMConfig: {},
|
||||
}));
|
||||
|
||||
|
||||
return mockApi;
|
||||
}
|
||||
|
||||
|
|
@ -128,4 +136,4 @@ export function mockLLMError(errorMessage: string) {
|
|||
*/
|
||||
export function clearLLMMocks() {
|
||||
vi.unmock("@continuedev/openai-adapters");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,9 @@ export async function createTestContext(): Promise<CLITestContext> {
|
|||
try {
|
||||
await fs.access(cliPath);
|
||||
} catch {
|
||||
throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`);
|
||||
throw new Error(
|
||||
`CLI file not found at ${cliPath}. Please run 'npm run build' first.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -50,7 +52,7 @@ export async function createTestContext(): Promise<CLITestContext> {
|
|||
* Cleans up test context
|
||||
*/
|
||||
export async function cleanupTestContext(
|
||||
context: CLITestContext
|
||||
context: CLITestContext,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await fs.rm(context.testDir, { recursive: true, force: true });
|
||||
|
|
@ -64,7 +66,7 @@ export async function cleanupTestContext(
|
|||
*/
|
||||
export async function runCLI(
|
||||
context: CLITestContext,
|
||||
options: CLIRunOptions = {}
|
||||
options: CLIRunOptions = {},
|
||||
): Promise<CLIRunResult> {
|
||||
const {
|
||||
args = [],
|
||||
|
|
@ -85,7 +87,7 @@ export async function runCLI(
|
|||
HOMEDRIVE: path.parse(context.testDir).root,
|
||||
HOMEPATH: path.relative(
|
||||
path.parse(context.testDir).root,
|
||||
context.testDir
|
||||
context.testDir,
|
||||
),
|
||||
...env,
|
||||
},
|
||||
|
|
@ -121,7 +123,7 @@ export async function runCLI(
|
|||
*/
|
||||
export async function createTestConfig(
|
||||
context: CLITestContext,
|
||||
config: any
|
||||
config: any,
|
||||
): Promise<string> {
|
||||
const configPath = path.join(context.testDir, "test-config.yaml");
|
||||
const configContent =
|
||||
|
|
@ -139,7 +141,7 @@ export async function createTestConfig(
|
|||
export async function createTestRule(
|
||||
context: CLITestContext,
|
||||
ruleName: string,
|
||||
content: string
|
||||
content: string,
|
||||
): Promise<string> {
|
||||
const rulePath = path.join(context.testDir, `${ruleName}.md`);
|
||||
await fs.writeFile(rulePath, content);
|
||||
|
|
@ -150,7 +152,7 @@ export async function createTestRule(
|
|||
* Reads the session file if it exists
|
||||
*/
|
||||
export async function readSession(
|
||||
context: CLITestContext
|
||||
context: CLITestContext,
|
||||
): Promise<any | null> {
|
||||
try {
|
||||
const sessionDir = path.join(context.testDir, ".continue", "sessions");
|
||||
|
|
@ -176,7 +178,7 @@ export async function readSession(
|
|||
*/
|
||||
export async function createMockSession(
|
||||
context: CLITestContext,
|
||||
messages: any[]
|
||||
messages: any[],
|
||||
): Promise<string> {
|
||||
const sessionDir = path.join(context.testDir, ".continue", "sessions");
|
||||
await fs.mkdir(sessionDir, { recursive: true });
|
||||
|
|
@ -203,7 +205,7 @@ export async function createMockSession(
|
|||
export function waitForPattern(
|
||||
proc: Subprocess,
|
||||
pattern: RegExp | string,
|
||||
timeout: number = 5000
|
||||
timeout: number = 5000,
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = "";
|
||||
|
|
@ -236,7 +238,7 @@ export function waitForPattern(
|
|||
export async function withInteractiveInput(
|
||||
context: CLITestContext,
|
||||
args: string[],
|
||||
inputs: string[]
|
||||
inputs: string[],
|
||||
): Promise<CLIRunResult> {
|
||||
const proc = execaNode(context.cliPath, args, {
|
||||
cwd: context.testDir,
|
||||
|
|
@ -249,7 +251,7 @@ export async function withInteractiveInput(
|
|||
HOMEDRIVE: path.parse(context.testDir).root,
|
||||
HOMEPATH: path.relative(
|
||||
path.parse(context.testDir).root,
|
||||
context.testDir
|
||||
context.testDir,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -12,13 +12,15 @@ export interface MockAPIOptions {
|
|||
*/
|
||||
export function mockOpenAIChat(
|
||||
response: string,
|
||||
options: MockAPIOptions = {}
|
||||
options: MockAPIOptions = {},
|
||||
): nock.Scope {
|
||||
const { baseURL = "https://api.openai.com", delay = 0, error = false } = options;
|
||||
const {
|
||||
baseURL = "https://api.openai.com",
|
||||
delay = 0,
|
||||
error = false,
|
||||
} = options;
|
||||
|
||||
const scope = nock(baseURL)
|
||||
.post("/v1/chat/completions")
|
||||
.delay(delay);
|
||||
const scope = nock(baseURL).post("/v1/chat/completions").delay(delay);
|
||||
|
||||
if (error) {
|
||||
return scope.reply(500, { error: { message: "Internal server error" } });
|
||||
|
|
@ -52,46 +54,52 @@ export function mockOpenAIChat(
|
|||
*/
|
||||
export function mockOpenAIStream(
|
||||
chunks: string[],
|
||||
options: MockAPIOptions = {}
|
||||
options: MockAPIOptions = {},
|
||||
): nock.Scope {
|
||||
const { baseURL = "https://api.openai.com", delay = 0, error = false } = options;
|
||||
const {
|
||||
baseURL = "https://api.openai.com",
|
||||
delay = 0,
|
||||
error = false,
|
||||
} = options;
|
||||
|
||||
const scope = nock(baseURL)
|
||||
.post("/v1/chat/completions")
|
||||
.delay(delay);
|
||||
const scope = nock(baseURL).post("/v1/chat/completions").delay(delay);
|
||||
|
||||
if (error) {
|
||||
return scope.reply(500, { error: { message: "Internal server error" } });
|
||||
}
|
||||
|
||||
return scope.reply(200, () => {
|
||||
// Return a stream of Server-Sent Events
|
||||
const events = chunks.map((chunk, index) => {
|
||||
const data = {
|
||||
id: `chatcmpl-test`,
|
||||
object: "chat.completion.chunk",
|
||||
created: Date.now(),
|
||||
model: "gpt-4",
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
content: chunk,
|
||||
return scope.reply(
|
||||
200,
|
||||
() => {
|
||||
// Return a stream of Server-Sent Events
|
||||
const events = chunks.map((chunk, index) => {
|
||||
const data = {
|
||||
id: `chatcmpl-test`,
|
||||
object: "chat.completion.chunk",
|
||||
created: Date.now(),
|
||||
model: "gpt-4",
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
content: chunk,
|
||||
},
|
||||
finish_reason: index === chunks.length - 1 ? "stop" : null,
|
||||
},
|
||||
finish_reason: index === chunks.length - 1 ? "stop" : null,
|
||||
},
|
||||
],
|
||||
};
|
||||
return `data: ${JSON.stringify(data)}\n\n`;
|
||||
});
|
||||
|
||||
events.push("data: [DONE]\n\n");
|
||||
return events.join("");
|
||||
}, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
});
|
||||
],
|
||||
};
|
||||
return `data: ${JSON.stringify(data)}\n\n`;
|
||||
});
|
||||
|
||||
events.push("data: [DONE]\n\n");
|
||||
return events.join("");
|
||||
},
|
||||
{
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -113,10 +121,15 @@ export function mockWorkOSAuth(options: {
|
|||
// Mock token exchange
|
||||
nock("https://api.workos.com")
|
||||
.post("/user_management/authenticate")
|
||||
.reply(error ? 401 : 200, error ? { error: "Invalid credentials" } : {
|
||||
access_token: accessToken,
|
||||
user: userInfo,
|
||||
});
|
||||
.reply(
|
||||
error ? 401 : 200,
|
||||
error
|
||||
? { error: "Invalid credentials" }
|
||||
: {
|
||||
access_token: accessToken,
|
||||
user: userInfo,
|
||||
},
|
||||
);
|
||||
|
||||
// Mock get user info
|
||||
nock("https://api.workos.com")
|
||||
|
|
@ -128,9 +141,14 @@ export function mockWorkOSAuth(options: {
|
|||
nock("https://api.workos.com")
|
||||
.get("/user_management/organizations")
|
||||
.matchHeader("authorization", `Bearer ${accessToken}`)
|
||||
.reply(error ? 401 : 200, error ? { error: "Unauthorized" } : {
|
||||
data: organizations,
|
||||
});
|
||||
.reply(
|
||||
error ? 401 : 200,
|
||||
error
|
||||
? { error: "Unauthorized" }
|
||||
: {
|
||||
data: organizations,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -150,7 +168,9 @@ export function createMockConfig(overrides: any = {}): any {
|
|||
/**
|
||||
* Creates mock chat messages
|
||||
*/
|
||||
export function createMockMessages(count: number = 2): ChatCompletionMessageParam[] {
|
||||
export function createMockMessages(
|
||||
count: number = 2,
|
||||
): ChatCompletionMessageParam[] {
|
||||
const messages: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
];
|
||||
|
|
@ -158,7 +178,7 @@ export function createMockMessages(count: number = 2): ChatCompletionMessagePara
|
|||
for (let i = 0; i < count; i++) {
|
||||
messages.push(
|
||||
{ role: "user", content: `Test message ${i + 1}` },
|
||||
{ role: "assistant", content: `Test response ${i + 1}` }
|
||||
{ role: "assistant", content: `Test response ${i + 1}` },
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -170,4 +190,4 @@ export function createMockMessages(count: number = 2): ChatCompletionMessagePara
|
|||
*/
|
||||
export function cleanupMocks(): void {
|
||||
nock.cleanAll();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export interface MockLLMServer {
|
|||
* @returns A promise that resolves to the mock server instance
|
||||
*/
|
||||
export async function createMockLLMServer(
|
||||
options: MockLLMServerOptions = {}
|
||||
options: MockLLMServerOptions = {},
|
||||
): Promise<MockLLMServer> {
|
||||
const {
|
||||
response = "Hello World!",
|
||||
|
|
@ -55,7 +55,7 @@ export async function createMockLLMServer(
|
|||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.setHeader(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Content-Type, Authorization"
|
||||
"Content-Type, Authorization",
|
||||
);
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
|
|
@ -115,7 +115,7 @@ export async function createMockLLMServer(
|
|||
// Properly escape JSON content
|
||||
const escapedContent = JSON.stringify(content).slice(1, -1);
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
|
||||
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
|
|
@ -123,7 +123,7 @@ export async function createMockLLMServer(
|
|||
// Properly escape JSON content
|
||||
const escapedContent = JSON.stringify(responseText).slice(1, -1);
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
|
||||
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -188,7 +188,7 @@ export async function createMockLLMServer(
|
|||
*/
|
||||
export function createMockLLMConfig(
|
||||
mockServer: MockLLMServer,
|
||||
modelName: string = "gpt-4"
|
||||
modelName: string = "gpt-4",
|
||||
): string {
|
||||
return `name: Test Assistant
|
||||
version: 1.0.0
|
||||
|
|
@ -212,7 +212,7 @@ models:
|
|||
*/
|
||||
export async function setupMockLLMTest(
|
||||
context: CLITestContext,
|
||||
options: MockLLMServerOptions = {}
|
||||
options: MockLLMServerOptions = {},
|
||||
): Promise<MockLLMServer> {
|
||||
// Create mock server
|
||||
const mockServer = await createMockLLMServer(options);
|
||||
|
|
@ -227,7 +227,7 @@ export async function setupMockLLMTest(
|
|||
const onboardingFlagPath = path.join(
|
||||
context.testDir,
|
||||
".continue",
|
||||
".onboarding_complete"
|
||||
".onboarding_complete",
|
||||
);
|
||||
await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
|
||||
await fs.writeFile(onboardingFlagPath, new Date().toISOString());
|
||||
|
|
@ -240,7 +240,7 @@ export async function setupMockLLMTest(
|
|||
* @param mockServer The mock server to clean up
|
||||
*/
|
||||
export async function cleanupMockLLMServer(
|
||||
mockServer: MockLLMServer
|
||||
mockServer: MockLLMServer,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (!mockServer?.server) {
|
||||
|
|
@ -273,7 +273,7 @@ export async function cleanupMockLLMServer(
|
|||
}
|
||||
resolveOnce();
|
||||
});
|
||||
|
||||
|
||||
// Force close after a short timeout
|
||||
setTimeout(() => {
|
||||
if (mockServer.server.listening) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
import { render } from 'ink-testing-library';
|
||||
import React from 'react';
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
|
||||
import { ServiceContainerProvider } from '../services/ServiceContainerContext.js';
|
||||
import { ServiceContainerProvider } from "../services/ServiceContainerContext.js";
|
||||
|
||||
import { createTestServiceContainer, TestServiceContainer } from './testServiceContainer.js';
|
||||
import {
|
||||
createTestServiceContainer,
|
||||
TestServiceContainer,
|
||||
} from "./testServiceContainer.js";
|
||||
|
||||
export interface RenderWithServicesOptions {
|
||||
services?: Record<string, any>;
|
||||
|
|
@ -23,25 +26,25 @@ export interface RenderWithServicesResult {
|
|||
|
||||
export function renderWithServices(
|
||||
ui: React.ReactElement,
|
||||
options?: RenderWithServicesOptions
|
||||
options?: RenderWithServicesOptions,
|
||||
): RenderWithServicesResult {
|
||||
const container = options?.container || createTestServiceContainer();
|
||||
|
||||
|
||||
// Register default services if provided
|
||||
if (options?.services) {
|
||||
Object.entries(options.services).forEach(([name, value]) => {
|
||||
container.register(name, () => Promise.resolve(value));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const rendered = render(
|
||||
<ServiceContainerProvider container={container}>
|
||||
{ui}
|
||||
</ServiceContainerProvider>
|
||||
</ServiceContainerProvider>,
|
||||
);
|
||||
|
||||
|
||||
return {
|
||||
...rendered,
|
||||
container,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ServiceContainer } from '../services/ServiceContainer.js';
|
||||
import { ServiceState } from '../services/types.js';
|
||||
import { ServiceContainer } from "../services/ServiceContainer.js";
|
||||
import { ServiceState } from "../services/types.js";
|
||||
|
||||
export interface TestServiceContainer extends ServiceContainer {
|
||||
waitForReady(...serviceNames: string[]): Promise<void>;
|
||||
|
|
@ -10,108 +10,112 @@ export interface TestServiceContainer extends ServiceContainer {
|
|||
|
||||
export function createTestServiceContainer(): TestServiceContainer {
|
||||
const container = new ServiceContainer() as TestServiceContainer;
|
||||
const serviceResolvers = new Map<string, {
|
||||
resolve: (value: any) => void;
|
||||
reject: (error: Error) => void;
|
||||
promise?: Promise<any>;
|
||||
}>();
|
||||
|
||||
const serviceResolvers = new Map<
|
||||
string,
|
||||
{
|
||||
resolve: (value: any) => void;
|
||||
reject: (error: Error) => void;
|
||||
promise?: Promise<any>;
|
||||
}
|
||||
>();
|
||||
|
||||
// Override load instead of register to have more control
|
||||
container.load = async function(serviceName: string) {
|
||||
container.load = async function (serviceName: string) {
|
||||
// Check if we already have a resolver for this service
|
||||
const existing = serviceResolvers.get(serviceName);
|
||||
if (existing && existing.promise) {
|
||||
return existing.promise;
|
||||
}
|
||||
|
||||
|
||||
// Create a controllable promise
|
||||
let promiseResolve: (value: any) => void;
|
||||
let promiseReject: (error: Error) => void;
|
||||
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
promiseResolve = resolve;
|
||||
promiseReject = reject;
|
||||
});
|
||||
|
||||
serviceResolvers.set(serviceName, {
|
||||
resolve: promiseResolve!,
|
||||
reject: promiseReject!,
|
||||
promise
|
||||
|
||||
serviceResolvers.set(serviceName, {
|
||||
resolve: promiseResolve!,
|
||||
reject: promiseReject!,
|
||||
promise,
|
||||
});
|
||||
|
||||
|
||||
// Update service state to loading
|
||||
const currentState = container.getSync(serviceName);
|
||||
if (currentState.state === 'idle' || currentState.state === 'error') {
|
||||
if (currentState.state === "idle" || currentState.state === "error") {
|
||||
container.emit(`${serviceName}:loading`);
|
||||
// Manually update the internal state (we'll need to expose this)
|
||||
(container as any).services.set(serviceName, {
|
||||
value: null,
|
||||
state: 'loading' as ServiceState,
|
||||
error: null
|
||||
state: "loading" as ServiceState,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
|
||||
// Helper to resolve a service on demand
|
||||
container.resolveService = function(name, value) {
|
||||
container.resolveService = function (name, value) {
|
||||
const resolver = serviceResolvers.get(name);
|
||||
if (resolver) {
|
||||
// Update internal state
|
||||
(container as any).services.set(name, {
|
||||
value,
|
||||
state: 'ready' as ServiceState,
|
||||
state: "ready" as ServiceState,
|
||||
error: null,
|
||||
lastUpdated: new Date()
|
||||
lastUpdated: new Date(),
|
||||
});
|
||||
|
||||
|
||||
// Emit ready event
|
||||
container.emit(`${name}:ready`, value);
|
||||
|
||||
|
||||
// Resolve the promise
|
||||
resolver.resolve(value);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Helper to reject a service
|
||||
container.rejectService = function(name, error) {
|
||||
container.rejectService = function (name, error) {
|
||||
const resolver = serviceResolvers.get(name);
|
||||
if (resolver) {
|
||||
// Update internal state
|
||||
(container as any).services.set(name, {
|
||||
value: null,
|
||||
state: 'error' as ServiceState,
|
||||
state: "error" as ServiceState,
|
||||
error,
|
||||
lastUpdated: new Date()
|
||||
lastUpdated: new Date(),
|
||||
});
|
||||
|
||||
|
||||
// Emit error event
|
||||
container.emit(`${name}:error`, error);
|
||||
|
||||
|
||||
// Reject the promise
|
||||
resolver.reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Wait for specific services to be ready
|
||||
container.waitForReady = async function(...names) {
|
||||
const promises = names.map(name =>
|
||||
new Promise<void>(resolve => {
|
||||
container.once(`${name}:ready`, () => resolve());
|
||||
container.once(`${name}:error`, () => resolve());
|
||||
})
|
||||
container.waitForReady = async function (...names) {
|
||||
const promises = names.map(
|
||||
(name) =>
|
||||
new Promise<void>((resolve) => {
|
||||
container.once(`${name}:ready`, () => resolve());
|
||||
container.once(`${name}:error`, () => resolve());
|
||||
}),
|
||||
);
|
||||
await Promise.all(promises);
|
||||
};
|
||||
|
||||
|
||||
// Wait for a specific service and return its value
|
||||
container.waitForService = async function(name) {
|
||||
container.waitForService = async function (name) {
|
||||
return new Promise((resolve) => {
|
||||
container.once(`${name}:ready`, (value) => resolve(value));
|
||||
container.once(`${name}:error`, (error) => resolve(error));
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
return container;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,6 +56,6 @@ export function createMinimalTestContext() {
|
|||
return {
|
||||
cleanup: () => {
|
||||
vi.clearAllMocks();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,14 +11,16 @@ export interface UITestContext {
|
|||
/**
|
||||
* Creates a test context with common UI mocks for TUI components
|
||||
*/
|
||||
export function createUITestContext(options: {
|
||||
serviceValue?: any;
|
||||
serviceState?: "idle" | "loading" | "ready" | "error";
|
||||
services?: Record<string, any>;
|
||||
allServicesReady?: boolean;
|
||||
chatMessages?: any[];
|
||||
isWaitingForResponse?: boolean;
|
||||
} = {}): UITestContext {
|
||||
export function createUITestContext(
|
||||
options: {
|
||||
serviceValue?: any;
|
||||
serviceState?: "idle" | "loading" | "ready" | "error";
|
||||
services?: Record<string, any>;
|
||||
allServicesReady?: boolean;
|
||||
chatMessages?: any[];
|
||||
isWaitingForResponse?: boolean;
|
||||
} = {},
|
||||
): UITestContext {
|
||||
const {
|
||||
serviceValue = null,
|
||||
serviceState = "idle",
|
||||
|
|
@ -101,4 +103,4 @@ export function createMinimalTestContext(): { cleanup: () => void } {
|
|||
};
|
||||
|
||||
return { cleanup };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,11 +42,11 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS;
|
|||
// Get dynamic tools based on current state
|
||||
function getDynamicTools(): Tool[] {
|
||||
const dynamicTools: Tool[] = [];
|
||||
|
||||
|
||||
// Add headless-specific tools if in headless mode
|
||||
try {
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
const isHeadless = serviceResult.value?.isHeadless ?? false;
|
||||
if (isHeadless) {
|
||||
|
|
@ -55,7 +55,7 @@ function getDynamicTools(): Tool[] {
|
|||
} catch {
|
||||
// Service not ready yet, no dynamic tools
|
||||
}
|
||||
|
||||
|
||||
return dynamicTools;
|
||||
}
|
||||
|
||||
|
|
@ -71,7 +71,7 @@ export function getToolDisplayName(toolName: string): string {
|
|||
}
|
||||
|
||||
export function extractToolCalls(
|
||||
response: string
|
||||
response: string,
|
||||
): Array<{ name: string; arguments: Record<string, any> }> {
|
||||
const toolCallRegex = /<tool>([\s\S]*?)<\/tool>/g;
|
||||
const matches = [...response.matchAll(toolCallRegex)];
|
||||
|
|
@ -112,7 +112,6 @@ function convertInputSchemaToParameters(inputSchema: any): ToolParameters {
|
|||
}
|
||||
|
||||
export async function getAvailableTools() {
|
||||
|
||||
// Load MCP tools
|
||||
const mcpTools: Tool[] =
|
||||
MCPService.getInstance()
|
||||
|
|
@ -135,7 +134,7 @@ export async function getAvailableTools() {
|
|||
}
|
||||
|
||||
export async function executeToolCall(
|
||||
toolCall: PreprocessedToolCall
|
||||
toolCall: PreprocessedToolCall,
|
||||
): Promise<string> {
|
||||
const startTime = Date.now();
|
||||
|
||||
|
|
@ -148,7 +147,7 @@ export async function executeToolCall(
|
|||
// IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args
|
||||
// Preprocessed arg names may be different
|
||||
const result = await toolCall.tool.run(
|
||||
toolCall.preprocessResult?.args ?? toolCall.arguments
|
||||
toolCall.preprocessResult?.args ?? toolCall.arguments,
|
||||
);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
|
|
@ -159,7 +158,7 @@ export async function executeToolCall(
|
|||
undefined, // no error
|
||||
undefined, // no decision
|
||||
undefined, // no source
|
||||
JSON.stringify(toolCall.arguments)
|
||||
JSON.stringify(toolCall.arguments),
|
||||
);
|
||||
|
||||
logger.debug("Tool execution completed", {
|
||||
|
|
@ -179,7 +178,7 @@ export async function executeToolCall(
|
|||
errorMessage,
|
||||
undefined, // no decision
|
||||
undefined, // no source
|
||||
JSON.stringify(toolCall.arguments)
|
||||
JSON.stringify(toolCall.arguments),
|
||||
);
|
||||
|
||||
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
|
||||
|
|
@ -194,7 +193,7 @@ export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) {
|
|||
toolCall.arguments[paramName] === null)
|
||||
) {
|
||||
throw new Error(
|
||||
`Required parameter "${paramName}" missing for tool "${toolCall.name}"`
|
||||
`Required parameter "${paramName}" missing for tool "${toolCall.name}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,9 +46,10 @@ export const runTerminalCommandTool: Tool = {
|
|||
let timeoutId: NodeJS.Timeout;
|
||||
let isResolved = false;
|
||||
|
||||
const TIMEOUT_MS = process.env.NODE_ENV === 'test' && process.env.TEST_TERMINAL_TIMEOUT
|
||||
? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10)
|
||||
: 30000; // 30 seconds default, configurable for tests
|
||||
const TIMEOUT_MS =
|
||||
process.env.NODE_ENV === "test" && process.env.TEST_TERMINAL_TIMEOUT
|
||||
? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10)
|
||||
: 30000; // 30 seconds default, configurable for tests
|
||||
|
||||
const resetTimeout = () => {
|
||||
if (timeoutId) {
|
||||
|
|
@ -60,7 +61,8 @@ export const runTerminalCommandTool: Tool = {
|
|||
child.kill();
|
||||
const output = stdout + (stderr ? `\nStderr: ${stderr}` : "");
|
||||
resolve(
|
||||
output + `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`
|
||||
output +
|
||||
`\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`,
|
||||
);
|
||||
}, TIMEOUT_MS);
|
||||
};
|
||||
|
|
@ -81,7 +83,7 @@ export const runTerminalCommandTool: Tool = {
|
|||
child.on("close", (code) => {
|
||||
if (isResolved) return;
|
||||
isResolved = true;
|
||||
|
||||
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
|
@ -111,7 +113,7 @@ export const runTerminalCommandTool: Tool = {
|
|||
child.on("error", (error) => {
|
||||
if (isResolved) return;
|
||||
isResolved = true;
|
||||
|
||||
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export interface SearchMatchResult extends BasicMatchResult {
|
|||
*/
|
||||
type MatchStrategy = (
|
||||
fileContent: string,
|
||||
searchContent: string
|
||||
searchContent: string,
|
||||
) => BasicMatchResult | null;
|
||||
|
||||
/**
|
||||
|
|
@ -29,7 +29,7 @@ type MatchStrategy = (
|
|||
*/
|
||||
function exactMatch(
|
||||
fileContent: string,
|
||||
searchContent: string
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
const exactIndex = fileContent.indexOf(searchContent);
|
||||
if (exactIndex !== -1) {
|
||||
|
|
@ -46,7 +46,7 @@ function exactMatch(
|
|||
*/
|
||||
function trimmedMatch(
|
||||
fileContent: string,
|
||||
searchContent: string
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
|
||||
|
|
@ -65,7 +65,7 @@ function trimmedMatch(
|
|||
*/
|
||||
function whitespaceIgnoredMatch(
|
||||
fileContent: string,
|
||||
searchContent: string
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
// Remove all whitespace (spaces, tabs, newlines, etc.)
|
||||
const strippedFileContent = fileContent.replace(/\s/g, "");
|
||||
|
|
@ -171,7 +171,7 @@ function jaroSimilarity(s1: string, s2: string): number {
|
|||
function jaroWinklerSimilarity(
|
||||
s1: string,
|
||||
s2: string,
|
||||
prefixScale = 0.1
|
||||
prefixScale = 0.1,
|
||||
): number {
|
||||
const jaroSim = jaroSimilarity(s1, s2);
|
||||
|
||||
|
|
@ -198,7 +198,7 @@ function jaroWinklerSimilarity(
|
|||
function findFuzzyMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
threshold: number = 0.9
|
||||
threshold: number = 0.9,
|
||||
): BasicMatchResult | null {
|
||||
const searchLines = searchContent.split("\n");
|
||||
const fileLines = fileContent.split("\n");
|
||||
|
|
@ -296,7 +296,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
|
|||
*/
|
||||
export function findSearchMatch(
|
||||
fileContent: string,
|
||||
searchContent: string
|
||||
searchContent: string,
|
||||
): SearchMatchResult | null {
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
|
|||
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`Search content not found in block ${i + 1}:\n${searchContent}`
|
||||
`Search content not found in block ${i + 1}:\n${searchContent}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -162,7 +162,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
|
|||
// Get lines for telemetry
|
||||
const { added, removed } = calculateLinesOfCodeDiff(
|
||||
args.oldContent,
|
||||
args.newContent
|
||||
args.newContent,
|
||||
);
|
||||
const language = getLanguageFromFilePath(args.filepath);
|
||||
|
||||
|
|
@ -173,7 +173,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
|
|||
telemetryService.recordLinesOfCodeModified(
|
||||
"removed",
|
||||
removed,
|
||||
language
|
||||
language,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -183,7 +183,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
|
|||
throw new Error(
|
||||
`Error: failed to edit ${args.filepath}:\n ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue