Add 'extensions/cli/' from commit 'e27a5c87d520e28844c9eac10bc6d301feee4b5e'

git-subtree-dir: extensions/cli
git-subtree-mainline: 1674c2aff1
git-subtree-split: e27a5c87d5
This commit is contained in:
Nate 2025-08-20 17:19:56 -07:00
commit be45ab63ca
352 changed files with 69223 additions and 0 deletions

View file

@ -0,0 +1,12 @@
name: CLI Agent
version: 0.0.1
schema: v1
models:
- uses: anthropic/claude-3-7-sonnet
with:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
mcpServers:
- uses: repomix/repomix-mcp
- uses: anthropic/memory-mcp

View file

@ -0,0 +1,36 @@
name: Continue SDK CLI and Hub Context
version: 0.0.1
schema: v1
rules:
- name: Continue SDK CLI and Hub Context
rule: >-
This repository is a CLI for the Continue SDK, which provides programmatic
access to Continue's APIs.
Key components:
- Continue SDK: Experimental package in early development, subject to
breaking changes
- Continue Hub: Registry for custom AI code agent
- Hub functionality: Manages agent building blocks (models, rules,
context providers, prompts, docs, etc.)
- Governance: Allows central configuration for organizations
Important libraries:
- WorkOS: Handles authentication flows
- Model Context Protocol (MCP): Manages MCP server interactions
- readline-sync: Provides synchronous CLI user interactions
- Vitest: Used for testing framework
All code should follow established patterns for a Node.js CLI tool
interfacing with this experimental SDK.

View file

@ -0,0 +1,7 @@
# Continue API settings
# API base URL - defaults to https://api.continue.dev/ if not specified
CONTINUE_API_BASE=http://localhost:3001
# Continue API key
# This is required for authentication with the Continue API
CONTINUE_API_KEY=

1
extensions/cli/.github/CODEOWNERS vendored Normal file
View file

@ -0,0 +1 @@
* @continuedev/continue-code-reviewers

View file

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

View file

@ -0,0 +1,25 @@
name: Continue Detailed Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
detailed-code-review:
name: Continue Detailed Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@5361d5e33b880add1d3d050eeadd01971434fb75
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev
continue-config: continuedev/review-bot

View file

@ -0,0 +1,25 @@
name: Continue General Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-code-review:
name: Continue General Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@5361d5e33b880add1d3d050eeadd01971434fb75
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
continue-config: "continuedev/review-bot"

View file

@ -0,0 +1,204 @@
name: PR Description Generator
on:
pull_request:
types: [opened, reopened]
issue_comment:
types: [created]
permissions:
contents: read
issues: write
pull-requests: write
jobs:
generate-description:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI
run: npm install -g @continuedev/cli
- name: Prepare PR Analysis Files
run: |
# Save changed files list to file
git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > changed_files.txt
# Create a summarized diff file (limit to 10k lines to avoid size issues)
git diff ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} | head -n 1000 > pr_diff.txt
# Create a prompt file that we'll use with continue-cli
cat > prompt.txt << EOL
Analyze this PR and come up with a concise description for the changes.
Do not use any tools, just analyze the provided files and the diff.
Do not write any preamble, just immediately start with the description.
The PR includes these files:
$(cat changed_files.txt)
Here are the changes (first 10k lines):
$(cat pr_diff.txt)
EOL
- name: Analyze PR with Continue
id: analyze
run: |
continue-cli -p --config "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt
echo "analysis_file=analysis.txt" >> $GITHUB_OUTPUT
env:
## TODO: This needs to be set on the repo
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
- name: Add PR Comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const analysisText = fs.readFileSync('analysis.txt', 'utf8');
const comment = `## 🤖 Suggested PR Description
${analysisText}
---
To use this as your PR description, reply with a comment containing just: \`/apply-description\``;
const { data: newComment } = await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: comment
});
update-description:
runs-on: ubuntu-latest
if: |
github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
github.event.comment.body == '/apply-description'
steps:
- name: React to Comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// Add eyes reaction to show we're processing
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'eyes'
});
- name: Find Bot Comment
id: find_comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
const botComment = comments
.reverse()
.find(comment => comment.body.includes('🤖 Suggested PR Description'));
if (botComment) {
core.setOutput('comment_body', botComment.body);
return true;
}
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: '-1' // thumbs down
});
core.setFailed('No bot comment found');
return false;
- name: Update PR Description
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const commentBody = process.env.COMMENT_BODY;
console.log('Processing comment body:', commentBody);
// Extract the description part (between the header and footer)
const descriptionMatch = commentBody.match(/## 🤖 Suggested PR Description\s+([\s\S]*?)\s+---/);
if (descriptionMatch && descriptionMatch[1]) {
const newDescription = descriptionMatch[1].trim();
console.log('Extracted description:', newDescription);
// Update PR description
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: newDescription
});
// Add a confirmation reply
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `✅ PR description has been updated with the suggested text.`
});
} else {
core.setFailed('Failed to extract description from comment');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `❌ Error: Could not extract the description from the original comment.`
});
}
env:
COMMENT_BODY: ${{ steps.find_comment.outputs.comment_body }}
- name: Final Reaction
if: success()
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// Remove eyes reaction
const { data: reactions } = await github.rest.reactions.listForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id
});
const eyesReaction = reactions.find(r => r.content === 'eyes');
if (eyesReaction) {
await github.rest.reactions.deleteForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
reaction_id: eyesReaction.id
});
}
// Add success reaction
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: '+1' // thumbs up
});

View file

@ -0,0 +1,104 @@
name: CI
on:
pull_request:
branches: [main]
permissions:
contents: read
pull-requests: write
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: Debug environment info
run: |
echo "Node.js version: $(node --version)"
echo "npm version: $(npm --version)"
echo "Prettier version: $(npx prettier --version)"
echo "Platform: $(uname -a)"
- name: Check code formatting
run: npm run format:check
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
# e2e tests are failing on Windows specifically - likely due to stdout flush issues
- name: Run tests
if: matrix.os != 'windows-latest'
run: npm test
- name: Run tests (excluding e2e on Windows)
if: matrix.os == 'windows-latest'
shell: bash
run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
# This action at least lets us manage the list of required tests via source control
# so that creators of new jobs can add them to this list
require-all-checks-to-pass:
if: always()
runs-on: ubuntu-latest
needs:
- lint
- format-check
- test
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
jobs: ${{ toJSON(needs) }}

View file

@ -0,0 +1,111 @@
name: Legacy Release (Deprecated)
on:
# schedule:
# # Run every day at 9am UTC
# - cron: "0 9 * * *"
workflow_dispatch:
# Keep manual triggering for emergencies
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Install dependencies
run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# - name: Check beta version age
# run: |
# echo "Checking if any beta versions are less than 7 days old..."
# # Get all beta versions from npm
# BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' 2>/dev/null || echo "[]")
# if [ "$BETA_VERSIONS" = "[]" ] || [ -z "$BETA_VERSIONS" ]; then
# echo "No beta versions found, proceeding with release"
# exit 0
# fi
# # Current date in seconds since epoch
# CURRENT_DATE=$(date +%s)
# SEVEN_DAYS_AGO=$((CURRENT_DATE - 7 * 24 * 60 * 60))
# # Check each beta version
# echo "$BETA_VERSIONS" | while read -r version; do
# if [ -z "$version" ]; then
# continue
# fi
# echo "Checking version: $version"
# # Extract date from beta version (format: X.Y.Z-beta.YYYYMMDD or X.Y.Z-beta.YYYYMMDD.HHMM)
# DATE_PART=$(echo "$version" | sed -n 's/.*-beta\.\([0-9]\{8\}\).*/\1/p')
# if [ -z "$DATE_PART" ]; then
# echo "Could not extract date from version $version, skipping"
# continue
# fi
# # Convert YYYYMMDD to epoch seconds (assuming midnight UTC)
# YEAR=${DATE_PART:0:4}
# MONTH=${DATE_PART:4:2}
# DAY=${DATE_PART:6:2}
# # Validate date components
# if [ ${#YEAR} -ne 4 ] || [ ${#MONTH} -ne 2 ] || [ ${#DAY} -ne 2 ]; then
# echo "Invalid date format in version $version, skipping"
# continue
# fi
# # Convert to epoch seconds
# VERSION_DATE=$(date -d "${YEAR}-${MONTH}-${DAY}" +%s 2>/dev/null || continue)
# echo "Version $version date: ${YEAR}-${MONTH}-${DAY} (${VERSION_DATE})"
# echo "Seven days ago: $(date -d @${SEVEN_DAYS_AGO} '+%Y-%m-%d') (${SEVEN_DAYS_AGO})"
# # Check if beta version is less than 7 days old
# if [ "$VERSION_DATE" -gt "$SEVEN_DAYS_AGO" ]; then
# echo "❌ ERROR: Beta version $version was created on ${YEAR}-${MONTH}-${DAY}, which is less than 7 days ago."
# echo "Cannot create a stable release until at least 7 days have passed since the latest beta."
# echo "Please wait until $(date -d @$((VERSION_DATE + 7 * 24 * 60 * 60)) '+%Y-%m-%d') before creating a stable release."
# exit 1
# else
# echo "✅ Beta version $version is older than 7 days (created ${YEAR}-${MONTH}-${DAY})"
# fi
# done
# echo "All beta versions are at least 7 days old, proceeding with release"
- name: Install semantic-release and plugins
run: npm install -D semantic-release @semantic-release/changelog @semantic-release/git @semantic-release/github @semantic-release/npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Semantic Release
id: semantic
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release

View file

@ -0,0 +1,215 @@
name: Respond to @continuedev Comments
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
respond-to-comment:
# Only run on pull request comments
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v7
with:
script: |
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
core.setOutput('head_ref', pr.head.ref);
core.setOutput('head_sha', pr.head.sha);
return pr;
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
git checkout ${{ steps.pr-info.outputs.head_ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create the prompt for remote session
PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
${{ github.event.comment.body }}
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
# Start remote session and capture JSON output
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Original comment: ${{ github.event.comment.body }}"
respond-to-review-comment:
# Only run on pull request review comments
if: github.event_name == 'pull_request_review_comment'
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
echo "PROMPT content:"
cat /tmp/prompt.txt
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
const commentParams = {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: ${{ github.event.pull_request.number }},
body: commentBody,
commit_id: '${{ github.event.pull_request.head.sha }}',
path: '${{ github.event.comment.path }}',
in_reply_to: ${{ github.event.comment.id }}
};
await github.rest.pulls.createReviewComment(commentParams);
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
echo "Original comment: ${{ github.event.comment.body }}"

View file

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

13
extensions/cli/.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
node_modules
dist
.env
/*-repomix.xml
chat.log
*notes.md
# Local config files (users should not commit their personal configs)
config.yaml
.continue-debug/

12
extensions/cli/.npmignore Normal file
View file

@ -0,0 +1,12 @@
.env*
test
.vscode
.github
.continue
.releaserc.json
AGENTS.md
vitest.config.ts
tsconfig.json
tsconfig.build.json
TESTING_STRATEGY.md
.env.example

1
extensions/cli/.nvmrc Normal file
View file

@ -0,0 +1 @@
v20.11.0

View file

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

View file

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

View file

@ -0,0 +1,38 @@
{
"branches": ["main"],
"plugins": [
[
"@semantic-release/commit-analyzer",
{
"releaseRules": [
{ "type": "feat", "release": "patch" },
{ "type": "fix", "release": "patch" },
{ "type": "perf", "release": "patch" },
{ "type": "revert", "release": "patch" },
{ "type": "docs", "release": false },
{ "type": "style", "release": false },
{ "type": "chore", "release": false },
{ "type": "refactor", "release": false },
{ "type": "test", "release": false },
{ "type": "build", "release": false },
{ "type": "ci", "release": false }
]
}
],
"@semantic-release/release-notes-generator",
[
"@semantic-release/changelog",
{
"changelogFile": "CHANGELOG.md"
}
],
[
"@semantic-release/npm",
{
"npmPublish": true,
"pkgRoot": "."
}
],
"@semantic-release/github"
]
}

46
extensions/cli/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,46 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CLI",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"args": [],
"env": {
"NODE_ENV": "development"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"runtimeArgs": ["--loader", "ts-node/esm"],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "watch-logs"
},
{
"name": "Debug Tests",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/.bin/vitest",
"args": ["--run", "--no-cache"],
"env": {
"NODE_ENV": "test"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
]
}
]
}

56
extensions/cli/.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,56 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "build",
"group": "build",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": ["$tsc"]
},
{
"type": "npm",
"script": "test",
"group": "test",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
}
},
{
"label": "watch-logs",
"type": "shell",
"command": "npm run watch:logs",
"isBackground": true,
"problemMatcher": {
"pattern": {
"regexp": "^$",
"file": 1,
"location": 2,
"message": 3
},
"background": {
"activeOnStart": true,
"beginsPattern": "^.*$",
"endsPattern": "^.*$"
}
},
"presentation": {
"reveal": "always",
"panel": "new",
"focus": false
}
}
]
}

75
extensions/cli/AGENTS.md Normal file
View file

@ -0,0 +1,75 @@
# AGENTS.md
This file provides guidance to AI coding agents when working with code in this repository.
## Development Commands
- **Build**: `npm run build` - Compiles TypeScript to JavaScript in dist/
- **Test**: `npm test` - Runs Vitest tests with ESM support
- **Type Check**: `npm run lint` - Runs TypeScript compiler without emitting files for type checking
- **Format**: `npm run format` - Runs Prettier with --write flag to check + fix formatting
- **Start**: `npm start` - Runs the built CLI from dist/index.js
- **Development**: After building, test locally with `node dist/index.js`
## Architecture Overview
This is a CLI tool for Continue Dev that provides an interactive AI-assisted development experience. The architecture consists of:
### 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
- Diff viewing
- Exit tool (headless mode only)
6. **MCP Integration** (`src/mcp.ts`): Model Context Protocol service for extended tool capabilities
### Key Features
- **Streaming Responses**: Real-time AI response streaming (`streamChatResponse.ts`)
- **Slash Commands**: Built-in commands like `/help`, `/exit` (`slashCommands.ts`)
- **Multi-mode Operation**: Supports TUI, headless, and standard chat modes
- **Tool Integration**: Extensible tool system for development tasks
### Testing Setup
- Uses Vitest with TypeScript and ESM support
- Configuration in `vitest.config.ts`
- Tests should be written with `.test.ts` extension
- No existing test files found - tests should be added when writing new functionality
- Run tests using `npm run test path/or/pattern`
### Build System
- TypeScript compilation with declaration files
- ESNext target with NodeNext module resolution
- Outputs to `dist/` directory
- Source maps and inline sources enabled
- JSX support for React components
- Relative import paths require explicit file extensions, e.g. 'from "./test.js"' instead of 'from "./test"'
### Important rules
- Whenever you create / update a test, you should run the test to be certain that it passes
- If you ever create a PR, you should be sure to check the formatting and linting first with `npm run format` and `npm run lint` / `npm run lint:fix`.

134
extensions/cli/CHANGELOG.md Normal file
View file

@ -0,0 +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))
## [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))
# [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))
## [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))
## [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))
## [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))
## [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))
## [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))
## [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))
# [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))
# [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))
### 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))
# [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))
### Features
- 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))
# 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))
### 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))

201
extensions/cli/LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Continue Dev, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

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

60
extensions/cli/README.md Normal file
View file

@ -0,0 +1,60 @@
# Continue CLI
The Continue CLI (`cn`) is a customizable command line coding agent.
![Continue CLI Demo](./media/demo.gif)
## Installation
```bash
npm i -g @continuedev/cli
```
## Usage
```bash
cn
```
### Headless Mode
```bash
cn -p "Generate a conventional commit name for the current git changes."
```
### Session Management
The CLI automatically saves your chat history for each terminal session. You can resume where you left off:
```bash
# Resume the last session in this terminal
cn --resume
# List recent sessions and choose one to resume
cn ls
# List sessions in JSON format (for scripting)
cn ls --json
```
## Command Line Options
- `-p`: Run in headless mode (no TUI)
- `--config <path>`: Specify agent configuration path
- `--resume`: Resume the last session for this terminal
- `<prompt>`: Optional prompt to start with
## Commands
- `cn`: Start an interactive chat session
- `cn ls`: List recent sessions with TUI selector to choose one to resume
- `cn login`: Authenticate with Continue
- `cn logout`: Sign out of current session
- `cn remote`: Launch a remote instance
- `cn serve`: Start HTTP server mode
### Session Listing (`cn ls`)
Shows recent sessions, limited by screen height to ensure it fits on your terminal.
- `--json`: Output in JSON format for scripting (always shows 10 sessions)

View file

@ -0,0 +1,254 @@
# Reactive Service Architecture Refactoring Plan
## Problem Statement
The current codebase has tightly coupled dependencies (config, apiClient, MCP service, model, etc.) that require full reloads when any component changes. This causes:
1. **Slow startup**: TUI can't start until all components are loaded
2. **Poor UX**: Slash commands like `/config` trigger complete restarts
3. **Tight coupling**: Can't change individual components without reloading everything
4. **Blocking initialization**: All dependencies must load before anything works
## Solution Overview
Implement a **Reactive Service Architecture** using:
- Custom ServiceContainer with Node.js EventEmitter
- React hooks for service consumption
- Progressive loading and error handling
- Independent service lifecycle management
## Current Architecture Analysis
### Key Components to Refactor
- **Config Management** (`src/config.ts`, `src/onboarding.ts`)
- **Authentication** (`src/auth/workos.ts`)
- **LLM/Model handling** (`src/config.ts` - `initializeLlmApi()`)
- **MCP Service** (`src/mcp.ts`)
- **API Client** (`src/CLIPlatformClient.ts`)
### Current Initialization Flow
```
chat() -> initializeChat() -> initializeWithOnboarding() -> initialize()
-> Returns: { config, llmApi, model, mcpService, apiClient }
-> startTUIChat() with all dependencies
```
### Current Problem Areas
- `src/commands/chat.ts` - `initializeChat()` loads everything synchronously
- `src/ui/index.ts` - `startTUIChat()` requires all deps upfront
- `src/slashCommands.ts` - `/config`, `/login` trigger full reloads via `onReload()`
- `src/ui/TUIChat.tsx` - Assumes all services are available at startup
## Implementation Strategy
### Phase 1: Extract Current Initialization into Services ✅ COMPLETE
Create the service infrastructure and extract existing initialization logic.
#### 1.1 Create Service Infrastructure
- [x] Create `src/services/ServiceContainer.ts` - Core service management
- [x] Create `src/hooks/useService.ts` - React hook for service consumption
- [x] Create `src/services/types.ts` - Service-related TypeScript types
#### 1.2 Create Individual Services
- [x] Create `src/services/AuthService.ts` - Extract auth logic from `src/auth/workos.ts`
- [x] Create `src/services/ConfigService.ts` - Extract config logic from `src/config.ts`
- [x] Create `src/services/ModelService.ts` - Extract model initialization
- [x] Create `src/services/MCPServiceWrapper.ts` - Extract MCP logic from `src/mcp.ts`
- [x] Create `src/services/ApiClientService.ts` - Extract API client management
#### 1.3 Create Service Registry
- [x] Create `src/services/index.ts` - Central service registry and initialization
- [x] Add service dependency management (e.g., ModelService depends on ConfigService)
### Phase 2: Make TUI Reactive to Service Changes ✅ COMPLETE
Update the TUI to consume services reactively instead of requiring all deps upfront.
#### 2.1 Update TUI Components
- [x] Update `src/ui/TUIChat.tsx` - Use `useService` hooks instead of props
- [x] Add loading states for individual services
- [x] Add error boundaries for service failures
- [x] Remove service props from component interface
#### 2.2 Update TUI Entry Point
- [x] Update `src/ui/index.ts` - Remove dependency injection, just start TUI
- [x] Update `src/commands/chat.ts` - Start TUI immediately, services load async
#### 2.3 Handle Service Dependencies in UI
- [x] Show progressive loading (e.g., "Config loaded, loading model...")
- [x] Handle missing services gracefully
- [x] Allow partial functionality when some services unavailable
### Phase 3: Update Slash Commands to Use Services ✅ COMPLETE
Make slash commands reactive by updating services instead of triggering reloads.
#### 3.1 Update Slash Command Handlers
- [x] Update `src/slashCommands.ts` - Remove `onReload` callback pattern
- [x] Update `/login` command to use AuthService.login()
- [x] Update `/logout` command to use AuthService.logout()
- [x] ~~Add `/org` command to use AuthService.switchOrg()~~ **Merged into `/config` command**
- [x] Update `/config` command (handled via ConfigSelector UI)
#### 3.2 Remove Reload Mechanisms
- [x] Remove `onReload` callbacks from TUIChat
- [x] Remove full restart logic from slash commands
- [x] Services now auto-propagate changes to UI
### Phase 4: Add Progressive Loading and Better Error Handling ✅ FUTURE
Enhance the user experience with better loading states and error recovery.
#### 4.1 Enhanced Loading States
- [ ] Add service loading indicators in TUI
- [ ] Show which services are loading/ready
- [ ] Allow using available functionality while other services load
#### 4.2 Error Handling and Recovery
- [ ] Add retry mechanisms for failed service initialization
- [ ] Add service health monitoring
- [ ] Graceful degradation when services fail
- [ ] Better error messages for specific service failures
#### 4.3 Performance Optimizations
- [ ] Lazy load services only when needed
- [ ] Cache service results appropriately
- [ ] Debounce rapid service changes
## File Changes Required
### New Files
- [x] `src/services/ServiceContainer.ts`
- [x] `src/services/types.ts`
- [x] `src/services/AuthService.ts`
- [x] `src/services/ConfigService.ts`
- [x] `src/services/ModelService.ts`
- [x] `src/services/MCPServiceWrapper.ts`
- [x] `src/services/ApiClientService.ts`
- [x] `src/services/index.ts`
- [x] `src/hooks/useService.ts`
### Modified Files
- [x] `src/commands/chat.ts` - Remove synchronous initialization
- [x] `src/ui/index.ts` - Remove dependency injection
- [x] `src/ui/TUIChat.tsx` - Use service hooks instead of props
- [x] `src/slashCommands.ts` - Use services instead of reload callbacks
- [x] `src/ui/hooks/useChat.ts` - Remove onReload dependency
- [ ] `src/onboarding.ts` - Integrate with service architecture
### Files to Analyze for Extraction
- [x] `src/config.ts` - Extract initialization logic
- [x] `src/auth/workos.ts` - Extract auth management
- [x] `src/mcp.ts` - Extract MCP service logic
## Success Criteria
### Phase 1 Success ✅ COMPLETE
- [x] Services can be initialized independently
- [x] Existing functionality works through service layer
- [x] No breaking changes to current behavior
### Phase 2 Success ✅ COMPLETE
- [x] TUI starts immediately without waiting for all services
- [x] UI updates reactively when services load/change
- [x] Loading states provide clear user feedback
### Phase 3 Success ✅ COMPLETE
- [x] Slash commands work without full reloads
- [x] `/login` and `/logout` commands update UI instantly
- [x] ~~New `/org` command for organization switching~~ **Merged into `/config` command**
- [x] No more blocking reinitialization
### Phase 4 Success
- [ ] Better error handling for service failures
- [ ] Progressive enhancement - partial functionality available
- [ ] Improved startup performance
## Benefits Achieved
### ✅ Immediate Benefits
1. **Fast Startup**: TUI starts immediately, shows progressive loading
2. **Reactive Updates**: Services auto-propagate changes without reloads
3. **Better UX**: `/login`, `/logout`, `/config` commands work instantly
4. **Cleaner Architecture**: Clear separation of concerns between services
5. **Type Safety**: Full TypeScript support with proper service typing
### ✅ Technical Improvements
1. **Dependency Management**: Services declare dependencies explicitly
2. **Error Boundaries**: Service failures don't crash the entire app
3. **Memory Management**: Proper EventEmitter cleanup in React hooks
4. **Testability**: Services can be tested in isolation
5. **Maintainability**: Changes to one service don't require touching others
## Testing Strategy
### Unit Tests
- [ ] Test each service in isolation
- [ ] Test service dependencies and lifecycle
- [ ] Test React hooks with service changes
### Integration Tests
- [ ] Test service interactions
- [ ] Test UI updates with service changes
- [ ] Test slash command service updates
### E2E Tests
- [ ] Test full user flows with new architecture
- [ ] Test error recovery scenarios
- [ ] Test performance improvements
## Migration Strategy
1. **Backward Compatibility**: ✅ Existing functionality preserved
2. **Incremental Migration**: ✅ Each phase was deployable independently
3. **Rollback Plan**: ✅ Old patterns kept for headless mode
4. **Monitoring**: Added comprehensive logging for service lifecycle
## Risk Mitigation
### Technical Risks
- **Service dependency cycles**: ✅ Resolved with proper dependency injection
- **Memory leaks**: ✅ Proper EventEmitter cleanup implemented
- **Race conditions**: ✅ Used proper async/await patterns
### User Experience Risks
- **Broken functionality**: ✅ Extensive TypeScript checking at each phase
- **Performance regressions**: ✅ TUI starts faster, no blocking initialization
- **Confusing loading states**: ✅ Clear progressive loading indicators
## Notes
- ✅ **Phase 1-3 Complete**: Core reactive service architecture implemented
- ✅ **Major Benefits Realized**: Fast startup, reactive updates, better UX
- 🚀 **Ready for Production**: All TypeScript errors resolved, backward compatibility maintained
- 📈 **Future Improvements**: Phase 4 can be added incrementally for enhanced error handling and performance

49
extensions/cli/demo.md Normal file
View file

@ -0,0 +1,49 @@
# `cn` Demo
```bash
cn
```
```bash
cn --rule nate/spanish
```
```bash
cn --rule continuedev/sentry-nextjs
```
```bash
cn -p "generate a commit msg for the current git diff. your output should be ONLY the commit message, nothing else"
```
GitHub workflow
```bash
cn remote
```
Please add a new slash command "/init" sends the following message to the model: "please generate an "AGENT.md" file at the root of this repository that includes basic information necessary to work in and understand it. Should include install, build, lint, test, run instructions and other important know-how / practices.
Watch a few updates.
Copy the URL
```bash
cn remote --resume <URL>
```
Queue a message: make sure to title the file with "Important agent context"
Show the dashboard at https://hub.continue.dev/agents
Explain that behind the scenes we are just running `cn serve` by running it locally
```bash
cn serve
```
and then connecting with
```bash
cn remote --resume http://localhost:8000
```

View file

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

View file

@ -0,0 +1,186 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
import importPlugin from "eslint-plugin-import";
import unusedImports from "eslint-plugin-unused-imports";
export default [
{
files: ["**/*.ts", "**/*.tsx"],
plugins: {
"@typescript-eslint": tsPlugin,
import: importPlugin,
"unused-imports": unusedImports,
},
languageOptions: {
parser: tsParser,
parserOptions: {
project: "./tsconfig.json",
ecmaVersion: "latest",
sourceType: "module",
},
},
rules: {
// Core rules - all as errors
"max-classes-per-file": ["error", 1],
"prefer-const": "error",
// "class-methods-use-this": [
// "error",
// {
// exceptMethods: [
// "render",
// "shouldComponentUpdate",
// "componentDidMount",
// "componentDidUpdate",
// "componentWillUnmount",
// ],
// },
// ],
"no-negated-condition": "error",
"max-lines": [
"error",
{ max: 500, skipBlankLines: true, skipComments: true },
],
complexity: ["error", { max: 20 }],
// "max-lines-per-function": [
// "error",
// { max: 150, skipBlankLines: true, skipComments: true },
// ],
"max-statements": ["error", { max: 50 }],
"max-depth": ["error", { max: 4 }],
"max-nested-callbacks": ["error", { max: 3 }],
"max-params": ["error", { max: 5 }],
eqeqeq: "error",
// TypeScript specific rules
// "@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-explicit-any": "error",
// "@typescript-eslint/member-ordering": [
// "error",
// {
// default: [
// // Static fields
// "public-static-field",
// "protected-static-field",
// "private-static-field",
// // Instance fields
// "public-instance-field",
// "protected-instance-field",
// "private-instance-field",
// // Constructors
// "constructor",
// // Static methods
// "public-static-method",
// "protected-static-method",
// "private-static-method",
// // Instance methods
// "public-instance-method",
// "protected-instance-method",
// "private-instance-method",
// ],
// },
// ],
// Import rules
"import/order": [
"error",
{
groups: [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
],
"newlines-between": "always",
alphabetize: {
order: "asc",
caseInsensitive: true,
},
},
],
"import/no-default-export": "error",
// Unused code detection
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"error",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
},
],
// Turn off rules that might be too strict for CLI
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-non-null-assertion": "off",
// Allow console for CLI tool
"no-console": "off",
},
settings: {
"import/resolver": {
typescript: {
project: "./tsconfig.json",
},
node: true,
},
},
},
{
// Allow default exports in specific files
files: ["src/index.ts", "*.config.js", "*.config.ts"],
rules: {
"import/no-default-export": "off",
},
},
{
// Test files can have different rules
files: [
"**/*.test.ts",
"**/*.test.tsx",
"**/*.spec.ts",
"**/*.spec.tsx",
"**/test-helpers/**/*.ts",
"**/test-helpers/**/*.tsx",
"**/__tests__/**/*.ts",
"**/__tests__/**/*.tsx",
"**/__mocks__/**/*.ts",
"**/__mocks__/**/*.tsx",
],
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-floating-promises": "off",
"unused-imports/no-unused-vars": "off",
"max-classes-per-file": "off",
"max-lines": "off",
"max-lines-per-function": "off",
"max-statements": "off",
complexity: "off",
"class-methods-use-this": "off",
"max-nested-callbacks": "off",
},
},
{
ignores: [
"dist/**",
"node_modules/**",
"coverage/**",
"*.d.ts",
"src/__mocks__/**",
"vitest.config.ts",
"*.config.js",
"*.config.ts",
],
},
];

View file

@ -0,0 +1,23 @@
# Example permissions.yaml file
# This shows how you can configure tool permissions
# Tools that are automatically allowed without prompting
allow:
- 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
# Tools that are completely excluded (model won't know they exist)
exclude:
- Exit # or exit
# You can also use wildcards
# allow:
# - mcp__* # Allow all MCP tools
# exclude:
# - * # Exclude everything else

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

19580
extensions/cli/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

130
extensions/cli/package.json Normal file
View file

@ -0,0 +1,130 @@
{
"name": "@continuedev/cli",
"version": "0.0.0-dev",
"description": "Continue CLI",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"bin": {
"cn": "dist/index.js"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch",
"test:ui": "vitest --ui",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
"lint": "tsc --noEmit && eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit",
"watch:logs": "touch ~/.continue/logs/cn.log && tail -f ~/.continue/logs/cn.log",
"prepare": "npm run build",
"semantic-release": "semantic-release",
"semantic-release:dry-run": "semantic-release --dry-run"
},
"author": "Continue Dev, Inc.",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/cli.git"
},
"bugs": {
"url": "https://github.com/continuedev/continue/issues"
},
"homepage": "https://continue.dev",
"dependencies": {
"@continuedev/config-yaml": "^1.0.96",
"@continuedev/openai-adapters": "^1.4.1",
"@continuedev/sdk": "^0.0.13",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
"@opentelemetry/exporter-metrics-otlp-http": "^0.203.0",
"@opentelemetry/instrumentation-fs": "^0.23.0",
"@opentelemetry/instrumentation-http": "^0.203.0",
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@sentry/profiling-node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
"@workos-inc/node": "^7.45.0",
"chalk": "^5.4.1",
"commander": "^14.0.0",
"date-fns": "^4.1.0",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"glob": "^11.0.3",
"gpt-tokenizer": "^3.0.1",
"gradient-string": "^3.0.0",
"ignore-walk": "^7.0.0",
"ink": "^6.1.0",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"shell-quote": "^1.8.3",
"swr": "^2.3.4",
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uuid": "^9.0.1",
"winston": "^3.17.0",
"yaml": "^2.8.0"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
"@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"conventional-changelog-conventionalcommits": "^9.1.0",
"cross-env": "^7.0.3",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"happy-dom": "^18.0.1",
"ink-testing-library": "^4.0.0",
"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",
"tsx": "^4.20.3",
"vitest": "^3.2.4"
},
"engine": {
"node": ">=18"
}
}

View file

@ -0,0 +1,189 @@
# Configuration Loading Behavior Specification
## Overview
This document specifies the behavior of the CLI's configuration loading system, including precedence rules, authentication interactions, and error handling.
## Authentication Precedence
**Authentication Source Priority:**
1. **Environment Variable**: `CONTINUE_API_KEY` environment variable
2. **File-Based Auth**: `~/.continue/auth.json` file
3. **No Authentication**: Unauthenticated mode
**Authentication Effects:**
- **Environment Auth**: Always uses personal organization, no config URI persistence
- **File Auth**: Supports organizations, persists config URIs, token refresh
- **No Auth**: Limited to default assistant, no personalization
## Configuration Source Precedence
**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
3. **Default Resolution** (if no flag and no saved URI)
- **Authenticated**: First user assistant from `listAssistants()`
- **config.yaml**: The saved config file at `~/.continue/config.yaml`
- **Unauthenticated**: Falls back to `continuedev/default-agent`
## Authentication State Interactions
### Authenticated Users
**Available Options:**
- Personal assistants
- Organization assistants (if organization selected)
- Local YAML files
- Public assistants
**Behavior:**
- `listAssistants()` returns personalized results
- Config selections are saved as URIs in auth config
- Organization context affects available assistants
### Unauthenticated Users
**Available Options:**
- Local YAML files only
- Default assistant (`continuedev/default-agent`)
**Behavior:**
- No access to personal or organization assistants
- No config URI persistence
- Direct fallback to default when no config specified
### Environment Variable Auth (`CONTINUE_API_KEY`)
**Behavior:**
- Treated as authenticated for API access
- Always uses personal organization context
- No persistence of config URIs
- Cannot switch organizations
## Organization Context
**Organization Selection:**
- **Interactive Mode**: Auto-selects first available organization
- **Headless Mode**: Defaults to personal organization
- **Environment Auth**: Always personal organization
**Effects on Config Loading:**
- Organization ID passed to all API calls
- Affects which assistants appear in `listAssistants()`
- Organization changes trigger complete config reload
## Error Handling Behavior
### Config Loading Errors
**File Not Found:**
- Local file specified but doesn't exist
- **Result**: Error thrown, CLI exits
**Invalid YAML:**
- Local file exists but has syntax errors
- **Result**: Parsing error thrown, CLI exits
**Network Failures:**
- API calls fail for assistant slugs
- **Result**: Network error bubbled up, CLI exits
**Assistant Not Found:**
- Valid slug format but assistant doesn't exist
- **Result**: 404 error from API, CLI exits
### Fallback Scenarios
**No User Assistants:**
- Authenticated user has no personal assistants
- **Result**: Falls back to `continuedev/default-agent`
**Default Agent Unavailable:**
- Fallback to default agent fails
- **Result**: Error thrown, CLI cannot start
**Token Expired:**
- Saved auth token is expired
- **Result**: Automatic refresh attempted, re-auth required if refresh fails
## Config URI Persistence
**When URIs are Saved:**
- Any successful config load via service layer
- File paths converted to `file://path/to/config.yaml`
- Assistant slugs converted to `slug://owner/package`
**When URIs are NOT Saved:**
- Environment variable authentication in use
- Config loading failures
- Unauthenticated sessions
## Rule Integration
**Rule Processing:**
- `--rule` flags processed independently of config loading
- Multiple rules supported, injected into system message
- Rule failures are warnings, don't prevent config loading
- Rule sources: file paths, hub slugs, direct strings
## Session Continuity
**Next Session Behavior:**
- **With Saved URI**: Uses saved config automatically
- **CLI Override**: `--config` flag overrides saved URI and updates it
- **Config Switching**: UI actions update saved URI for future sessions
**Cross-Session State:**
- Authentication persists until logout
- Organization selection persists
- Config URI persists (except for environment auth)
## Complete Decision Flow
```
1. Parse CLI arguments
2. Load authentication state (env var > file > none)
3. Determine config source:
- CLI --config flag provided? Use it
- Saved config URI exists? Use it
- Default resolution based on auth state
4. Load configuration:
- File path? Parse YAML locally
- Assistant slug? Fetch from API
- Default resolution? List assistants or use default
5. Process and inject rules
6. Save config URI (if authenticated via file)
7. Initialize services with loaded config
```
This behavior ensures users get predictable config loading with clear precedence rules while maintaining session continuity and graceful fallbacks.

View file

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

View file

@ -0,0 +1,44 @@
# Continue CLI Model Context Protocol (MCP) integration
## Intro
Model Context Protocol is a protocol for giving models access to resources and tools. MCP servers can run locally (stdio) or be remote (http/streamable/etc). See https://modelcontextprotocol.io/specification. The Continue CLI uses MCP to extend model's capabilities with MCP prompts and tools. MCP server configurations are stored in the `mcpServers` field of an assistant/config.yaml configuration.
## MCP Service
The CLI has an MCP Service should manage connections to MCP servers and provide state to the terminal app regarding MCP server connections.
Service initialization for MCP servers can take especially long, so it should not block service initialization. Instead, initialization should kick off server connections and then resolve.
All configured server connections can be initialized simultaneously using Promise.all
Each server configuration should have its own connection and state separated, but the service should also have an easy way to retrieve all tools and prompts from all servers to pass to the model.
Servers should have a status "idle", "connecting", "connected", or "error". Only "connected" servers contribute prompts and tools.
If a server successfully connects but there is an error retrieving prompts or tools, it should have an array of warning messages that can be accessed in the terminal app.
When the process exits, all servers should be shut down and disconnected.
Only MCP servers for the CURRENT config should be loaded
- Logs from MCP servers should be routed through the winston logger, not the standard console.log (since this is a terminal app)
## MCP slash command
Users can manage MCP connections using the /mcp slash command.
/mcp shows a menu with the following options
- "No servers" if there are no servers
- Restart all servers
- Stop all servers
- View servers
- Back (esc also goes back)
View servers should open a submenu that has each server name with its status icon
- red if error, yellow if warnings, green if connected, gray if idle
- "No Servers" if there are none
- Back (esc also goes back)
Finally, selecting a server opens a sub-submenu that keeps the name/icon as header and lists
- Back (esc also goes back)
- Restart server
- Stop server
- warnings the server currently has
- prompts the server contributes
- tools the server contributes

View file

