feat: integrate SDK into CLI (#1)
* feat: integrate SDK into CLI * bump sdk version * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update package.json * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update index.ts * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * update ci * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml * Update pr-description.yml
This commit is contained in:
parent
1fefd488c4
commit
597e35b5be
18 changed files with 1882 additions and 707 deletions
|
|
@ -1,4 +1,4 @@
|
|||
name: Main
|
||||
name: CLI Assistant
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
||||
|
|
@ -6,3 +6,7 @@ models:
|
|||
- uses: anthropic/claude-3-7-sonnet
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
|
||||
mcpServers:
|
||||
- uses: repomix/repomix-mcp
|
||||
- uses: anthropic/memory-mcp
|
||||
36
.continue/rules/continue-sdk-cli-and-hub-context.yaml
Normal file
36
.continue/rules/continue-sdk-cli-and-hub-context.yaml
Normal 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 assistants
|
||||
|
||||
- Hub functionality: Manages assistant 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
|
||||
|
||||
- Jest: Used for testing framework
|
||||
|
||||
|
||||
All code should follow established patterns for a Node.js CLI tool
|
||||
interfacing with this experimental SDK.
|
||||
7
.env.example
Normal file
7
.env.example
Normal 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=
|
||||
209
.github/workflows/pr-description.yml
vendored
Normal file
209
.github/workflows/pr-description.yml
vendored
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
name: PR Description Generator
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
actions: write
|
||||
checks: write
|
||||
statuses: write
|
||||
deployments: write
|
||||
discussions: 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 --headless --assistant "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt
|
||||
echo "analysis_file=analysis.txt" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
CONTINUE_API_KEY: con-05c7fd30d8932830c76dca916b866fcb25f65a543b53f11668cfc0c2349322e3
|
||||
# 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
|
||||
});
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -1,3 +1,4 @@
|
|||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env
|
||||
/*-repomix.xml
|
||||
|
|
|
|||
115
README.md
115
README.md
|
|
@ -1 +1,114 @@
|
|||
# cli
|
||||
# Continue CLI
|
||||
|
||||
A command-line interface for Continue Dev that provides an interactive AI-assisted development experience.
|
||||
|
||||
## Features
|
||||
|
||||
- 🤖 Interactive AI Assistant Chat
|
||||
- 🔐 Secure Authentication via WorkOS
|
||||
- 🛠️ Built-in Development Tools
|
||||
- ⚡ Real-time Response Streaming
|
||||
- 🎯 Slash Command Support
|
||||
- 🤫 Headless Mode for Automation
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @continuedev/cli -g
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```bash
|
||||
continue-cli
|
||||
```
|
||||
|
||||
### With Custom Assistant
|
||||
|
||||
```bash
|
||||
continue-cli --assistant-path /path/to/assistant.json
|
||||
```
|
||||
|
||||
### Headless Mode
|
||||
|
||||
```bash
|
||||
continue-cli --headless --prompt "Your command here"
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
The CLI supports various slash commands during interaction:
|
||||
|
||||
- `/help` - Display help information
|
||||
- `/exit` - Exit the CLI
|
||||
- Additional commands available during chat sessions
|
||||
|
||||
## Development
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js (version specified in .nvmrc)
|
||||
- npm or yarn
|
||||
|
||||
### Setup
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Build the project:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
4. Start in development mode:
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
Run the test suite:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── auth/ # Authentication implementation
|
||||
├── tools/ # CLI tools and utilities
|
||||
├── index.ts # Main entry point
|
||||
├── args.ts # Command line argument parsing
|
||||
├── client.ts # Client implementation
|
||||
├── mcp.ts # Model Context Protocol integration
|
||||
└── ... # Various utility files
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
- `@continuedev/*` packages for core functionality
|
||||
- `@workos-inc/node` for authentication
|
||||
- `openai` for AI capabilities
|
||||
- Various utility packages (chalk, axios, etc.)
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0 - see LICENSE file for details
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||
|
||||
## Support
|
||||
|
||||
For issues and feature requests, please use the GitHub issue tracker.
|
||||
|
|
|
|||
1884
package-lock.json
generated
1884
package-lock.json
generated
File diff suppressed because it is too large
Load diff
10
package.json
10
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@continuedev/cli",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.15",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
|
@ -11,15 +11,15 @@
|
|||
"scripts": {
|
||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js"
|
||||
"start": "node dist/index.js",
|
||||
"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"
|
||||
},
|
||||
"author": "Continue Dev, Inc.",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-yaml": "^1.0.78",
|
||||
"@continuedev/hub": "^0.0.6",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@continuedev/sdk": "^0.0.2",
|
||||
"@continuedev/sdk": "^0.0.9",
|
||||
"@modelcontextprotocol/sdk": "^1.9.0",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
|
|
|
|||
|
|
@ -114,7 +114,7 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string {
|
|||
const params = {
|
||||
response_type: "code",
|
||||
client_id: env.workOsClientId,
|
||||
redirect_uri: `${env.appUrl}tokens/${
|
||||
redirect_uri: `${env.appUrl}/tokens/${
|
||||
useOnboarding ? "onboarding-" : ""
|
||||
}callback`,
|
||||
state: uuidv4(),
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { Configuration, DefaultApi } from "@continuedev/sdk";
|
||||
|
||||
export const client = new DefaultApi(
|
||||
new Configuration({
|
||||
basePath: "https://api.continue.dev",
|
||||
accessToken: () => "TOKEN", // Replace with your actual token
|
||||
})
|
||||
);
|
||||
36
src/continueSDK.ts
Normal file
36
src/continueSDK.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { Continue, ContinueClient } from "@continuedev/sdk";
|
||||
import { env } from "./env.js";
|
||||
import chalk from "chalk";
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import dotenv from "dotenv";
|
|||
dotenv.config();
|
||||
|
||||
export const env = {
|
||||
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev/",
|
||||
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev",
|
||||
workOsClientId: "client_01J0FW6XN8N2XJAECF7NE0Y65J",
|
||||
appUrl: "https://hub.continue.dev/",
|
||||
appUrl: "https://hub.continue.dev",
|
||||
};
|
||||
|
|
|
|||
92
src/index.ts
92
src/index.ts
|
|
@ -1,58 +1,91 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { ContinueHubClient } from "@continuedev/hub";
|
||||
|
||||
import chalk from "chalk";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
import { parseArgs } from "./args.js";
|
||||
import { ensureAuthenticated } from "./auth/ensureAuth.js";
|
||||
import { loadAuthConfig } from "./auth/workos.js";
|
||||
import { env } from "./env.js";
|
||||
import { introMessage, loadAssistant, loadSystemMessage } from "./intro.js";
|
||||
import { initializeContinueSDK } from "./continueSDK.js";
|
||||
import { introMessage } from "./intro.js";
|
||||
import { MCPService } from "./mcp.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import * as fs from "fs";
|
||||
import { ContinueClient } from "@continuedev/sdk";
|
||||
|
||||
// Parse command line arguments
|
||||
const args = parseArgs();
|
||||
|
||||
// client
|
||||
// .listAssistants({
|
||||
// alwaysUseProxy: "true",
|
||||
// })
|
||||
// .then((result) => {
|
||||
// console.log("API result:", result);
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// console.log("API error:", error);
|
||||
// });
|
||||
|
||||
async function chat() {
|
||||
// Ensure authenticated
|
||||
const isAuthenticated = await ensureAuthenticated(true);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
console.error(chalk.red("Authentication failed. Exiting..."));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
const hub = new ContinueHubClient({
|
||||
apiKey: authConfig.accessToken,
|
||||
currentUserSlug: "nate",
|
||||
orgScopeId: null,
|
||||
apiBase: env.apiBase,
|
||||
});
|
||||
// Check if the assistant path is a file or a slug
|
||||
let assistant: ContinueClient["assistant"];
|
||||
let client: ContinueClient["client"];
|
||||
|
||||
// Load assistant
|
||||
const assistant = await loadAssistant(hub, args.assistantPath);
|
||||
if (fs.existsSync(args.assistantPath)) {
|
||||
// // If it's a file, load it directly
|
||||
// console.log(
|
||||
// chalk.yellow(`Loading assistant from file: ${args.assistantPath}`)
|
||||
// );
|
||||
// // We need to extract the assistant slug from the yaml to use with the SDK
|
||||
// // For now, let's just use a placeholder slug and use the file content for assistant config
|
||||
// // In a real implementation, we'd need to parse the YAML and extract the slug
|
||||
// const assistantSlug = "default/assistant";
|
||||
// try {
|
||||
// sdkClient = await initializeContinueSDK(
|
||||
// authConfig.accessToken,
|
||||
// assistantSlug
|
||||
// );
|
||||
// // Since we're using a file, we need to manually set the assistant config
|
||||
// assistant = JSON.parse(JSON.stringify(sdkClient.assistant.config));
|
||||
// } catch (error) {
|
||||
// console.error(
|
||||
// chalk.red("Error initializing SDK with local file:"),
|
||||
// error
|
||||
// );
|
||||
// throw error;
|
||||
// }
|
||||
} else {
|
||||
// If it's not a file, assume it's a slug
|
||||
// console.log(
|
||||
// chalk.yellow(`Loading assistant using slug: ${args.assistantPath}`)
|
||||
// );
|
||||
try {
|
||||
let continueSdk = await initializeContinueSDK(
|
||||
authConfig.accessToken,
|
||||
args.assistantPath
|
||||
);
|
||||
|
||||
const mcpService = await MCPService.create(assistant);
|
||||
assistant = continueSdk.assistant;
|
||||
client = continueSdk.client;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
chalk.red(`Error loading assistant ${args.assistantPath}:`),
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const mcpService = await MCPService.create(assistant!.config);
|
||||
|
||||
// Only show intro message if not in headless mode
|
||||
if (!args.isHeadless) {
|
||||
introMessage(assistant, mcpService);
|
||||
introMessage(assistant!, mcpService);
|
||||
}
|
||||
|
||||
// Rules
|
||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
||||
const systemMessage = loadSystemMessage(assistant);
|
||||
const systemMessage = assistant!.systemMessage;
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
@ -73,7 +106,7 @@ async function chat() {
|
|||
isFirstMessage = false;
|
||||
|
||||
// Handle slash commands
|
||||
const commandResult = handleSlashCommands(userInput, assistant);
|
||||
const commandResult = handleSlashCommands(userInput, assistant!.config);
|
||||
if (commandResult) {
|
||||
if (commandResult.exit) {
|
||||
break;
|
||||
|
|
@ -97,13 +130,12 @@ async function chat() {
|
|||
}
|
||||
|
||||
try {
|
||||
await streamChatResponse(chatHistory, assistant);
|
||||
await streamChatResponse(chatHistory, assistant!, client!);
|
||||
} catch (e: any) {
|
||||
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
||||
console.log(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
|
||||
);
|
||||
} finally {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
56
src/intro.ts
56
src/intro.ts
|
|
@ -1,51 +1,29 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { ContinueHubClient } from "@continuedev/hub";
|
||||
|
||||
import chalk from "chalk";
|
||||
import * as fs from "fs";
|
||||
import { CONTINUE_ASCII_ART } from "./asciiArt.js";
|
||||
import { MCPService } from "./mcp.js";
|
||||
import { getAllTools, getLlmFromAssistant } from "./streamChatResponse.js";
|
||||
|
||||
export async function loadAssistant(
|
||||
hub: ContinueHubClient,
|
||||
filepathOrSlug: string
|
||||
): Promise<AssistantUnrolled> {
|
||||
console.log("Loading assistant ", filepathOrSlug);
|
||||
if (!fs.existsSync(filepathOrSlug)) {
|
||||
// Assume it's a slug
|
||||
console.log("Loading assistant from slug");
|
||||
return await hub.loadAssistant(filepathOrSlug);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(filepathOrSlug, "utf-8");
|
||||
console.log("Loading assistant from file");
|
||||
const assistant = await hub.loadAssistantFromContent(content);
|
||||
console.log("loaded: ", assistant.name);
|
||||
return assistant;
|
||||
}
|
||||
import { getAllTools } from "./streamChatResponse.js";
|
||||
import { Assistant, type AssistantConfig } from "@continuedev/sdk";
|
||||
|
||||
export function loadSystemMessage(
|
||||
assistant: AssistantUnrolled
|
||||
assistant: AssistantConfig
|
||||
): string | undefined {
|
||||
return assistant.rules
|
||||
?.filter((rule) => !!rule)
|
||||
.map((rule) => (typeof rule === "string" ? rule : rule.rule))
|
||||
.map((rule) => (typeof rule === "string" ? rule : rule?.rule))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
export function introMessage(
|
||||
assistant: AssistantUnrolled,
|
||||
mcpService: MCPService
|
||||
) {
|
||||
export function introMessage(assistant: Assistant, mcpService: MCPService) {
|
||||
const assistantConfig = assistant.config;
|
||||
|
||||
const mcpTools = mcpService.getTools() ?? [];
|
||||
const mcpPrompts = mcpService.getPrompts() ?? [];
|
||||
|
||||
console.log(chalk.cyan(CONTINUE_ASCII_ART));
|
||||
|
||||
const { model } = getLlmFromAssistant(assistant);
|
||||
console.log(`\n${chalk.bold.blue(`Assistant: ${assistant.name}`)}`);
|
||||
console.log(`${chalk.blue(`Model: ${model}`)}\n`);
|
||||
console.log(`\n${chalk.bold.blue(`Assistant: ${assistantConfig.name}`)}`);
|
||||
console.log(`${chalk.blue(`Model: ${assistant.getModel()}`)}\n`);
|
||||
|
||||
console.log(chalk.yellow("Available tools:"));
|
||||
getAllTools().forEach((tool) => {
|
||||
|
|
@ -66,22 +44,24 @@ export function introMessage(
|
|||
console.log("- /login: Authenticate with your account");
|
||||
console.log("- /logout: Sign out of your current session");
|
||||
console.log("- /whoami: Check who you're currently logged in as");
|
||||
for (const prompt of assistant.prompts ?? []) {
|
||||
console.log(`- /${prompt.name}: ${prompt.description}`);
|
||||
for (const prompt of assistantConfig.prompts ?? []) {
|
||||
console.log(`- /${prompt?.name}: ${prompt?.description}`);
|
||||
}
|
||||
for (const prompt of mcpPrompts) {
|
||||
console.log(`- /${prompt.name}: ${prompt.description}`);
|
||||
}
|
||||
console.log("");
|
||||
|
||||
if (assistant.rules?.length) {
|
||||
console.log(chalk.yellow("\nAssistant rules: " + assistant.rules.length));
|
||||
if (assistantConfig.rules?.length) {
|
||||
console.log(
|
||||
chalk.yellow("\nAssistant rules: " + assistantConfig.rules.length)
|
||||
);
|
||||
}
|
||||
|
||||
if (assistant.mcpServers?.length) {
|
||||
if (assistantConfig.mcpServers?.length) {
|
||||
console.log(chalk.yellow("\nMCP Servers:"));
|
||||
assistant.mcpServers.forEach((server) => {
|
||||
console.log(`- ${chalk.cyan(server.name)}`);
|
||||
assistantConfig.mcpServers.forEach((server: any) => {
|
||||
console.log(`- ${chalk.cyan(server?.name)}`);
|
||||
});
|
||||
}
|
||||
console.log("");
|
||||
|
|
|
|||
21
src/mcp.ts
21
src/mcp.ts
|
|
@ -1,4 +1,4 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
|
||||
|
|
@ -6,11 +6,11 @@ export class MCPService {
|
|||
private readonly connections: MCPConnection[] = [];
|
||||
private static instance: MCPService | null = null;
|
||||
|
||||
private constructor(private readonly assistant: AssistantUnrolled) {
|
||||
private constructor(private readonly assistant: AssistantConfig) {
|
||||
this.assistant = assistant;
|
||||
}
|
||||
|
||||
public static async create(assistant: AssistantUnrolled) {
|
||||
public static async create(assistant: AssistantConfig) {
|
||||
// If instance already exists, return it
|
||||
if (MCPService.instance) {
|
||||
return MCPService.instance;
|
||||
|
|
@ -21,7 +21,7 @@ export class MCPService {
|
|||
|
||||
if (assistant.mcpServers?.length) {
|
||||
const connectionPromises = assistant.mcpServers.map((server) =>
|
||||
MCPConnection.create(server),
|
||||
MCPConnection.create(server)
|
||||
);
|
||||
const connections = await Promise.all(connectionPromises);
|
||||
service.connections.push(...connections);
|
||||
|
|
@ -65,24 +65,29 @@ export class MCPConnection {
|
|||
private constructor(public readonly client: Client) {}
|
||||
|
||||
public static async create(
|
||||
config: NonNullable<AssistantUnrolled["mcpServers"]>[number],
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number]
|
||||
) {
|
||||
const client = new Client(
|
||||
{
|
||||
name: "continue-cli-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{ capabilities: {} },
|
||||
{ capabilities: {} }
|
||||
);
|
||||
|
||||
// Construct transport
|
||||
const env: Record<string, string> = config.env || {};
|
||||
const env: Record<string, string> = config?.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
if (!config?.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: config.command,
|
||||
args: config.args,
|
||||
args: config?.args,
|
||||
env,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import chalk from "chalk";
|
||||
import {
|
||||
isAuthenticated,
|
||||
|
|
@ -6,10 +5,11 @@ import {
|
|||
login,
|
||||
logout,
|
||||
} from "./auth/workos.js";
|
||||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
|
||||
export function handleSlashCommands(
|
||||
input: string,
|
||||
assistant: AssistantUnrolled,
|
||||
assistant: AssistantConfig
|
||||
): {
|
||||
output?: string;
|
||||
exit?: boolean;
|
||||
|
|
@ -28,13 +28,16 @@ export function handleSlashCommands(
|
|||
"/whoami - Check who you're currently logged in as",
|
||||
"/models - List available AI models",
|
||||
...(assistant.prompts?.map(
|
||||
(prompt) => `/${prompt.name} - ${prompt.description}`,
|
||||
(prompt) => `/${prompt?.name} - ${prompt?.description}`
|
||||
) ?? []),
|
||||
].join("\n");
|
||||
return { output: helpMessage };
|
||||
case "models":
|
||||
return {
|
||||
output: `Available models:\n• ${assistant.models?.map((model) => model.name)?.join("\n• ") || "None"}`,
|
||||
output: `Available models:\n• ${
|
||||
assistant.models?.map((model) => model?.name)?.join("\n• ") ||
|
||||
"None"
|
||||
}`,
|
||||
};
|
||||
case "exit":
|
||||
return { exit: true, output: "Goodbye!" };
|
||||
|
|
@ -42,9 +45,7 @@ export function handleSlashCommands(
|
|||
login()
|
||||
.then((config) => {
|
||||
console.log(
|
||||
chalk.green(
|
||||
`\nLogged in as ${config.userEmail || config.userId}`,
|
||||
),
|
||||
chalk.green(`\nLogged in as ${config.userEmail || config.userId}`)
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
|
|
@ -78,7 +79,7 @@ export function handleSlashCommands(
|
|||
|
||||
default:
|
||||
const assistantPrompt = assistant.prompts?.find(
|
||||
(prompt) => prompt.name === command,
|
||||
(prompt) => prompt?.name === command
|
||||
);
|
||||
if (assistantPrompt) {
|
||||
const newInput = assistantPrompt.prompt + args.join(" ");
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { constructLlmApi } from "@continuedev/openai-adapters";
|
||||
import chalk from "chalk";
|
||||
import * as dotenv from "dotenv";
|
||||
import {
|
||||
ChatCompletionChunk,
|
||||
import type {
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionMessageToolCall,
|
||||
ChatCompletionTool,
|
||||
|
|
@ -11,30 +8,10 @@ import {
|
|||
import { MCPService } from "./mcp.js";
|
||||
import { executeToolCall } from "./tools.js";
|
||||
import { BUILTIN_TOOLS } from "./tools/index.js";
|
||||
import { ContinueClient } from "@continuedev/sdk";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export function getLlmFromAssistant(assistant: AssistantUnrolled) {
|
||||
const chatModel = assistant.models?.filter((model) =>
|
||||
model?.roles?.includes("chat"),
|
||||
)?.[0];
|
||||
if (!chatModel) {
|
||||
console.error(chalk.red("Error: No chat model found in the assistant."));
|
||||
process.exit(1);
|
||||
}
|
||||
const llm = constructLlmApi({
|
||||
provider: chatModel.provider as any,
|
||||
apiKey: chatModel.apiKey,
|
||||
apiBase: chatModel.apiBase,
|
||||
});
|
||||
if (!llm) {
|
||||
console.error(chalk.red("Error: Failed to construct LLM API."));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return { llm, model: chatModel.model };
|
||||
}
|
||||
|
||||
export function getAllTools() {
|
||||
const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({
|
||||
type: "function" as const,
|
||||
|
|
@ -47,7 +24,7 @@ export function getAllTools() {
|
|||
Object.entries(tool.parameters).map(([key, param]) => [
|
||||
key,
|
||||
{ type: param.type, description: param.description },
|
||||
]),
|
||||
])
|
||||
),
|
||||
required: Object.entries(tool.parameters)
|
||||
.filter(([_, param]) => param.required)
|
||||
|
|
@ -65,7 +42,7 @@ export function getAllTools() {
|
|||
description: tool.description,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
})),
|
||||
}))
|
||||
);
|
||||
|
||||
return allTools;
|
||||
|
|
@ -76,10 +53,9 @@ type TODO = any;
|
|||
// Define a function to handle streaming responses with tool calling
|
||||
export async function streamChatResponse(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
assistant: AssistantUnrolled,
|
||||
assistant: ContinueClient["assistant"],
|
||||
client: ContinueClient["client"]
|
||||
) {
|
||||
const { llm, model } = getLlmFromAssistant(assistant);
|
||||
|
||||
// Prepare tools for the API call
|
||||
const toolsForRequest = getAllTools();
|
||||
|
||||
|
|
@ -88,21 +64,19 @@ export async function streamChatResponse(
|
|||
let shouldContinueConversation = true;
|
||||
|
||||
while (shouldContinueConversation) {
|
||||
let stream: AsyncGenerator<ChatCompletionChunk, any, any>;
|
||||
let stream;
|
||||
|
||||
try {
|
||||
stream = llm.chatCompletionStream(
|
||||
{
|
||||
model,
|
||||
messages: chatHistory,
|
||||
stream: true,
|
||||
tools: toolsForRequest,
|
||||
},
|
||||
new AbortController().signal,
|
||||
);
|
||||
stream = await client.chat.completions.create({
|
||||
model: assistant.getModel(),
|
||||
messages: chatHistory,
|
||||
stream: true,
|
||||
tools: toolsForRequest,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Error in streamChatResponse:"),
|
||||
chalk.red(error.message),
|
||||
chalk.red(error.message)
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
|
@ -138,13 +112,15 @@ export async function streamChatResponse(
|
|||
// Add function name if present
|
||||
if (toolCallDelta.function?.name) {
|
||||
const toolCall = currentToolCalls.find(
|
||||
(tc) => tc.id === currentToolCallId,
|
||||
(tc) => tc.id === currentToolCallId
|
||||
);
|
||||
if (toolCall) {
|
||||
if (!toolCall.name) {
|
||||
toolCall.name = toolCallDelta.function.name;
|
||||
process.stdout.write(
|
||||
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(toolCall.name)}${chalk.yellow("]")}`,
|
||||
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
|
||||
toolCall.name
|
||||
)}${chalk.yellow("]")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -153,7 +129,7 @@ export async function streamChatResponse(
|
|||
// Collect function arguments
|
||||
if (toolCallDelta.function?.arguments) {
|
||||
const toolCall = currentToolCalls.find(
|
||||
(tc) => tc.id === currentToolCallId,
|
||||
(tc) => tc.id === currentToolCallId
|
||||
);
|
||||
if (toolCall) {
|
||||
// Accumulate arguments as string to later parse as JSON
|
||||
|
|
@ -184,7 +160,7 @@ export async function streamChatResponse(
|
|||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
chatHistory.push({
|
||||
role: "assistant",
|
||||
|
|
@ -212,14 +188,18 @@ export async function streamChatResponse(
|
|||
|
||||
console.log(chalk.green(toolResult) + "\n");
|
||||
} catch (error) {
|
||||
const errorMessage = `Error executing tool ${toolCall.name}: ${error instanceof Error ? error.message : String(error)}`;
|
||||
const errorMessage = `Error executing tool ${toolCall.name}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`;
|
||||
chatHistory.push({
|
||||
role: "tool",
|
||||
tool_call_id: toolCall.id,
|
||||
content: errorMessage,
|
||||
});
|
||||
console.log(
|
||||
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(")")}`,
|
||||
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(
|
||||
")"
|
||||
)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "ESNext"],
|
||||
"allowJs": true,
|
||||
|
|
@ -10,14 +11,14 @@
|
|||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"moduleResolution": "NodeNext",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": false,
|
||||
"noEmitOnError": false,
|
||||
"types": ["node", "jest"],
|
||||
"outDir": "dist",
|
||||
"declaration": true
|
||||
// "sourceMap": true
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue