merge main

This commit is contained in:
Nate 2025-07-20 16:27:46 -07:00
commit 15c022a710
56 changed files with 4316 additions and 654 deletions

View file

@ -1,4 +1,4 @@
name: CLI Assistant
name: CLI Agent
version: 0.0.1
schema: v1

View file

@ -13,9 +13,9 @@ rules:
- Continue SDK: Experimental package in early development, subject to
breaking changes
- Continue Hub: Registry for custom AI code assistants
- Continue Hub: Registry for custom AI code agent
- Hub functionality: Manages assistant building blocks (models, rules,
- Hub functionality: Manages agent building blocks (models, rules,
context providers, prompts, docs, etc.)
- Governance: Allows central configuration for organizations

View file

@ -53,7 +53,7 @@ jobs:
- name: Analyze PR with Continue
id: analyze
run: |
continue-cli -p --assistant "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt
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

View file

@ -7,3 +7,6 @@ test
AGENTS.md
jest.config.mjs
tsconfig.json
tsconfig.build.json
TESTING_STRATEGY.md
.env.example

View file

@ -33,13 +33,6 @@
"pkgRoot": "."
}
],
[
"@semantic-release/git",
{
"assets": ["package.json", "CHANGELOG.md"],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
],
"@semantic-release/github"
]
}

2
.vscode/launch.json vendored
View file

@ -25,7 +25,7 @@
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"args": ["--config", "nate/default-assistant"],
"args": [],
"env": {
"NODE_ENV": "development"
},

View file

@ -32,7 +32,6 @@ cn --resume
## Command Line Options
- `-p`: Run in headless mode (no TUI)
- `--config <path>`: Specify assistant configuration path
- `--config <path>`: Specify agent configuration path
- `--resume`: Resume the last session for this terminal
- `<prompt>`: Optional prompt to start with

View file

@ -15,6 +15,8 @@ export default {
"<rootDir>/node_modules/ink-testing-library/build/index.js",
"^./SyntaxHighlighter\\.js$":
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
"^./FreeTrialStatus\\.js$":
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
@ -23,6 +25,7 @@ export default {
testPathIgnorePatterns: ["<rootDir>/dist/"],
modulePathIgnorePatterns: ["<rootDir>/dist/"],
transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
globals: {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),

2
jest.setup.ts Normal file
View file

@ -0,0 +1,2 @@
// Disable telemetry for tests
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";

794
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -35,6 +35,14 @@
"@continuedev/openai-adapters": "^1.0.48-beta",
"@continuedev/sdk": "^0.0.13",
"@modelcontextprotocol/sdk": "^1.9.0",
"@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",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
"@workos-inc/node": "^7.45.0",
@ -45,6 +53,7 @@
"glob": "^11.0.3",
"ignore-walk": "^7.0.0",
"ink": "^6.0.1",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
@ -68,6 +77,7 @@
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jest": "^29.5.14",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"conventional-changelog-conventionalcommits": "^9.1.0",

View file

@ -4,9 +4,10 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
## 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. If the user has a ~/.continue/config.yaml with an acceptable model, load this config automatically
3. Otherwise, we will present the user with two options:
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
@ -26,8 +27,10 @@ When something in the onboarding flow is done automatically, we should tell the
## 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
5. If none of the above, then bring the user to step 3 of the onboarding flow

342
spec/otlp-metrics.md Normal file
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

@ -1,4 +1,5 @@
import { parseArgs } from "./args.js";
import { jest } from '@jest/globals';
import { parseArgs, processRule } from "./args.js";
describe("parseArgs", () => {
const originalArgv = process.argv;
@ -245,3 +246,196 @@ describe("parseArgs", () => {
]);
});
});
describe("processRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
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();
});
});
});

View file

@ -1,5 +1,7 @@
import * as fs from "fs";
import JSZip from "jszip";
import * as path from "path";
import { env } from "./env.js";
export interface CommandLineArgs {
isHeadless: boolean;
@ -29,13 +31,52 @@ function loadRuleFromFile(filePath: string): string {
}
/**
* Load rule content from hub.continue.dev (not yet implemented)
* Load rule content from hub.continue.dev
* @param slug - The slug in format "owner/package"
* @returns The rule content from the hub
*/
function loadRuleFromHub(slug: string): string {
// TODO: Implement hub integration
throw new Error(`Hub rules not yet supported: ${slug}`);
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}`);
}
}
/**
@ -43,14 +84,14 @@ function loadRuleFromHub(slug: string): string {
* @param ruleSpec - Can be a file path, hub slug, or direct string content
* @returns The processed rule content
*/
export function processRule(ruleSpec: string): string {
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 loadRuleFromHub(ruleSpec);
return await loadRuleFromHub(ruleSpec);
}
// If it looks like a file path (contains . or / or ends with common file extensions)

View file

@ -1,9 +1,20 @@
import chalk from "chalk";
const b = chalk.bold.magenta;
const d = chalk.dim;
export const CONTINUE_ASCII_ART = `
_________ _ _____________ ____ ______
/ ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/
/ /__/ /_/ / / / / _/ // / /_/ / _/
\\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/
${b("_____")}${d("____ ")}${b("_ __")}${d("___________ ____ ______")}
${b("/ ___/")}${d(" __ \\")}${b("/ |/ /")}${d("_ __/ _/ |/ / / / / __/")}
${b("/ /__")}${d("/ /_/ ")}${b("/ /")}${d(" / / _/ // / /_/ / _/ ")}
${b("\\___/")}${d("\\____")}${b("/_/|_/")}${d(" /_/ /___/_/|_/\\____/___/")}
`;
// export const CONTINUE_ASCII_ART = `
// _________ _ _____________ ____ ______
// / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/
// / /__/ /_/ / / / / _/ // / /_/ / _/
// \\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/
// `;
export const CONTINUE_LOGO_ASCII_ART = `
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ -31,7 +42,7 @@ export const CONTINUE_LOGO_ASCII_ART = `
@@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@
@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@
CONTINUE @@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@

View file

@ -1,7 +1,3 @@
import {
Configuration,
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import open from "open";
@ -12,6 +8,7 @@ import { env } from "../env.js";
// Polyfill fetch for Node < 18
import nodeFetch from "node-fetch";
import { getApiClient } from "../config.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
@ -231,6 +228,7 @@ 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
@ -426,46 +424,39 @@ export async function login(): Promise<AuthConfig> {
};
}
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 {
console.info(chalk.cyan("\nStarting authentication with Continue..."));
// Request device authorization
const deviceAuth = await requestDeviceAuthorization();
console.info(
chalk.yellow(
`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 (error) {
console.info(chalk.yellow("Unable to open browser automatically"));
}
console.info(chalk.cyan("\nWaiting for confirmation..."));
// Poll for token
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in
);
console.info(chalk.green("\nAuthentication successful!"));
return authConfig;
} catch (error: any) {
console.error(chalk.red("Authentication error:"), error.message || error);
throw error;
await open(deviceAuth.verification_uri_complete);
} catch (error) {
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;
}
/**
@ -509,11 +500,7 @@ export async function ensureOrganization(
}
// Need to select organization
const apiClient = new DefaultApi(
new Configuration({
accessToken: authenticatedConfig.accessToken,
})
);
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
@ -586,11 +573,7 @@ export async function listUserOrganizations(): Promise<
return null;
}
const apiClient = new DefaultApi(
new Configuration({
accessToken: authConfig.accessToken,
})
);
const apiClient = getApiClient(authConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();

View file

@ -1,16 +1,24 @@
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { ensureOrganization, loadAuthConfig } from "../auth/workos.js";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import {
ensureOrganization,
getOrganizationId,
loadAuthConfig,
} from "../auth/workos.js";
import { introMessage } from "../intro.js";
import { configureLogger } from "../logger.js";
import { initializeWithOnboarding } from "../onboarding.js";
import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import telemetryService from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { getVersion } from "../version.js";
export interface ChatOptions {
headless?: boolean;
@ -23,7 +31,15 @@ async function initializeChat(options: ChatOptions) {
const authConfig = loadAuthConfig();
// Use onboarding flow for initialization
const result = await initializeWithOnboarding(authConfig, options.config);
if (!options.headless) {
console.log(chalk.white(CONTINUE_ASCII_ART));
console.info(chalk.gray(`v${getVersion()}\n`));
}
const result = await initializeWithOnboarding(
authConfig,
options.config,
options.rule
);
// Ensure organization is selected if authenticated
let finalAuthConfig = authConfig;
@ -32,6 +48,14 @@ async function initializeChat(options: ChatOptions) {
authConfig,
options.headless ?? false
);
// Update telemetry with organization info
if (finalAuthConfig) {
const organizationId = getOrganizationId(finalAuthConfig);
if (organizationId) {
telemetryService.updateOrganization(organizationId);
}
}
}
return {
@ -39,6 +63,7 @@ async function initializeChat(options: ChatOptions) {
llmApi: result.llmApi,
model: result.model,
mcpService: result.mcpService,
apiClient: result.apiClient,
};
}
@ -47,7 +72,15 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
configureLogger(options.headless ?? false);
try {
let { config, llmApi, model, mcpService } = await initializeChat(options);
let { config, llmApi, model, mcpService, apiClient } = await initializeChat(
options
);
// Record session start
telemetryService.recordSessionStart();
// Start active time tracking
telemetryService.startActiveTime();
// If not in headless mode, start the TUI chat (default)
if (!options.headless) {
@ -56,6 +89,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
llmApi,
model,
mcpService,
apiClient,
prompt,
options.resume,
options.config,
@ -86,7 +120,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// If no session loaded or not resuming, initialize with system message
if (chatHistory.length === 0) {
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
const systemMessage = constructSystemMessage(rulesSystemMessage, options.rule);
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
options.rule
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
}
@ -107,6 +144,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
isFirstMessage = false;
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
// Add user message to history
chatHistory.push({ role: "user", content: userInput });
@ -124,9 +164,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
abortController
);
// In headless mode, only print the final response
// In headless mode, only print the final response using safe stdout
if (options.headless && finalResponse.trim()) {
console.log(finalResponse);
safeStdout(finalResponse + "\n");
}
// Save session after each successful response
@ -143,5 +183,8 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
} catch (error: any) {
logger.error(chalk.red(`Fatal error: ${formatError(error)}`));
process.exit(1);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();
}
}
}

91
src/commands/commands.ts Normal file
View file

@ -0,0 +1,91 @@
import { type AssistantConfig } from "@continuedev/sdk";
export interface SlashCommand {
name: string;
description: string;
category: "system" | "assistant";
}
export interface SystemCommand extends SlashCommand {
category: "system";
requiresMultipleOrgs?: boolean;
}
// 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: "exit",
description: "Exit the chat",
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: "org",
description: "Switch organization",
category: "system",
requiresMultipleOrgs: true,
},
{
name: "config",
description: "Switch configuration",
category: "system",
},
];
/**
* Get all available slash commands including system commands and assistant prompts
*/
export function getAllSlashCommands(
assistant: AssistantConfig
): SlashCommand[] {
// Filter system commands based on requirements
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

@ -1,5 +1,19 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { logout as workosLogout } from "../auth/workos.js";
export async function logout() {
const onboardingFlagPath = path.join(
os.homedir(),
".continue",
".onboarding_complete"
);
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
fs.unlinkSync(onboardingFlagPath);
}
workosLogout();
}

View file

@ -1,5 +1,6 @@
import {
AssistantUnrolled,
ModelConfig,
RegistryClient,
unrollAssistant,
} from "@continuedev/config-yaml";
@ -13,6 +14,7 @@ import {
DefaultApi,
DefaultApiInterface,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { dirname } from "node:path";
import {
AuthConfig,
@ -27,7 +29,7 @@ import { MCPService } from "./mcp.js";
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig
): [BaseLlmApi, string] {
): [BaseLlmApi, ModelConfig] {
const model = assistant.models?.find((model) =>
model?.roles?.includes("chat")
);
@ -71,7 +73,7 @@ export function getLlmApi(
);
}
return [llmApi, model.model];
return [llmApi, model];
}
async function loadConfigYaml(
@ -97,24 +99,40 @@ async function loadConfigYaml(
}
);
if (unrollResult.errors?.length || !unrollResult.config) {
const errorDetails = unrollResult.errors?.join("\n") ?? "Unknown error";
const errorDetails = unrollResult.errors;
if (!unrollResult.config) {
throw new Error(`Failed to load config file:\n${errorDetails}`);
} else if (errorDetails?.length) {
const warnings =
errorDetails?.length > 1
? errorDetails.map((d) => `\n- ${d.message}`)
: errorDetails[0].message;
console.warn(chalk.dim(`Warning: ${warnings}`));
}
return unrollResult.config;
}
export function getApiClient(
accessToken: string | undefined | null
): DefaultApi {
return new DefaultApi(
new Configuration({
basePath: env.apiBase.replace(/\/$/, ""),
accessToken: accessToken ?? undefined,
})
);
}
export async function loadConfig(
authConfig: AuthConfig,
config: string | undefined,
organizationId: string | null
organizationId: string | null,
apiClient?: DefaultApiInterface
): Promise<AssistantUnrolled> {
const apiClient = new DefaultApi(
new Configuration({
accessToken: authConfig?.accessToken ?? undefined,
})
);
if (!apiClient) {
apiClient = getApiClient(authConfig?.accessToken);
}
if (!config) {
// Check if there's a saved assistant slug in auth config
@ -129,7 +147,22 @@ export async function loadConfig(
organizationId: organizationId ?? undefined,
});
if (assistants.length === 0) {
// In case the user doesn't have any assistants, we fall back to a default - TODO
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;
}
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(
result.errors?.join("\n") ?? "Failed to load assistant."
@ -179,15 +212,20 @@ export async function initialize(
): Promise<{
config: AssistantUnrolled;
llmApi: BaseLlmApi;
model: string;
model: ModelConfig;
mcpService: MCPService;
apiClient: DefaultApiInterface;
}> {
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config = await loadConfig(authConfig, configPath, organizationId);
const apiClient = getApiClient(authConfig?.accessToken);
const config = await loadConfig(
authConfig,
configPath,
organizationId,
apiClient
);
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = await MCPService.create(config);
return { config, llmApi, model, mcpService };
return { config, llmApi, model, mcpService, apiClient };
}

181
src/freeTrialTransition.ts Normal file
View file

@ -0,0 +1,181 @@
import chalk from "chalk";
import { spawn } from "child_process";
import * as fs from "fs";
import open from "open";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import * as YAML from "yaml";
import { env } from "./env.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const newModel = {
uses: "anthropic/claude-4-sonnet",
with: {
ANTHROPIC_API_KEY: apiKey,
},
};
if (fs.existsSync(CONFIG_PATH)) {
const existingContent = fs.readFileSync(CONFIG_PATH, "utf8");
let config;
try {
config = YAML.parse(existingContent);
// Make sure models array exists
if (!config.models) {
config.models = [];
}
// Check if model already exists
const existingModelIndex = config.models.findIndex(
(model: any) => model.uses === "anthropic/claude-4-sonnet"
);
if (existingModelIndex >= 0) {
// Update existing model
config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey;
} else {
// Add new model
config.models.push(newModel);
}
} catch (error) {
// If parsing fails, create a new config
config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
}
// Write back to file
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
} else {
// Create new config file
const config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
}
}
/**
* Handles the free trial transition flow for users who have maxed out their free trial
* This function provides a specialized flow that:
* 1. Assumes the user is already authenticated
* 2. Provides two specific options for continuing
* 3. Returns to the chat without restarting the entire CLI
*/
export async function handleMaxedOutFreeTrial(): Promise<void> {
// Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
console.clear();
console.log(chalk.yellow("🚀 Free trial limit reached!\n"));
console.log("Choose how you'd like to Continue:");
console.log(chalk.white("1. 💳 Sign up for models add-on"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
limit: ["1", "2", ""],
limitMessage: chalk.dim("Please enter 1 or 2"),
});
if (choice === "1" || choice === "") {
// Option 1: Open models setup page
const modelsUrl = new URL("setup-models", env.appUrl).toString();
console.log(chalk.blue(`Opening ${modelsUrl}...`));
try {
await open(modelsUrl);
console.log(chalk.green("\n✓ Browser opened successfully!"));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
);
} catch (error) {
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
console.log(chalk.white(`Please visit: ${modelsUrl}`));
console.log(
chalk.dim(
"After setting up your models subscription, restart the CLI to continue."
)
);
}
// Wait for user to acknowledge
readlineSync.question(chalk.dim("\nPress Enter to exit..."));
process.exit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
const apiKey = readlineSync.question(
chalk.white("\nEnter your Anthropic API key: "),
{
limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters
limitMessage: chalk.dim(
"Please enter a valid Anthropic key that starts with 'sk-ant'"
),
hideEchoBack: true,
}
);
if (!apiKey || !apiKey.startsWith("sk-ant-")) {
console.log(
chalk.red(
"❌ Invalid Anthropic API key. Please make sure it starts with 'sk-ant'"
)
);
process.exit(1);
}
try {
await createOrUpdateConfig(apiKey);
console.log(chalk.green(`✓ API key saved successfully!`));
} catch (error) {
console.log(chalk.red(`❌ Error saving API key: ${error}`));
process.exit(1);
}
}
// After setup completes, restart the CLI to resume the conversation
console.log(
chalk.green("\n🔄 Restarting Continue CLI to resume your conversation...\n")
);
// Get the path to the current script
const scriptPath = path.resolve(process.argv[1]);
// Restart the CLI with the same arguments, except for the first two (node and script path)
// Use spawn instead of spawnSync, since we want to exit this process
const child = spawn(
process.execPath,
[scriptPath, ...process.argv.slice(2)],
{
stdio: "inherit",
detached: true,
}
);
// Unref the child to allow the parent process to exit
child.unref();
// Exit the current process
process.exit(0);
}

View file

@ -3,7 +3,9 @@
// Add immediate logging to debug Windows CI issues
// Only log on Windows when DEBUG_CLI_TESTS is set
if (process.env.DEBUG_CLI_TESTS === "1" && process.platform === "win32") {
console.error(`[CLI_START] Node ${process.version} on ${process.platform} ${process.arch}`);
console.error(
`[CLI_START] Node ${process.version} on ${process.platform} ${process.arch}`
);
console.error(`[CLI_START] Args: ${JSON.stringify(process.argv)}`);
console.error(`[CLI_START] CWD: ${process.cwd()}`);
console.error(`[CLI_START] __dirname: ${import.meta.url}`);
@ -13,8 +15,9 @@ import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { getVersion } from "./version.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import logger from "./util/logger.js";
import { getVersion } from "./version.js";
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
@ -56,21 +59,28 @@ program
[] as string[]
)
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
const isHeadless = options.print;
configureConsoleForHeadless(isHeadless);
if (options.verbose) {
logger.setLevel('debug');
logger.setLevel("debug");
const logPath = logger.getLogPath();
const sessionId = logger.getSessionId();
console.log(`Verbose logging enabled (session: ${sessionId})`);
console.log(`Logs: ${logPath}`);
console.log(`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`);
logger.debug('Verbose logging enabled');
// In headless mode, suppress these verbose logs
if (!isHeadless) {
console.log(`Verbose logging enabled (session: ${sessionId})`);
console.log(`Logs: ${logPath}`);
console.log(
`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`
);
}
logger.debug("Verbose logging enabled");
}
// Map CLI options to chat options
const chatOptions = {
...options,
headless: options.print, // Map --print to headless mode
};
await chat(prompt, chatOptions);
// Map --print to headless mode
options.headless = options.print;
options.print = undefined;
await chat(prompt, options);
});
// Login subcommand
@ -105,12 +115,14 @@ async function main() {
console.error("[CLI_ERROR] Message:", error.message);
console.error("[CLI_ERROR] Stack:", error.stack);
console.error("[CLI_ERROR] Code:", error.code);
// More specific error messages
if (error.code === 'MODULE_NOT_FOUND') {
console.error("[CLI_ERROR] Missing module. This might be a build or path issue.");
if (error.code === "MODULE_NOT_FOUND") {
console.error(
"[CLI_ERROR] Missing module. This might be a build or path issue."
);
}
process.exit(1);
}
}

View file

@ -1,9 +1,24 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import { CONTINUE_ASCII_ART } from "./asciiArt.js";
import { readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { getAllSlashCommands } from "./commands/commands.js";
import { MCPService } from "./mcp.js";
import { getAllTools } from "./streamChatResponse.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function getVersion(): string {
try {
const packagePath = join(__dirname, "..", "package.json");
const packageJson = JSON.parse(readFileSync(packagePath, "utf-8"));
return packageJson.version;
} catch (error) {
return "unknown";
}
}
export function loadSystemMessage(
assistant: AssistantConfig
@ -14,43 +29,42 @@ export function loadSystemMessage(
.join("\n");
}
export function introMessage(
export async function introMessage(
config: AssistantUnrolled,
modelName: string,
model: ModelConfig,
mcpService: MCPService
) {
const mcpTools = mcpService.getTools() ?? [];
const mcpPrompts = mcpService.getPrompts() ?? [];
console.info(chalk.cyan(CONTINUE_ASCII_ART));
// Get all slash commands from central definition
const allCommands = getAllSlashCommands(config);
console.info(`\n${chalk.bold.blue(`Agent: ${config.name}\n`)}`);
console.info(`${chalk.yellow("Model:")} ${modelName.split("/").pop()}\n`);
console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`);
console.info(`${chalk.blue("Model:")} ${model.name.split("/").pop()}\n`);
console.info(chalk.yellow("Tools:"));
getAllTools().forEach((tool) => {
// console.info(chalk.blue("Tools:"));
// BUILTIN_TOOLS.forEach((tool) => {
// console.info(
// `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.description ?? "")}`
// );
// });
// console.info("");
console.info(chalk.blue("Slash commands:"));
// Display all commands from central definition
for (const command of allCommands) {
console.info(
`- ${chalk.green(tool.function.name)}: ${tool.function.description ?? ""}`
`- ${chalk.white("/" + command.name)}: ${chalk.dim(command.description)}`
);
});
console.info("");
console.info(chalk.yellow("Slash commands:"));
console.info(`- ${chalk.green("/exit")}: Exit the chat`);
console.info(`- ${chalk.green("/clear")}: Clear the chat history`);
console.info(`- ${chalk.green("/help")}: Show help message`);
console.info(`- ${chalk.green("/login")}: Authenticate with your account`);
console.info(`- ${chalk.green("/logout")}: Sign out of your current session`);
console.info(
`- ${chalk.green("/whoami")}: Check who you're currently logged in as`
);
console.info(`- ${chalk.green("/org")}: Switch organization`);
console.info(`- ${chalk.green("/config")}: Switch configuration`);
for (const prompt of config.prompts ?? []) {
console.info(`- /${prompt?.name}: ${prompt?.description}`);
}
// Display MCP prompts separately since they're not part of our central definition
for (const prompt of mcpPrompts) {
console.info(`- /${prompt.name}: ${prompt.description}`);
console.info(
`- ${chalk.white("/" + prompt.name)}: ${chalk.dim(prompt.description)}`
);
}
console.info("");

View file

@ -1,10 +1,12 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { MCPService } from "./mcp.js";
@ -14,8 +16,9 @@ const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
export interface OnboardingResult {
config: AssistantUnrolled;
llmApi: BaseLlmApi;
model: string;
model: ModelConfig;
mcpService: MCPService;
apiClient: DefaultApiInterface;
wasOnboarded: boolean;
}
@ -103,48 +106,35 @@ export async function runOnboardingFlow(
configPath: string | undefined,
authConfig: AuthConfig
): Promise<OnboardingResult> {
console.log(chalk.cyan("\n🚀 Welcome to Continue CLI!"));
// Step 1: Check if --config flag is provided
if (configPath) {
const result = await initialize(authConfig, configPath);
return { ...result, wasOnboarded: false };
}
// Step 2: Check if user has ~/.continue/config.yaml with acceptable model
if (await checkHasAcceptableModel(CONFIG_PATH)) {
console.log(chalk.blue(`✓ Using existing ${CONFIG_PATH}`));
const result = await initialize(authConfig, CONFIG_PATH);
// Step 2: Present user with two options
console.log(chalk.yellow("How do you want to get started?"));
console.log(chalk.white("1. ⏩ Log in with Continue"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
limit: ["1", "2", ""],
limitMessage: chalk.dim("Please enter 1 or 2"),
});
if (choice === "1" || choice === "") {
const newAuthConfig = await login();
const result = await initialize(newAuthConfig, undefined);
return { ...result, wasOnboarded: true };
}
// Step 3: Present user with two options
console.log(chalk.yellow("Choose how you'd like to set up your agent:"));
console.log(chalk.white("1. Log in with Continue"));
console.log(chalk.white("2. Enter your Anthropic API key"));
const choice = readlineSync.question(
chalk.green("\nSelect option (1 or 2): ")
);
if (choice === "1") {
console.log(chalk.cyan("\n🔐 Logging in with Continue..."));
try {
const newAuthConfig = await login();
const result = await initialize(newAuthConfig, undefined);
return { ...result, wasOnboarded: true };
} catch (error) {
console.error(
chalk.red("❌ Login failed. Please try again or use option 2.")
);
throw error;
}
} else if (choice === "2") {
console.log(chalk.cyan("\n🔑 Setting up with Anthropic API key..."));
const apiKey = readlineSync.question(
chalk.green("Enter your Anthropic API key: "),
chalk.white("\nEnter your Anthropic API key: "),
{
limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters
limitMessage: chalk.dim(
"Please enter a valid Anthropic key that starts with 'sk-ant'"
),
hideEchoBack: true,
}
);
@ -181,7 +171,7 @@ export async function runNormalFlow(
if (isAuthenticated()) {
try {
const result = await initialize(authConfig, undefined);
return { ...result, wasOnboarded: true };
return { ...result, wasOnboarded: false };
} catch (error) {}
}
@ -189,7 +179,7 @@ export async function runNormalFlow(
if (fs.existsSync(CONFIG_PATH)) {
try {
const result = await initialize(authConfig, CONFIG_PATH);
return { ...result, wasOnboarded: true };
return { ...result, wasOnboarded: false };
} catch (error) {
console.log(chalk.yellow("⚠ Invalid config file found"));
}
@ -201,7 +191,7 @@ export async function runNormalFlow(
await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`));
const result = await initialize(authConfig, CONFIG_PATH);
return { ...result, wasOnboarded: true };
return { ...result, wasOnboarded: false };
}
// Step 5: Fall back to onboarding flow
@ -225,9 +215,60 @@ export async function markOnboardingComplete(): Promise<void> {
fs.writeFileSync(flagPath, new Date().toISOString());
}
/**
* Process rules and inject them into the assistant config
* @param config - The assistant config to modify
* @param rules - Array of rule specifications to process and inject
* @returns The modified config with injected rules
*/
async function injectRulesIntoConfig(
config: AssistantUnrolled,
rules: string[]
): Promise<AssistantUnrolled> {
if (!rules || rules.length === 0) {
return config;
}
let processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(
chalk.yellow(
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
)
);
}
}
if (processedRules.length === 0) {
return config;
}
// Clone the config to avoid mutating the original
const modifiedConfig = { ...config };
// Combine processed rules with existing system message if the config has one
const existingSystemMessage = (modifiedConfig as any).systemMessage || "";
const rulesSection = processedRules.join("\n\n");
if (existingSystemMessage) {
(
modifiedConfig as any
).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`;
} else {
(modifiedConfig as any).systemMessage = rulesSection;
}
return modifiedConfig;
}
export async function initializeWithOnboarding(
authConfig: AuthConfig,
configPath: string | undefined
configPath: string | undefined,
rules?: string[]
): Promise<OnboardingResult> {
const firstTime = await isFirstTime();
@ -242,5 +283,10 @@ export async function initializeWithOnboarding(
result = await runNormalFlow(configPath, authConfig);
}
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return result;
}

View file

@ -7,6 +7,7 @@ import {
login,
logout,
} from "./auth/workos.js";
import { getAllSlashCommands } from "./commands/commands.js";
export async function handleSlashCommands(
input: string,
@ -25,19 +26,10 @@ export async function handleSlashCommands(
const [command, ...args] = input.slice(1).split(" ");
switch (command) {
case "help":
const allCommands = getAllSlashCommands(assistant);
const helpMessage = [
"Available commands:",
"/help - Show this help message",
"/clear - Clear the chat history",
"/exit - Exit the chat",
"/login - Authenticate with your account",
"/logout - Sign out of your current session",
"/whoami - Check who you're currently logged in as",
"/org - Switch organization",
"/config - Switch configuration",
...(assistant.prompts?.map(
(prompt) => `/${prompt?.name} - ${prompt?.description}`
) ?? []),
...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`),
].join("\n");
return { output: helpMessage };
case "clear":
@ -58,7 +50,7 @@ export async function handleSlashCommands(
} else {
console.info(chalk.green(`\nLogged in successfully`));
}
// Reload everything after successful login
if (onReload) {
await onReload();
@ -112,4 +104,4 @@ export async function handleSlashCommands(
}
}
return null;
}
}

View file

@ -1,28 +1,35 @@
import { CompletionOptions, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import chalk from "chalk";
import * as dotenv from "dotenv";
import type {
ChatCompletionCreateParamsStreaming,
ChatCompletionMessageParam,
ChatCompletionMessageToolCall,
ChatCompletionTool,
} from "openai/resources.mjs";
import { parseArgs } from "./args.js";
import { MCPService } from "./mcp.js";
import telemetryService from "./telemetry/telemetryService.js";
import { calculateTokenCost } from "./telemetry/utils.js";
import { executeToolCall } from "./tools.js";
import { BUILTIN_TOOLS } from "./tools/index.js";
import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js";
import {
chatCompletionStreamWithBackoff,
withExponentialBackoff,
} from "./util/exponentialBackoff.js";
import logger from "./util/logger.js";
dotenv.config();
export function getAllTools() {
const args = parseArgs();
// If no-tools mode is enabled, return empty array
if (args.noTools) {
return [];
}
const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({
type: "function" as const,
function: {
@ -59,8 +66,6 @@ export function getAllTools() {
return allTools;
}
type TODO = any;
export interface StreamCallbacks {
onContent?: (content: string) => void;
onContentComplete?: (content: string) => void;
@ -69,199 +74,343 @@ export interface StreamCallbacks {
onToolError?: (error: string, toolName?: string) => void;
}
// Define a function to handle streaming responses with tool calling
interface ToolCall {
id: string;
name: string;
arguments: any;
argumentsStr: string;
startNotified: boolean;
}
function getDefaultCompletionOptions(
opts?: CompletionOptions
): Partial<ChatCompletionCreateParamsStreaming> {
if (!opts) return {};
return {
max_tokens: opts.maxTokens,
temperature: opts.temperature,
frequency_penalty: opts.frequencyPenalty,
presence_penalty: opts.presencePenalty,
top_p: opts.topP,
};
}
// Process a single streaming response and return whether we need to continue
async function processStreamingResponse(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
llmApi: BaseLlmApi,
abortController: AbortController,
callbacks?: StreamCallbacks,
isHeadless?: boolean,
tools?: ChatCompletionTool[]
): Promise<{
content: string;
toolCalls: ToolCall[];
shouldContinue: boolean;
}> {
const requestStartTime = Date.now();
const streamFactory = async () => {
logger.debug("Creating chat completion stream", {
model,
messageCount: chatHistory.length,
toolCount: tools?.length || 0,
});
return await chatCompletionStreamWithBackoff(
llmApi,
{
model: model.model,
messages: chatHistory,
stream: true,
tools,
...getDefaultCompletionOptions(model.defaultCompletionOptions),
},
abortController.signal
);
};
let aiResponse = "";
const toolCallsMap = new Map<string, ToolCall>();
let firstTokenTime: number | null = null;
let inputTokens = 0;
let outputTokens = 0;
try {
const streamWithBackoff = withExponentialBackoff(
streamFactory,
abortController.signal
);
let chunkCount = 0;
for await (const chunk of streamWithBackoff) {
chunkCount++;
logger.debug("Received chunk", { chunkCount, chunk });
// Track first token time
if (
firstTokenTime === null &&
(chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls)
) {
firstTokenTime = Date.now();
telemetryService.recordResponseTime(
firstTokenTime - requestStartTime,
model.model,
"time_to_first_token",
(tools?.length || 0) > 0
);
}
// Track token usage if available
if (chunk.usage) {
inputTokens = chunk.usage.prompt_tokens || 0;
outputTokens = chunk.usage.completion_tokens || 0;
}
// Check if we should abort
if (abortController?.signal.aborted) {
logger.debug("Stream aborted");
break;
}
// Safety check: ensure chunk has the expected structure
if (!chunk.choices || !chunk.choices[0]) {
logger.warn("Malformed chunk received - missing choices", { chunk });
continue;
}
const choice = chunk.choices[0];
if (!choice.delta) {
logger.warn("Malformed chunk received - missing delta", { chunk });
continue;
}
// Handle regular content
if (choice.delta.content) {
const content = choice.delta.content;
if (callbacks?.onContent) {
callbacks.onContent(content);
} else if (!isHeadless) {
process.stdout.write(chalk.white(content));
}
aiResponse += content;
}
// Handle tool calls
if (choice.delta.tool_calls) {
for (const toolCallDelta of choice.delta.tool_calls) {
// Get or create tool call
if (toolCallDelta.id) {
if (!toolCallsMap.has(toolCallDelta.id)) {
toolCallsMap.set(toolCallDelta.id, {
id: toolCallDelta.id,
name: "",
arguments: null,
argumentsStr: "",
startNotified: false,
});
}
}
const toolCall = toolCallsMap.get(toolCallDelta.id || "");
if (!toolCall) continue;
// Update name
if (toolCallDelta.function?.name) {
toolCall.name = toolCallDelta.function.name;
}
// Accumulate arguments
if (toolCallDelta.function?.arguments) {
toolCall.argumentsStr += toolCallDelta.function.arguments;
// Try to parse when we might have complete JSON
try {
toolCall.arguments = JSON.parse(toolCall.argumentsStr);
// Notify on first successful parse
if (!toolCall.startNotified && toolCall.name) {
toolCall.startNotified = true;
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
} else if (!isHeadless) {
process.stdout.write(
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
);
}
}
} catch (e) {
// JSON not complete yet, continue
}
}
}
}
}
const responseEndTime = Date.now();
const totalDuration = responseEndTime - requestStartTime;
// Record API request metrics
const cost = calculateTokenCost(inputTokens, outputTokens, model.model);
telemetryService.recordTokenUsage(inputTokens, "input", model.model);
telemetryService.recordTokenUsage(outputTokens, "output", model.model);
telemetryService.recordCost(cost, model.model);
telemetryService.recordResponseTime(
totalDuration,
model.model,
"total_response_time",
(tools?.length || 0) > 0
);
// Log API request event
telemetryService.logApiRequest(
model.model,
totalDuration,
true, // success
undefined, // no error
inputTokens,
outputTokens,
cost
);
logger.debug("Stream complete", {
chunkCount,
responseLength: aiResponse.length,
toolCallsCount: toolCallsMap.size,
inputTokens,
outputTokens,
cost,
duration: totalDuration,
});
} catch (error: any) {
const errorDuration = Date.now() - requestStartTime;
// Log failed API request
telemetryService.logApiRequest(
model.model,
errorDuration,
false, // failed
error.message || String(error)
);
if (error.name === "AbortError" || abortController?.signal.aborted) {
logger.debug("Stream aborted by user");
return { content: aiResponse, toolCalls: [], shouldContinue: false };
}
throw error;
}
const toolCalls = Array.from(toolCallsMap.values());
// Validate tool calls have complete arguments
const validToolCalls = toolCalls.filter((tc) => {
if (!tc.arguments || !tc.name) {
logger.error("Incomplete tool call", {
id: tc.id,
name: tc.name,
hasArguments: !!tc.arguments,
argumentsStr: tc.argumentsStr,
});
return false;
}
return true;
});
return {
content: aiResponse,
toolCalls: validToolCalls,
shouldContinue: validToolCalls.length > 0,
};
}
// Main function that handles the conversation loop
export async function streamChatResponse(
chatHistory: ChatCompletionMessageParam[],
model: string,
model: ModelConfig,
llmApi: BaseLlmApi,
abortController: AbortController,
callbacks?: StreamCallbacks
) {
logger.debug("streamChatResponse called", {
model,
historyLength: chatHistory.length,
hasCallbacks: !!callbacks,
});
const args = parseArgs();
const isHeadless = args.isHeadless;
// Prepare tools for the API call
const toolsForRequest = getAllTools();
const tools = getAllTools();
logger.debug("Tools prepared", {
toolCount: tools.length,
toolNames: tools.map((t) => t.function.name),
});
let fullResponse = "";
let currentToolCalls: TODO[] = [];
let shouldContinueConversation = true;
while (shouldContinueConversation) {
logger.debug('Starting new conversation iteration', { hasToolCalls: currentToolCalls.length > 0 });
// Factory function to create the stream generator
const streamFactory = async () => {
logger.debug('Creating chat completion stream', { model, messageCount: chatHistory.length, toolCount: toolsForRequest.length });
return await chatCompletionStreamWithBackoff(
while (true) {
logger.debug("Starting conversation iteration");
// Get response from LLM
const { content, toolCalls, shouldContinue } =
await processStreamingResponse(
chatHistory,
model,
llmApi,
{
model,
messages: chatHistory,
stream: true,
tools: toolsForRequest,
},
abortController.signal
);
};
let aiResponse = "";
currentToolCalls = [];
let currentToolCallId = "";
let toolArguments = "";
try {
// Use the exponential backoff wrapper for the entire stream
const streamWithBackoff = withExponentialBackoff(
streamFactory,
abortController.signal
abortController,
callbacks,
isHeadless,
tools
);
for await (const chunk of streamWithBackoff) {
logger.debug('Received stream chunk', { hasContent: !!chunk.choices[0].delta.content, hasToolCalls: !!chunk.choices[0].delta.tool_calls });
// Check if we should abort
if (abortController?.signal.aborted) {
break;
}
fullResponse += content;
// Handle regular content
if (chunk.choices[0].delta.content) {
const content = chunk.choices[0].delta.content;
if (callbacks?.onContent) {
callbacks.onContent(content);
} else if (!isHeadless) {
process.stdout.write(chalk.white(content));
}
aiResponse += content;
fullResponse += content;
}
// Handle tool calls
if (chunk.choices[0].delta.tool_calls) {
for (const toolCallDelta of chunk.choices[0].delta.tool_calls) {
// Initialize a new tool call if we get an index and id
if (toolCallDelta.index !== undefined && toolCallDelta.id) {
if (!currentToolCalls[toolCallDelta.index]) {
currentToolCalls[toolCallDelta.index] = {
id: toolCallDelta.id,
name: "",
arguments: {},
startNotified: false,
};
}
currentToolCallId = toolCallDelta.id;
}
// Add function name if present
if (toolCallDelta.function?.name) {
const toolCall = currentToolCalls.find(
(tc) => tc.id === currentToolCallId
);
if (toolCall) {
if (!toolCall.name) {
toolCall.name = toolCallDelta.function.name;
toolCall.startNotified = false;
}
}
}
// Collect function arguments
if (toolCallDelta.function?.arguments) {
const toolCall = currentToolCalls.find(
(tc) => tc.id === currentToolCallId
);
if (toolCall) {
// Accumulate arguments as string to later parse as JSON
toolArguments += toolCallDelta.function.arguments;
try {
// Try to parse complete JSON
const parsed = JSON.parse(toolArguments);
toolCall.arguments = parsed;
// Notify start if we haven't already and have both name and args
if (toolCall.name && !toolCall.startNotified) {
toolCall.startNotified = true;
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
} else if (!isHeadless) {
process.stdout.write(
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
);
}
}
} catch (e) {
// Not complete JSON yet, continue collecting
}
}
}
}
}
}
} catch (error: any) {
// Handle AbortError gracefully - this is expected when user cancels
if (error.name === 'AbortError' || abortController?.signal.aborted) {
// Stream was aborted, this is expected behavior
return fullResponse;
}
// For other errors, re-throw them
logger.error(
chalk.red("Error in streamChatResponse:"),
error
);
throw error;
// Add newline after content if needed
if (!callbacks?.onContent && !isHeadless && content) {
logger.info("");
}
if (!callbacks?.onContent && !isHeadless) {
logger.info(""); // Add a newline after the response
// Notify content complete
if (content && callbacks?.onContentComplete) {
callbacks.onContentComplete(content);
}
// Notify that content is complete if we have content and are about to process tool calls
if (
aiResponse.trim() &&
currentToolCalls.length > 0 &&
callbacks?.onContentComplete
) {
callbacks.onContentComplete(aiResponse);
}
// Add the assistant's response to chat history if there's content or tool calls
if (currentToolCalls.length > 0) {
const toolCalls: ChatCompletionMessageToolCall[] = currentToolCalls.map(
(tc) => ({
// Add assistant message to history
if (toolCalls.length > 0) {
const toolCallsForHistory: ChatCompletionMessageToolCall[] =
toolCalls.map((tc) => ({
id: tc.id,
type: "function",
function: {
name: tc.name,
arguments: JSON.stringify(tc.arguments),
},
})
);
}));
chatHistory.push({
role: "assistant",
content: aiResponse,
tool_calls: toolCalls,
content: content || null,
tool_calls: toolCallsForHistory,
});
} else if (aiResponse.trim()) {
// Only add assistant response if there's actual content
chatHistory.push({ role: "assistant", content: aiResponse });
// Also notify content complete for standalone messages
if (callbacks?.onContentComplete) {
callbacks.onContentComplete(aiResponse);
}
}
// If we have tool calls, execute them
if (currentToolCalls.length > 0) {
for (const toolCall of currentToolCalls) {
// Execute tool calls
for (const toolCall of toolCalls) {
try {
// Execute the tool
logger.debug("Executing tool", {
name: toolCall.name,
arguments: toolCall.arguments,
});
const toolResult = await executeToolCall({
name: toolCall.name,
arguments: toolCall.arguments,
});
// Add tool result to chat history
chatHistory.push({
role: "tool",
tool_call_id: toolCall.id,
@ -277,30 +426,45 @@ export async function streamChatResponse(
const errorMessage = `Error executing tool ${toolCall.name}: ${
error instanceof Error ? error.message : String(error)
}`;
logger.error("Tool execution failed", {
name: toolCall.name,
error: errorMessage,
});
chatHistory.push({
role: "tool",
tool_call_id: toolCall.id,
content: errorMessage,
});
if (callbacks?.onToolError) {
callbacks.onToolError(errorMessage, toolCall.name);
} else if (!isHeadless) {
console.info(
`${chalk.red("[Tool error:")} ${chalk.red(
errorMessage
)}${chalk.red(")")}`
)}${chalk.red("]")}`
);
}
}
}
} else if (content) {
// Just content, no tools
chatHistory.push({ role: "assistant", content });
}
// Continue the conversation with the tool results
shouldContinueConversation = true;
} else {
// No more tool calls, end the conversation
shouldContinueConversation = false;
// Check if we should continue
if (!shouldContinue) {
logger.debug("Conversation complete - no more tool calls");
break;
}
}
logger.debug("streamChatResponse complete", {
totalResponseLength: fullResponse.length,
totalMessages: chatHistory.length,
});
return fullResponse;
}

View file

@ -1,9 +1,9 @@
import { constructSystemMessage } from './systemMessage.js';
describe('constructSystemMessage', () => {
it('should return base system message with rules when rulesSystemMessage is provided', () => {
it('should return base system message with rules when rulesSystemMessage is provided', async () => {
const rulesMessage = 'These are the rules for the assistant.';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
@ -11,17 +11,17 @@ describe('constructSystemMessage', () => {
expect(result).toContain('</context>');
});
it('should return base system message with agent content when no rules but agent file exists', () => {
it('should return base system message with agent content when no rules but agent file exists', async () => {
// The implementation checks for agent files like AGENTS.md which exists in this project
const result = constructSystemMessage('');
const result = await constructSystemMessage('');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
expect(result).toContain('AGENTS.md');
});
it('should include base system message components', () => {
const result = constructSystemMessage('');
it('should include base system message components', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<env>');
@ -30,72 +30,72 @@ describe('constructSystemMessage', () => {
expect(result).toContain('Any file paths you return in your final response MUST be absolute');
});
it('should handle whitespace-only rules message', () => {
const result = constructSystemMessage(' ');
it('should handle whitespace-only rules message', async () => {
const result = await constructSystemMessage(' ');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
});
it('should include working directory information', () => {
const result = constructSystemMessage('');
it('should include working directory information', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Working directory:');
expect(result).toContain('<env>');
});
it('should include platform information', () => {
const result = constructSystemMessage('');
it('should include platform information', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Platform:');
});
it('should include current date', () => {
const result = constructSystemMessage('');
it('should include current date', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Today\'s date:');
expect(result).toContain(new Date().toISOString().split('T')[0]);
});
it('should format rules section correctly', () => {
it('should format rules section correctly', async () => {
const rulesMessage = 'Rule 1: Do this\nRule 2: Do that';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);
expect(result).toContain('</context>');
});
it('should handle multiline rules message', () => {
it('should handle multiline rules message', async () => {
const rulesMessage = `Rule 1: First rule
Rule 2: Second rule
Rule 3: Third rule`;
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain('</context>');
});
it('should handle special characters in rules message', () => {
it('should handle special characters in rules message', async () => {
const rulesMessage = 'Rule with <special> characters & symbols!';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
});
it('should handle very long rules message', () => {
it('should handle very long rules message', async () => {
const rulesMessage = 'A'.repeat(1000);
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
});
it('should combine rules and agent content when both are present', () => {
it('should combine rules and agent content when both are present', async () => {
const rulesMessage = 'These are the rules.';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);

View file

@ -99,7 +99,10 @@ ${getGitStatus()}
* @param additionalRules - Additional rules from --rule flags
* @returns The comprehensive system message with base message and rules section
*/
export function constructSystemMessage(rulesSystemMessage: string, additionalRules?: string[]): string {
export async function constructSystemMessage(
rulesSystemMessage: string,
additionalRules?: string[]
): Promise<string> {
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
let agentContent = "";
@ -123,10 +126,12 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul
if (additionalRules && additionalRules.length > 0) {
for (const ruleSpec of additionalRules) {
try {
const processedRule = processRule(ruleSpec);
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(`Warning: Failed to process rule "${ruleSpec}": ${error.message}`);
console.warn(
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
);
}
}
}
@ -149,7 +154,7 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul
// Add processed rules from --rule flags
if (processedRules.length > 0) {
const separator = (rulesSystemMessage || agentContent) ? "\n\n" : "\n";
const separator = rulesSystemMessage || agentContent ? "\n\n" : "\n";
systemMessage += `${separator}${processedRules.join("\n\n")}`;
}

View file

@ -0,0 +1,548 @@
import { metrics } from "@opentelemetry/api";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import {
ConsoleMetricExporter,
MeterProvider,
PeriodicExportingMetricReader,
} from "@opentelemetry/sdk-metrics";
import {
SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
SEMRESATTRS_OS_TYPE,
SEMRESATTRS_PROCESS_PID,
SEMRESATTRS_SERVICE_NAME,
SEMRESATTRS_SERVICE_VERSION,
} from "@opentelemetry/semantic-conventions";
import os from "os";
import { v4 as uuidv4 } from "uuid";
import logger from "../util/logger.js";
import { getVersion } from "../version.js";
export interface TelemetryConfig {
enabled: boolean;
sessionId: string;
organizationId?: string;
accountUuid?: string;
includeSessionId: boolean;
includeVersion: boolean;
includeAccountUuid: boolean;
}
class TelemetryService {
private meterProvider: MeterProvider | null = null;
private meter: any = null;
private config: TelemetryConfig;
private startTime = Date.now();
private activeStartTime: number | null = null;
private totalActiveTime = 0;
// Metrics
private sessionCounter: any = null;
private linesOfCodeCounter: any = null;
private pullRequestCounter: any = null;
private commitCounter: any = null;
private costCounter: any = null;
private tokenCounter: any = null;
private codeEditDecisionCounter: any = null;
private activeTimeCounter: any = null;
private authAttemptsCounter: any = null;
private mcpConnectionsGauge: any = null;
private startupTimeHistogram: any = null;
private responseTimeHistogram: any = null;
constructor() {
this.config = this.loadConfig();
if (this.config.enabled) {
this.initialize();
}
}
private loadConfig(): TelemetryConfig {
const hasOtelConfig = !!(
process.env.OTEL_EXPORTER_OTLP_ENDPOINT ||
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
process.env.OTEL_METRICS_EXPORTER
);
const enabled =
process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0" && hasOtelConfig;
const sessionId = uuidv4();
return {
enabled,
sessionId,
organizationId: process.env.ORGANIZATION_ID,
accountUuid: process.env.ACCOUNT_UUID,
includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false",
includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
includeAccountUuid:
process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
};
}
private initialize() {
try {
// Create resource
const resource = resourceFromAttributes({
[SEMRESATTRS_SERVICE_NAME]: "continue-cli",
[SEMRESATTRS_SERVICE_VERSION]: getVersion(),
[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
process.env.NODE_ENV || "development",
[SEMRESATTRS_OS_TYPE]: os.type(),
[SEMRESATTRS_PROCESS_PID]: process.pid.toString(),
});
// Configure exporters
const readers: any[] = [];
const metricsExporters = (
process.env.OTEL_METRICS_EXPORTER || "console"
).split(",");
for (const exporterType of metricsExporters) {
switch (exporterType.trim()) {
case "otlp":
readers.push(
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({
url:
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
"http://localhost:4318/v1/metrics",
headers: this.parseHeaders(
process.env.OTEL_EXPORTER_OTLP_HEADERS || ""
),
}),
exportIntervalMillis: parseInt(
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
),
})
);
break;
case "console":
readers.push(
new PeriodicExportingMetricReader({
exporter: new ConsoleMetricExporter(),
exportIntervalMillis: parseInt(
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
),
})
);
break;
}
}
// Create meter provider
this.meterProvider = new MeterProvider({
resource,
readers,
});
metrics.setGlobalMeterProvider(this.meterProvider);
this.meter = metrics.getMeter("continue-cli", getVersion());
this.initializeMetrics();
logger.debug("Telemetry service initialized", {
sessionId: this.config.sessionId,
exporters: metricsExporters,
});
} catch (error) {
logger.error("Failed to initialize telemetry", error);
}
}
private parseHeaders(headersStr: string): Record<string, string> {
const headers: Record<string, string> = {};
if (!headersStr) return headers;
headersStr.split(",").forEach((header) => {
const [key, value] = header.split("=");
if (key && value) {
headers[key.trim()] = value.trim();
}
});
return headers;
}
private initializeMetrics() {
if (!this.meter) return;
// Core metrics (Claude Code compatible)
this.sessionCounter = this.meter.createCounter(
"continue.cli.session.count",
{
description: "Count of CLI sessions started",
unit: "count",
}
);
this.linesOfCodeCounter = this.meter.createCounter(
"continue.cli.lines_of_code.count",
{
description: "Count of lines of code modified",
unit: "count",
}
);
this.pullRequestCounter = this.meter.createCounter(
"continue.cli.pull_request.count",
{
description: "Number of pull requests created",
unit: "count",
}
);
this.commitCounter = this.meter.createCounter("continue.cli.commit.count", {
description: "Number of git commits created",
unit: "count",
});
this.costCounter = this.meter.createCounter("continue.cli.cost.usage", {
description: "Cost of the Continue CLI session",
unit: "USD",
});
this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", {
description: "Number of tokens used",
unit: "tokens",
});
this.codeEditDecisionCounter = this.meter.createCounter(
"continue.cli.code_edit_tool.decision",
{
description: "Count of code editing tool permission decisions",
unit: "count",
}
);
this.activeTimeCounter = this.meter.createCounter(
"continue.cli.active_time.total",
{
description: "Total active time in seconds",
unit: "s",
}
);
// Additional Continue CLI specific metrics
this.authAttemptsCounter = this.meter.createCounter(
"continue.cli.auth.attempts",
{
description: "Authentication attempts",
unit: "{attempt}",
}
);
this.mcpConnectionsGauge = this.meter.createObservableGauge(
"continue.cli.mcp.connections",
{
description: "Active MCP connections",
unit: "{connection}",
}
);
this.startupTimeHistogram = this.meter.createHistogram(
"continue.cli.startup.time",
{
description: "Time from CLI start to ready state",
unit: "ms",
}
);
this.responseTimeHistogram = this.meter.createHistogram(
"continue.cli.response_time",
{
description: "LLM response time metrics",
unit: "ms",
}
);
}
// Check if telemetry is enabled - this is the single point of checking
private isEnabled(): boolean {
return this.config.enabled && this.meter !== null;
}
private getStandardAttributes(
additionalAttributes: Record<string, string> = {}
) {
const attributes: Record<string, string> = { ...additionalAttributes };
if (this.config.includeSessionId) {
attributes["session.id"] = this.config.sessionId;
}
if (this.config.includeVersion) {
attributes["app.version"] = getVersion();
}
if (this.config.organizationId) {
attributes["organization.id"] = this.config.organizationId;
}
if (this.config.includeAccountUuid && this.config.accountUuid) {
attributes["user.account_uuid"] = this.config.accountUuid;
}
// Detect terminal type
const terminalType = this.detectTerminalType();
if (terminalType) {
attributes["terminal.type"] = terminalType;
}
return attributes;
}
private detectTerminalType(): string | undefined {
if (process.env.TERM_PROGRAM) {
return process.env.TERM_PROGRAM;
}
if (process.env.VSCODE_PID) {
return "vscode";
}
if (process.env.TMUX) {
return "tmux";
}
return undefined;
}
// Public methods for tracking metrics
public recordSessionStart() {
if (!this.isEnabled()) return;
this.sessionCounter.add(1, this.getStandardAttributes());
this.recordStartupTime(Date.now() - this.startTime);
}
public recordLinesOfCodeModified(
type: "added" | "removed",
count: number,
language?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({ type });
if (language) {
attributes.language = language;
}
this.linesOfCodeCounter.add(count, attributes);
}
public recordPullRequestCreated() {
if (!this.isEnabled()) return;
this.pullRequestCounter.add(1, this.getStandardAttributes());
}
public recordCommitCreated() {
if (!this.isEnabled()) return;
this.commitCounter.add(1, this.getStandardAttributes());
}
public recordCost(cost: number, model: string) {
if (!this.isEnabled()) return;
this.costCounter.add(cost, this.getStandardAttributes({ model }));
}
public recordTokenUsage(
tokens: number,
type: "input" | "output" | "cacheRead" | "cacheCreation",
model: string
) {
if (!this.isEnabled()) return;
this.tokenCounter.add(tokens, this.getStandardAttributes({ type, model }));
}
public recordCodeEditDecision(
tool: string,
decision: "accept" | "reject",
language?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({ tool, decision });
if (language) {
attributes.language = language;
}
this.codeEditDecisionCounter.add(1, attributes);
}
public startActiveTime() {
if (!this.isEnabled()) return;
if (this.activeStartTime === null) {
this.activeStartTime = Date.now();
}
}
public stopActiveTime() {
if (!this.isEnabled()) return;
if (this.activeStartTime !== null) {
this.totalActiveTime += Date.now() - this.activeStartTime;
this.activeStartTime = null;
this.activeTimeCounter.add(
this.totalActiveTime / 1000,
this.getStandardAttributes()
);
}
}
public recordAuthAttempt(
result: "success" | "failure" | "cancelled",
method: "workos" | "token"
) {
if (!this.isEnabled()) return;
this.authAttemptsCounter.add(
1,
this.getStandardAttributes({ result, method })
);
}
public recordMCPConnection(
serverName: string,
status: "connected" | "disconnected" | "error"
) {
if (!this.isEnabled()) return;
const value = status === "connected" ? 1 : 0;
// Note: Observable gauge callback will be implemented when MCP monitoring is added
if (this.mcpConnectionsGauge) {
// This is a placeholder - observable gauges work differently
logger.debug("MCP connection status", { serverName, status, value });
}
}
public recordStartupTime(
timeMs: number,
mode?: "tui" | "headless" | "standard",
coldStart?: boolean
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes();
if (mode) attributes.mode = mode;
if (coldStart !== undefined) attributes.cold_start = coldStart.toString();
this.startupTimeHistogram.record(timeMs, attributes);
}
public recordResponseTime(
timeMs: number,
model: string,
metricType: "time_to_first_token" | "total_response_time",
hasTools?: boolean
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
model,
metric_type: metricType,
});
if (hasTools !== undefined) attributes.has_tools = hasTools.toString();
this.responseTimeHistogram.record(timeMs, attributes);
}
// Event logging methods (these will be implemented when OTLP logs support is added)
public logUserPrompt(promptLength: number, prompt?: string) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "user_prompt",
"event.timestamp": new Date().toISOString(),
prompt_length: promptLength.toString(),
});
if (process.env.OTEL_LOG_USER_PROMPTS === "1" && prompt) {
attributes.prompt = prompt;
}
// TODO: Implement OTLP logs export
logger.debug("User prompt event", attributes);
}
public logToolResult(
toolName: string,
success: boolean,
durationMs: number,
error?: string,
decision?: "accept" | "reject",
source?: string,
toolParameters?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "tool_result",
"event.timestamp": new Date().toISOString(),
tool_name: toolName,
success: success.toString(),
duration_ms: durationMs.toString(),
});
if (error) attributes.error = error;
if (decision) attributes.decision = decision;
if (source) attributes.source = source;
if (toolParameters) attributes.tool_parameters = toolParameters;
// TODO: Implement OTLP logs export
logger.debug("Tool result event", attributes);
}
public logApiRequest(
model: string,
durationMs: number,
success: boolean,
error?: string,
inputTokens?: number,
outputTokens?: number,
costUsd?: number
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "api_request",
"event.timestamp": new Date().toISOString(),
model,
duration_ms: durationMs.toString(),
success: success.toString(),
});
if (error) attributes.error = error;
if (inputTokens) attributes.input_tokens = inputTokens.toString();
if (outputTokens) attributes.output_tokens = outputTokens.toString();
if (costUsd) attributes.cost_usd = costUsd.toString();
// TODO: Implement OTLP logs export
logger.debug("API request event", attributes);
}
public updateOrganization(organizationId: string) {
this.config.organizationId = organizationId;
}
public updateAccountUuid(accountUuid: string) {
this.config.accountUuid = accountUuid;
}
public getSessionId(): string {
return this.config.sessionId;
}
public shutdown() {
this.stopActiveTime();
return this.meterProvider?.shutdown();
}
}
// Export the singleton instance directly
export const telemetryService = new TelemetryService();
export default telemetryService;

154
src/telemetry/utils.ts Normal file
View file

@ -0,0 +1,154 @@
import { diffLines } from "diff";
import path from "path";
/**
* Calculate lines of code added/removed from a file diff
*/
export function calculateLinesOfCodeDiff(
oldContent: string,
newContent: string
): { added: number; removed: number } {
const diff = diffLines(oldContent, newContent);
let added = 0;
let removed = 0;
for (const part of diff) {
if (part.added) {
added += part.count || 0;
} else if (part.removed) {
removed += part.count || 0;
}
}
return { added, removed };
}
/**
* Extract programming language from file path
*/
export function getLanguageFromFilePath(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
const languageMap: Record<string, string> = {
".js": "JavaScript",
".jsx": "JavaScript",
".ts": "TypeScript",
".tsx": "TypeScript",
".py": "Python",
".java": "Java",
".cpp": "C++",
".c": "C",
".cs": "C#",
".php": "PHP",
".rb": "Ruby",
".go": "Go",
".rs": "Rust",
".swift": "Swift",
".kt": "Kotlin",
".scala": "Scala",
".clj": "Clojure",
".hs": "Haskell",
".ml": "OCaml",
".elm": "Elm",
".dart": "Dart",
".lua": "Lua",
".r": "R",
".m": "Objective-C",
".mm": "Objective-C++",
".sh": "Shell",
".bash": "Bash",
".zsh": "Zsh",
".fish": "Fish",
".ps1": "PowerShell",
".html": "HTML",
".css": "CSS",
".scss": "SCSS",
".sass": "Sass",
".less": "Less",
".vue": "Vue",
".svelte": "Svelte",
".md": "Markdown",
".json": "JSON",
".xml": "XML",
".yaml": "YAML",
".yml": "YAML",
".toml": "TOML",
".ini": "INI",
".cfg": "Config",
".conf": "Config",
".sql": "SQL",
".dockerfile": "Dockerfile",
};
return languageMap[ext] || "unknown";
}
/**
* Extract the first word (command type) from a shell command
*/
export function extractCommandType(command: string): string {
return command.trim().split(/\s+/)[0] || "unknown";
}
/**
* Check if a command is a git commit command
*/
export function isGitCommitCommand(command: string): boolean {
const trimmed = command.trim().toLowerCase();
return trimmed.startsWith("git commit") || trimmed.startsWith("git-commit");
}
/**
* Check if a command is a pull request creation command
*/
export function isPullRequestCommand(command: string): boolean {
const trimmed = command.trim().toLowerCase();
return (
trimmed.includes("gh pr create") ||
(trimmed.includes("git push") && trimmed.includes("pull-request")) ||
trimmed.includes("hub pull-request") ||
trimmed.includes("gitlab mr create")
);
}
/**
* Simple cost calculation based on tokens and model
* This should be updated with actual pricing from model providers
*/
export function calculateTokenCost(
inputTokens: number,
outputTokens: number,
model: string
): number {
// Pricing per 1K tokens (these are approximate and should be updated)
const pricingMap: Record<string, { input: number; output: number }> = {
"gpt-4": { input: 0.03, output: 0.06 },
"gpt-4-turbo": { input: 0.01, output: 0.03 },
"gpt-3.5-turbo": { input: 0.0015, output: 0.002 },
"claude-3-5-sonnet-20241022": { input: 0.003, output: 0.015 },
"claude-3-sonnet": { input: 0.003, output: 0.015 },
"claude-3-haiku": { input: 0.00025, output: 0.00125 },
"claude-3-opus": { input: 0.015, output: 0.075 },
};
// Find pricing for model (case insensitive partial match)
const modelKey = Object.keys(pricingMap).find((key) =>
model.toLowerCase().includes(key.toLowerCase())
);
if (!modelKey) {
// Default pricing if model not found
return (inputTokens * 0.001 + outputTokens * 0.002) / 1000;
}
const pricing = pricingMap[modelKey];
return (inputTokens * pricing.input + outputTokens * pricing.output) / 1000;
}
/**
* Get file type from extension for metrics
*/
export function getFileTypeFromPath(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
return ext.startsWith(".") ? ext.substring(1) : "unknown";
}

View file

@ -1,5 +1,5 @@
import { Tool } from "./types.js";
import TurndownService from "turndown";
import { Tool } from "./types.js";
const turndownService = new TurndownService({
headingStyle: "atx",
@ -31,7 +31,7 @@ turndownService.addRule("pre", {
export const fetchTool: Tool = {
name: "fetch",
displayName: "Fetch URL",
displayName: "Fetch",
description: "Fetches content from a URL and converts it to markdown format",
parameters: {
url: {
@ -64,7 +64,8 @@ export const fetchTool: Tool = {
signal: controller.signal,
headers: {
"User-Agent": "Continue-CLI/1.0 (https://continue.dev)",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
@ -78,7 +79,7 @@ export const fetchTool: Tool = {
}
const contentType = response.headers.get("content-type") || "";
// Handle different content types
if (contentType.includes("application/json")) {
const json = await response.json();
@ -96,10 +97,10 @@ export const fetchTool: Tool = {
// Process HTML content
const html = await response.text();
// Convert HTML to markdown
const markdown = turndownService.turndown(html);
// Clean up the markdown
const cleanedMarkdown = markdown
.replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines
@ -108,7 +109,6 @@ export const fetchTool: Tool = {
.replace(/\\\]/g, "]");
return `# Content from ${url}\n\n${cleanedMarkdown}`;
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`;
@ -119,4 +119,4 @@ export const fetchTool: Tool = {
return `Error: ${error instanceof Error ? error.message : String(error)}`;
}
},
};
};

View file

@ -1,5 +1,7 @@
import { parseArgs } from "../args.js";
import { MCPService } from "../mcp.js";
import telemetryService from "../telemetry/telemetryService.js";
import logger from "../util/logger.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
import { listFilesTool } from "./listFiles.js";
@ -7,9 +9,7 @@ import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
import { searchCodeTool } from "./searchCode.js";
import { type Tool, type ToolParameters } from "./types.js";
import { viewDiffTool } from "./viewDiff.js";
import { writeFileTool } from "./writeFile.js";
import logger from "../util/logger.js";
export type { Tool, ToolParameters };
@ -17,7 +17,6 @@ const ALL_BUILTIN_TOOLS: Tool[] = [
readFileTool,
writeFileTool,
listFilesTool,
viewDiffTool,
searchCodeTool,
runTerminalCommandTool,
fetchTool,
@ -115,6 +114,8 @@ export async function executeToolCall(toolCall: {
name: string;
arguments: Record<string, any>;
}): Promise<string> {
const startTime = Date.now();
const args = parseArgs();
let mcpTools: Tool[] = [];
@ -151,6 +152,13 @@ export async function executeToolCall(toolCall: {
const tool = allTools.find((t) => t.name === toolCall.name);
if (!tool) {
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
false,
duration,
`Tool "${toolCall.name}" not found`
);
return `Error: Tool "${toolCall.name}" not found`;
}
@ -160,18 +168,52 @@ export async function executeToolCall(toolCall: {
(toolCall.arguments[paramName] === undefined ||
toolCall.arguments[paramName] === null)
) {
return `Error: Required parameter "${paramName}" missing for tool "${toolCall.name}"`;
const duration = Date.now() - startTime;
const error = `Required parameter "${paramName}" missing for tool "${toolCall.name}"`;
telemetryService.logToolResult(toolCall.name, false, duration, error);
return `Error: ${error}`;
}
}
try {
logger.debug('Executing tool', { toolName: toolCall.name, arguments: toolCall.arguments });
logger.debug("Executing tool", {
toolName: toolCall.name,
arguments: toolCall.arguments,
});
const result = await tool.run(toolCall.arguments);
logger.debug('Tool execution completed', { toolName: toolCall.name, resultLength: result?.length || 0 });
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
true,
duration,
undefined, // no error
undefined, // no decision
undefined, // no source
JSON.stringify(toolCall.arguments)
);
logger.debug("Tool execution completed", {
toolName: toolCall.name,
resultLength: result?.length || 0,
});
return result;
} catch (error) {
return `Error executing tool "${toolCall.name}": ${
error instanceof Error ? error.message : String(error)
}`;
const duration = Date.now() - startTime;
const errorMessage = error instanceof Error ? error.message : String(error);
telemetryService.logToolResult(
toolCall.name,
false,
duration,
errorMessage,
undefined, // no decision
undefined, // no source
JSON.stringify(toolCall.arguments)
);
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
}
}

View file

@ -1,10 +1,15 @@
import { Tool } from "./types.js";
import { exec } from "child_process";
import telemetryService from "../telemetry/telemetryService.js";
import {
isGitCommitCommand,
isPullRequestCommand,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
export const runTerminalCommandTool: Tool = {
name: "run_terminal_command",
displayName: "Terminal",
description: "Executes a terminal command and returns the output.",
displayName: "Bash",
description: "Executes a terminal command and returns the output",
parameters: {
command: {
type: "string",
@ -16,10 +21,20 @@ export const runTerminalCommandTool: Tool = {
run: async ({ command }: { command: string }): Promise<string> => {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
const exitCode = error?.code || 0;
if (error) {
reject(`Error: ${error.message}`);
return;
}
// Track specific git operations
if (isGitCommitCommand(command)) {
telemetryService.recordCommitCreated();
} else if (isPullRequestCommand(command)) {
telemetryService.recordPullRequestCreated();
}
if (stderr) {
resolve(`Stderr: ${stderr}`);
return;
@ -28,4 +43,4 @@ export const runTerminalCommandTool: Tool = {
});
});
},
};
};

View file

@ -1,9 +1,18 @@
import { createTwoFilesPatch } from "diff";
import * as fs from "fs";
import * as path from "path";
import { createTwoFilesPatch } from "diff";
import telemetryService from "../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
function generateDiff(oldContent: string, newContent: string, filePath: string): string {
function generateDiff(
oldContent: string,
newContent: string,
filePath: string
): string {
return createTwoFilesPatch(
filePath,
filePath,
@ -40,23 +49,56 @@ export const writeFileTool: Tool = {
}
// Read existing file content if it exists
let oldContent = '';
let oldContent = "";
if (fs.existsSync(args.filepath)) {
oldContent = fs.readFileSync(args.filepath, "utf-8");
}
// Write new content
fs.writeFileSync(args.filepath, args.content, "utf-8");
// Generate diff if file existed before
// Track lines of code changes if file existed before
if (oldContent) {
const { added, removed } = calculateLinesOfCodeDiff(
oldContent,
args.content
);
const language = getLanguageFromFilePath(args.filepath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
}
if (removed > 0) {
telemetryService.recordLinesOfCodeModified(
"removed",
removed,
language
);
}
const diff = generateDiff(oldContent, args.content, args.filepath);
// Record file operation
return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`;
} else {
// New file creation - count all lines as added
const lineCount = args.content.split("\n").length;
const language = getLanguageFromFilePath(args.filepath);
telemetryService.recordLinesOfCodeModified(
"added",
lineCount,
language
);
return `Successfully created file: ${args.filepath}`;
}
} catch (error) {
return `Error writing to file: ${error instanceof Error ? error.message : String(error)}`;
const errorMessage =
error instanceof Error ? error.message : String(error);
return `Error writing to file: ${errorMessage}`;
}
},
};
};

View file

@ -1,7 +1,3 @@
import {
Configuration,
DefaultApi,
} from "@continuedev/sdk/dist/api/dist/index.js";
import * as fs from "fs";
import { Box, Text, useInput } from "ink";
import * as os from "os";
@ -12,6 +8,7 @@ import {
getOrganizationId,
loadAuthConfig,
} from "../auth/workos.js";
import { getApiClient } from "../config.js";
interface ConfigOption {
id: string;
@ -56,11 +53,7 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
// Add assistants from current organization if authenticated
if (accessToken) {
const apiClient = new DefaultApi(
new Configuration({
accessToken,
})
);
const apiClient = getApiClient(accessToken);
try {
const assistants = await apiClient.listAssistants({
@ -69,13 +62,13 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
});
for (const assistant of assistants) {
// Use packageSlug as the slug and create a display name from ownerSlug/packageSlug
// Use full ownerSlug/packageSlug as the slug and create a display name from ownerSlug/packageSlug
const displayName = `${assistant.ownerSlug}/${assistant.packageSlug}`;
options.push({
id: assistant.packageSlug,
name: displayName,
type: "assistant",
slug: assistant.packageSlug,
slug: `${assistant.ownerSlug}/${assistant.packageSlug}`,
});
}
} catch (err) {

View file

@ -18,25 +18,19 @@ interface FileItem {
const fileCache = new Map<string, FileItem[]>();
let allFiles: FileItem[] = [];
let cacheInitialized = false;
let cacheInitializationPromise: Promise<void> | null = null;
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
const initializingRef = useRef(false);
// Initialize cache once
const initializeCache = async () => {
if (cacheInitialized || initializingRef.current) {
return;
}
initializingRef.current = true;
// Initialize cache once
const initializeCache = async (): Promise<void> => {
if (cacheInitialized) {
return;
}
if (cacheInitializationPromise) {
return cacheInitializationPromise;
}
cacheInitializationPromise = (async () => {
try {
// Use a single, more efficient pattern
const patterns = [
@ -127,79 +121,94 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
cacheInitialized = true;
} catch (error) {
console.error("Error initializing file cache:", error);
} finally {
initializingRef.current = false;
}
};
})();
return cacheInitializationPromise;
};
// Filter files from cache
const filterFiles = (filterText: string): FileItem[] => {
if (!cacheInitialized) {
return [];
}
// Export function to start indexing proactively
export const startFileIndexing = (): Promise<void> => {
return initializeCache();
};
if (filterText.length === 0) {
// Show most recently modified files when no filter
return allFiles
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
}
// Filter files from cache
const filterFiles = (filterText: string): FileItem[] => {
if (!cacheInitialized) {
return [];
}
const lowerFilter = filterText.toLowerCase();
// Check cache first
const cacheKey = lowerFilter;
if (fileCache.has(cacheKey)) {
return fileCache.get(cacheKey)!;
}
const filteredFiles = allFiles
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
if (filterText.length === 0) {
// Show most recently modified files when no filter
return allFiles
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
}
// Cache the result
fileCache.set(cacheKey, filteredFiles);
// Limit cache size
if (fileCache.size > 100) {
const firstKey = fileCache.keys().next().value;
if (firstKey) {
fileCache.delete(firstKey);
}
const lowerFilter = filterText.toLowerCase();
// Check cache first
const cacheKey = lowerFilter;
if (fileCache.has(cacheKey)) {
return fileCache.get(cacheKey)!;
}
const filteredFiles = allFiles
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
// Cache the result
fileCache.set(cacheKey, filteredFiles);
// Limit cache size
if (fileCache.size > 100) {
const firstKey = fileCache.keys().next().value;
if (firstKey) {
fileCache.delete(firstKey);
}
}
return filteredFiles;
};
return filteredFiles;
};
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const searchFiles = async () => {

108
src/ui/FreeTrialStatus.tsx Normal file
View file

@ -0,0 +1,108 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
DefaultApiInterface,
GetFreeTrialStatus200Response,
} from "@continuedev/sdk/dist/api/dist/index.js";
import { Text } from "ink";
import React, { useEffect, useState } from "react";
export function isModelUsingFreeTrial(model: ModelConfig): boolean {
return (
model.provider === "continue-proxy" &&
(model as any).apiKeyLocation.startsWith("free_trial:")
);
}
interface FreeTrialStatusProps {
apiClient?: DefaultApiInterface;
onTransitionStateChange?: (isShowingTransition: boolean) => void;
model: ModelConfig;
}
const FreeTrialStatus: React.FC<FreeTrialStatusProps> = ({
apiClient,
onTransitionStateChange,
model,
}) => {
const [status, setStatus] = useState<GetFreeTrialStatus200Response | null>(
null
);
const [loading, setLoading] = useState(true);
const fetchStatus = async () => {
try {
if (!apiClient) {
setStatus(null);
setLoading(false);
return;
}
const response = await apiClient.getFreeTrialStatus();
setStatus(response);
setLoading(false);
} catch (error) {
// Silently handle errors - component returns null if no status
setStatus(null);
setLoading(false);
}
};
useEffect(() => {
// Initial fetch
fetchStatus();
// Don't poll in test environment
if (process.env.NODE_ENV === "test") {
return;
}
// Poll every 5 seconds
const interval = setInterval(fetchStatus, 5000);
return () => clearInterval(interval);
}, []);
// Check if user has maxed out their free trial and notify parent
useEffect(() => {
if (!status || !status.optedInToFreeTrial || loading) {
// No transition needed
if (onTransitionStateChange) {
onTransitionStateChange(false);
}
return;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Check if user has maxed out their free trial
const shouldShowTransition =
chatUsed >= chatLimit && isModelUsingFreeTrial(model);
if (onTransitionStateChange) {
onTransitionStateChange(shouldShowTransition);
}
}, [status, loading, onTransitionStateChange, model]);
// Don't render anything while loading or if no status
if (
loading ||
!status ||
!status.optedInToFreeTrial ||
!isModelUsingFreeTrial(model)
) {
return null;
}
const chatUsed = status.chatCount ?? 0;
const chatLimit = status.chatLimit;
// Only show the normal status text - transition UI is handled by parent
return (
<Text color="dim">
{chatUsed}/{chatLimit} free trial
</Text>
);
};
export default FreeTrialStatus;

View file

@ -0,0 +1,304 @@
import * as fs from "fs";
import { Box, Text, useInput } from "ink";
import open from "open";
import * as os from "os";
import * as path from "path";
import React, { useState } from "react";
import * as YAML from "yaml";
import { env } from "../env.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
interface FreeTrialTransitionUIProps {
onComplete: () => void;
onSwitchToLocalConfig?: () => void;
onFullReload?: () => void;
}
/**
* Creates or updates the local config with Anthropic API key
*/
async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const newModel = {
uses: "anthropic/claude-4-sonnet",
with: {
ANTHROPIC_API_KEY: apiKey,
},
};
if (fs.existsSync(CONFIG_PATH)) {
const existingContent = fs.readFileSync(CONFIG_PATH, "utf8");
let config;
try {
config = YAML.parse(existingContent);
// Make sure models array exists
if (!config.models) {
config.models = [];
}
// Check if model already exists
const existingModelIndex = config.models.findIndex(
(model: any) => model.uses === "anthropic/claude-4-sonnet"
);
if (existingModelIndex >= 0) {
// Update existing model
config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey;
} else {
// Add new model
config.models.push(newModel);
}
} catch (error) {
// If parsing fails, create a new config
config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
}
// Write back to file
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
} else {
// Create new config file
const config = {
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [newModel],
};
fs.writeFileSync(CONFIG_PATH, YAML.stringify(config));
}
}
const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
onComplete,
onSwitchToLocalConfig,
onFullReload,
}) => {
const [currentStep, setCurrentStep] = useState<
"choice" | "enterApiKey" | "processing" | "success" | "error"
>("choice");
const [selectedOption, setSelectedOption] = useState(1);
const [apiKey, setApiKey] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [successMessage, setSuccessMessage] = useState("");
const [wasModelsSetup, setWasModelsSetup] = useState(false);
useInput((input, key) => {
if (currentStep === "choice") {
if (key.upArrow && selectedOption > 1) {
setSelectedOption(selectedOption - 1);
} else if (key.downArrow && selectedOption < 2) {
setSelectedOption(selectedOption + 1);
} else if (input === "1") {
setSelectedOption(1);
} else if (input === "2") {
setSelectedOption(2);
} else if (key.return) {
handleOptionSelect();
}
} else if (currentStep === "enterApiKey") {
if (key.return) {
if (apiKey && apiKey.startsWith("sk-ant-")) {
handleApiKeySubmit();
} else {
setErrorMessage(
"Please enter a valid Anthropic API key that starts with 'sk-ant-'"
);
}
} else if (key.backspace || key.delete) {
setApiKey(apiKey.slice(0, -1));
setErrorMessage("");
} else if (input && !key.ctrl && !key.meta) {
setApiKey(apiKey + input);
setErrorMessage("");
}
} else if (currentStep === "success" || currentStep === "error") {
if (key.return) {
// If user went through models setup, do a full reload to register their purchase
if (wasModelsSetup && onFullReload) {
onFullReload();
} else {
onComplete();
}
}
}
});
const handleOptionSelect = async () => {
if (selectedOption === 1) {
// Option 1: Open models setup page
setCurrentStep("processing");
const modelsUrl = new URL("setup-models", env.appUrl).toString();
setWasModelsSetup(true); // Track that user went through models setup
try {
await open(modelsUrl);
setSuccessMessage(
`Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.`
);
setCurrentStep("success");
} catch (error) {
setErrorMessage(
`Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`
);
setCurrentStep("error");
}
} else {
// Option 2: Enter API key
setCurrentStep("enterApiKey");
setWasModelsSetup(false); // This is not models setup
}
};
const handleApiKeySubmit = async () => {
setCurrentStep("processing");
try {
await createOrUpdateConfig(apiKey);
setSuccessMessage(
"✓ API key saved successfully! Switching to local configuration..."
);
setCurrentStep("success");
// After a brief delay, switch to local configuration
setTimeout(() => {
if (onSwitchToLocalConfig) {
onSwitchToLocalConfig();
} else {
onComplete();
}
}, 1000);
} catch (error) {
setErrorMessage(
`❌ Error saving API key: ${error}. Press Enter to try again.`
);
setCurrentStep("error");
}
};
if (currentStep === "choice") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Text bold color="yellow">
🚀 Free trial limit reached!
</Text>
<Text>Choose how you'd like to continue:</Text>
<Text></Text>
<Text color={selectedOption === 1 ? "cyan" : "white"}>
{selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on
(recommended)
</Text>
<Text color={selectedOption === 2 ? "cyan" : "white"}>
{selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API key
</Text>
<Text></Text>
<Text color="gray">
Use ↑↓ arrows or 1/2 to select, Enter to confirm
</Text>
</Box>
);
}
if (currentStep === "enterApiKey") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Text bold color="yellow">
Enter your Anthropic API key
</Text>
<Text></Text>
<Text>API Key: {"*".repeat(apiKey.length)}</Text>
<Text></Text>
{errorMessage && <Text color="red">{errorMessage}</Text>}
<Text color="gray">
Type your API key and press Enter (must start with 'sk-ant-')
</Text>
</Box>
);
}
if (currentStep === "processing") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text bold color="blue">
Processing...
</Text>
<Text>Please wait...</Text>
</Box>
);
}
if (currentStep === "success") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="green"
>
<Text bold color="green">
Success!
</Text>
<Text>{successMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and continue with your new subscription"
: "Press Enter to continue your conversation"}
</Text>
</Box>
);
}
if (currentStep === "error") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="red"
>
<Text bold color="red">
Error
</Text>
<Text>{errorMessage}</Text>
<Text></Text>
<Text color="gray">
{wasModelsSetup
? "Press Enter to reload and try again"
: "Press Enter to continue"}
</Text>
</Box>
);
}
return null;
};
export default FreeTrialTransitionUI;

View file

@ -150,7 +150,7 @@ interface LoadingAnimationProps {
const LoadingAnimation: React.FC<LoadingAnimationProps> = ({
visible = true,
color = "blue",
color = "magenta",
}) => {
const [currentIndex, setCurrentIndex] = useState(0);
const animationChars =

View file

@ -1,72 +1,25 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import { hasMultipleOrganizations } from "../auth/workos.js";
import React, { useMemo } from "react";
import { getAllSlashCommands } from "../commands/commands.js";
interface SlashCommandUIProps {
assistant: AssistantConfig;
filter: string;
selectedIndex: number;
onSelect: (command: string) => void;
}
interface SlashCommand {
name: string;
description: string;
category: "system" | "assistant";
}
const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
assistant,
filter,
selectedIndex,
onSelect,
}) => {
const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false);
useEffect(() => {
hasMultipleOrganizations().then(setHasMultipleOrgs);
}, []);
// Get all available slash commands
const getSlashCommands = (): SlashCommand[] => {
const systemCommands: SlashCommand[] = [
{ name: "help", description: "Show help message", category: "system" },
{ name: "clear", description: "Clear the chat history", category: "system" },
{ name: "exit", description: "Exit the chat", 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",
},
...(hasMultipleOrgs ? [{
name: "org",
description: "Switch organization",
category: "system" as const,
}] : []),
];
const assistantCommands: SlashCommand[] =
assistant.prompts?.map((prompt) => ({
name: prompt?.name || "",
description: prompt?.description || "",
category: "assistant" as const,
})) || [];
return [...systemCommands, ...assistantCommands];
};
const allCommands = getSlashCommands();
// Memoize the slash commands to prevent excessive re-renders
// Only recalculate when assistant.prompts changes
const allCommands = useMemo(() => {
return getAllSlashCommands(assistant);
}, [assistant.prompts]);
// Filter commands based on the current filter
const filteredCommands = allCommands

View file

@ -1,25 +1,36 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { Box, Text } from "ink";
import React, { useState } from "react";
import * as os from "node:os";
import * as path from "node:path";
import React, { useEffect, useState } from "react";
import { loadAuthConfig } from "../auth/workos.js";
import { initialize } from "../config.js";
import { introMessage } from "../intro.js";
import { MCPService } from "../mcp.js";
import ConfigSelector from "./ConfigSelector.js";
import { startFileIndexing } from "./FileSearchUI.js";
import FreeTrialStatus from "./FreeTrialStatus.js";
import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js";
import { useChat } from "./hooks/useChat.js";
import { useConfigSelector } from "./hooks/useConfigSelector.js";
import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js";
import LoadingAnimation from "./LoadingAnimation.js";
import OrganizationSelector from "./OrganizationSelector.js";
import Timer from "./Timer.js";
import UpdateNotification from "./UpdateNotification.js";
import UserInput from "./UserInput.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
interface TUIChatProps {
config: AssistantUnrolled;
model: string;
model: ModelConfig;
llmApi: BaseLlmApi;
mcpService: MCPService;
apiClient?: DefaultApiInterface;
configPath?: string;
initialPrompt?: string;
resume?: boolean;
@ -31,6 +42,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
model: initialModel,
llmApi: initialLlmApi,
mcpService: initialMcpService,
apiClient,
configPath,
initialPrompt,
resume,
@ -49,6 +61,18 @@ const TUIChat: React.FC<TUIChatProps> = ({
} | null>(null);
const [loginToken, setLoginToken] = useState("");
// State for free trial transition
const [isShowingFreeTrialTransition, setIsShowingFreeTrialTransition] =
useState(false);
// Start file indexing as soon as the component mounts
useEffect(() => {
// Start indexing files in the background immediately
startFileIndexing().catch((error) => {
console.error("Failed to start file indexing:", error);
});
}, []);
// Custom login prompt handler for TUI
const handleLoginPrompt = (promptText: string): Promise<string> => {
return new Promise((resolve) => {
@ -65,7 +89,37 @@ const TUIChat: React.FC<TUIChatProps> = ({
}
};
// Reload function for after login
// Full reload function - clears history and reinitializes (for models subscription)
const handleFullReload = async () => {
try {
// Reload auth config and reinitialize
const authConfig = loadAuthConfig();
const {
config: newAssistant,
llmApi: newLlmApi,
model: newModel,
mcpService: newMcpService,
} = await initialize(authConfig, configPath);
// Update all the state
setAssistant(newAssistant);
setModel(newModel);
setLlmApi(newLlmApi);
setMcpService(newMcpService);
// Clear the screen completely
process.stdout.write("\x1b[2J\x1b[H");
// Show the new intro message
introMessage(newAssistant, newModel, newMcpService);
} catch (error: any) {
console.error(
`Failed to reload after models subscription: ${error.message}`
);
}
};
// Partial reload function - preserves history (for login or other config changes)
const handleReload = async () => {
try {
// Reload auth config and reinitialize
@ -92,7 +146,56 @@ const TUIChat: React.FC<TUIChatProps> = ({
// Show the new intro message
introMessage(newAssistant, newModel, newMcpService);
} catch (error: any) {
console.error(`Failed to reload after login: ${error.message}`);
console.error(
`Failed to reload after configuration change: ${error.message}`
);
}
};
// Switch to local config - preserves chat history unlike handleReload
const handleSwitchToLocalConfig = async () => {
try {
// Reload auth config and reinitialize with local config path
const authConfig = loadAuthConfig();
const {
config: newAssistant,
llmApi: newLlmApi,
model: newModel,
mcpService: newMcpService,
} = await initialize(authConfig, CONFIG_PATH);
// Update configuration state but preserve chat history
setAssistant(newAssistant);
setModel(newModel);
setLlmApi(newLlmApi);
setMcpService(newMcpService);
// Add a system message to indicate the configuration switch
setMessages((prev) => [
...prev,
{
role: "system",
content:
"✓ Switched to local configuration with your Anthropic API key",
messageType: "system" as const,
},
]);
// Don't clear screen or reset chat history - just continue the conversation!
} catch (error: any) {
console.error(
`Failed to switch to local configuration: ${error.message}`
);
// Show error message in chat but don't break the flow
setMessages((prev) => [
...prev,
{
role: "system",
content: `❌ Error switching to local configuration: ${error.message}`,
messageType: "system" as const,
},
]);
}
};
@ -100,6 +203,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
messages,
setMessages,
isWaitingForResponse,
responseStartTime,
inputMode,
handleUserMessage,
handleInterrupt,
@ -158,6 +262,29 @@ const TUIChat: React.FC<TUIChatProps> = ({
onChatReset: resetChatHistory,
});
// Handle free trial transition completion
const handleFreeTrialTransitionComplete = () => {
setIsShowingFreeTrialTransition(false);
handleReload();
};
const handleFreeTrialSwitchToLocal = () => {
setIsShowingFreeTrialTransition(false);
handleSwitchToLocalConfig();
};
const handleFreeTrialFullReload = () => {
setIsShowingFreeTrialTransition(false);
handleFullReload();
};
// Determine if input should be disabled
const isInputDisabled =
showOrgSelector ||
showConfigSelector ||
!!loginPrompt ||
isShowingFreeTrialTransition;
return (
<Box flexDirection="column" height="100%">
{/* Chat history - takes up all available space above input */}
@ -168,10 +295,12 @@ const TUIChat: React.FC<TUIChatProps> = ({
{/* Fixed bottom section */}
<Box flexDirection="column" flexShrink={0}>
{/* Status */}
{isWaitingForResponse && (
{isWaitingForResponse && responseStartTime && (
<Box paddingX={1} flexDirection="row" gap={1}>
<LoadingAnimation visible={isWaitingForResponse} />
<Text color="gray">esc to interrupt</Text>
<Text color="gray">(</Text>
<Timer startTime={responseStartTime} />
<Text color="gray">• esc to interrupt )</Text>
</Box>
)}
@ -216,22 +345,48 @@ const TUIChat: React.FC<TUIChatProps> = ({
/>
)}
{/* Input area - always at bottom */}
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={showOrgSelector || showConfigSelector || !!loginPrompt}
/>
<Box marginRight={2} justifyContent="flex-end">
<Text color="gray">● Continue CLI</Text>
{/* Free trial transition UI - replaces input when active */}
{isShowingFreeTrialTransition && (
<FreeTrialTransitionUI
onComplete={handleFreeTrialTransitionComplete}
onSwitchToLocalConfig={handleFreeTrialSwitchToLocal}
onFullReload={handleFreeTrialFullReload}
/>
)}
{/* Input area - only show when not showing free trial transition */}
{!isShowingFreeTrialTransition && (
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={isInputDisabled}
/>
)}
{/* Free trial status and Continue CLI info - always show */}
<Box
flexDirection="row"
justifyContent="space-between"
alignItems="center"
>
<Box>
<FreeTrialStatus
apiClient={apiClient}
model={model}
onTransitionStateChange={setIsShowingFreeTrialTransition}
/>
</Box>
<Box marginRight={2}>
<UpdateNotification />
</Box>
</Box>
</Box>
</Box>
);
};
export default TUIChat;
export default TUIChat;

25
src/ui/Timer.tsx Normal file
View file

@ -0,0 +1,25 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
interface TimerProps {
startTime: number;
color?: string;
}
const Timer: React.FC<TimerProps> = ({ startTime, color = "gray" }) => {
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
const now = Date.now();
const elapsedSeconds = Math.floor((now - startTime) / 1000);
setElapsed(elapsedSeconds);
}, 1000); // Update every 1000ms for efficient display
return () => clearInterval(interval);
}, [startTime]);
return <Text color={color}>{elapsed}s</Text>;
};
export default Timer;

View file

@ -0,0 +1,40 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
import { compareVersions, getLatestVersion, getVersion } from "../version.js";
const UpdateNotification: React.FC = () => {
const [updateAvailable, setUpdateAvailable] = useState(false);
const [latestVersion, setLatestVersion] = useState<string>("");
const [currentVersion] = useState(getVersion());
useEffect(() => {
const checkForUpdate = async () => {
try {
const latest = await getLatestVersion();
if (latest) {
setLatestVersion(latest);
const comparison = compareVersions(currentVersion, latest);
setUpdateAvailable(comparison === "older");
}
} catch (error) {
// Silently fail - we don't want to interrupt the user experience
console.debug("Failed to check for updates:", error);
}
};
// Check for updates but don't block
checkForUpdate();
}, [currentVersion]);
if (!updateAvailable) {
return <Text color="gray">● Continue CLI</Text>;
}
return (
<Text color="dim">
Update available: v{latestVersion} (npm i -g @continuedev/cli)
</Text>
);
};
export default UpdateNotification;

View file

@ -91,14 +91,31 @@ const UserInput: React.FC<UserInputProps> = ({
// Only show slash commands if slash is the very first character
if (text.trimStart().startsWith("/")) {
const trimmedText = text.trimStart();
const beforeCursor = trimmedText.slice(0, cursor - (text.length - trimmedText.length));
const beforeCursor = trimmedText.slice(
0,
cursor - (text.length - trimmedText.length)
);
// Only show if cursor is after the slash and before any whitespace
if (beforeCursor.length > 0 && beforeCursor.startsWith("/")) {
const afterSlash = beforeCursor.slice(1);
if (!afterSlash.includes(" ") && !afterSlash.includes("\n")) {
// We're in a slash command context
// We're in a slash command context - check if it's a complete command
const allCommands = getSlashCommands();
const exactMatch = allCommands.find(cmd => cmd.name === afterSlash);
// Hide selector if we have an exact match and there's more content after the cursor
if (exactMatch) {
const restOfText = text.slice(cursor);
// If there's a space immediately after cursor, or we're at end of line/text, hide selector
if (restOfText.startsWith(" ") || restOfText === "" || restOfText.startsWith("\n")) {
setShowSlashCommands(false);
return;
}
}
// Show selector for partial matches
setShowSlashCommands(true);
setSlashCommandFilter(afterSlash);
setSelectedCommandIndex(0);
@ -488,7 +505,6 @@ const UserInput: React.FC<UserInputProps> = ({
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
onSelect={selectSlashCommand}
/>
)}
@ -505,4 +521,4 @@ const UserInput: React.FC<UserInputProps> = ({
);
};
export default UserInput;
export default UserInput;

View file

@ -0,0 +1,11 @@
import React from "react";
// Mock FreeTrialStatus component that doesn't create any timers
const FreeTrialStatus: React.FC<any> = () => {
return null;
};
export default FreeTrialStatus;
export function isModelUsingFreeTrial(): boolean {
return false;
}

View file

@ -44,20 +44,20 @@ describe("TUIChat - Basic UI Tests", () => {
});
describe("Loading States", () => {
it("shows loading spinner when loading", async () => {
it("shows UI correctly when loading", async () => {
const { lastFrame, stdin } = render(<TUIChat {...createProps()} />);
// Trigger loading by sending a message
stdin.write("trigger loading");
stdin.write("test message");
stdin.write("\r");
// Give it a moment to start loading
// Give it a moment to process
await new Promise((resolve) => setTimeout(resolve, 50));
const frame = lastFrame();
// The message was submitted (shows in the UI)
expect(frame).toContain("trigger loading");
// Note: The actual loading spinner might not be visible in this test environment
// The UI should still be properly rendered
expect(frame).toContain("Ask anything");
// Note: The actual loading spinner behavior might not be visible in this test environment
});
it("hides loading spinner when not loading", () => {
@ -78,13 +78,10 @@ describe("TUIChat - Basic UI Tests", () => {
const frame = lastFrame();
// Should show the submitted message
expect(frame).toContain("test");
// Should show placeholder message rather than text in input box
expect(frame).toContain(
"Ask anything, @ for context, / for slash commands"
);
});
});
});
});

View file

@ -95,11 +95,35 @@ jest.mock("glob", () => ({
]),
}));
// Mock API Client
export class MockApiClient {
async getFreeTrialStatus() {
return {
optedInToFreeTrial: true,
chatCount: 5,
chatLimit: 100,
};
}
async listAssistants() {
return [];
}
async getAssistant() {
return { configResult: { config: mockAssistant } };
}
async listOrganizations() {
return { organizations: [] };
}
async syncSecrets() {
return [];
}
}
export const createProps = (overrides: any = {}) => ({
config: mockAssistant,
model: "test-model",
llmApi: new MockLlmApi(),
mcpService: new MockMCPService(),
apiClient: new MockApiClient(),
configPath: undefined,
initialPrompt: undefined,
resume: false,
@ -113,4 +137,4 @@ describe("TUIChat setup", () => {
expect(createProps).toBeDefined();
expect(mockAssistant).toBeDefined();
});
});
});

View file

@ -11,7 +11,7 @@ describe("TUIChat - Slash Commands Tests", () => {
stdin.write("/log");
// Wait a bit for the UI to update
await new Promise((resolve) => setTimeout(resolve, 50));
await new Promise((resolve) => setTimeout(resolve, 100));
const frame = lastFrame();
@ -38,4 +38,89 @@ describe("TUIChat - Slash Commands Tests", () => {
// Should autocomplete to /login (first matching command)
expect(frameAfterTab).toContain("/login ");
});
it("hides slash command selector when complete command is typed", async () => {
const { lastFrame, stdin } = render(<TUIChat {...createProps()} />);
// Type /cle to show partial command dropdown
stdin.write("/cle");
await new Promise((resolve) => setTimeout(resolve, 50));
const framePartial = lastFrame();
// Should show the slash command dropdown for partial match
expect(framePartial).toContain("/clear");
expect(framePartial).toContain("Clear the chat history");
// Type the rest to complete the command /clear
stdin.write("ar");
await new Promise((resolve) => setTimeout(resolve, 50));
const frameComplete = lastFrame();
// Should NOT show the slash command dropdown anymore since we have a complete command
expect(frameComplete).not.toContain("Clear the chat history");
expect(frameComplete).not.toContain(
"Use ↑/↓ to navigate, Enter to select, Tab to complete"
);
// But should still show the input with /clear
expect(frameComplete).toContain("/clear");
});
it("shows slash command selector again if typing continues past complete command", async () => {
const { lastFrame, stdin } = render(<TUIChat {...createProps()} />);
// Type complete command /clear
stdin.write("/clear");
await new Promise((resolve) => setTimeout(resolve, 50));
const frameComplete = lastFrame();
// Should NOT show the dropdown for complete command
expect(frameComplete).not.toContain("Clear the chat history");
// Type more characters to make it not match any command
stdin.write("xyz");
await new Promise((resolve) => setTimeout(resolve, 50));
const frameInvalid = lastFrame();
// Should show "No matching commands found" since /clearxyz doesn't match anything
expect(frameInvalid).toContain("No matching commands found");
});
it("hides slash command selector when space is typed after complete command", async () => {
const { lastFrame, stdin } = render(<TUIChat {...createProps()} />);
// Type complete command /help
stdin.write("/help");
await new Promise((resolve) => setTimeout(resolve, 50));
const frameComplete = lastFrame();
// Should NOT show the dropdown for complete command
expect(frameComplete).not.toContain("Show help message");
// Type a space after the complete command
stdin.write(" ");
await new Promise((resolve) => setTimeout(resolve, 50));
const frameWithSpace = lastFrame();
// Should still NOT show the dropdown after space
expect(frameWithSpace).not.toContain("Show help message");
expect(frameWithSpace).not.toContain(
"Use ↑/↓ to navigate, Enter to select, Tab to complete"
);
// But should show the input with /help
expect(frameWithSpace).toContain("/help ");
});
});

View file

@ -1,4 +1,4 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { useApp } from "ink";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
@ -11,6 +11,7 @@ import {
streamChatResponse,
} from "../../streamChatResponse.js";
import { constructSystemMessage } from "../../systemMessage.js";
import telemetryService from "../../telemetry/telemetryService.js";
import { getToolDisplayName } from "../../tools.js";
import { formatError } from "../../util/formatError.js";
import logger from "../../util/logger.js";
@ -19,7 +20,7 @@ import { DisplayMessage } from "../types.js";
interface UseChatProps {
assistant: AssistantUnrolled;
model: string;
model: ModelConfig;
llmApi: BaseLlmApi;
initialPrompt?: string;
resume?: boolean;
@ -57,8 +58,19 @@ export function useChat({
if (history.length === 0) {
const rulesSystemMessage = "";
const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules);
if (systemMessage) {
const systemMessage = constructSystemMessage(
rulesSystemMessage,
additionalRules
);
if (systemMessage instanceof Promise) {
// Handle the promise case - we'll need to initialize this asynchronously
systemMessage.then((resolvedMessage) => {
if (resolvedMessage) {
history.push({ role: "system", content: resolvedMessage });
setChatHistory([...history]);
}
});
} else if (systemMessage) {
history.push({ role: "system", content: systemMessage });
}
}
@ -83,6 +95,9 @@ export function useChat({
});
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
const [responseStartTime, setResponseStartTime] = useState<number | null>(
null
);
const [inputMode, setInputMode] = useState(true);
const [abortController, setAbortController] =
useState<AbortController | null>(null);
@ -90,6 +105,25 @@ export function useChat({
Array<{ path: string; content: string }>
>([]);
useEffect(() => {
// Initialize system message asynchronously
const initializeSystemMessage = async () => {
if (chatHistory.length === 0 || !chatHistory.some(msg => msg.role === "system")) {
const rulesSystemMessage = "";
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
additionalRules
);
if (systemMessage) {
const newHistory = [{ role: "system" as const, content: systemMessage }];
setChatHistory(newHistory);
}
}
};
initializeSystemMessage();
}, []);
useEffect(() => {
if (initialPrompt) {
handleUserMessage(initialPrompt);
@ -110,7 +144,12 @@ export function useChat({
}
// Handle slash commands
const commandResult = await handleSlashCommands(message, assistant, onLoginPrompt, onReload);
const commandResult = await handleSlashCommands(
message,
assistant,
onLoginPrompt,
onReload
);
if (commandResult) {
if (commandResult.exit) {
exit();
@ -160,6 +199,12 @@ export function useChat({
}
}
// Start active time tracking for telemetry
telemetryService.startActiveTime();
// Track user prompt
telemetryService.logUserPrompt(message.length, message);
// Add user message to history and display
let messageContent = message;
@ -185,8 +230,12 @@ export function useChat({
const controller = new AbortController();
setAbortController(controller);
setIsWaitingForResponse(true);
setResponseStartTime(Date.now());
setInputMode(false);
logger.debug('Starting chat response stream', { messageLength: message.length, historyLength: newHistory.length });
logger.debug("Starting chat response stream", {
messageLength: message.length,
historyLength: newHistory.length,
});
try {
let currentStreamingMessage: DisplayMessage | null = null;
@ -312,12 +361,14 @@ export function useChat({
// Update the chat history with the complete conversation after streaming
setChatHistory(finalHistory);
logger.debug('Chat history updated', { finalHistoryLength: finalHistory.length });
logger.debug("Chat history updated", {
finalHistoryLength: finalHistory.length,
});
// Save the updated history to session
logger.debug('Saving session', { historyLength: finalHistory.length });
logger.debug("Saving session", { historyLength: finalHistory.length });
saveSession(finalHistory);
logger.debug('Session saved');
logger.debug("Session saved");
} catch (error: any) {
const errorMessage = `Error: ${formatError(error)}`;
setMessages((prev) => [
@ -329,8 +380,12 @@ export function useChat({
},
]);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();
setAbortController(null);
setIsWaitingForResponse(false);
setResponseStartTime(null);
setInputMode(true);
}
};
@ -353,9 +408,12 @@ export function useChat({
setAttachedFiles((prev) => [...prev, { path: filePath, content }]);
};
const resetChatHistory = () => {
const resetChatHistory = async () => {
const rulesSystemMessage = "";
const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules);
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
additionalRules
);
const newHistory = systemMessage
? [{ role: "system" as const, content: systemMessage }]
: [];
@ -369,6 +427,7 @@ export function useChat({
chatHistory,
setChatHistory,
isWaitingForResponse,
responseStartTime,
inputMode,
attachedFiles,
handleUserMessage,

View file

@ -1,13 +1,13 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { useState } from "react";
import { exec } from "child_process";
import * as os from "os";
import * as path from "path";
import { useState } from "react";
import { loadAuthConfig, updateAssistantSlug } from "../../auth/workos.js";
import { initialize } from "../../config.js";
import { introMessage } from "../../intro.js";
import { MCPService } from "../../mcp.js";
import * as path from "path";
import * as os from "os";
interface ConfigOption {
id: string;
@ -20,7 +20,7 @@ interface UseConfigSelectorProps {
configPath?: string;
onAssistantChange: (
assistant: AssistantUnrolled,
model: string,
model: ModelConfig,
llmApi: BaseLlmApi,
mcpService: MCPService
) => void;
@ -48,7 +48,7 @@ export function useConfigSelector({
if (config.type === "create") {
// Open the web browser to create new assistant
const url = "https://hub.continue.dev/new?type=assistant";
try {
let command: string;
if (process.platform === "darwin") {
@ -58,13 +58,13 @@ export function useConfigSelector({
} else {
command = `xdg-open "${url}"`;
}
exec(command, (error) => {
if (error) {
console.error("Failed to open browser:", error);
}
});
onMessage({
role: "system",
content: `Opening ${url} in your browser to create a new assistant...`,
@ -152,4 +152,4 @@ export function useConfigSelector({
handleConfigCancel,
showConfigSelectorUI,
};
}
}

View file

@ -58,7 +58,7 @@ export function useMessageRenderer() {
return (
<Box key={index} marginBottom={1}>
<Text color={isUser ? "green" : "blue"}>●</Text>
<Text color={isUser ? "green" : "magenta"}>●</Text>
<Text> </Text>
{isUser ? (
<Text color="gray">{message.content}</Text>

View file

@ -1,4 +1,4 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { useState } from "react";
import {
@ -14,7 +14,7 @@ interface UseOrganizationSelectorProps {
configPath?: string;
onAssistantChange: (
assistant: AssistantUnrolled,
model: string,
model: ModelConfig,
llmApi: BaseLlmApi,
mcpService: MCPService
) => void;

View file

@ -1,5 +1,6 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { render } from "ink";
import React from "react";
import { introMessage } from "../intro.js";
@ -11,8 +12,9 @@ export { default as MarkdownRenderer } from "./MarkdownRenderer.js";
export async function startTUIChat(
config: AssistantUnrolled,
llmApi: BaseLlmApi,
model: string,
model: ModelConfig,
mcpService: MCPService,
apiClient?: DefaultApiInterface,
initialPrompt?: string,
resume?: boolean,
configPath?: string,
@ -28,6 +30,7 @@ export async function startTUIChat(
model,
llmApi,
mcpService,
apiClient,
configPath,
initialPrompt,
resume,
@ -42,4 +45,4 @@ export async function startTUIChat(
});
return { unmount };
}
}

View file

@ -0,0 +1,98 @@
/**
* Console override utility to prevent unwanted output in headless mode
* This ensures that only intentional stdout output reaches the user
*/
interface ConsoleBackup {
log: typeof console.log;
info: typeof console.info;
warn: typeof console.warn;
error: typeof console.error;
debug: typeof console.debug;
}
let originalConsole: ConsoleBackup | null = null;
let isHeadlessMode = false;
/**
* Override console methods to prevent unwanted output in headless mode
* In headless mode, only console.error and explicitly allowed outputs should reach stdout
*/
export function configureConsoleForHeadless(headless: boolean): void {
isHeadlessMode = headless;
if (headless && !originalConsole) {
// Backup original console methods
originalConsole = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug,
};
// Override console methods to suppress output in headless mode
console.log = () => {}; // Suppress all console.log
console.info = () => {}; // Suppress all console.info
console.warn = () => {}; // Suppress all console.warn
console.debug = () => {}; // Suppress all console.debug
// Keep console.error for genuine errors, but send to stderr
console.error = (...args: any[]) => {
originalConsole!.error(...args);
};
} else if (!headless && originalConsole) {
// Restore original console methods
console.log = originalConsole.log;
console.info = originalConsole.info;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
console.debug = originalConsole.debug;
originalConsole = null;
}
}
/**
* Safe stdout output that bypasses console overrides
* Use this for intentional output in headless mode
*/
export function safeStdout(message: string): void {
process.stdout.write(message);
}
/**
* Safe stderr output that bypasses console overrides
* Use this for error messages that should always be visible
*/
export function safeStderr(message: string): void {
process.stderr.write(message);
}
/**
* Temporarily restore console for a specific operation
* Useful for debugging or when you need original console behavior
*/
export function withOriginalConsole<T>(fn: () => T): T {
if (!originalConsole || !isHeadlessMode) {
return fn();
}
// Temporarily restore
const tempConsole = { ...console };
Object.assign(console, originalConsole);
try {
return fn();
} finally {
// Restore overrides
Object.assign(console, tempConsole);
}
}
/**
* Check if currently in headless mode
*/
export function isInHeadlessMode(): boolean {
return isHeadlessMode;
}

View file

@ -14,3 +14,46 @@ export function getVersion(): string {
return "unknown";
}
}
export async function getLatestVersion(): Promise<string | null> {
try {
const response = await fetch(
"https://registry.npmjs.org/@continuedev/cli/latest"
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.version;
} catch (error) {
console.warn("Warning: Could not fetch latest version from npm registry");
return null;
}
}
export function compareVersions(
current: string,
latest: string
): "newer" | "same" | "older" {
if (current === "unknown" || latest === "unknown") {
return "same";
}
// Simple semantic version comparison
const parseVersion = (version: string) => {
const parts = version.replace(/^v/, "").split(".").map(part => parseInt(part, 10));
return { major: parts[0] || 0, minor: parts[1] || 0, patch: parts[2] || 0 };
};
const currentParts = parseVersion(current);
const latestParts = parseVersion(latest);
if (currentParts.major > latestParts.major) return "newer";
if (currentParts.major < latestParts.major) return "older";
if (currentParts.minor > latestParts.minor) return "newer";
if (currentParts.minor < latestParts.minor) return "older";
if (currentParts.patch > latestParts.patch) return "newer";
if (currentParts.patch < latestParts.patch) return "older";
return "same";
}