@ -0,0 +1,84 @@
# Modes
Modes are a system for managing tool permissions in the CLI. They can be set via command-line flags at startup or switched dynamically during chat sessions. The following modes are available:
## 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)
- **Current directory:** Visible in status bar for context
- **Permission behavior:** Uses existing permission policies as configured
- **Backward compatibility:** Existing configurations work unchanged
### `plan`
Planning mode that **completely overrides all user permissions** to enforce read-only access with command execution. This mode prevents file modifications but allows command execution for analysis, regardless of user configuration.
- **Command-line flag:** `--readonly` (for backward compatibility)
- **UI Indicator:** `[plan]` shown in blue
- **Current directory:** Hidden to save space and focus on analysis
- **Permission override:** **Absolute** - excludes write tools (Write, Edit, etc.) and allows read tools (Read, Grep, LS, etc.) and Bash for command execution
- **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)
- **UI Indicator:** `[auto]` shown in green
- **Current directory:** Hidden to save space and focus on automation
- **Permission override:** **Absolute** - allows all tools with `*: allow` policy
- **User config ignored:** Any user `--exclude` flags are overridden - everything is allowed
## 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
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)
- **Keyboard shortcuts**: Shift+Tab cycles through modes instantly
- **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`
3. Default tool policies
### Mode-Specific Behaviors
- **normal**: No mode policies applied, uses existing user configuration; shows current directory
- **plan**: **Absolute override** - excludes write tools (Write, Edit), allows read tools (Read, Grep, LS) and Bash; hides current directory
- **auto**: **Absolute override** - allows all tools with `*: allow` policy; hides current directory

View file

@ -0,0 +1,35 @@
# Onboarding
When a user first runs `cn` in interactive mode, they will be taken through "onboarding". After they have completed onboarding once, they will follow a normal config loading flow.
## Onboarding flow
**The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.**
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
```yaml
name: Local Config
version: 1.0.0
schema: v1
models:
- uses: anthropic/claude-4-sonnet
with:
ANTHROPIC_API_KEY: <THEIR_ANTHROPIC_API_KEY>
```
When something in the onboarding flow is done automatically, we should tell the user what happened.
## Normal flow
**The normal flow runs when the user has already completed onboarding.**
1. If the --config flag is provided, load this config
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

View file

@ -0,0 +1,342 @@
# OTLP Metrics Specification for Continue CLI
This document specifies the OpenTelemetry Protocol (OTLP) metrics that should be emitted by the Continue CLI to provide comprehensive observability and usage monitoring. The metrics are designed to be compatible with Claude Code dashboards for easy migration.
## Overview
The Continue CLI should emit metrics that provide insights into:
- Usage patterns and session analytics
- Performance and reliability
- Tool usage and effectiveness
- Error rates and types
- Resource utilization
- Code modification tracking
## Configuration
### Environment Variables
| Environment Variable | Description | Example Values |
| ------------------------------- | --------------------------------------------------------- | ------------------------------------ |
| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |
| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |
| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |
| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
### Metrics Cardinality Control
| Environment Variable | Description | Default Value | Example to Disable |
| ----------------------------------- | ---------------------------------------------- | ------------- | ------------------ |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |
| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |
| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account_uuid attribute in metrics | `true` | `false` |
## Standard Attributes
All metrics and events share these standard attributes:
| Attribute | Description | Controlled By |
| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |
| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
| `app.version` | Current Continue CLI version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
| `organization.id` | Organization UUID (when authenticated) | Always included when available |
| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
## Core Metrics
### ✅ `continue.cli.session.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of CLI sessions started
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in `src/commands/chat.ts` when session starts
---
### ✅ `continue.cli.lines_of_code.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of lines of code modified
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"added"`, `"removed"`)
**Implementation:** Track in `src/tools/writeFile.ts` by analyzing file diffs
---
### ✅ `continue.cli.pull_request.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of pull requests created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes git/gh commands for PR creation
---
### ✅ `continue.cli.commit.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of git commits created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes `git commit` commands
---
### ✅ `continue.cli.cost.usage`
**Type:** Counter
**Unit:** `USD`
**Description:** Cost of the Continue CLI session
**Attributes:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Calculate costs based on token usage and model pricing in `src/streamChatResponse.ts`
---
### ✅ `continue.cli.token.usage`
**Type:** Counter
**Unit:** `tokens`
**Description:** Number of tokens used
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Track in `src/streamChatResponse.ts` after each API response
---
### ❌ `continue.cli.code_edit_tool.decision`
**Type:** Counter
**Unit:** `count`
**Description:** Count of code editing tool permission decisions
**Attributes:**
- All [standard attributes](#standard-attributes)
- `tool`: Tool name (`"writeFile"`, `"runTerminalCommand"`, etc.)
- `decision`: User decision (`"accept"`, `"reject"`)
- `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
**Implementation:** Track in tool execution when user confirmation is required (if implemented)
---
### ✅ `continue.cli.active_time.total`
**Type:** Counter
**Unit:** `s`
**Description:** Total active time in seconds
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in TUI mode (`src/ui/TUIChat.tsx`) and standard chat mode, measuring time during active interactions
## Core Events
### ✅ User Prompt Event
**Event Name:** `continue.cli.user_prompt`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"user_prompt"`
- `event.timestamp`: ISO 8601 timestamp
- `prompt_length`: Length of the prompt
- `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)
**Implementation:** Log in `src/streamChatResponse.ts` when user message is added to chat history
---
### ✅ Tool Result Event
**Event Name:** `continue.cli.tool_result`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"tool_result"`
- `event.timestamp`: ISO 8601 timestamp
- `tool_name`: Name of the tool
- `success`: `"true"` or `"false"`
- `duration_ms`: Execution time in milliseconds
- `error`: Error message (if failed)
- `decision`: Either `"accept"` or `"reject"` (if applicable)
- `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` (if applicable)
- `tool_parameters`: JSON string containing tool-specific parameters (when available)
**Implementation:** Log in `src/tools/index.ts` `executeToolCall` function
---
### ✅ API Request Event
**Event Name:** `continue.cli.api_request`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"api_request"`
- `event.timestamp`: ISO 8601 timestamp
- `model`: Model identifier
- `duration_ms`: Request duration in milliseconds
- `success`: `"true"` or `"false"`
- `error`: Error message (if failed)
- `input_tokens`: Number of input tokens
- `output_tokens`: Number of output tokens
- `cost_usd`: Request cost in USD
**Implementation:** Log in `src/streamChatResponse.ts` for each API request
## Additional Metrics
These metrics are unique to Continue CLI and provide additional insights without conflicting with compatibility:
### Authentication Metrics
#### ✅ `continue.cli.auth.attempts`
**Type:** Counter
**Unit:** `{attempt}`
**Description:** Authentication attempts
**Labels:**
- All [standard attributes](#standard-attributes)
- `result`: `success` | `failure` | `cancelled`
- `method`: `workos` | `token`
**Implementation:** Track in `src/auth/workos.ts`
### MCP Integration Metrics
#### ❌ `continue.cli.mcp.connections`
**Type:** Gauge
**Unit:** `{connection}`
**Description:** Active MCP connections
**Labels:**
- All [standard attributes](#standard-attributes)
- `server_name`: MCP server identifier
- `status`: `connected` | `disconnected` | `error`
**Implementation:** Track in `src/mcp.ts`
### Performance Metrics
#### ❌ `continue.cli.startup.time`
**Type:** Histogram
**Unit:** `ms`
**Description:** Time from CLI start to ready state
**Labels:**
- All [standard attributes](#standard-attributes)
- `mode`: `tui` | `headless` | `standard`
- `cold_start`: `true` | `false`
**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts`
#### ✅ `continue.cli.response_time`
**Type:** Histogram
**Unit:** `ms`
**Description:** LLM response time metrics (supplements API request events)
**Labels:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier
- `metric_type`: `time_to_first_token` | `total_response_time`
- `has_tools`: `true` | `false`
**Implementation:** Track in `src/streamChatResponse.ts`
## Implementation Guidelines
### Migration from Claude Code Dashboards
The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`.
### Privacy Considerations
- **No PII**: Avoid logging file paths, user content, or other personally identifiable information
- **Redacted by Default**: User prompts are redacted unless `OTEL_LOG_USER_PROMPTS=1`
- **Configurable Attributes**: Use cardinality control variables to manage data granularity
- **Opt-out**: Provide mechanism to disable telemetry entirely
### Resource Attributes
All metrics should include these resource attributes:
- `service.name`: `continue-cli`
- `service.version`: CLI version
- `deployment.environment`: `development` | `production`
- `os.type`: Operating system
- `process.pid`: Process ID
### Implementation Points
1. **Session Tracking**: Initialize session ID and track lifecycle in `src/commands/chat.ts`
2. **Token/Cost Tracking**: Implement in `src/streamChatResponse.ts` with model-specific pricing
3. **Tool Usage**: Track in `src/tools/index.ts` and individual tool implementations
4. **File Operations**: Implement diff analysis in `src/tools/writeFile.ts` for LOC tracking
5. **Command Detection**: Parse git/gh commands in `src/tools/runTerminalCommand.ts`
6. **Authentication**: Track auth flows in `src/auth/workos.ts`
7. **Performance**: Add timing measurements throughout the application lifecycle
## Implementation Status
✅ = Implemented
❌ = Not implemented yet
**Core metrics:** 6/7 implemented (83%)
**Core events:** 3/3 implemented (100%)
**Additional metrics:** 4/7 implemented (57%)
**Missing implementations:**
- `continue.cli.code_edit_tool.decision` - requires user confirmation UI
- `continue.cli.mcp.connections` - needs MCP service monitoring
- `continue.cli.startup.time` - needs startup time tracking

View file

@ -0,0 +1,112 @@
# Permissions
## Permission types
To make sure that users can oversee the actions of the LLM, we implement a permissions system. Every tool has one of the following permissions:
- `allow`: The tool will be automatically called without asking
- `ask`: We will ask the user before calling the tool, giving them the options to accept or reject
- `exclude`: This tool will be completely excluded, so the model won't even know it exists
## Rule precedence
There is a default set of permissions for the builtin tools in [`src/permissions/defaultPolicies.ts`](../src/permissions/defaultPolicies.ts). But these policies can be overriden by multiple layers. The order of precedence is as follows, which the earlier items taking precedence:
1. **Mode policies** (highest priority - see [modes.md](./modes.md))
2. Command line flags (`--allow`, `--ask`, `--exclude`)
3. Permissions in `config.yaml` / configuration
4. Permissions in `~/.continue/permissions.yaml`
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)
## Tool matching patterns
We use a tool matching pattern to match tools to permissions. This format looks like the following:
- `Read` matches any call to the `Read` tool
- `Read(*)` also matches any call to the `Read` tool
- `Read(**/*.ts)` matches any call to the `Read` tool where the primary parameter matches the glob pattern `**/*.ts`.
Note that for an `exclude` policy, it doesn't make sense to have argument matching.
## Command line flags
Each of the `--allow`, `--ask`, and `--exclude` flags allow you to set the permission for a tool. Usage must be a "tool matching pattern" as described above for each flag, with each providing a policy that will be added to the list of policies in order.
```bash
# Allow Read, Ask Write, and Exclude Bash
cn --allow Read --ask Write --exclude Bash
# Start in plan mode (read-only tools only)
cn --readonly "Help me understand this codebase"
# Use mode switching during chat
cn "Let me work on this feature" # Starts in normal mode
# Then use Shift+Tab to cycle through modes
```
## `config.yaml` / Configuration (implement later)
::: info
This should not be implemented yet.
:::
To let users define their permissions as a part of their custom assistant, they can do so in the permissions section of `config.yaml` or their configuration:
```yaml
permissions:
allow:
- Read(*)
ask:
- Write(**/*.py)
exclude:
- Write
```
## `~/.continue/permissions.yaml` (personal settings)
It would be frustrating for users to have to set the same permissions across all of their assistants, so we provide them a file for personal settings. It should be basically equivalent to the `permissions` section of `config.yaml`:
```yaml title="~/.continue/permissions.yaml"
allow:
- Read(*)
ask:
- Write(**/*.py)
exclude:
- Write
```
Except that it's important to understand that this file is _not_ intended to be edited by the user. It is only for persistence, and users should interact with their permissions by using the TUI.
This file should be created the first time that the CLI starts.
## Headless mode permissions
When running in headless mode (using the `-p` or `--print` flag), the CLI uses the same default policies as normal mode, but with different behavior for tools that require confirmation:
- **Normal mode**: Write operations and terminal commands require confirmation (`ask`) - user is prompted
- **Headless mode**: Same default policies, but tools requiring confirmation (`ask`) will cause the process to exit with an error message
To use tools that normally require confirmation in headless mode, you must explicitly allow them:
```bash
# 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)
cn -p --allow "*" "Write and run a script"
# Headless mode with specific restrictions
cn -p --exclude run_terminal_command "Clean up the codebase"
```
This approach ensures that headless mode is secure by default while providing clear guidance on how to enable the needed permissions.

View file

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

View file

@ -0,0 +1,149 @@
# Testing Strategies
This document provides an overview of the different testing strategies used in this repository, when to use each type, and links to examples.
## Test Types
### 1. Unit Tests
**Purpose**: Test individual functions, utilities, and modules in isolation.
**When to use**:
- Testing pure functions with predictable inputs/outputs
- Testing utility functions and helpers
- Testing business logic components
- Testing error handling and edge cases
**Framework**: Vitest with TypeScript support
**Examples**:
- [`src/util/formatError.test.ts`](../src/util/formatError.test.ts) - Tests error formatting utility
- [`src/util/exponentialBackoff.test.ts`](../src/util/exponentialBackoff.test.ts) - Tests backoff logic
- [`src/logging.test.ts`](../src/logging.test.ts) - Tests logging functionality
- [`src/args.test.ts`](../src/args.test.ts) - Tests argument parsing
**How to run**: `npm test` (includes linting)
### 2. Service Tests
**Purpose**: Test service classes and dependency injection system.
**When to use**:
- Testing service initialization and lifecycle
- Testing service dependencies and injection
- Testing service container behavior
- Testing service configuration loading
**Examples**:
- [`src/services/ServiceContainer.test.ts`](../src/services/ServiceContainer.test.ts) - Tests dependency injection
- [`src/services/ConfigService.test.ts`](../src/services/ConfigService.test.ts) - Tests configuration loading
- [`src/services/circular-dependencies.test.ts`](../src/services/circular-dependencies.test.ts) - Tests circular dependency detection
### 3. UI Component Tests
**Purpose**: Test React components using Ink testing library for terminal UI.
**When to use**:
- Testing component rendering and display
- Testing user interactions and input handling
- Testing component state changes
- Testing message display and formatting
**Framework**: Vitest + Ink Testing Library + React Testing utilities
**Examples**:
- [`src/ui/__tests__/TUIChat.basic.test.tsx`](../src/ui/__tests__/TUIChat.basic.test.tsx) - Basic rendering tests
- [`src/ui/__tests__/TUIChat.messages.test.tsx`](../src/ui/__tests__/TUIChat.messages.test.tsx) - Message display tests
- [`src/ui/__tests__/TUIChat.input.test.tsx`](../src/ui/__tests__/TUIChat.input.test.tsx) - Input handling tests
- [`src/ui/MarkdownRenderer.test.tsx`](../src/ui/MarkdownRenderer.test.tsx) - Markdown rendering tests
**Test Checklist**: See [`src/ui/UI_TEST_CHECKLIST.md`](../src/ui/UI_TEST_CHECKLIST.md) for comprehensive UI testing guidelines.
### 4. E2E (End-to-End) Tests
**Purpose**: Test complete user workflows and CLI behavior in realistic scenarios.
**When to use**:
- Testing full CLI command execution
- Testing authentication flows
- Testing configuration loading and switching
- Testing tool execution and responses
- Testing headless and interactive modes
**Examples**:
- [`src/e2e/auth.test.ts`](../src/e2e/auth.test.ts) - Authentication workflows
- [`src/e2e/basic-commands.test.ts`](../src/e2e/basic-commands.test.ts) - Basic CLI commands
- [`src/e2e/headless-tool-calls.test.ts`](../src/e2e/headless-tool-calls.test.ts) - Tool execution in headless mode
- [`src/e2e/config-switching.test.tsx`](../src/e2e/config-switching.test.tsx) - Configuration switching
## Testing Infrastructure
### Test Helpers
**Service Container Testing**:
- [`src/test-helpers/testServiceContainer.ts`](../src/test-helpers/testServiceContainer.ts) - Mock service container setup
- [`src/test-helpers/ui-test-context.ts`](../src/test-helpers/ui-test-context.ts) - UI test context setup
**CLI Testing**:
- Test helpers in [`src/test-helpers/`](../src/test-helpers/) for CLI command execution
### Mocks
**UI Mocks**: [`src/ui/__mocks__/`](../src/ui/__mocks__/)
- Syntax highlighter mocks
- Component mocks for testing
**Service Mocks**: [`src/__mocks__/`](../src/__mocks__/)
- Authentication mocks
- Service mocks
- Logging mocks
## Configuration
**Vitest Configuration**: [`vitest.config.ts`](../vitest.config.ts)
- TypeScript support with ES modules
- React/Ink component testing setup
- Mock configurations
- Test timeout and environment settings
## Running Tests
```bash
# Run all tests with linting
npm test
# Run tests in watch mode
npx vitest --watch
# Run specific test file
npx vitest src/util/formatError.test.ts
# Run tests with coverage
npx vitest --coverage
```
## Best Practices
1. **Unit Tests**: Focus on pure functions and isolated logic
2. **Service Tests**: Test dependency injection and service lifecycle
3. **UI Tests**: Test user-visible behavior, not implementation details
4. **E2E Tests**: Test complete user workflows and CLI behavior
5. **Keep tests focused**: One behavior per test
6. **Use descriptive names**: Test names should explain what's being tested
7. **Minimal mocking**: Only mock external dependencies and APIs
8. **Test error cases**: Include negative test cases and edge conditions
9. **Maintain test isolation**: Each test should be independent

View file

@ -0,0 +1,171 @@
# HTTP Wire Protocol: `cn remote` <20> `cn serve`
This document describes the HTTP protocol used for communication between the `cn remote` client and `cn serve` server
## Overview
The protocol uses a polling-based REST API where:
- The server (`cn serve`) runs an Express HTTP server on port 3000
- The client (`cn remote`) polls the server every 500ms for state updates
- All communication uses JSON payloads
## Endpoints
### `GET /state`
Returns the current chat state including message history and processing status.
**Response:**
```json
{
"chatHistory": [
{
"role": "user" | "assistant" | "system",
"content": "string",
"isStreaming": boolean,
"messageType": "tool-start" | "tool-result" | "tool-error" | "system",
"toolName": "string",
"toolResult": "string"
}
],
"isProcessing": boolean,
"messageQueueLength": number
}
```
### `POST /message`
Sends a user message to the server. Messages are queued and processed sequentially.
**Request Body:**
```json
{
"message": "string"
}
```
**Response:**
```json
{
"queued": true,
"position": number,
"willInterrupt": boolean
}
```
**Special Cases:**
- Empty message (`""`) interrupts current processing
- Message `/exit` initiates server shutdown
### `GET /diff`
Returns the git diff between the current branch and main branch.
**Response (Success):**
```json
{
"diff": "string"
}
```
**Response (Error):**
- 404: Not in a git repository
- 500: Git command failed
### `POST /exit`
Gracefully shuts down the server.
**Response:**
```json
{
"message": "Server shutting down",
"success": true
}
```
## Message Types
Messages in the chat history can have different types:
- **Regular messages**: Standard user/assistant messages
- **Tool messages**: Messages with `messageType` set to:
- `tool-start`: Tool execution started
- `tool-result`: Tool execution completed
- `tool-error`: Tool execution failed
- `system`: System messages
## Protocol Flow
1. **Client starts**: Begins polling `GET /state` every 500ms
2. **User sends message**: Client posts to `POST /message`
3. **Server queues message**: Returns queue position
4. **Server processes**: Updates state with streaming responses
5. **Client displays**: Shows updates from state polling
6. **Interruption**: Client sends empty message to interrupt
7. **Exit**: Client sends `/exit` or `POST /exit` to shutdown
## Implementation Files
### Server Implementation
- **Main server**: `src/commands/serve.ts:51-363`
- Express server setup
- Endpoint handlers
- State management
- Message processing
### Client Implementation
- **Remote chat hook**: `src/ui/hooks/useChat.ts:170-310`
- State polling logic
- Message sending
- Interrupt handling
### Type Definitions
- **Display message types**: `src/ui/types.ts:1-16`
- **Server state interface**: `src/commands/serve.ts:20-33`
### Testing
- **Mock server**: `src/ui/__tests__/mockRemoteServer.ts`
- Complete mock implementation for testing
- Simulates streaming and message processing
## Features
### Message Queueing
- Messages are queued and processed one at a time
- Queue position returned on message submission
- Supports interruption of current processing
### Streaming Support
- `isStreaming` flag indicates ongoing response
- Character-by-character updates for real-time display
### Auto-shutdown
- Server shuts down after timeout (default: 300 seconds)
- Configurable via `--timeout` flag
### Error Handling
- HTTP status codes for error conditions
- Graceful error messages in responses
## Security Considerations
- Server binds to `127.0.0.1` (localhost only)
- No authentication implemented (local use only)
- File system access through tool execution

View file

@ -0,0 +1,134 @@
import * as fs from "node:fs";
import * as path from "node:path";
import {
FQSN,
PlatformClient,
SecretResult,
SecretType,
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api";
import * as dotenv from "dotenv";
import { env } from "./env.js";
export class CLIPlatformClient implements PlatformClient {
constructor(
private orgScopeId: string | null,
private readonly apiClient: DefaultApiInterface,
) {}
private findSecretInEnvFile(
filePath: string,
secretName: string,
): string | undefined {
try {
if (!fs.existsSync(filePath)) return undefined;
const envContent = fs.readFileSync(filePath, "utf8");
const env = dotenv.parse(envContent);
return env[secretName];
} catch (error) {
console.warn(
`Error reading .env file at ${filePath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
return undefined;
}
}
private findSecretInProcessEnv(fqsn: FQSN): SecretResult | undefined {
const secretValue = process.env[fqsn.secretName];
if (secretValue) {
return {
found: true,
fqsn,
value: secretValue,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.LocalEnv,
},
};
}
return undefined;
}
private findSecretInLocalEnvFiles(fqsn: FQSN): SecretResult | undefined {
// First check process.env (highest priority)
const processEnvSecret = this.findSecretInProcessEnv(fqsn);
if (processEnvSecret) {
return processEnvSecret;
}
// Then check in priority order: ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
const workspaceDir = process.cwd();
const envPaths = [
path.join(env.continueHome, ".env"),
path.join(workspaceDir, ".continue", ".env"),
path.join(workspaceDir, ".env"),
];
for (const envPath of envPaths) {
const secretValue = this.findSecretInEnvFile(envPath, fqsn.secretName);
if (secretValue) {
return {
found: true,
fqsn,
value: secretValue,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.LocalEnv,
},
};
}
}
return undefined;
}
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
if (fqsns.length === 0) {
return [];
}
const results: (SecretResult | undefined)[] = new Array(fqsns.length).fill(
undefined,
);
// Try to resolve secrets through the API client first
try {
const apiResults: any = await this.apiClient.syncSecrets({
syncSecretsRequest: {
fqsns,
orgScopeId: this.orgScopeId,
},
});
// Merge API results into our results array
for (let i = 0; i < apiResults.length; i++) {
if (apiResults[i]?.found) {
results[i] = apiResults[i];
}
}
} catch (error) {
console.warn(
`Error resolving FQSNs through API: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
// For any secret that wasn't found via API, look in local .env files
for (let i = 0; i < fqsns.length; i++) {
if (!results[i]?.found) {
const secretFromEnv = this.findSecretInLocalEnvFiles(fqsns[i]);
if (secretFromEnv?.found) {
results[i] = secretFromEnv;
}
}
}
return results;
}
}

View file

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

View file

@ -0,0 +1,6 @@
import { vi } from "vitest";
export const pathToUri = vi.fn((path: string) => path);
export const slugToUri = vi.fn((slug: string) => slug);
export const uriToPath = vi.fn(() => null);
export const uriToSlug = vi.fn(() => null);

View file

@ -0,0 +1,24 @@
import { vi } from "vitest";
import type { AuthConfig } from "../../auth/workos.js";
export const isAuthenticated = vi.fn(() => false);
export const isAuthenticatedConfig = vi.fn(() => false);
export const isEnvironmentAuthConfig = vi.fn(() => false);
export const loadAuthConfig = vi.fn(() => null);
export const login = vi.fn();
export const logout = vi.fn();
export const ensureOrganization = vi.fn();
export const getOrganizationId = vi.fn(() => null);
export const saveAuthConfig = vi.fn();
export const listUserOrganizations = vi.fn();
export const hasMultipleOrganizations = vi.fn();
export const initWorkOS = vi.fn();
export const getModelName = vi.fn(() => null);
export const getAccessToken = vi.fn(() => null);
export const getConfigUri = vi.fn(() => null);
export const getAssistantSlug = vi.fn(() => null);
export const getLocalConfigPath = vi.fn(() => null);
export const updateConfigUri = vi.fn();
export const updateModelName = vi.fn();
export const updateAssistantSlug = vi.fn();
export const updateLocalConfigPath = vi.fn();

View file

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

View file

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

View file

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

View file

@ -0,0 +1,21 @@
import { vi } from "vitest";
export const useService = vi.fn(() => ({
value: null,
state: "idle",
error: null,
reload: vi.fn(() => Promise.resolve()),
}));
export const useServices = vi.fn(() => ({
services: {
auth: { isAuthenticated: true },
config: { config: { name: "test-assistant" } },
model: { model: "test-model", llmApi: {} },
mcp: {},
apiClient: { apiClient: {} },
},
loading: false,
error: null,
allReady: true,
}));

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,7 @@
import { vi } from "vitest";
export const constructSystemMessage = vi
.fn()
.mockResolvedValue(
"You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question.",
);

View file

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

View file

@ -0,0 +1,414 @@
import { vi } from 'vitest';
import { parseArgs, processRule } from "./args.js";
describe("parseArgs", () => {
const originalArgv = process.argv;
beforeEach(() => {
// Reset process.argv before each test
process.argv = ["node", "script.js"];
});
afterAll(() => {
// Restore original argv
process.argv = originalArgv;
});
it("should return default values when no arguments provided", () => {
const result = parseArgs();
expect(result).toEqual({});
});
it("should set resume to true when --resume flag is present", () => {
process.argv = ["node", "script.js", "--resume"];
const result = parseArgs();
expect(result.resume).toBe(true);
});
it("should set readonly to true when --readonly flag is present", () => {
process.argv = ["node", "script.js", "--readonly"];
const result = parseArgs();
expect(result.readonly).toBe(true);
});
it("should parse config path from --config flag", () => {
process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"];
const result = parseArgs();
expect(result.configPath).toBe("/path/to/config.yaml");
});
it("should parse single rule from --rule flag", () => {
process.argv = ["node", "script.js", "--rule", "my-rule"];
const result = parseArgs();
expect(result.rules).toEqual(["my-rule"]);
});
it("should parse multiple rules from multiple --rule flags", () => {
process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"];
const result = parseArgs();
expect(result.rules).toEqual(["rule1", "rule2"]);
});
it("should parse prompt from last non-flag argument", () => {
process.argv = ["node", "script.js", "Hello world"];
const result = parseArgs();
expect(result.prompt).toBe("Hello world");
});
it("should handle multiple flags together", () => {
process.argv = ["node", "script.js", "--print", "--readonly", "--resume"];
const result = parseArgs();
expect(result).toEqual({
readonly: true,
resume: true,
});
});
it("should handle config flag with other flags", () => {
process.argv = ["node", "script.js", "--config", "config.yaml", "--print"];
const result = parseArgs();
expect(result).toEqual({
configPath: "config.yaml",
});
});
it("should handle rule flag with other flags", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "--print"];
const result = parseArgs();
expect(result).toEqual({
rules: ["my-rule"],
});
});
it("should handle prompt with flags", () => {
process.argv = ["node", "script.js", "--print", "What is the weather?"];
const result = parseArgs();
expect(result).toEqual({
prompt: "What is the weather?",
});
});
it("should handle config flag with prompt", () => {
process.argv = [
"node",
"script.js",
"--config",
"config.yaml",
"Test prompt",
];
const result = parseArgs();
expect(result).toEqual({
configPath: "config.yaml",
prompt: "Test prompt",
});
});
it("should handle rule flag with prompt", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"];
const result = parseArgs();
expect(result).toEqual({
rules: ["my-rule"],
prompt: "Test prompt",
});
});
it("should ignore config and rule flag values when extracting prompt", () => {
process.argv = [
"node",
"script.js",
"--config",
"config.yaml",
"--rule",
"my-rule",
"actual-prompt",
];
const result = parseArgs();
expect(result.prompt).toBe("actual-prompt");
expect(result.configPath).toBe("config.yaml");
expect(result.rules).toEqual(["my-rule"]);
});
it("should handle multiple non-flag arguments and use the last one as prompt", () => {
process.argv = ["node", "script.js", "first", "second", "third"];
const result = parseArgs();
expect(result.prompt).toBe("third");
});
it("should handle complex argument combinations", () => {
process.argv = [
"node",
"script.js",
"--print",
"--config",
"my-config.yaml",
"--rule",
"rule1",
"--rule",
"rule2",
"--readonly",
"--resume",
"Complex prompt with spaces",
];
const result = parseArgs();
expect(result).toEqual({
configPath: "my-config.yaml",
rules: ["rule1", "rule2"],
readonly: true,
resume: true,
prompt: "Complex prompt with spaces",
});
});
it("should handle config flag without value", () => {
process.argv = ["node", "script.js", "--config"];
const result = parseArgs();
expect(result.configPath).toBeUndefined();
});
it("should handle rule flag without value", () => {
process.argv = ["node", "script.js", "--rule"];
const result = parseArgs();
expect(result.rules).toEqual([]);
});
it("should handle config flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--config"];
const result = parseArgs();
expect(result.configPath).toBeUndefined();
});
it("should handle rule flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--rule"];
const result = parseArgs();
expect(result.rules).toEqual([]);
});
it("should handle empty arguments array", () => {
process.argv = ["node", "script.js"];
const result = parseArgs();
expect(result).toEqual({
});
});
it("should handle multiple boolean flags", () => {
process.argv = ["node", "script.js", "--readonly", "--resume"];
const result = parseArgs();
expect(result.readonly).toBe(true);
expect(result.resume).toBe(true);
});
it("should handle multiple rules with complex combinations", () => {
process.argv = [
"node",
"script.js",
"--rule",
"file.txt",
"--rule",
"owner/package",
"--rule",
"direct string rule",
];
const result = parseArgs();
expect(result.rules).toEqual([
"file.txt",
"owner/package",
"direct string rule",
]);
});
});
describe("processRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;
const mockFetch = vi.fn() as any;
beforeAll(() => {
global.fetch = mockFetch;
});
afterAll(() => {
global.fetch = originalFetch;
});
beforeEach(() => {
mockFetch.mockClear();
});
describe("loadRuleFromHub", () => {
it("should successfully load a rule from the Continue Hub", async () => {
// Create a mock zip file containing a markdown rule
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const ruleContent = "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
zip.file("rule.md", ruleContent);
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
// Mock successful fetch response
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/sentry-nextjs");
expect(result).toBe(ruleContent);
expect(mockFetch).toHaveBeenCalledWith(
new URL("v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/")
);
});
it("should handle HTTP errors when loading from hub", async () => {
mockFetch.mockResolvedValue({
ok: false,
status: 404,
statusText: "Not Found",
} as Response);
await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found'
);
});
it("should handle network errors when loading from hub", async () => {
mockFetch.mockRejectedValue(new Error("Network error"));
await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
'Failed to load rule from hub "continuedev/sentry-nextjs": Network error'
);
});
it("should handle invalid slug format", async () => {
// "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
// Let's test with a slug that has wrong format but contains "/"
await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts'
);
});
it("should handle empty zip file", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file'
);
});
it("should handle zip with only directories", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.folder("docs"); // Create a directory but no files
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
await expect(processRule("continuedev/directory-only")).rejects.toThrow(
'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file'
);
});
it("should prefer markdown files and ignore other file types", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const mdContent = "# Main Rule\n\nThis is the markdown rule content.";
const txtContent = "This is just a text file.";
zip.file("README.txt", txtContent);
zip.file("rule.md", mdContent);
zip.file("package.json", '{"name": "test"}');
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/mixed-files");
expect(result).toBe(mdContent);
});
it("should handle multiple markdown files and use the first one", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const rule1Content = "# First Rule\n\nThis is the first rule.";
const rule2Content = "# Second Rule\n\nThis is the second rule.";
zip.file("rule1.md", rule1Content);
zip.file("rule2.md", rule2Content);
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/multiple-rules");
// Should use the first markdown file found (alphabetically)
expect(result).toBe(rule1Content);
});
it("should handle malformed zip files", async () => {
const invalidZipBuffer = new ArrayBuffer(10);
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(invalidZipBuffer),
} as Response);
await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
'Failed to load rule from hub "continuedev/corrupted-zip"'
);
});
});
describe("processRule logic", () => {
it("should identify hub slugs correctly", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.file("rule.md", "# Hub Rule");
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("owner/package");
expect(result).toBe("# Hub Rule");
expect(mockFetch).toHaveBeenCalled();
});
it("should treat direct strings as content", async () => {
const directContent = "This is direct rule content";
const result = await processRule(directContent);
expect(result).toBe(directContent);
expect(mockFetch).not.toHaveBeenCalled();
});
it("should distinguish between hub slugs and file paths", async () => {
// This would be treated as a file path, not a hub slug
// since it starts with "."
await expect(processRule("./owner/package")).rejects.toThrow(
'Failed to read rule file "./owner/package": Rule file not found'
);
expect(mockFetch).not.toHaveBeenCalled();
});
});
});

192
extensions/cli/src/args.ts Normal file
View file

@ -0,0 +1,192 @@
import * as fs from "fs";
import * as path from "path";
import JSZip from "jszip";
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
}
/**
* Load rule content from a file path
* @param filePath - Path to the rule file
* @returns The content of the rule file
*/
function loadRuleFromFile(filePath: string): string {
try {
const absolutePath = path.resolve(filePath);
if (!fs.existsSync(absolutePath)) {
throw new Error(`Rule file not found: ${filePath}`);
}
return fs.readFileSync(absolutePath, "utf-8");
} catch (error: any) {
throw new Error(`Failed to read rule file "${filePath}": ${error.message}`);
}
}
/**
* Load rule content from hub.continue.dev
* @param slug - The slug in format "owner/package"
* @returns The rule content from the hub
*/
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}`,
);
}
const [ownerSlug, ruleSlug] = parts;
const downloadUrl = new URL(
`v0/${ownerSlug}/${ruleSlug}/latest/download`,
env.apiBase,
);
try {
const response = await fetch(downloadUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// The API returns a zip file, so we need to extract the rule content
const arrayBuffer = await response.arrayBuffer();
const zip = new JSZip();
const zipContents = await zip.loadAsync(arrayBuffer);
// Find the first .md or .txt file (rule content)
const ruleFiles = Object.keys(zipContents.files).filter(
(filename) =>
filename.endsWith(".md") && !zipContents.files[filename].dir,
);
if (ruleFiles.length === 0) {
throw new Error("No rule content found in downloaded zip file");
}
// Use the first rule file found - TODO support multiple rules and parse frontmatter
const ruleFile = zipContents.files[ruleFiles[0]];
const content = await ruleFile.async("text");
return content;
} catch (error: any) {
throw new Error(`Failed to load rule from hub "${slug}": ${error.message}`);
}
}
/**
* Process a rule specification and return its content
* @param ruleSpec - Can be a file path, hub slug, or direct string content
* @returns The processed rule content
*/
export async function processRule(ruleSpec: string): Promise<string> {
// If it looks like a hub slug (contains / but doesn't start with . or /)
if (
ruleSpec.includes("/") &&
!ruleSpec.startsWith(".") &&
!ruleSpec.startsWith("/")
) {
return await loadRuleFromHub(ruleSpec);
}
// If it looks like a file path (contains . or / or ends with common file extensions)
if (
ruleSpec.includes(".") ||
ruleSpec.includes("/") ||
ruleSpec.includes("\\")
) {
return loadRuleFromFile(ruleSpec);
}
// Otherwise, treat it as direct string content
return ruleSpec;
}
/**
* Parse command line arguments for non-permission related flags
* @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
* @returns Parsed command line arguments
*/
export function parseArgs(): CommandLineArgs {
const args = process.argv.slice(2);
// Default values
const result: CommandLineArgs = {};
if (args.includes("--resume")) {
result.resume = true;
}
if (args.includes("--readonly")) {
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";
}
}
// Get config path from --config flag
const configIndex = args.indexOf("--config");
if (configIndex !== -1 && configIndex + 1 < args.length) {
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++) {
if (args[i] === "--rule") {
ruleIndices.push(i);
}
}
if (ruleIndices.length > 0) {
result.rules = [];
for (const ruleIndex of ruleIndices) {
if (ruleIndex + 1 < args.length) {
result.rules.push(args[ruleIndex + 1]);
}
}
}
// Find the last argument that's not a flag or a flag value
const flagsWithValues = ["--config", "--org", "--rule", "--format"];
const nonFlagArgs = args.filter((arg, index) => {
// Skip flags (starting with --)
if (arg.startsWith("--") || arg === "-p") return false;
// Skip flag values
const prevArg = index > 0 ? args[index - 1] : "";
if (flagsWithValues.includes(prevArg)) return false;
return true;
});
// If there are any non-flag arguments, use the last one as the prompt
if (nonFlagArgs.length > 0) {
result.prompt = nonFlagArgs[nonFlagArgs.length - 1];
}
return result;
}

View file

@ -0,0 +1,71 @@
import { describe, expect, it, beforeEach, afterEach } from "vitest";
import { getDisplayableAsciiArt, CONTINUE_ASCII_ART } from "./asciiArt.js";
describe("asciiArt", () => {
let originalColumns: number | undefined;
beforeEach(() => {
originalColumns = process.stdout.columns;
});
afterEach(() => {
if (originalColumns === undefined) {
delete (process.stdout as any).columns;
} else {
process.stdout.columns = originalColumns;
}
});
describe("getDisplayableAsciiArt", () => {
it("should return full ASCII art when terminal is wide enough", () => {
// Set process.stdout.columns to simulate wide terminal
process.stdout.columns = 80;
const result = getDisplayableAsciiArt();
expect(result).toBe(CONTINUE_ASCII_ART);
});
it("should return simple text version when terminal is too narrow", () => {
// Set process.stdout.columns to simulate narrow terminal
process.stdout.columns = 60;
const result = getDisplayableAsciiArt();
expect(result).toContain("CONTINUE");
expect(result).toContain("v0.0.0-dev");
expect(result).not.toBe(CONTINUE_ASCII_ART);
// Should be much shorter than the full ASCII art
expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2);
});
it("should return simple text version when terminal is below threshold", () => {
// Test the edge case at exactly 74 columns (below our threshold of 75)
process.stdout.columns = 74;
const result = getDisplayableAsciiArt();
expect(result).toContain("CONTINUE");
expect(result).not.toBe(CONTINUE_ASCII_ART);
});
it("should return full ASCII art when terminal is exactly at threshold", () => {
// Test the edge case at exactly 75 columns (our threshold)
process.stdout.columns = 75;
const result = getDisplayableAsciiArt();
expect(result).toBe(CONTINUE_ASCII_ART);
});
it("should default to full ASCII art when columns is undefined", () => {
// Set process.stdout.columns to undefined (should default to 80)
delete (process.stdout as any).columns;
const result = getDisplayableAsciiArt();
expect(result).toBe(CONTINUE_ASCII_ART);
});
});
});

View file

@ -0,0 +1,87 @@
import chalk from "chalk";
import { mind } from "gradient-string";
import { getVersion } from "./version.js";
const d = chalk.dim;
export const CONTINUE_ASCII_ART = `
${mind.multiline(` ██████╗ ██████╗ ███╗ ██╗████████╗██╗███╗ ██╗██╗ ██╗███████╗
██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██║████╗ ██║██║ ██║██╔════╝
██║ ██║ ██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ██║█████╗
██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝
╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗
╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)}
${d("v" + getVersion())}`;
// Minimum terminal width required to display ASCII art properly
const MIN_WIDTH_FOR_ASCII_ART = 75;
/**
* Returns the ASCII art only if the terminal is wide enough to display it properly.
* If terminal is too narrow, returns just the version string.
*/
export function getDisplayableAsciiArt(): string {
const terminalWidth = process.stdout.columns || 80;
if (terminalWidth >= MIN_WIDTH_FOR_ASCII_ART) {
return CONTINUE_ASCII_ART;
}
// If terminal is too narrow, just show a simple version
return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`;
}
export const CONTINUE_LOGO_ASCII_ART = `
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @
@@@@@@@@@@@@ @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@@@@@@ @@@@
@@@@@@@@@@@@ @@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@ @@@@@@@@@@@ @@@@@@@
@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@
CONTINUE @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@ @@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@ @@@@@@@@@@@ @@@@@@
@@@@@@@@@@@@ @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@ @@@@@@@@@@@ @@@@
@@@@@@@@@@@@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @
@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
`;

View file

@ -0,0 +1,29 @@
import chalk from "chalk";
import { isAuthenticated, login } from "./workos.js";
/**
* Ensures the user is authenticated before proceeding
* Returns true if authentication is successful, false otherwise
*/
export async function ensureAuthenticated(
requireAuth: boolean = true,
): Promise<boolean> {
if (isAuthenticated()) {
return true;
}
if (!requireAuth) {
return false;
}
console.info(chalk.yellow("Authentication required."));
try {
await login();
return true;
} catch (error) {
console.error(chalk.red("Failed to authenticate."), error);
return false;
}
}

View file

@ -0,0 +1,25 @@
/**
* URI utility functions for auth config
*/
export function pathToUri(path: string): string {
return `file://${path}`;
}
export function slugToUri(slug: string): string {
return `slug://${slug}`;
}
export function uriToPath(uri: string): string | null {
if (!uri.startsWith("file://")) {
return null;
}
return uri.slice(7);
}
export function uriToSlug(uri: string): string | null {
if (!uri.startsWith("slug://")) {
return null;
}
return uri.slice(7);
}

View file

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

View file

@ -0,0 +1,164 @@
import chalk from "chalk";
import { getApiClient } from "../config.js";
import type {
AuthConfig,
AuthenticatedConfig,
EnvironmentAuthConfig,
} from "./workos.js";
import { saveAuthConfig } from "./workos.js";
/**
* Creates an updated AuthenticatedConfig with a new organization ID
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
organizationId: string | null,
): AuthenticatedConfig {
return {
userId: config.userId,
userEmail: config.userEmail,
accessToken: config.accessToken,
refreshToken: config.refreshToken,
expiresAt: config.expiresAt,
organizationId,
configUri: config.configUri,
modelName: config.modelName,
};
}
/**
* Helper function to resolve organization by slug
*/
export 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`);
}
}
/**
* Handle CLI organization flag for environment auth configs
*/
export async function handleCliOrgForEnvironmentAuth(
authConfig: EnvironmentAuthConfig,
cliOrganizationSlug: string,
isHeadless: boolean,
): Promise<AuthConfig> {
// 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);
}
const apiClient = getApiClient(authConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
// Return modified environment auth config with organization ID
return {
...authConfig,
organizationId: resolvedOrg.id,
};
}
/**
* Handle CLI organization flag for authenticated configs
*/
export async function handleCliOrgForAuthenticatedConfig(
authenticatedConfig: AuthenticatedConfig,
cliOrganizationSlug: string,
isHeadless: boolean,
): Promise<AuthConfig> {
// 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);
}
const apiClient = getApiClient(authenticatedConfig.accessToken);
const resolvedOrg = await resolveOrganizationBySlug(
apiClient,
cliOrganizationSlug,
);
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
resolvedOrg.id,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
/**
* Automatically select organization for authenticated config
*/
export async function autoSelectOrganization(
authenticatedConfig: AuthenticatedConfig,
): Promise<AuthConfig> {
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
if (organizations.length === 0) {
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// Automatically select the first organization if available
const selectedOrg = organizations[0];
const selectedOrgId = selectedOrg.id;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
selectedOrgId,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
} catch (error: any) {
console.error(
chalk.red("Error fetching organizations:"),
error.response?.data?.message || error.message || error,
);
console.info(chalk.yellow("Continuing without organization selection."));
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}

View file

@ -0,0 +1,187 @@
import { slugToUri } from "./uriUtils.js";
import {
AuthenticatedConfig,
EnvironmentAuthConfig,
getAccessToken,
getAssistantSlug,
getOrganizationId,
isAuthenticatedConfig,
isEnvironmentAuthConfig,
} from "./workos.js";
describe("workos utility functions", () => {
describe("isAuthenticatedConfig", () => {
it("should return true for authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(isAuthenticatedConfig(config)).toBe(true);
});
it("should return false for environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(isAuthenticatedConfig(config)).toBe(false);
});
it("should return false for null config", () => {
expect(isAuthenticatedConfig(null)).toBe(false);
});
});
describe("isEnvironmentAuthConfig", () => {
it("should return true for environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(isEnvironmentAuthConfig(config)).toBe(true);
});
it("should return false for authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(isEnvironmentAuthConfig(config)).toBe(false);
});
it("should return false for null config", () => {
expect(isEnvironmentAuthConfig(null)).toBe(false);
});
});
describe("getAccessToken", () => {
it("should return access token from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getAccessToken(config)).toBe("token123");
});
it("should return access token from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getAccessToken(config)).toBe("env-token123");
});
it("should return null for null config", () => {
expect(getAccessToken(null)).toBe(null);
});
});
describe("getOrganizationId", () => {
it("should return organization ID from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe("org123");
});
it("should return null organization ID from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe(null);
});
it("should return null from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("assistant123"),
};
expect(getOrganizationId(config)).toBe(null);
});
it("should return null for null config", () => {
expect(getOrganizationId(null)).toBe(null);
});
});
describe("getAssistantSlug", () => {
it("should return assistant slug from authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: slugToUri("assistant123"),
};
expect(getAssistantSlug(config)).toBe("assistant123");
});
it("should return null when assistant slug is undefined in authenticated config", () => {
const config: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: "org123",
configUri: undefined,
};
expect(getAssistantSlug(config)).toBe(null);
});
it("should return assistant slug from environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: slugToUri("env-assistant123"),
};
expect(getAssistantSlug(config)).toBe("env-assistant123");
});
it("should return null when assistant slug is undefined in environment auth config", () => {
const config: EnvironmentAuthConfig = {
accessToken: "env-token123",
organizationId: null,
configUri: undefined,
};
expect(getAssistantSlug(config)).toBe(null);
});
it("should return null for null config", () => {
expect(getAssistantSlug(null)).toBe(null);
});
});
});

View file

@ -0,0 +1,652 @@
import * as fs from "fs";
import * as path from "path";
import chalk from "chalk";
// Polyfill fetch for Node < 18
import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
// Config file path
const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
// Represents an authenticated user's configuration
export interface AuthenticatedConfig {
userId: string;
userEmail: string;
accessToken: string;
refreshToken: string;
expiresAt: number;
organizationId: string | null; // null means personal organization
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
// 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: 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
}
// Union type representing the possible authentication states
export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null;
/**
* Type guard to check if config is authenticated via file-based auth
*/
export function isAuthenticatedConfig(
config: AuthConfig,
): config is AuthenticatedConfig {
return config !== null && "userId" in config;
}
/**
* Type guard to check if config is authenticated via environment variable
*/
export function isEnvironmentAuthConfig(
config: AuthConfig,
): config is EnvironmentAuthConfig {
return config !== null && !("userId" in config);
}
/**
* Gets the access token from any auth config type
*/
export function getAccessToken(config: AuthConfig): string | null {
if (config === null) return null;
return config.accessToken;
}
/**
* Gets the organization ID from any auth config type
*/
export function getOrganizationId(config: AuthConfig): string | null {
if (config === null) return null;
return config.organizationId;
}
/**
* Gets the config URI from any auth config type
*/
export function getConfigUri(config: AuthConfig): string | null {
if (config === null) return null;
return config.configUri || null;
}
/**
* Gets the model name from any auth config type
*/
export function getModelName(config: AuthConfig): string | null {
if (config === null) return null;
return config.modelName || null;
}
// URI utility functions have been moved to ./uriUtils.ts
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
autoSelectOrganization,
createUpdatedAuthConfig,
handleCliOrgForAuthenticatedConfig,
handleCliOrgForEnvironmentAuth,
} from "./workos.helpers.js";
/**
* Legacy functions for backward compatibility
*/
export function getAssistantSlug(config: AuthConfig): string | null {
const uri = getConfigUri(config);
return uri ? uriToSlug(uri) : null;
}
export function getLocalConfigPath(config: AuthConfig): string | null {
const uri = getConfigUri(config);
return uri ? uriToPath(uri) : null;
}
/**
* Loads the authentication configuration from disk
*/
export function loadAuthConfig(): AuthConfig {
// If CONTINUE_API_KEY environment variable exists, use that instead
if (process.env.CONTINUE_API_KEY) {
return {
accessToken: process.env.CONTINUE_API_KEY,
organizationId: null,
};
}
try {
if (fs.existsSync(AUTH_CONFIG_PATH)) {
const data = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, "utf8"));
// Validate that we have all required fields for authenticated config
if (
data.userId &&
data.userEmail &&
data.accessToken &&
data.refreshToken &&
data.expiresAt
) {
return {
userId: data.userId,
userEmail: data.userEmail,
accessToken: data.accessToken,
refreshToken: data.refreshToken,
expiresAt: data.expiresAt,
organizationId: data.organizationId || null,
configUri: data.configUri,
modelName: data.modelName,
};
} else {
console.warn("Invalid auth config found, ignoring.");
return null;
}
}
} catch (error) {
console.error(`Error loading auth config: ${error}`);
}
return null;
}
/**
* Saves the authentication configuration to disk
*/
export function saveAuthConfig(config: AuthenticatedConfig): void {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
}
try {
// Make sure the directory exists
const dir = path.dirname(AUTH_CONFIG_PATH);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(AUTH_CONFIG_PATH, JSON.stringify(config, null, 2));
} catch (error) {
console.error(`Error saving auth config: ${error}`);
}
}
/**
* Updates the config URI in the authentication configuration
*/
export function updateConfigUri(configUri: string | null): void {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
}
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
configUri: configUri || undefined,
};
saveAuthConfig(updatedConfig);
}
}
/**
* Updates the model name in the authentication configuration
*/
export function updateModelName(modelName: string | null): void {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
}
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
modelName: modelName || undefined,
};
saveAuthConfig(updatedConfig);
}
}
/**
* Legacy functions for backward compatibility
*/
export function updateAssistantSlug(assistantSlug: string | null): void {
updateConfigUri(assistantSlug ? slugToUri(assistantSlug) : null);
}
export function updateLocalConfigPath(localConfigPath: string | null): void {
updateConfigUri(localConfigPath ? pathToUri(localConfigPath) : null);
}
/**
* Checks if the user is authenticated and the token is valid
*/
export function isAuthenticated(): boolean {
const config = loadAuthConfig();
if (config === null) {
return false;
}
// Environment auth is always valid
if (isEnvironmentAuthConfig(config)) {
return true;
}
/**
* 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(() => {
// If refresh fails, we're not authenticated
return false;
});
}
return true;
}
/**
* Device authorization response from WorkOS
*/
interface DeviceAuthorizationResponse {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete: string;
expires_in: number;
interval: number;
}
/**
* Request device authorization from WorkOS
*/
async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse> {
try {
const params = new URLSearchParams({
client_id: env.workOsClientId,
screen_hint: "sign-up",
});
// Use WorkOS User Management device authorization endpoint
const response = await fetch(
"https://api.workos.com/user_management/authorize/device",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params,
},
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error: any) {
console.error(
chalk.red("Device authorization error:"),
error.message || error,
);
throw error;
}
}
/**
* Poll for device authorization completion
*/
async function pollForDeviceToken(
deviceCode: string,
interval: number,
expiresIn: number,
): Promise<AuthenticatedConfig> {
const startTime = Date.now();
const expirationTime = startTime + expiresIn * 1000;
let currentInterval = interval;
while (Date.now() < expirationTime) {
try {
const params = new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
device_code: deviceCode,
client_id: env.workOsClientId,
});
const headers: Record<string, string> = {
"Content-Type": "application/x-www-form-urlencoded",
};
// Poll WorkOS User Management token endpoint
const response = await fetch(
"https://api.workos.com/user_management/authenticate",
{
method: "POST",
headers,
body: params,
},
);
if (response.ok) {
const data = await response.json();
const { access_token, refresh_token, user } = data;
// Calculate token expiration (assuming 1 hour validity)
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
const authConfig: AuthenticatedConfig = {
userId: user.id,
userEmail: user.email,
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: tokenExpiresAt,
organizationId: null,
};
// Save the config
saveAuthConfig(authConfig);
return authConfig;
} else {
// Handle HTTP error responses
const errorData = await response.json().catch(() => ({}));
const errorCode = errorData.error;
// 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.",
);
}
if (errorCode === "authorization_pending") {
// Continue polling
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "slow_down") {
// Increase polling interval
currentInterval += 5;
await new Promise((resolve) =>
setTimeout(resolve, currentInterval * 1000),
);
continue;
} else if (errorCode === "access_denied") {
throw new Error("User denied access");
} else if (errorCode === "expired_token") {
throw new Error("Device code has expired");
} else {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
}
} catch (error: any) {
console.error(chalk.red("Token polling error:"), error.message || error);
throw error;
}
}
throw new Error("Device authorization timeout");
}
/**
* Refreshes the access token using a refresh token
*/
async function refreshToken(
refreshToken: string,
): Promise<AuthenticatedConfig> {
try {
// Load existing config to preserve organizationId and other fields
const existingConfig = loadAuthConfig();
const response = await fetch(new URL("auth/refresh", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
refreshToken,
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
const { accessToken, refreshToken: newRefreshToken, user } = data;
// Calculate token expiration (assuming 1 hour validity)
const tokenExpiresAt = Date.now() + 60 * 60 * 1000;
const authConfig: AuthenticatedConfig = {
userId: user.id,
userEmail: user.email,
accessToken,
refreshToken: newRefreshToken,
expiresAt: tokenExpiresAt,
// Preserve existing organizationId if it exists, otherwise set to null
organizationId: isAuthenticatedConfig(existingConfig)
? existingConfig.organizationId
: null,
// Preserve existing configUri if it exists
configUri: isAuthenticatedConfig(existingConfig)
? existingConfig.configUri
: undefined,
// Preserve existing modelName if it exists
modelName: isAuthenticatedConfig(existingConfig)
? existingConfig.modelName
: undefined,
};
// Save the config
saveAuthConfig(authConfig);
return authConfig;
} catch (error: any) {
console.error(chalk.red("Token refresh error:"), error.message || error);
throw error;
}
}
/**
* Authenticates using the WorkOS device flow
*/
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"),
);
return {
accessToken: process.env.CONTINUE_API_KEY,
organizationId: null,
};
}
console.info(chalk.white("\nSigning in with Continue..."));
// Request device authorization
const deviceAuth = await requestDeviceAuthorization();
console.info(
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}`,
),
);
// Try to open the complete verification URL in browser
try {
await open(deviceAuth.verification_uri_complete);
} catch {
console.info(chalk.yellow("Unable to open browser automatically"));
}
console.info(chalk.dim("\nWaiting for confirmation..."));
// Poll for token
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in,
);
console.info(chalk.white("✅ Success!"));
return authConfig;
}
/**
* Ensures the user has selected an organization, automatically selecting the first one if available
*/
export async function ensureOrganization(
authConfig: AuthConfig,
isHeadless: boolean = false,
cliOrganizationSlug?: string,
): Promise<AuthConfig> {
// Handle CLI organization slug if provided (undefined means no --org flag or --org personal)
if (cliOrganizationSlug) {
// For environment auth configs
if (isEnvironmentAuthConfig(authConfig)) {
return handleCliOrgForEnvironmentAuth(
authConfig,
cliOrganizationSlug,
isHeadless,
);
}
} else if (isEnvironmentAuthConfig(authConfig)) {
// No CLI organization slug (or "personal" was specified) - return as-is
return authConfig;
}
// If not authenticated, return as-is
if (!isAuthenticatedConfig(authConfig)) {
return authConfig;
}
// TypeScript now knows authConfig is AuthenticatedConfig
const authenticatedConfig: AuthenticatedConfig = authConfig;
// If a CLI organization slug is provided, try to use it (for authenticated configs)
if (cliOrganizationSlug) {
return handleCliOrgForAuthenticatedConfig(
authenticatedConfig,
cliOrganizationSlug,
isHeadless,
);
}
// If already have organization ID (including null for personal), return as-is
if (authenticatedConfig.organizationId !== undefined) {
return authenticatedConfig;
}
// In headless mode, default to personal organization if none saved
if (isHeadless) {
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// Need to select organization
return autoSelectOrganization(authenticatedConfig);
}
/**
* Gets the list of available organizations for the user
*/
export async function listUserOrganizations(): Promise<
{ id: string; name: string; slug: string }[] | null
> {
const authConfig = loadAuthConfig();
// If using CONTINUE_API_KEY environment variable, organization switching is not supported
if (isEnvironmentAuthConfig(authConfig)) {
return null;
}
if (!isAuthenticatedConfig(authConfig)) {
return null;
}
const apiClient = getApiClient(authConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
// Map the organizations to include slug field
return (
resp.organizations?.map((org) => ({
id: org.id,
name: org.name,
slug: org.slug,
})) || []
);
} catch {
return null;
}
}
/**
* Checks if the user has multiple organizations available
*/
export async function hasMultipleOrganizations(): Promise<boolean> {
const organizations = await listUserOrganizations();
// Has multiple organizations if there's at least one organization (plus personal)
return organizations !== null && organizations.length > 0;
}
/**
* Logs the user out by clearing saved credentials
*/
export function logout(): void {
const onboardingFlagPath = path.join(
env.continueHome,
".onboarding_complete",
);
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
fs.unlinkSync(onboardingFlagPath);
}
if (process.env.CONTINUE_API_KEY) {
console.info(
chalk.yellow(
"Using CONTINUE_API_KEY from environment variables, nothing to log out",
),
);
return;
}
if (fs.existsSync(AUTH_CONFIG_PATH)) {
fs.unlinkSync(AUTH_CONFIG_PATH);
console.info(chalk.green("Successfully logged out"));
} else {
console.info(chalk.yellow("No active session found"));
}
}

View file

@ -0,0 +1,27 @@
/**
* Base interface for command options that are shared across multiple commands
*/
export interface BaseCommandOptions {
/** Path to configuration file */
config?: string;
/** Array of rule specifications (can be file paths, hub slugs, or string content) */
rule?: string[];
/** Array of tools to allow (overrides default policies) */
allow?: string[];
/** Array of tools to ask permission for (overrides default policies) */
ask?: string[];
/** Array of tools to exclude from use (overrides default policies) */
exclude?: string[];
}
/**
* Extended base options that include verbose and tool control flags
*/
export interface ExtendedCommandOptions extends BaseCommandOptions {
/** Enable verbose logging */
verbose?: boolean;
/** Start in plan mode (backward compatibility) */
readonly?: boolean;
/** Start in auto mode (all tools allowed) */
auto?: boolean;
}

View file

@ -0,0 +1,501 @@
import { ModelConfig } from "@continuedev/config-yaml";
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { getDisplayableAsciiArt } from "../asciiArt.js";
import {
compactChatHistory,
findCompactionIndex,
getHistoryForLLM,
} from "../compaction.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { sentryService } from "../sentry.js";
import { initializeServices } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatAnthropicError, formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
shouldAutoCompact,
} from "../util/tokenizer.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
/**
* Processes and validates JSON output for headless mode
* @param response - The raw response from the LLM
* @returns Valid JSON string
*/
function processJsonOutput(response: string): string {
const trimmedResponse = response.trim();
try {
// Try to parse the response as JSON to validate it
JSON.parse(trimmedResponse);
// If it parses successfully, return as-is
return trimmedResponse;
} catch {
// If it's not valid JSON, wrap it in a JSON object
return JSON.stringify({
response: trimmedResponse,
status: "success",
note: "Response was not valid JSON, so it was wrapped in a JSON object",
});
}
}
/**
* Strips <think></think> tags and excess whitespace from response
* @param response - The raw response from the LLM
* @returns Cleaned response
*/
function stripThinkTags(response: string): string {
// Remove <think></think> tags and their content
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
// Remove excess whitespace: multiple consecutive newlines become single newlines
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
// Trim leading and trailing whitespace
cleaned = cleaned.trim();
return cleaned;
}
export interface ChatOptions extends ExtendedCommandOptions {
headless?: boolean;
resume?: boolean;
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
silent?: boolean; // Strip <think></think> tags and excess whitespace
org?: string; // Organization slug to use for this session
}
export async function initializeChatHistory(
options: ChatOptions,
): Promise<ChatCompletionMessageParam[]> {
let chatHistory: ChatCompletionMessageParam[] = [];
// Load previous session if --resume flag is used
if (options.resume) {
const savedHistory = loadSession();
if (savedHistory) {
chatHistory = savedHistory;
logger.info(chalk.yellow("Resuming previous session..."));
} else {
logger.info(chalk.yellow("No previous session found, starting fresh..."));
}
}
// If no session loaded or not resuming, initialize with system message
if (chatHistory.length === 0) {
const systemMessage = await constructSystemMessage(
options.rule,
options.format,
options.headless,
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
}
}
return chatHistory;
}
// Helper function to handle manual compaction
async function handleManualCompaction(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
llmApi: any,
isHeadless: boolean,
): Promise<{ compactionIndex?: number | null } | void> {
if (!isHeadless) {
console.info(chalk.yellow("Compacting chat history..."));
}
try {
const result = await compactChatHistory(chatHistory, model, llmApi);
// Replace chat history with compacted version
chatHistory.length = 0;
chatHistory.push(...result.compactedHistory);
// Save the compacted session
saveSession(chatHistory);
if (isHeadless) {
safeStdout(
JSON.stringify({
status: "success",
message: "Chat history compacted",
historyLength: chatHistory.length,
}) + "\n",
);
} else {
console.info(chalk.green("Chat history compacted successfully."));
}
return { compactionIndex: result.compactionIndex };
} catch (error) {
const errorMsg = `Compaction error: ${formatError(error)}`;
if (isHeadless) {
safeStdout(JSON.stringify({ status: "error", message: errorMsg }) + "\n");
} else {
console.error(chalk.red(errorMsg));
}
return;
}
}
// Helper function to handle auto-compaction
async function handleAutoCompaction(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
llmApi: any,
isHeadless: boolean,
format?: "json",
): Promise<number | null> {
logger.info("Auto-compacting triggered due to context limit");
if (!isHeadless) {
console.info(
chalk.yellow(
"\nApproaching context limit. Auto-compacting chat history...",
),
);
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "info",
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(chatHistory),
model,
) + "%",
}) + "\n",
);
}
try {
const result = await compactChatHistory(chatHistory, model, llmApi);
chatHistory.length = 0;
chatHistory.push(...result.compactedHistory);
saveSession(chatHistory);
if (!isHeadless) {
console.info(chalk.green("✓ Chat history auto-compacted successfully."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "success",
message: "Auto-compacted successfully",
historyLength: chatHistory.length,
}) + "\n",
);
}
return result.compactionIndex;
} catch (error) {
const errorMsg = `Auto-compaction error: ${formatError(error)}`;
logger.error(errorMsg);
if (!isHeadless) {
console.error(chalk.red(`Warning: ${errorMsg}`));
console.info(chalk.yellow("Continuing without compaction..."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "warning",
message: "Auto-compaction failed, continuing without compaction",
}) + "\n",
);
}
return null;
}
}
interface ProcessMessageOptions {
userInput: string;
chatHistory: ChatCompletionMessageParam[];
model: ModelConfig;
llmApi: any;
isHeadless: boolean;
format?: "json";
silent?: boolean;
compactionIndex?: number | null;
}
async function processMessage(
options: ProcessMessageOptions,
): Promise<{ compactionIndex?: number | null } | void> {
const {
userInput,
chatHistory,
model,
llmApi,
isHeadless,
format,
silent,
compactionIndex: initialCompactionIndex,
} = options;
let compactionIndex = initialCompactionIndex;
// Check for slash commands in headless mode
if (userInput.trim() === "/compact") {
return handleManualCompaction(chatHistory, model, llmApi, isHeadless);
}
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
// Check if auto-compacting is needed BEFORE adding user message
if (shouldAutoCompact(chatHistory, model)) {
const newIndex = await handleAutoCompaction(
chatHistory,
model,
llmApi,
isHeadless,
format,
);
if (newIndex !== null) {
compactionIndex = newIndex;
}
}
// Add user message to history AFTER potential compaction
chatHistory.push({ role: "user", content: userInput });
// Get AI response with potential tool usage
if (!isHeadless) {
console.info(`\n${chalk.bold.blue("Assistant:")}`);
}
try {
const abortController = new AbortController();
// Handle compaction properly - streamChatResponse modifies the array in place
let finalResponse;
if (compactionIndex !== null && compactionIndex !== undefined) {
// When using compaction, we need to send a subset but capture the full history
const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
const originalLength = historyForLLM.length;
finalResponse = await streamChatResponse(
historyForLLM,
model,
llmApi,
abortController,
);
// Append any new messages (assistant/tool) that were added by streamChatResponse
const newMessages = historyForLLM.slice(originalLength);
chatHistory.push(...newMessages);
} else {
// No compaction - just pass the full history directly
finalResponse = await streamChatResponse(
chatHistory,
model,
llmApi,
abortController,
);
}
// In headless mode, only print the final response using safe stdout
if (isHeadless && finalResponse && finalResponse.trim()) {
let processedResponse = finalResponse;
// Strip think tags if --silent flag is enabled
if (silent) {
processedResponse = stripThinkTags(processedResponse);
}
// Process output based on format
const outputResponse =
format === "json"
? processJsonOutput(processedResponse)
: processedResponse;
safeStdout(outputResponse + "\n");
}
// Save session after each successful response
saveSession(chatHistory);
} catch (e: any) {
const error = e instanceof Error ? e : new Error(String(e));
if (model.provider === "anthropic") {
logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
} else {
logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
}
sentryService.captureException(error, {
context: "chat_response",
isHeadless,
chatHistoryLength: chatHistory.length,
});
if (!isHeadless) {
logger.info(
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`),
);
}
}
}
async function runHeadlessMode(
prompt: string | undefined,
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,
});
// Get required services from the service container
const modelState = await serviceContainer.get<ModelServiceState>(
SERVICE_NAMES.MODEL,
);
const { llmApi, model } = modelState;
if (!model) {
throw new Error("No models were found.");
}
// Initialize chat history
const chatHistory = await initializeChatHistory(options);
// Track compaction index if resuming with compacted history
let compactionIndex: number | null = null;
if (options.resume) {
compactionIndex = findCompactionIndex(chatHistory);
}
let isFirstMessage = true;
while (true) {
// When in headless mode, don't ask for user input
if (!isFirstMessage && prompt && options.headless) {
break;
}
// Get user input
const userInput =
isFirstMessage && prompt
? prompt
: readlineSync.question(`\n${chalk.bold.green("You:")} `);
isFirstMessage = false;
const result = await processMessage({
userInput,
chatHistory,
model,
llmApi,
isHeadless: true,
format: options.format,
silent: options.silent,
compactionIndex,
});
// Update compaction index if compaction occurred
if (result && result.compactionIndex !== undefined) {
compactionIndex = result.compactionIndex;
}
}
}
export async function chat(prompt?: string, options: ChatOptions = {}) {
// Configure logger based on headless mode
configureLogger(options.headless ?? false);
// Configure headless-aware logging system
logging.configureLogger({ headless: options.headless ?? false });
try {
// Record session start
telemetryService.recordSessionStart();
await posthogService.capture("sessionStart", {});
// Start active time tracking
telemetryService.startActiveTime();
// If not in headless mode, use unified initialization with TUI
if (!options.headless) {
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
configPath: options.config,
organizationSlug: options.org,
rules: options.rule,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
// If onboarding was completed, show success message
if (initResult.wasOnboarded) {
console.log(chalk.green("✓ Setup complete! Starting chat..."));
}
// Show ASCII art and version for TUI mode
console.log(getDisplayableAsciiArt());
// Start TUI with skipOnboarding since we already handled it
const tuiOptions: any = {
initialPrompt: prompt,
resume: options.resume,
configPath: options.config,
organizationSlug: options.org,
additionalRules: options.rule,
toolPermissionOverrides: permissionOverrides,
skipOnboarding: true,
};
// If we detected piped input, create a custom stdin for TUI
if ((options as any).hasPipedInput) {
const fs = await import("fs");
const { ReadStream } = await import("tty");
const ttyFd = fs.openSync("/dev/tty", "r");
const customStdin = new ReadStream(ttyFd);
tuiOptions.customStdin = customStdin;
logger.debug("Created custom TTY stdin for TUI mode");
}
await startTUIChat(tuiOptions);
return;
}
// Run headless mode
await runHeadlessMode(prompt, options);
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error));
// Use headless-aware error logging to ensure fatal errors are shown in headless mode
logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
process.exit(1);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();
}
}

View file

@ -0,0 +1,68 @@
import type { AssistantConfig } from '@continuedev/sdk';
import { describe, expect, it } from 'vitest';
import { getAllSlashCommands } from './commands.js';
describe('Slash Commands Integration', () => {
const mockAssistant: AssistantConfig = {
name: 'test-assistant',
version: '1.0.0',
prompts: [
{ name: 'test-prompt', prompt: 'Test prompt', description: 'Test prompt description' }
]
};
describe('System Commands Registration', () => {
it('should include all system commands in the commands list', () => {
const commands = getAllSlashCommands(mockAssistant);
const commandNames = commands.map(cmd => cmd.name);
// Check that system commands are present (mode commands have been removed)
expect(commandNames).toContain('help');
expect(commandNames).toContain('clear');
expect(commandNames).toContain('exit');
expect(commandNames).toContain('login');
expect(commandNames).toContain('logout');
expect(commandNames).toContain('whoami');
expect(commandNames).toContain('model');
expect(commandNames).toContain('config');
});
it('should include assistant prompt commands', () => {
const commands = getAllSlashCommands(mockAssistant);
const commandNames = commands.map(cmd => cmd.name);
expect(commandNames).toContain('test-prompt');
});
it('should categorize system commands correctly', () => {
const commands = getAllSlashCommands(mockAssistant);
const systemCommands = commands.filter(cmd =>
['help', 'clear', 'exit', 'login', 'logout', 'whoami', 'model', 'config'].includes(cmd.name)
);
systemCommands.forEach(cmd => {
expect(cmd.category).toBe('system');
});
});
it('should categorize assistant commands correctly', () => {
const commands = getAllSlashCommands(mockAssistant);
const assistantCommands = commands.filter(cmd => cmd.name === 'test-prompt');
assistantCommands.forEach(cmd => {
expect(cmd.category).toBe('assistant');
});
});
it('should only show exit command in remote mode', () => {
const commands = getAllSlashCommands(mockAssistant, { isRemoteMode: true });
const commandNames = commands.map(cmd => cmd.name);
// In remote mode, only exit command should be available
expect(commandNames).toContain('exit');
expect(commandNames).toHaveLength(1);
});
});
});

View file

@ -0,0 +1,131 @@
import { type AssistantConfig } from "@continuedev/sdk";
// Export command functions
export { chat } from "./chat.js";
export { login } from "./login.js";
export { logout } from "./logout.js";
export { remote } from "./remote.js";
export { serve } from "./serve.js";
export { listSessionsCommand } from "./ls.js";
export interface SlashCommand {
name: string;
description: string;
category: "system" | "assistant";
}
export interface SystemCommand extends SlashCommand {
category: "system";
}
// Central definition of all system slash commands
export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
{
name: "help",
description: "Show help message",
category: "system",
},
{
name: "clear",
description: "Clear the chat history",
category: "system",
},
{
name: "login",
description: "Authenticate with your account",
category: "system",
},
{
name: "logout",
description: "Sign out of your current session",
category: "system",
},
{
name: "whoami",
description: "Check who you're currently logged in as",
category: "system",
},
{
name: "model",
description: "Switch between available chat models",
category: "system",
},
{
name: "config",
description: "Switch configuration or organization",
category: "system",
},
{
name: "mcp",
description: "Manage MCP server connections",
category: "system",
},
{
name: "compact",
description: "Summarize chat history into a compact form",
category: "system",
},
{
name: "resume",
description: "Resume a previous chat session",
category: "system",
},
{
name: "exit",
description: "Exit the chat",
category: "system",
},
];
// Remote mode specific commands
export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
{
name: "exit",
description: "Exit the remote environment",
category: "system",
},
];
/**
* Get all available slash commands including system commands and assistant prompts
*/
export function getAllSlashCommands(
assistant: AssistantConfig,
options: { isRemoteMode?: boolean } = {},
): SlashCommand[] {
const { isRemoteMode = false } = options;
// In remote mode, only show the exit command
if (isRemoteMode) {
return REMOTE_MODE_SLASH_COMMANDS;
}
// All system commands are available
const systemCommands = SYSTEM_SLASH_COMMANDS;
// Get assistant prompt commands
const assistantCommands: SlashCommand[] =
assistant?.prompts?.map((prompt) => ({
name: prompt?.name || "",
description: prompt?.description || "",
category: "assistant" as const,
})) || [];
return [...systemCommands, ...assistantCommands];
}
/**
* Get assistant prompt commands only
*/
export function getAssistantSlashCommands(
assistant: AssistantConfig,
): SlashCommand[] {
return (
assistant?.prompts?.map((prompt) => ({
name: prompt?.name || "",
description: prompt?.description || "",
category: "assistant" as const,
})) || []
);
}

View file

@ -0,0 +1,15 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
try {
await workosLogin();
console.info(chalk.green("Successfully logged in!"));
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
process.exit(1);
}
}

View file

@ -0,0 +1,5 @@
import { logout as workosLogout } from "../auth/workos.js";
export async function logout() {
workosLogout();
}

View file

@ -0,0 +1,129 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as sessionModule from "../session.js";
import { listSessionsCommand } from "./ls.js";
// Mock the session module
vi.mock("../session.js", () => ({
listSessions: vi.fn(),
loadSessionById: vi.fn(),
}));
// Mock the TUI components
vi.mock("../ui/SessionSelector.js", () => ({
SessionSelector: () => null,
}));
// Mock ink
vi.mock("ink", () => ({
render: vi.fn(() => ({ unmount: vi.fn() })),
}));
// Mock react
vi.mock("react", () => ({
createElement: vi.fn(),
}));
// Mock the chat command
vi.mock("./chat.js", () => ({
chat: vi.fn(),
}));
describe("listSessionsCommand", () => {
const mockListSessions = vi.mocked(sessionModule.listSessions);
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("should output JSON format when format is json", async () => {
const mockSessions = [
{
id: "session-1",
path: "/path/to/session1.json",
timestamp: new Date("2023-01-01T10:00:00Z"),
messageCount: 5,
firstUserMessage: "Hello world",
},
{
id: "session-2",
path: "/path/to/session2.json",
timestamp: new Date("2023-01-01T09:00:00Z"),
messageCount: 3,
firstUserMessage: "Test message",
},
];
mockListSessions.mockReturnValue(mockSessions);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({ format: "json" });
expect(consoleSpy).toHaveBeenCalledWith(
JSON.stringify({
sessions: [
{
id: "session-1",
timestamp: "2023-01-01T10:00:00.000Z",
messageCount: 5,
firstUserMessage: "Hello world",
},
{
id: "session-2",
timestamp: "2023-01-01T09:00:00.000Z",
messageCount: 3,
firstUserMessage: "Test message",
},
],
}, null, 2)
);
consoleSpy.mockRestore();
});
it("should use limit of 10 for JSON and 20 for TUI", async () => {
mockListSessions.mockReturnValue([]);
// JSON mode should fetch 10
await listSessionsCommand({ format: "json" });
expect(mockListSessions).toHaveBeenCalledWith(10);
// TUI mode should fetch 20 (so UI can choose how many to display)
await listSessionsCommand({});
expect(mockListSessions).toHaveBeenCalledWith(20);
});
it("should handle empty sessions gracefully in JSON mode", async () => {
mockListSessions.mockReturnValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({ format: "json" });
expect(consoleSpy).toHaveBeenCalledWith(
JSON.stringify({ sessions: [] }, null, 2)
);
consoleSpy.mockRestore();
});
it("should handle empty sessions gracefully in TUI mode", async () => {
mockListSessions.mockReturnValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await listSessionsCommand({});
expect(consoleSpy).toHaveBeenCalledWith(
"No previous sessions found. Start a new conversation with: cn"
);
consoleSpy.mockRestore();
});
});

View file

@ -0,0 +1,108 @@
import { render } from "ink";
import React from "react";
import { loadSessionById, listSessions } from "../session.js";
import { SessionSelector } from "../ui/SessionSelector.js";
import { logger } from "../util/logger.js";
import { chat } from "./chat.js";
interface ListSessionsOptions {
format?: "json";
}
/**
* Set a specific session ID for the current process
* This allows us to load a selected session as if it were the current session
*/
function setSessionId(sessionId: string): void {
// Use the same environment variable that getSessionId() checks
process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
"continue-cli-",
"",
);
}
/**
* List recent chat sessions and allow selection
*/
export async function listSessionsCommand(
options: ListSessionsOptions = {},
): Promise<void> {
// Fetch more sessions than we might display so the UI can choose based on screen height
// But still limit for JSON output to keep it reasonable
const sessions = listSessions(options.format === "json" ? 10 : 20);
// Handle JSON format output
if (options.format === "json") {
console.log(
JSON.stringify(
{
sessions: sessions.map((session) => ({
id: session.id,
timestamp: session.timestamp.toISOString(),
messageCount: session.messageCount,
firstUserMessage: session.firstUserMessage,
})),
},
null,
2,
),
);
return;
}
// Handle empty sessions case
if (sessions.length === 0) {
console.log(
"No previous sessions found. Start a new conversation with: cn",
);
return;
}
// Start TUI selector
return new Promise<void>((resolve, reject) => {
const handleSelect = async (sessionId: string) => {
try {
app.unmount();
// Verify the session exists before trying to load it
const sessionHistory = loadSessionById(sessionId);
if (!sessionHistory) {
console.error(`Session ${sessionId} could not be loaded.`);
resolve();
return;
}
logger.info(`Loading session: ${sessionId}`);
// Set the session ID so that when chat() runs, it will load this session
setSessionId(sessionId);
// Start chat with resume flag to load the selected session
await chat(undefined, {
resume: true,
headless: false,
});
resolve();
} catch (error) {
logger.error("Error loading session:", error);
reject(error);
}
};
const handleExit = () => {
app.unmount();
resolve();
};
const app = render(
React.createElement(SessionSelector, {
sessions,
onSelect: handleSelect,
onExit: handleExit,
}),
);
});
}

View file

@ -0,0 +1,30 @@
import chalk from "chalk";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
prompt?: string,
url: string = "http://localhost:8000",
) {
console.info(chalk.white(`Connecting to remote environment at ${url}...`));
try {
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
try {
// Start the TUI in remote mode
await startRemoteTUIChat(url, prompt);
} finally {
telemetryService.stopActiveTime();
}
} catch (error: any) {
logger.error(
chalk.red(`Failed to connect to remote environment: ${error.message}`),
);
process.exit(1);
}
}

View file

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

View file

@ -0,0 +1,158 @@
import chalk from "chalk";
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
export async function remote(
prompt: string | undefined,
options: {
url?: string;
idempotencyKey?: string;
start?: boolean;
branch?: string;
} = {},
) {
// Check if prompt should come from stdin instead of parameter
let actualPrompt = prompt;
if (prompt) {
// If prompt is provided, still check for stdin and combine them
const stdinInput = readStdinSync();
if (stdinInput) {
// Combine stdin and prompt argument - stdin comes first in XML block
actualPrompt = `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`;
}
} else {
// Try to read from stdin (for piped input like: echo "hello" | cn remote -s)
const stdinInput = readStdinSync();
if (stdinInput) {
actualPrompt = stdinInput;
}
}
// If --url is provided, connect directly to that URL
if (options.url) {
if (options.start) {
// In start mode, output connection details as JSON and exit
console.log(
JSON.stringify({
status: "success",
message: "Remote environment connection details",
url: options.url,
mode: "direct_url",
}),
);
return;
}
console.info(
chalk.white(`Connecting to remote environment at: ${options.url}`),
);
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
try {
// Start the TUI in remote mode
await startRemoteTUIChat(options.url, actualPrompt);
} finally {
telemetryService.stopActiveTime();
}
return;
}
try {
const authConfig = loadAuthConfig();
// Check if we have any valid authentication (file-based or environment variable)
if (!authConfig || !getAccessToken(authConfig)) {
console.error(
chalk.red("Not authenticated. Please run 'cn login' first."),
);
process.exit(1);
}
const accessToken = getAccessToken(authConfig);
const requestBody: any = {
repoUrl: getRepoUrl(),
name: `devbox-${Date.now()}`,
prompt: actualPrompt,
idempotencyKey: options.idempotencyKey,
};
// Add branchName to request body if branch option is provided
if (options.branch) {
requestBody.branchName = options.branch;
}
const response = await fetch(new URL("agents/devboxes", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Failed to create remote environment: ${response.status} ${errorText}`,
);
}
const result = await response.json();
if (options.start) {
// In start mode, output connection details as JSON and exit
console.log(
JSON.stringify({
status: "success",
message: "Remote development environment created successfully",
url: `${env.appUrl}/agents/${result.id}`,
containerUrl: result.url,
containerPort: result.port,
name: requestBody.name,
mode: "new_environment",
}),
);
return;
}
console.info(
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}`),
);
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
try {
// Start the TUI in remote mode (prompt is optional)
await startRemoteTUIChat(remoteUrl, actualPrompt);
} finally {
telemetryService.stopActiveTime();
}
} else {
throw new Error(
"No URL or port returned from remote environment creation",
);
}
} catch (error: any) {
logger.error(
chalk.red(`Failed to create remote environment: ${error.message}`),
);
process.exit(1);
}
}

View file

@ -0,0 +1,153 @@
import type { Server } from "http";
import {
afterEach,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
describe("serve command", () => {
let context: any;
let originalProcessExit: typeof process.exit;
let serverRef: Server | null = null;
beforeEach(() => {
context = createMinimalTestContext();
// Mock process.exit to prevent actual exit during tests
originalProcessExit = process.exit;
process.exit = vi.fn() as any;
// Mock console.log to prevent output during tests
vi.spyOn(console, "log").mockImplementation(() => {});
// Mock all required modules at test level with correct relative paths
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn(() => null),
ensureOrganization: vi.fn(),
getOrganizationId: vi.fn(),
isAuthenticated: vi.fn(() => false),
}));
vi.mock("../onboarding.js", () => ({
runNormalFlow: vi.fn(() =>
Promise.resolve({
config: { models: [] },
llmApi: { chat: vi.fn() },
model: { name: "test-model" },
})
),
}));
vi.mock("../session.js", () => ({
saveSession: vi.fn(),
}));
vi.mock("../systemMessage.js", () => ({
constructSystemMessage: vi.fn(() => Promise.resolve("System message")),
}));
vi.mock("../telemetry/telemetryService.js", () => ({
default: {
recordSessionStart: vi.fn(),
startActiveTime: vi.fn(),
stopActiveTime: vi.fn(),
updateOrganization: vi.fn(),
},
}));
vi.mock("chalk", () => ({
default: {
green: (str: string) => str,
dim: (str: string) => str,
yellow: (str: string) => str,
red: (str: string) => str,
},
}));
});
afterEach(async () => {
context.cleanup();
// Restore original process.exit
process.exit = originalProcessExit;
// Restore console.log
vi.restoreAllMocks();
// Clean up server if it's still running
if (serverRef) {
await new Promise<void>((resolve) => {
serverRef!.close(() => resolve());
});
serverRef = null;
}
vi.clearAllMocks();
});
it.skip("should have /exit endpoint that returns success response", async () => {
// This test is complex and requires proper module mocking setup
// Skip for now to focus on removing top-level mocks
expect(true).toBe(true);
});
it("should pass the --org flag through to initializeServices", async () => {
// Import the services module to spy on
const servicesModule = await import("../services/index.js");
// Create spy on initializeServices
const initializeServicesSpy = vi.spyOn(servicesModule, "initializeServices")
.mockResolvedValue({
config: { models: [] },
llmApi: { chat: vi.fn() },
model: { name: "test-model" }
} as any);
// Create spy on getService
const getServiceSpy = vi.spyOn(servicesModule, "getService")
.mockResolvedValueOnce({
config: { name: "test" },
llmApi: { chat: vi.fn() },
model: { provider: "test", model: "test" }
} as any)
.mockResolvedValueOnce({
config: { name: "test" },
llmApi: { chat: vi.fn() },
model: { provider: "test", model: "test" }
} as any);
// Import serve after setting up spies
const { serve } = await import("./serve.js");
// Call serve with --org flag
const testOptions = {
org: "test-organization-slug",
timeout: "60",
port: "9000"
};
try {
await serve("test prompt", testOptions);
} catch (error) {
// Expected to fail due to incomplete mocking
}
// Check that initializeServices was called with organization option
expect(initializeServicesSpy).toHaveBeenCalled();
expect(initializeServicesSpy).toHaveBeenCalledWith(
expect.objectContaining({
organizationSlug: "test-organization-slug"
})
);
// Clean up spies
initializeServicesSpy.mockRestore();
getServiceSpy.mockRestore();
});
});

View file

@ -0,0 +1,613 @@
import { exec } from "child_process";
import path from "path";
import { promisify } from "util";
import chalk from "chalk";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
getService,
initializeServices,
SERVICE_NAMES,
} from "../services/index.js";
import {
AuthServiceState,
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import { saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { StreamCallbacks } from "../streamChatResponse.types.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { getToolDisplayName } from "../tools/index.js";
import { DisplayMessage } from "../ui/types.js";
import { formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
const execAsync = promisify(exec);
interface ServeOptions extends ExtendedCommandOptions {
timeout?: string;
port?: string;
org?: string;
}
interface PendingPermission {
toolName: string;
toolArgs: any;
requestId: string;
timestamp: number;
}
interface ServerState {
chatHistory: ChatCompletionMessageParam[];
displayMessages: DisplayMessage[]; // Messages formatted for display with tool info
config: any;
model: any;
isProcessing: boolean;
lastActivity: number;
messageQueue: string[];
currentAbortController: AbortController | null;
shouldInterrupt: boolean;
serverRunning: boolean;
pendingPermission: PendingPermission | null;
}
export async function serve(prompt?: string, options: ServeOptions = {}) {
// Check if prompt should come from stdin instead of parameter
let actualPrompt = prompt;
if (!prompt) {
// Try to read from stdin (for piped input like: cat file | cn serve)
const stdinInput = readStdinSync();
if (stdinInput) {
actualPrompt = stdinInput;
}
}
const timeoutSeconds = parseInt(options.timeout || "300", 10);
const timeoutMs = timeoutSeconds * 1000;
const port = parseInt(options.port || "8000", 10);
// Initialize services with tool permission overrides
const { permissionOverrides } = processCommandFlags(options);
await initializeServices({
toolPermissionOverrides: permissionOverrides,
configPath: options.config,
rules: options.rule,
organizationSlug: options.org,
headless: true, // Skip onboarding in serve mode
});
// Get initialized services from the service container
const [configState, modelState] = await Promise.all([
getService<ConfigServiceState>(SERVICE_NAMES.CONFIG),
getService<ModelServiceState>(SERVICE_NAMES.MODEL),
]);
if (!configState.config || !modelState.llmApi || !modelState.model) {
throw new Error("Failed to initialize required services");
}
const { config, llmApi, model } = {
config: configState.config,
llmApi: modelState.llmApi,
model: modelState.model,
};
// Organization selection is already handled in initializeServices
const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH);
if (authState.organizationId) {
telemetryService.updateOrganization(authState.organizationId);
}
// Log configuration information
const organizationId = authState.organizationId || "personal";
const assistantName = config.name;
const assistantSlug = getAssistantSlug(authState.authConfig);
const modelProvider = model.provider;
const modelName = model.model;
console.log(chalk.blue(`\nConfiguration:`));
console.log(chalk.dim(` Organization: ${organizationId}`));
console.log(
chalk.dim(
` Assistant: ${assistantName}${
assistantSlug ? ` (${assistantSlug})` : ""
}`,
),
);
console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
if (options.config) {
console.log(chalk.dim(` Config file: ${options.config}`));
}
// Initialize chat history
const chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = await constructSystemMessage(
options.rule,
undefined,
true,
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
}
// Initialize server state
const state: ServerState = {
chatHistory,
displayMessages: [], // Initialize empty display messages
config,
model,
isProcessing: false,
lastActivity: Date.now(),
messageQueue: [],
currentAbortController: null,
shouldInterrupt: false,
serverRunning: true,
pendingPermission: null,
};
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
const app = express();
app.use(express.json());
// GET /state - Return the current state
app.get("/state", (_req: Request, res: Response) => {
state.lastActivity = Date.now();
res.json({
chatHistory: state.displayMessages, // Send display messages with proper formatting
isProcessing: state.isProcessing,
messageQueueLength: state.messageQueue.length,
pendingPermission: state.pendingPermission,
});
});
// POST /message - Queue a message and potentially interrupt
app.post("/message", async (req: Request, res: Response) => {
state.lastActivity = Date.now();
const { message } = req.body;
if (!message) {
return res.status(400).json({ error: "Message field is required" });
}
// Queue the message
state.messageQueue.push(message);
// If currently processing, set interrupt flag
if (state.isProcessing && state.currentAbortController) {
state.shouldInterrupt = true;
}
res.json({
queued: true,
position: state.messageQueue.length,
willInterrupt: state.shouldInterrupt,
});
// Process messages if not already processing
if (!state.isProcessing) {
processMessages(state, llmApi);
}
});
// POST /permission - Approve or reject pending tool permission
app.post("/permission", async (req: Request, res: Response) => {
state.lastActivity = Date.now();
const { requestId, approved } = req.body;
if (!state.pendingPermission) {
return res.status(400).json({ error: "No pending permission request" });
}
if (state.pendingPermission.requestId !== requestId) {
return res.status(400).json({ error: "Invalid request ID" });
}
// Remove the permission request message
const lastMsg = state.displayMessages[state.displayMessages.length - 1];
if (lastMsg && lastMsg.messageType === "tool-permission-request") {
state.displayMessages.pop();
}
// Send the permission response to the toolPermissionManager
if (approved) {
toolPermissionManager.approveRequest(requestId);
} else {
toolPermissionManager.rejectRequest(requestId);
}
// Clear pending permission state
state.pendingPermission = null;
res.json({
success: true,
approved,
});
});
// GET /diff - Return git diff against main branch
app.get("/diff", async (_req: Request, res: Response) => {
state.lastActivity = Date.now();
try {
// First check if we're in a git repository
await execAsync("git rev-parse --git-dir");
// Get the diff against main branch
const { stdout } = await execAsync("git diff main");
res.json({
diff: stdout,
});
} catch (error: any) {
// Git diff returns exit code 1 when there are differences, which is normal
if (error.code === 1 && error.stdout) {
res.json({
diff: error.stdout,
});
} else if (error.code === 128) {
// Handle case where we're not in a git repo or main branch doesn't exist
res.status(404).json({
error: "Not in a git repository or main branch doesn't exist",
diff: "",
});
} else {
logger.error(`Git diff error: ${formatError(error)}`);
res.status(500).json({
error: `Failed to get git diff: ${formatError(error)}`,
diff: "",
});
}
}
});
// Track intervals for cleanup
let inactivityChecker: NodeJS.Timeout | null = null;
// 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..."),
);
// Respond immediately before shutting down
res.json({
message: "Server shutting down",
success: true,
});
// Set server running flag to false to stop processing
state.serverRunning = false;
// Abort any current processing
if (state.currentAbortController) {
state.currentAbortController.abort();
}
// Clear the message queue
state.messageQueue = [];
// Clean up intervals
if (inactivityChecker) {
clearInterval(inactivityChecker);
inactivityChecker = null;
}
// Give a moment for the response to be sent
setTimeout(() => {
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
});
}, 100);
});
const server = app.listen(port, () => {
console.log(chalk.green(`Server started on http://localhost:${port}`));
console.log(chalk.dim("Endpoints:"));
console.log(chalk.dim(" GET /state - Get current agent state"));
console.log(
chalk.dim(
" POST /message - Send a message (body: { message: string })",
),
);
console.log(
chalk.dim(
" POST /permission - Approve/reject tool (body: { requestId, approved })",
),
);
console.log(
chalk.dim(" GET /diff - Get git diff against main branch"),
);
console.log(
chalk.dim(" POST /exit - Gracefully shut down the server"),
);
console.log(
chalk.dim(
`\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
),
);
// If initial prompt provided, queue it for processing
if (actualPrompt) {
console.log(chalk.dim("\nProcessing initial prompt..."));
state.messageQueue.push(actualPrompt);
processMessages(state, llmApi);
}
});
// Process messages from the queue
async function processMessages(state: ServerState, llmApi: any) {
while (state.messageQueue.length > 0 && state.serverRunning) {
const userMessage = state.messageQueue.shift()!;
state.isProcessing = true;
state.shouldInterrupt = false;
state.lastActivity = Date.now();
// Add user message to history
state.chatHistory.push({ role: "user", content: userMessage });
state.displayMessages.push({ role: "user", content: userMessage });
try {
// Create new abort controller for this response
state.currentAbortController = new AbortController();
// Stream the response with interruption support
await streamChatResponseWithInterruption(
state,
llmApi,
state.currentAbortController,
() => state.shouldInterrupt,
);
// Save session after successful response
saveSession(state.chatHistory);
state.lastActivity = Date.now();
} catch (e: any) {
if (e.name === "AbortError") {
logger.debug("Response interrupted");
// Remove the partial assistant message if it exists
const lastMessage = state.chatHistory[state.chatHistory.length - 1];
if (lastMessage.role === "assistant" && !lastMessage.content) {
state.chatHistory.pop();
}
// Also remove partial display messages
const lastDisplayMessage =
state.displayMessages[state.displayMessages.length - 1];
if (
lastDisplayMessage &&
lastDisplayMessage.role === "assistant" &&
lastDisplayMessage.isStreaming
) {
state.displayMessages.pop();
}
} else {
logger.error(`Error: ${formatError(e)}`);
// Add error message to chat history and display messages
const errorMessage = `Error: ${formatError(e)}`;
state.chatHistory.push({
role: "assistant",
content: errorMessage,
});
state.displayMessages.push({
role: "assistant",
content: errorMessage,
});
}
} finally {
state.currentAbortController = null;
state.isProcessing = false;
}
}
}
// Check for inactivity and shutdown
inactivityChecker = setInterval(() => {
if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
console.log(
chalk.yellow(
`\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
),
);
state.serverRunning = false;
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
});
if (inactivityChecker) {
clearInterval(inactivityChecker);
inactivityChecker = null;
}
}
}, 1000);
// Handle graceful shutdown
process.on("SIGINT", () => {
console.log(chalk.yellow("\nShutting down server..."));
state.serverRunning = false;
if (inactivityChecker) {
clearInterval(inactivityChecker);
inactivityChecker = null;
}
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
});
});
}
// Modified version of streamChatResponse that supports interruption
async function streamChatResponseWithInterruption(
state: ServerState,
llmApi: any,
abortController: AbortController,
shouldInterrupt: () => boolean,
): Promise<string> {
// Import the original streamChatResponse logic but add interruption checks
// Create a wrapper that checks for interruption
const originalSignal = abortController.signal;
const checkInterruption = () => {
if (shouldInterrupt() && !originalSignal.aborted) {
abortController.abort();
}
};
// Set up periodic interruption checks
const interruptionChecker = setInterval(checkInterruption, 100);
let currentStreamingMessage: DisplayMessage | null = null;
// Create callbacks to capture tool events
const callbacks: StreamCallbacks = {
onContent: (content: string) => {
if (!currentStreamingMessage) {
currentStreamingMessage = {
role: "assistant",
content: "",
isStreaming: true,
};
state.displayMessages.push(currentStreamingMessage);
}
currentStreamingMessage.content += content;
},
onContentComplete: (content: string) => {
if (currentStreamingMessage) {
currentStreamingMessage.content = content;
currentStreamingMessage.isStreaming = false;
currentStreamingMessage = null;
} else {
// Add complete assistant message
state.displayMessages.push({
role: "assistant",
content: content,
isStreaming: false,
});
}
},
onToolStart: (toolName: string, toolArgs?: any) => {
// Format tool call similar to local mode
const formatToolCall = (name: string, args: any) => {
const displayName = getToolDisplayName(name);
if (!args) return displayName;
const firstValue = Object.values(args)[0];
const formatPath = (value: any) => {
if (typeof value === "string" && path.isAbsolute(value)) {
const workspaceRoot = process.cwd();
const relativePath = path.relative(workspaceRoot, value);
return relativePath || value;
}
return value;
};
return `${displayName}(${formatPath(firstValue) || ""})`;
};
// If there was streaming content, finalize it first
if (currentStreamingMessage && currentStreamingMessage.content) {
currentStreamingMessage.isStreaming = false;
currentStreamingMessage = null;
}
state.displayMessages.push({
role: "system",
content: `○ ${formatToolCall(toolName, toolArgs)}`,
messageType: "tool-start",
toolName,
});
},
onToolResult: (result: string, toolName: string) => {
// Replace the tool-start message with tool-result
const displayName = getToolDisplayName(toolName);
// Find and replace the corresponding tool-start message
for (let i = state.displayMessages.length - 1; i >= 0; i--) {
if (
state.displayMessages[i].messageType === "tool-start" &&
state.displayMessages[i].toolName === toolName
) {
state.displayMessages[i] = {
...state.displayMessages[i],
content: `● ${displayName}`,
messageType: "tool-result",
toolResult: result,
};
return;
}
}
// If no tool-start found, add as new message (fallback)
state.displayMessages.push({
role: "system",
content: `● ${displayName}`,
messageType: "tool-result",
toolName,
toolResult: result,
});
},
onToolError: (error: string, toolName?: string) => {
state.displayMessages.push({
role: "system",
content: `✗ Tool error: ${error}`,
messageType: "tool-error",
toolName,
});
},
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
requestId: string,
) => {
// Set pending permission state
state.pendingPermission = {
toolName,
toolArgs,
requestId,
timestamp: Date.now(),
};
// Add a display message indicating permission is needed
state.displayMessages.push({
role: "system",
content: `⚠️ Tool ${toolName} requires permission`,
messageType: "tool-permission-request" as any,
toolName,
});
// Don't wait here - the streamChatResponse will handle waiting
},
};
try {
const response = await streamChatResponse(
state.chatHistory,
state.model,
llmApi,
abortController,
callbacks,
);
return response || "";
} finally {
clearInterval(interruptionChecker);
// Ensure any streaming message is finalized
if (currentStreamingMessage !== null) {
// TypeScript is having issues with this line - the message will be finalized anyway
// currentStreamingMessage.isStreaming = false;
}
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,56 @@
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
import { describe, expect, test, vi, beforeEach } from 'vitest';
// Mock dependencies
vi.mock('./auth/workos.js');
import type { AuthConfig } from './auth/workos.js';
import { getLlmApi } from './config.js';
describe('config', () => {
let mockAuthConfig: AuthConfig;
beforeEach(() => {
vi.clearAllMocks();
mockAuthConfig = {
accessToken: 'test-token',
refreshToken: 'test-refresh',
userEmail: 'test@example.com',
userId: 'test-user',
organizationId: 'test-org',
expiresAt: Date.now() + 3600000,
};
});
describe('getLlmApi()', () => {
test('should throw error when models array is empty', () => {
const assistant: AssistantUnrolled = {
name: 'test-assistant',
version: '1.0.0',
models: [],
};
expect(() => getLlmApi(assistant, mockAuthConfig))
.toThrow('No models found in the configured assistant');
});
test('should throw error when no chat models available', () => {
const assistant: AssistantUnrolled = {
name: 'test-assistant',
version: '1.0.0',
models: [
{
provider: 'openai',
model: 'text-embedding-ada-002',
name: 'Ada Embeddings',
roles: ['embed'],
} as ModelConfig,
],
};
expect(() => getLlmApi(assistant, mockAuthConfig))
.toThrow('No models with the chat role found in the configured assistant');
});
});
});

View file

@ -0,0 +1,106 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import {
BaseLlmApi,
constructLlmApi,
LLMConfig,
} from "@continuedev/openai-adapters";
import {
Configuration,
DefaultApi,
DefaultApiInterface,
} from "@continuedev/sdk/dist/api/dist/index.js";
import {
AuthConfig,
getAccessToken,
getOrganizationId,
} from "./auth/workos.js";
import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./services/MCPService.js";
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig,
): [BaseLlmApi, ModelConfig] {
if (!assistant.models || assistant.models.length === 0) {
throw new Error("No models found in the configured assistant");
}
const model = assistant.models?.find(
(model) =>
model?.roles?.includes("chat") || (model && model.roles === undefined),
);
if (!model) {
throw new Error(
"No models with the chat role found in the configured assistant",
);
}
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
model.provider === "continue-proxy"
? {
provider: model.provider,
requestOptions: model.requestOptions,
apiBase: model.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (model as any).apiKeyLocation,
// envSecretLocations: model.env,
orgScopeId: organizationId,
proxyUrl: undefined, // TODO
},
}
: {
provider: model.provider as any,
apiKey: model.apiKey,
apiBase: model.apiBase,
requestOptions: model.requestOptions,
env: model.env,
};
const llmApi = constructLlmApi(config);
if (!llmApi) {
throw new Error(
"Failed to initialize LLM. Please check your configuration.",
);
}
return [llmApi, model];
}
export function getApiClient(
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,
): Promise<{
config: AssistantUnrolled;
llmApi: BaseLlmApi;
model: ModelConfig;
mcpService: MCPService;
apiClient: DefaultApiInterface;
}> {
const apiClient = getApiClient(authConfig?.accessToken);
const result = await loadConfiguration(authConfig, configPath, apiClient);
const config = result.config;
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = new MCPService();
await mcpService.initialize(config, false);
return { config, llmApi, model, mcpService, apiClient };
}

View file

@ -0,0 +1,416 @@
import * as fs from "fs";
import { dirname } from "node:path";
import * as path from "path";
import {
AssistantUnrolled,
PackageIdentifier,
RegistryClient,
unrollAssistant,
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { uriToPath, uriToSlug } from "./auth/uriUtils.js";
import {
AuthConfig,
getAccessToken,
getConfigUri,
getOrganizationId,
isEnvironmentAuthConfig,
updateConfigUri,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
import { env } from "./env.js";
export interface ConfigLoadResult {
config: AssistantUnrolled;
source: ConfigSource;
}
export type ConfigSource =
| { type: "cli-flag"; path: string }
| { type: "saved-uri"; uri: string }
| { type: "user-assistant"; slug: string }
| { type: "default-config-yaml" }
| { type: "default-agent" };
/**
* Streamlined configuration loader that implements the specification
* with clear precedence and fallback logic in a single testable function.
*/
export async function loadConfiguration(
authConfig: AuthConfig,
cliConfigPath: string | undefined,
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,
);
// Step 3: Save config URI for session continuity (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const uri = getUriFromSource(configSource);
if (uri) {
updateConfigUri(uri);
}
}
return { config, source: configSource };
}
/**
* Determines the configuration source using the specification's precedence rules:
* 1. CLI --config flag (highest priority)
* 2. Saved config URI (if no CLI flag)
* 3. Default resolution (if no flag and no saved URI)
*/
function determineConfigSource(
authConfig: AuthConfig,
cliConfigPath: string | undefined,
): ConfigSource {
// Priority 1: CLI --config flag
if (cliConfigPath) {
return { type: "cli-flag", path: cliConfigPath };
}
// Priority 2: Saved config URI (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const savedUri = getConfigUri(authConfig);
if (savedUri) {
return { type: "saved-uri", uri: savedUri };
}
}
// Priority 3: Default resolution based on auth state
if (authConfig === null) {
// Unauthenticated: check for default config.yaml, then fallback to default agent
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
if (fs.existsSync(defaultConfigPath)) {
return { type: "default-config-yaml" };
}
return { type: "default-agent" };
} else {
// Authenticated: try user assistants first
return { type: "user-assistant", slug: "" }; // Empty slug means "first available"
}
}
/**
* Loads configuration from the determined source with appropriate error handling
*/
async function loadFromSource(
source: ConfigSource,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
try {
switch (source.type) {
case "cli-flag":
return await loadFromCliFlag(
source.path,
accessToken,
organizationId,
apiClient,
);
case "saved-uri":
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,
);
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",
),
);
return await loadDefaultAgent(organizationId, apiClient);
}
throw error;
}
}
/**
* Loads configuration from CLI --config flag
* Supports both file paths and assistant slugs
*/
async function loadFromCliFlag(
configPath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
if (isFilePath(configPath)) {
// Load local YAML file
return await loadConfigYaml(
configPath,
accessToken,
organizationId,
apiClient,
);
} else {
// Load assistant slug
return await loadAssistantSlug(configPath, organizationId, apiClient);
}
}
/**
* Loads configuration from saved URI in auth config
*/
async function loadFromSavedUri(
uri: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const filePath = uriToPath(uri);
if (filePath) {
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}`);
}
/**
* Loads first available user assistant with fallback to default agent
*/
async function loadUserAssistantWithFallback(
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
if (assistants.length > 0) {
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
// No user assistants, fall back to default agent
return await loadDefaultAgent(organizationId, apiClient);
}
/**
* Loads default config.yaml from ~/.continue/config.yaml
*/
async function loadDefaultConfigYaml(
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
return await loadConfigYaml(
defaultConfigPath,
accessToken,
organizationId,
apiClient,
);
}
/**
* Loads the default continuedev/default-agent
*/
async function loadDefaultAgent(
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const resp = await apiClient.getAssistant({
ownerSlug: "continuedev",
packageSlug: "default-agent",
organizationId: organizationId ?? undefined,
});
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
}
return resp.configResult.config as AssistantUnrolled;
}
/**
* Common function to unroll an assistant with consistent configuration
*/
async function unrollAssistantWithConfig(
packageIdentifier: PackageIdentifier,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const unrollResult = await unrollAssistant(
packageIdentifier,
new RegistryClient({
accessToken: accessToken ?? undefined,
apiBase: env.apiBase,
rootPath:
packageIdentifier.uriType === "file"
? dirname(packageIdentifier.filePath)
: undefined,
}),
{
currentUserSlug: "",
alwaysUseProxy: false,
orgScopeId: organizationId,
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
},
);
const errorDetails = unrollResult.errors;
if (!unrollResult.config) {
throw new Error(`Failed to load config:\n${errorDetails}`);
} else if (errorDetails?.length) {
const warnings =
errorDetails?.length > 1
? errorDetails.map((d) => `\n- ${d.message}`)
: errorDetails[0].message;
console.warn(chalk.dim(`Warning: ${warnings}`));
}
return unrollResult.config;
}
/**
* Loads a local YAML configuration file
*/
async function loadConfigYaml(
filePath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
return await unrollAssistantWithConfig(
{ filePath, uriType: "file" },
accessToken,
organizationId,
apiClient,
);
}
/**
* Loads an assistant by slug from the Continue platform
*/
async function loadAssistantSlug(
slug: string,
organizationId: string | null,
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
const [ownerSlug, packageSlug] = slug.split("/");
if (!ownerSlug || !packageSlug) {
throw new Error(
`Invalid assistant slug format. Expected "owner/package", got: ${slug}`,
);
}
// Unroll locally if not logged in
if (!(apiClient as any).configuration.apiKey) {
return await unrollAssistantWithConfig(
{
uriType: "slug",
fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" },
},
null,
organizationId,
apiClient,
);
}
const resp = await apiClient.getAssistant({
ownerSlug,
packageSlug,
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
const result = resp.configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
/**
* Determines if a config path is a file path vs assistant slug
*/
function isFilePath(configPath: string): boolean {
return (
configPath.startsWith(".") ||
configPath.startsWith("/") ||
configPath.startsWith("~") ||
// Windows absolute paths (C:\, D:\, etc.)
/^[A-Za-z]:[/\\]/.test(configPath) ||
// UNC paths (\\server\share)
configPath.startsWith("\\\\") ||
// Contains file extension
configPath.includes(".yaml") ||
configPath.includes(".yml") ||
configPath.includes(".json")
);
}
/**
* Converts a config source back to a URI for persistence
*/
function getUriFromSource(source: ConfigSource): string | null {
switch (source.type) {
case "cli-flag":
return isFilePath(source.path)
? `file://${source.path}`
: `slug://${source.path}`;
case "saved-uri":
return source.uri;
case "default-config-yaml":
return `file://${path.join(env.continueHome, "config.yaml")}`;
default:
return null;
}
}

View file

@ -0,0 +1,37 @@
import { Continue, ContinueClient } from "@continuedev/sdk";
import chalk from "chalk";
import { env } from "./env.js";
/**
* Initialize the Continue SDK with the given parameters
* @param apiKey - API key to use for authentication
* @param assistantSlug - Slug of the assistant to use
* @param organizationId - Optional organization ID
* @returns Promise resolving to the Continue SDK instance
*/
export async function initializeContinueSDK(
apiKey: string | undefined,
assistantSlug: string,
organizationId?: string,
): Promise<ContinueClient> {
if (!apiKey) {
console.error(chalk.red("Error: No API key provided for Continue SDK"));
throw new Error("No API key provided for Continue SDK");
}
try {
return await Continue.from({
apiKey,
assistant: assistantSlug,
organizationId,
baseURL: env.apiBase,
});
} catch (error) {
console.error(
chalk.red("Error initializing Continue SDK:"),
error instanceof Error ? error.message : String(error),
);
throw error;
}
}

View file

@ -0,0 +1,58 @@
import fs from "fs/promises";
import path from "path";
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import { cleanupMocks } from "../test-helpers/mock-helpers.js";
describe("E2E: Authentication", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
cleanupMocks();
await cleanupTestContext(context);
});
describe("logout command", () => {
it("should remove auth credentials", async () => {
const authPath = path.join(context.testDir, ".continue", "auth.json");
// Create auth file
await fs.mkdir(path.dirname(authPath), { recursive: true });
await fs.writeFile(
authPath,
JSON.stringify({
accessToken: "test-token",
user: { id: "test-user", email: "test@example.com" },
})
);
// Run logout
const result = await runCLI(context, { args: ["logout"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Successfully logged out");
// Check auth file is removed
const authExists = await fs
.access(authPath)
.then(() => true)
.catch(() => false);
expect(authExists).toBe(false);
});
it("should handle logout when not logged in", async () => {
const result = await runCLI(context, { args: ["logout"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("No active session found");
});
});
});

View file

@ -0,0 +1,81 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import { getVersion } from "../version.js";
describe("E2E: Basic Commands", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
describe("--version flag", () => {
it("should display version information", async () => {
const result = await runCLI(context, { args: ["--version"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(getVersion());
expect(result.stderr).toBe("");
});
});
describe("--help flag", () => {
it("should display help information", async () => {
const result = await runCLI(context, { args: ["--help"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Continue CLI");
expect(result.stdout).toContain("AI-powered development assistant");
expect(result.stdout).toContain("Options:");
expect(result.stdout).toContain("-p, --print");
expect(result.stdout).toContain("--config <path>");
expect(result.stdout).toContain("--resume");
expect(result.stdout).toContain("--readonly");
expect(result.stdout).toContain("--auto");
expect(result.stdout).toContain("--rule <rule>");
});
it("should show available commands", async () => {
const result = await runCLI(context, { args: ["--help"] });
expect(result.stdout).toContain("Commands:");
expect(result.stdout).toContain("login");
expect(result.stdout).toContain("logout");
});
});
describe("subcommand help", () => {
it("should show help for login command", async () => {
const result = await runCLI(context, { args: ["login", "--help"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Authenticate with Continue");
});
it("should show help for logout command", async () => {
const result = await runCLI(context, { args: ["logout", "--help"] });
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Log out from Continue");
});
});
describe("invalid commands", () => {
it("should show error for invalid flag", async () => {
const result = await runCLI(context, {
args: ["--invalid-flag"],
expectError: true,
});
expect(result.exitCode).not.toBe(0);
expect(result.stderr || result.stdout).toContain("error");
});
});
});

View file

@ -0,0 +1,115 @@
import { describe, expect, test } from 'vitest';
describe('Config Switching Implementation Test', () => {
test('ConfigService updateConfigPath method exists with correct signature', async () => {
const { ConfigService } = await import('../services/ConfigService.js');
const configService = new ConfigService();
// Verify the method exists
expect(configService.updateConfigPath).toBeDefined();
expect(typeof configService.updateConfigPath).toBe('function');
// Verify it takes 1 parameter (configPath: string | undefined)
expect(configService.updateConfigPath.length).toBe(1);
});
test('ServiceContainer has required reactive methods', async () => {
const { serviceContainer } = await import('../services/ServiceContainer.js');
// Verify service container has all methods needed for reactive updates
expect(typeof serviceContainer.set).toBe('function');
expect(typeof serviceContainer.reload).toBe('function');
expect(typeof serviceContainer.get).toBe('function');
// These are the methods that enable reactive config switching
});
test('SERVICE_NAMES constants exist for config switching', async () => {
const { SERVICE_NAMES } = await import('../services/types.js');
// Verify the service names our implementation uses (lowercase)
expect(SERVICE_NAMES.CONFIG).toBe('config');
expect(SERVICE_NAMES.MODEL).toBe('model');
expect(SERVICE_NAMES.MCP).toBe('mcp');
expect(SERVICE_NAMES.AUTH).toBe('auth');
expect(SERVICE_NAMES.API_CLIENT).toBe('apiClient');
});
test('ConfigService implementation structure is correct', async () => {
const { ConfigService } = await import('../services/ConfigService.js');
// Create instance to verify it can be instantiated
const configService = new ConfigService();
// Verify it has the required methods for our reactive system
expect(typeof configService.updateConfigPath).toBe('function');
expect(typeof configService.getState).toBe('function');
expect(typeof configService.initialize).toBe('function');
// The updateConfigPath method is key to reactive config switching
});
test('loadConfiguration function exists for configuration loading', async () => {
const configLoaderModule = await import('../configLoader.js');
// Verify loadConfiguration function exists and is callable
expect(typeof configLoaderModule.loadConfiguration).toBe('function');
// This is what ConfigService.updateConfigPath uses to load new configs
});
test('auth functions exist for assistant slug management', async () => {
const authModule = await import('../auth/workos.js');
// Verify auth functions exist for assistant slug handling
expect(typeof authModule.loadAuthConfig).toBe('function');
expect(typeof authModule.updateAssistantSlug).toBe('function');
// These are used by ConfigService.updateConfigPath for auth management
});
test('expected config switching flow is documented', () => {
// This test documents the expected behavior:
const configSwitchingFlow = {
trigger: '/config command in TUI',
userAction: 'select different configuration',
codeFlow: [
'useConfigSelector calls services.config.updateConfigPath(newPath)',
'ConfigService.updateConfigPath loads new config via loadConfiguration()',
'ConfigService calls serviceContainer.set(CONFIG, newState)',
'ConfigService calls serviceContainer.reload(MODEL)',
'ConfigService calls serviceContainer.reload(MCP)',
'MODEL service reloads with new model from new config',
'IntroMessage re-renders via useServices() reactive hook',
'IntroMessage displays new model name'
],
expectedResult: 'IntroMessage shows model from newly selected config'
};
// Verify our flow documentation is complete
expect(configSwitchingFlow.codeFlow).toHaveLength(8);
expect(configSwitchingFlow.expectedResult).toContain('IntroMessage shows model');
// The problem we're solving: step 4-5 (serviceContainer.reload calls)
// are what trigger the reactive updates to make IntroMessage update
});
test('real implementation inspection', async () => {
// This test inspects the actual implementation to verify it does what we expect
const { ConfigService } = await import('../services/ConfigService.js');
// Get the source code of updateConfigPath to verify it contains the right calls
const updateConfigPathSource = ConfigService.prototype.updateConfigPath.toString();
// Verify the implementation contains the key reactive method calls
expect(updateConfigPathSource).toContain('serviceContainer.set');
expect(updateConfigPathSource).toContain('serviceContainer.reload');
expect(updateConfigPathSource).toContain('SERVICE_NAMES.MODEL');
expect(updateConfigPathSource).toContain('SERVICE_NAMES.MCP');
expect(updateConfigPathSource).toContain('loadConfiguration');
// This confirms our implementation has the right structure for reactive updates
console.log('✅ ConfigService.updateConfigPath implementation contains required reactive calls');
});
});

View file

@ -0,0 +1,115 @@
import * as fs from "fs/promises";
import * as path from "path";
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
cleanupMockLLMServer,
type MockLLMServer,
createMockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should work when ANTHROPIC_API_KEY is set in environment", async () => {
// Create a mock LLM server using the same pattern as working tests
mockServer = await createMockLLMServer({
response: "Hello! This is a response from Claude.",
});
// Use OpenAI provider pointing to mock server (same as working tests)
const configContent = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- name: test-claude
model: claude-3-5-sonnet
provider: openai
apiKey: test-key
apiBase: ${mockServer.url}
roles:
- chat
`;
const configPath = path.join(context.testDir, "test-config.yaml");
await fs.writeFile(configPath, configContent);
context.configPath = configPath;
// Create onboarding flag to skip onboarding
const onboardingFlagPath = path.join(
context.testDir,
".continue",
".onboarding_complete",
);
await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
await fs.writeFile(onboardingFlagPath, new Date().toISOString());
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hi there"],
env: {
ANTHROPIC_API_KEY: "test-api-key-from-env"
},
timeout: 15000,
});
// Verify the CLI successfully runs (even if not using env var in this test)
expect(result.stdout).toContain("Hello! This is a response from Claude.");
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the user message in the request
const userMessage = mockServer.requests[0].body.messages.find(
(m: any) => m.role === "user"
);
expect(userMessage.content).toBe("Hi there");
}, 20000);
it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => {
// This test verifies the main fix: CLI automatically creates config from ANTHROPIC_API_KEY
// when no config file exists in headless mode
const result = await runCLI(context, {
args: ["-p", "test prompt"],
env: {
ANTHROPIC_API_KEY: "sk-test-invalid-key-format",
CONTINUE_GLOBAL_DIR: context.testDir + "/.continue"
},
expectError: true,
timeout: 15000,
});
// Should fail with authentication error (not service initialization error)
// This proves the fix works and CLI reaches the API call stage
expect(result.stderr).toContain("authentication_error");
// Should NOT contain the old error about service initialization
expect(result.stderr).not.toContain("Failed to initialize ConfigService");
// Verify config.yaml was automatically created
const configPath = path.join(context.testDir, ".continue", "config.yaml");
const configExists = await fs.stat(configPath).then(() => true).catch(() => false);
expect(configExists).toBe(true);
if (configExists) {
const configContent = await fs.readFile(configPath, "utf-8");
expect(configContent).toContain("anthropic/claude-4-sonnet");
expect(configContent).toContain("ANTHROPIC_API_KEY: sk-test-invalid-key-format");
}
}, 20000);
});

View file

@ -0,0 +1,212 @@
import * as fs from "fs/promises";
import * as path from "path";
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
createMockLLMServer,
createMockLLMConfig,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with Dynamic Responses", () => {
let context: any;
let mockServer: MockLLMServer;
let extraServers: MockLLMServer[] = [];
beforeEach(async () => {
context = undefined;
mockServer = undefined as any;
extraServers = [];
});
afterEach(async () => {
// Clean up all extra servers first
if (extraServers.length > 0) {
await Promise.all(extraServers.map(server => cleanupMockLLMServer(server)));
extraServers = [];
}
// Clean up main server
if (mockServer) {
await cleanupMockLLMServer(mockServer);
mockServer = undefined as any;
}
// Clean up context last
if (context) {
await cleanupTestContext(context);
context = undefined;
}
// Small delay to ensure cleanup completes
await new Promise(resolve => setTimeout(resolve, 50));
});
it("should respond dynamically based on prompt content", async () => {
context = await createTestContext();
// Create a mock server with dynamic responses
mockServer = await setupMockLLMTest(context, {
response: (prompt: string) => {
if (prompt.includes("weather")) {
return "It's sunny and 72°F today!";
} else if (prompt.includes("time")) {
return "The current time is 3:30 PM.";
} else {
return "I don't understand your question.";
}
},
});
// Test weather query
const weatherResult = await runCLI(context, {
args: ["-p", "--config", context.configPath, "What's the weather like?"],
timeout: 15000,
});
expect(weatherResult.stdout).toContain("It's sunny and 72°F today!");
// Test time query
const timeResult = await runCLI(context, {
args: ["-p", "--config", context.configPath, "What time is it?"],
timeout: 15000,
});
expect(timeResult.stdout).toContain("The current time is 3:30 PM.");
// Test unknown query
const unknownResult = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Tell me about quantum physics"],
timeout: 15000,
});
expect(unknownResult.stdout).toContain("I don't understand your question.");
// Verify all requests were tracked
expect(mockServer.requests).toHaveLength(3);
});
it("should work with non-streaming responses", async () => {
context = await createTestContext();
mockServer = await setupMockLLMTest(context, {
response: "Non-streaming response",
streaming: false,
});
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Test non-streaming"],
timeout: 15000,
});
expect(result.stdout).toContain("Non-streaming response");
expect(result.exitCode).toBe(0);
}, 20000);
it("should handle multiple mock servers for different models", async () => {
context = await createTestContext();
// Create two different mock servers and track them for cleanup
const gpt4Server = await createMockLLMServer({
response: "Response from GPT-4",
});
extraServers.push(gpt4Server);
const claudeServer = await createMockLLMServer({
response: "Response from Claude",
});
extraServers.push(claudeServer);
// Create a config with multiple models
const configContent = `name: Multi-Model Assistant
version: 1.0.0
schema: v1
models:
- name: test-gpt-4
model: gpt-4
provider: openai
apiKey: test-key-1
apiBase: ${gpt4Server.url}
roles:
- chat
- name: test-claude
model: claude-2
provider: anthropic
apiKey: test-key-2
apiBase: ${claudeServer.url}
`;
const configPath = path.join(context.testDir, "multi-model-config.yaml");
await fs.writeFile(configPath, configContent);
context.configPath = configPath;
// Create onboarding flag
const onboardingFlagPath = path.join(context.testDir, ".continue", ".onboarding_complete");
await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
await fs.writeFile(onboardingFlagPath, new Date().toISOString());
// Test with the first model (GPT-4 should be default)
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hello"],
timeout: 15000,
});
expect(result.stdout).toContain("Response from GPT-4");
expect(gpt4Server.requests).toHaveLength(1);
expect(claudeServer.requests).toHaveLength(0);
// Servers will be cleaned up in afterEach
});
it("should allow custom request handling", async () => {
context = await createTestContext();
let requestCount = 0;
const responses = ["First response", "Second response", "Third response"];
// Create server with custom handler
mockServer = await createMockLLMServer({
customHandler: (req, res) => {
if (req.method === "POST" && req.url === "/chat/completions") {
const response = responses[requestCount % responses.length];
requestCount++;
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
});
res.write(`data: {"choices":[{"delta":{"content":"${response}"},"index":0}]}\n\n`);
res.write(`data: [DONE]\n\n`);
res.end();
} else {
res.writeHead(404);
res.end();
}
},
});
// Set up the test environment
const configContent = createMockLLMConfig(mockServer);
const configPath = path.join(context.testDir, "test-config.yaml");
await fs.writeFile(configPath, configContent);
context.configPath = configPath;
const onboardingFlagPath = path.join(context.testDir, ".continue", ".onboarding_complete");
await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
await fs.writeFile(onboardingFlagPath, new Date().toISOString());
// Make multiple requests
for (let i = 0; i < 3; i++) {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, `Request ${i + 1}`],
timeout: 15000,
});
expect(result.stdout).toContain(responses[i]);
}
});
});

View file

@ -0,0 +1,112 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with JSON Format", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should output valid JSON when LLM returns valid JSON", async () => {
const validJsonResponse = {
response: "This is a JSON response",
status: "success",
files: ["test.ts"]
};
mockServer = await setupMockLLMTest(context, {
response: JSON.stringify(validJsonResponse),
streaming: false, // Use non-streaming to avoid JSON escaping issues
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput).toEqual(validJsonResponse);
expect(result.exitCode).toBe(0);
}, 20000);
it("should wrap non-JSON response in JSON object", async () => {
const nonJsonResponse = "This is just plain text response";
mockServer = await setupMockLLMTest(context, {
response: nonJsonResponse,
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput.response).toBe(nonJsonResponse);
expect(parsedOutput.status).toBe("success");
expect(parsedOutput.note).toBe("Response was not valid JSON, so it was wrapped in a JSON object");
expect(result.exitCode).toBe(0);
}, 20000);
it("should include JSON formatting instructions in system message", async () => {
mockServer = await setupMockLLMTest(context, {
response: '{"response": "I understand JSON format"}',
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Hello"],
timeout: 15000,
});
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the system message
const systemMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "system");
expect(systemMessage.content).toContain("JSON output mode");
expect(systemMessage.content).toContain("valid JSON that can be parsed by JSON.parse()");
}, 20000);
it("should fail validation when --format is used without -p flag", async () => {
const result = await runCLI(context, {
args: ["--format", "json", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format flag can only be used with -p/--print flag");
expect(result.exitCode).toBe(1);
}, 10000);
it("should fail validation with invalid format value", async () => {
const result = await runCLI(context, {
args: ["-p", "--format", "xml", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format currently only supports 'json'");
expect(result.exitCode).toBe(1);
}, 10000);
});

View file

@ -0,0 +1,42 @@
import fs from "fs/promises";
import path from "path";
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
describe("E2E: Headless Mode (Minimal)", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
it("should accept a config file path", async () => {
// Create a minimal YAML config
const configPath = path.join(context.testDir, "test-config.yaml");
await fs.writeFile(
configPath,
`name: Test Assistant
model: gpt-4
provider: openai`
);
// For now, just test that it tries to load the config
// Without proper mocking, it will fail to connect to OpenAI
const result = await runCLI(context, {
args: ["-p", "--config", configPath, "Hello"],
env: { OPENAI_API_KEY: "test-key" },
expectError: true,
});
// The fact that it gets past config loading is what we're testing
expect(result.exitCode).toBeDefined();
});
});

View file

@ -0,0 +1,125 @@
import { createTestContext, cleanupTestContext, runCLI, createTestConfig } from "../test-helpers/cli-helpers.js";
describe("E2E: Headless Mode - Missing Prompt", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
it("should exit with helpful error message when no prompt is provided with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
expectError: true,
timeout: 5000, // Short timeout to avoid hanging
});
// Should exit with non-zero exit code
expect(result.exitCode).toBe(1);
// Should provide helpful error message
const output = result.stderr + result.stdout;
expect(output).toContain("A prompt is required when using the -p/--print flag");
expect(output).toContain('cn -p "please review my current git diff"');
expect(output).toContain('echo "hello" | cn -p');
expect(output).toContain('cn -p "analyze the code in src/"');
});
it("should work correctly when prompt is provided with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hello assistant"],
env: { OPENAI_API_KEY: "test-key" },
expectError: true, // Will fail due to invalid API key, but should process the prompt
timeout: 5000,
});
// Should attempt to process the prompt (will fail due to invalid API key)
expect(result.exitCode).not.toBe(0);
// Should NOT show the "prompt required" error message
const output = result.stderr + result.stdout;
expect(output).not.toContain("A prompt is required when using the -p/--print flag");
});
it("should work correctly when prompt is provided via stdin with -p flag", async () => {
// NOTE: In our current implementation, stdin reading is disabled in test environments
// for safety (to prevent hanging). This test verifies the expected behavior when
// stdin input is provided but cannot be read during tests.
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
input: "Hello from stdin",
expectError: true, // Will show "prompt required" error because stdin is disabled in tests
timeout: 5000,
});
// Should exit with error code due to missing prompt (stdin reading is disabled in tests)
expect(result.exitCode).toBe(1);
// Should show the "prompt required" error message since stdin reading is disabled in test env
const output = result.stderr + result.stdout;
expect(output).toContain("A prompt is required when using the -p/--print flag");
});
it("should prioritize command line prompt over stdin when both are provided", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Command line prompt"],
env: { OPENAI_API_KEY: "test-key" },
input: "Stdin input that should be ignored",
expectError: true, // Will fail due to invalid API key
timeout: 5000,
});
// Should use command line prompt over stdin
expect(result.exitCode).not.toBe(0);
// Should NOT show the "prompt required" error message
const output = result.stderr + result.stdout;
expect(output).not.toContain("A prompt is required when using the -p/--print flag");
});
});

View file

@ -0,0 +1,66 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with Mock Server", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
mockServer = await setupMockLLMTest(context, {
response: "Hello World!",
});
});
afterEach(async () => {
await cleanupMockLLMServer(mockServer);
await cleanupTestContext(context);
});
it('should output "Hello World!" when using cn -p "Hi"', async () => {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hi"],
timeout: 15000,
});
// Verify stdout contains "Hello World!"
expect(result.stdout).toContain("Hello World!");
expect(result.exitCode).toBe(0);
}, 20000);
it("should handle streaming responses correctly", async () => {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Say hello"],
timeout: 15000,
});
expect(result.stdout).toContain("Hello World!");
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the user message (system message is first)
const userMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "user");
expect(userMessage.content).toBe("Say hello");
}, 20000);
it("should work with longer prompts", async () => {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Please respond with exactly 'Hello World!' and nothing else"],
timeout: 15000,
});
expect(result.stdout).toContain("Hello World!");
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the user message (system message is first)
const userMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "user");
expect(userMessage.content).toBe("Please respond with exactly 'Hello World!' and nothing else");
}, 20000);
});

View file

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

View file

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

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