Merge pull request #161 from continuedev/tomasz/eslint

ESLint
This commit is contained in:
Tomasz Stefaniak 2025-08-05 15:36:39 -07:00 • committed by GitHub
commit ee34a701ef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
168 changed files with 3968 additions and 773 deletions

112
eslint.config.js Normal file
View file

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

3310
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -17,7 +17,9 @@
"dev": "tsx src/index.ts",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
"lint": "tsc --noEmit",
"lint": "tsc --noEmit && eslint .",
"lint:fix": "eslint . --fix",
"typecheck": "tsc --noEmit",
"watch:logs": "tail -f ~/.continue/logs/cn.log",
"prepare": "npm run build",
"semantic-release": "semantic-release",
@ -87,9 +89,15 @@
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"@types/supertest": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"conventional-changelog-conventionalcommits": "^9.1.0",
"cross-env": "^7.0.3",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"happy-dom": "^18.0.1",

View file

@ -1,3 +1,7 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
FQSN,
PlatformClient,
@ -6,9 +10,6 @@ import {
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api";
import * as dotenv from "dotenv";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
export class CLIPlatformClient implements PlatformClient {
constructor(

57
src/MCPConnection.ts Normal file
View file

@ -0,0 +1,57 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { logger } from "./util/logger.js";
export class MCPConnection {
prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
private constructor(public readonly client: Client) {}
public static async create(
config: NonNullable<AssistantConfig["mcpServers"]>[number]
) {
const client = new Client(
{
name: "continue-cli-client",
version: "1.0.0",
},
{ capabilities: {} }
);
// Construct transport
const env: Record<string, string> = config?.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
if (!config?.command) {
throw new Error("MCP server command is not specified");
}
const transport = new StdioClientTransport({
command: config.command,
args: config?.args,
env,
});
// Connect and get all prompts and tools
const connection = new MCPConnection(client);
logger.debug('Connecting to MCP server', { command: config.command });
await client.connect(transport);
const capabilities = client.getServerCapabilities();
logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools });
if (capabilities?.prompts) {
connection.prompts = (await client.listPrompts()).prompts;
}
if (capabilities?.tools) {
connection.tools = (await client.listTools()).tools;
}
return connection;
}
}

View file

@ -1,4 +1,5 @@
import { vi } from 'vitest';
import { parseArgs, processRule } from "./args.js";
describe("parseArgs", () => {

View file

@ -1,6 +1,8 @@
import * as fs from "fs";
import JSZip from "jszip";
import * as path from "path";
import JSZip from "jszip";
import { env } from "./env.js";
export interface CommandLineArgs {

View file

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

View file

@ -1,4 +1,5 @@
import chalk from "chalk";
import { isAuthenticated, login } from "./workos.js";
/**
@ -22,7 +23,7 @@ export async function ensureAuthenticated(
await login();
return true;
} catch (error) {
console.error(chalk.red("Failed to authenticate."));
console.error(chalk.red("Failed to authenticate."), error);
return false;
}
}

View file

@ -1,14 +1,14 @@
import chalk from "chalk";
import * as fs from "fs";
import open from "open";
import * as os from "os";
import * as path from "path";
import { createInterface } from "readline";
import { env } from "../env.js";
import chalk from "chalk";
// Polyfill fetch for Node < 18
import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
@ -271,23 +271,6 @@ export function isAuthenticated(): boolean {
return true;
}
/**
* Prompt the user for input
*/
function prompt(question: string): Promise<string> {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer);
});
});
}
/**
* Device authorization response from WorkOS
*/
@ -524,7 +507,7 @@ export async function login(): Promise<AuthConfig> {
// Try to open the complete verification URL in browser
try {
await open(deviceAuth.verification_uri_complete);
} catch (error) {
} catch {
console.info(chalk.yellow("Unable to open browser automatically"));
}
@ -665,7 +648,7 @@ export async function listUserOrganizations(): Promise<
try {
const resp = await apiClient.listOrganizations();
return resp.organizations || [];
} catch (error) {
} catch {
return null;
}
}

View file

@ -2,6 +2,7 @@ import { ModelConfig } from "@continuedev/config-yaml";
import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import { loadAuthConfig } from "../auth/workos.js";
import {
@ -19,16 +20,17 @@ import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
shouldAutoCompact,
} from "../util/tokenizer.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
/**
@ -44,7 +46,7 @@ function processJsonOutput(response: string): string {
JSON.parse(trimmedResponse);
// If it parses successfully, return as-is
return trimmedResponse;
} catch (error) {
} catch {
// If it's not valid JSON, wrap it in a JSON object
return JSON.stringify({
response: trimmedResponse,

View file

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

View file

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

View file

@ -1,7 +1,8 @@
import chalk from "chalk";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
prompt?: string,

View file

@ -1,13 +1,14 @@
import chalk from "chalk";
import {
getAccessToken,
isAuthenticatedConfig,
loadAuthConfig,
} from "../auth/workos.js";
import { env } from "../env.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
export async function remote(
prompt: string | undefined,

View file

@ -1,3 +1,5 @@
import type { Server } from "http";
import {
afterEach,
beforeEach,
@ -6,13 +8,12 @@ import {
it,
vi,
} from "vitest";
import type { Server } from "http";
import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
describe("serve command", () => {
let context: any;
let originalProcessExit: typeof process.exit;
let serverPromise: Promise<void>;
let serverRef: Server | null = null;
beforeEach(() => {

View file

@ -1,12 +1,14 @@
import chalk from "chalk";
import { exec } from "child_process";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import path from "path";
import { promisify } from "util";
import chalk from "chalk";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import { getAssistantSlug } from "../auth/workos.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import { saveSession } from "../session.js";
import {
getService,
initializeServices,
@ -17,17 +19,19 @@ import {
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import { saveSession } from "../session.js";
import {
streamChatResponse,
type StreamCallbacks,
} from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { getToolDisplayName } from "../tools/index.js";
import { DisplayMessage } from "../ui/types.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import { getToolDisplayName } from "../tools/index.js";
const execAsync = promisify(exec);
@ -125,7 +129,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Initialize chat history
let chatHistory: ChatCompletionMessageParam[] = [];
const chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = await constructSystemMessage("", options.rule, undefined, true);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });

View file

@ -1,9 +1,11 @@
import { describe, it, expect, vi } from "vitest";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
import { streamChatResponse } from "./streamChatResponse.js";
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { describe, it, expect, vi } from "vitest";
import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
import { streamChatResponse } from "./streamChatResponse.js";
// Mock the streamChatResponse function
vi.mock("./streamChatResponse.js", () => ({

View file

@ -1,8 +1,9 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { StreamCallbacks, streamChatResponse } from "./streamChatResponse.js";
import logger from "./util/logger.js";
import { logger } from "./util/logger.js";
export const COMPACTION_MARKER = "[COMPACTED HISTORY]";

View file

@ -1,8 +1,7 @@
import {
AssistantUnrolled,
ModelConfig,
RegistryClient,
unrollAssistant,
} from "@continuedev/config-yaml";
import {
BaseLlmApi,
@ -14,14 +13,12 @@ import {
DefaultApi,
DefaultApiInterface,
} from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { dirname } from "node:path";
import {
AuthConfig,
getAccessToken,
getOrganizationId,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./mcp.js";
@ -77,43 +74,6 @@ export function getLlmApi(
return [llmApi, model];
}
async function loadConfigYaml(
accessToken: string | null,
filePath: string,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const unrollResult = await unrollAssistant(
{ filePath, uriType: "file" },
new RegistryClient({
accessToken: accessToken ?? undefined,
apiBase: env.apiBase,
rootPath: dirname(filePath),
}),
{
currentUserSlug: "",
alwaysUseProxy: false,
orgScopeId: organizationId,
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
}
);
const errorDetails = unrollResult.errors;
if (!unrollResult.config) {
throw new Error(`Failed to load config file:\n${errorDetails}`);
} else if (errorDetails?.length) {
const warnings =
errorDetails?.length > 1
? errorDetails.map((d) => `\n- ${d.message}`)
: errorDetails[0].message;
console.warn(chalk.dim(`Warning: ${warnings}`));
}
return unrollResult.config;
}
export function getApiClient(
accessToken: string | undefined | null
): DefaultApi {

View file

@ -1,3 +1,8 @@
import * as fs from "fs";
import { dirname } from "node:path";
import * as os from "os";
import * as path from "path";
import {
AssistantUnrolled,
RegistryClient,
@ -5,10 +10,7 @@ import {
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import { dirname } from "node:path";
import * as os from "os";
import * as path from "path";
import {
AuthConfig,
getAccessToken,

View file

@ -1,7 +1,8 @@
import { Continue, ContinueClient } from "@continuedev/sdk";
import { env } from "./env.js";
import chalk from "chalk";
import { env } from "./env.js";
/**
* Initialize the Continue SDK with the given parameters
* @param apiKey - API key to use for authentication

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,13 +1,15 @@
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 chalk from "chalk";
import open from "open";
import * as readlineSync from "readline-sync";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import { env } from "./env.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
@ -63,7 +65,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
"After setting up your models subscription, restart the CLI to continue."
)
);
} catch (error) {
} catch {
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
console.log(chalk.white(`Please visit: ${modelsUrl}`));
console.log(

View file

@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
import { useServiceContainer } from '../services/ServiceContainerContext.js';
import { ServiceResult } from '../services/types.js';
@ -104,25 +105,20 @@ export function useServices<T extends Record<string, any>>(
const newServices: Partial<T> = {};
let hasLoading = false;
let hasError: Error | null = null;
let allReady = true;
for (const serviceName of serviceNames) {
const result = container.getSync(serviceName as string);
if (result.state === 'loading') {
hasLoading = true;
allReady = false;
} else if (result.state === 'error') {
hasError = result.error;
allReady = false;
} else if (result.state === 'idle') {
allReady = false;
// Auto-load idle services
container.load(serviceName as string).catch(() => {});
} else if (result.state === 'ready' && result.value !== null) {
newServices[serviceName] = result.value as T[keyof T];
} else {
allReady = false;
}
}

View file

@ -1,6 +1,7 @@
#!/usr/bin/env node
import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
@ -9,7 +10,7 @@ import { remote } from "./commands/remote.js";
import { serve } from "./commands/serve.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import logger from "./util/logger.js";
import { logger } from "./util/logger.js";
import { readStdinSync } from "./util/stdin.js";
import { getVersion } from "./version.js";

View file

@ -1,3 +1,6 @@
import chalk from 'chalk';
import { vi } from 'vitest';
import {
configureLogger,
isLoggingEnabled,
@ -7,8 +10,6 @@ import {
warn,
loggers
} from './logging.js';
import { vi } from 'vitest';
import chalk from 'chalk';
describe('logging utilities', () => {
let consoleInfoSpy: ReturnType<typeof vi.spyOn>;

View file

@ -1,7 +1,7 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import logger from "./util/logger.js";
import { MCPConnection } from "./MCPConnection.js";
import { logger } from "./util/logger.js";
export class MCPService {
private readonly connections: MCPConnection[] = [];
@ -60,55 +60,3 @@ export class MCPService {
throw new Error(`Tool ${name} not found`);
}
}
export class MCPConnection {
prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
private constructor(public readonly client: Client) {}
public static async create(
config: NonNullable<AssistantConfig["mcpServers"]>[number]
) {
const client = new Client(
{
name: "continue-cli-client",
version: "1.0.0",
},
{ capabilities: {} }
);
// Construct transport
const env: Record<string, string> = config?.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
if (!config?.command) {
throw new Error("MCP server command is not specified");
}
const transport = new StdioClientTransport({
command: config.command,
args: config?.args,
env,
});
// Connect and get all prompts and tools
const connection = new MCPConnection(client);
logger.debug('Connecting to MCP server', { command: config.command });
await client.connect(transport);
const capabilities = client.getServerCapabilities();
logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools });
if (capabilities?.prompts) {
connection.prompts = (await client.listPrompts()).prompts;
}
if (capabilities?.tools) {
connection.tools = (await client.listTools()).tools;
}
return connection;
}
}

View file

@ -1,16 +1,19 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { MCPService } from "./mcp.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
@ -33,13 +36,11 @@ export async function checkHasAcceptableModel(
const content = fs.readFileSync(configPath, "utf8");
return content.includes("claude");
} catch (error) {
} catch {
return false;
}
}
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
export async function createOrUpdateConfig(apiKey: string): Promise<void> {
const configDir = path.dirname(CONFIG_PATH);
@ -111,7 +112,7 @@ export async function runNormalFlow(
): Promise<OnboardingResult> {
// Step 1: Check if --config flag is provided
if (configPath) {
let result = await initialize(authConfig, configPath);
const result = await initialize(authConfig, configPath);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
@ -122,25 +123,27 @@ export async function runNormalFlow(
// Step 2: If user is logged in, look for first assistant in selected org
if (isAuthenticated()) {
try {
let result = await initialize(authConfig, undefined);
const result = await initialize(authConfig, undefined);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch (error) {}
} catch {
// Silently ignore errors when loading default assistant
}
}
// Step 3: Look for local ~/.continue/config.yaml
if (fs.existsSync(CONFIG_PATH)) {
try {
let result = await initialize(authConfig, CONFIG_PATH);
const result = await initialize(authConfig, CONFIG_PATH);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return { ...result, wasOnboarded: false };
} catch (error) {
} catch {
console.log(chalk.yellow("⚠ Invalid config file found"));
}
}
@ -150,7 +153,7 @@ export async function runNormalFlow(
console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment"));
await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`));
let result = await initialize(authConfig, CONFIG_PATH);
const result = await initialize(authConfig, CONFIG_PATH);
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
@ -193,7 +196,7 @@ async function injectRulesIntoConfig(
return config;
}
let processedRules: string[] = [];
const processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
const processedRule = await processRule(ruleSpec);

View file

@ -1,6 +1,6 @@
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import { checkToolPermission } from "./permissionChecker.js";
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
describe("Headless Permissions Integration", () => {
describe("precedence resolution", () => {

View file

@ -1,5 +1,7 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach } from 'vitest';
import { ToolPermissionService } from '../services/ToolPermissionService.js';
import { checkToolPermission } from './permissionChecker.js';
describe('Permission Integration Tests', () => {

View file

@ -1,6 +1,7 @@
import { getServiceSync } from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import {
PermissionCheckResult,

View file

@ -1,4 +1,5 @@
import { EventEmitter } from "events";
import { ToolCallRequest } from "./types.js";
export interface PermissionRequestResult {

View file

@ -1,8 +1,11 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as yaml from "yaml";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { normalizeToolName } from "./toolNameMapping.js";
import { PermissionPolicy, ToolPermissionPolicy } from "./types.js";

View file

@ -1,8 +1,11 @@
import * as fs from "fs";
import * as yaml from "yaml";
import { logger } from "../util/logger.js";
import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js";
import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
import logger from "../util/logger.js";
/**
* Generates a policy rule for a given tool call
@ -34,7 +37,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string {
export async function addPolicyToYaml(policyRule: string): Promise<void> {
try {
// Load existing config or create empty one
let config: PermissionsYamlConfig = loadPermissionsYaml() || {};
const config: PermissionsYamlConfig = loadPermissionsYaml() || {};
// Ensure allow array exists
if (!config.allow) {

View file

@ -1,4 +1,3 @@
import { vi } from "vitest";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
import { ToolPermissionPolicy } from "./types.js";

View file

@ -1,8 +1,9 @@
import { logger } from "../util/logger.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js";
import { normalizeToolName } from "./toolNameMapping.js";
import { ToolPermissionPolicy } from "./types.js";
import logger from "../util/logger.js";
export interface PermissionSources {
/** Command line flags - highest precedence */

View file

@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import * as fs from 'fs';
import { loadPermissionsYaml, yamlConfigToPolicies } from './permissionsYamlLoader.js';
import { checkToolPermission } from './permissionChecker.js';
import { yamlConfigToPolicies } from './permissionsYamlLoader.js';
// Mock fs module
vi.mock('fs');

View file

@ -1,10 +1,11 @@
import { describe, expect, test, beforeEach, vi } from 'vitest';
import { ApiClientService } from './ApiClientService.js';
// Mock the config module
vi.mock('../config.js');
import * as config from '../config.js';
import { ApiClientService } from './ApiClientService.js';
describe('ApiClientService', () => {
let service: ApiClientService;
const mockApiClient = {

View file

@ -1,8 +1,9 @@
import { AuthConfig } from "../auth/workos.js";
import { getApiClient } from "../config.js";
import logger from "../util/logger.js";
import { ApiClientServiceState } from "./types.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import { ApiClientServiceState } from "./types.js";
/**
* Service for managing API client state

View file

@ -8,9 +8,10 @@ import {
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import logger from "../util/logger.js";
import { AuthServiceState } from "./types.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { AuthServiceState } from "./types.js";
/**
* Service for managing authentication state and operations

View file

@ -1,5 +1,4 @@
import { describe, expect, test, beforeEach, vi } from 'vitest';
import { AuthService } from './AuthService.js';
// Mock the workos module
vi.mock('../auth/workos.js');
@ -15,6 +14,8 @@ import {
listUserOrganizations
} from '../auth/workos.js';
import { AuthService } from './AuthService.js';
describe('AuthService', () => {
let service: AuthService;
const mockAuthConfig = {

View file

@ -8,9 +8,10 @@ import {
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import logger from "../util/logger.js";
import { AuthServiceState } from "./types.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { AuthServiceState } from "./types.js";
/**
* Service for managing authentication state and operations

View file

@ -1,4 +1,5 @@
import { describe, expect, test, beforeEach, vi } from 'vitest';
import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js';
// Test implementation of BaseService

View file

@ -1,5 +1,6 @@
import { EventEmitter } from "events";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
/**
* Base abstract class for all services

View file

@ -1,6 +1,4 @@
import { beforeEach, describe, expect, vi, test } from "vitest";
import { ConfigService } from "./ConfigService.js";
import { SERVICE_NAMES } from "./types.js";
// Mock modules
vi.mock("../auth/workos.js");
@ -8,10 +6,13 @@ vi.mock("../configLoader.js");
vi.mock("../args.js");
vi.mock("./ServiceContainer.js");
import * as args from "../args.js";
import * as workos from "../auth/workos.js";
import * as configLoader from "../configLoader.js";
import * as args from "../args.js";
import { ConfigService } from "./ConfigService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { SERVICE_NAMES } from "./types.js";
describe("ConfigService", () => {
let service: ConfigService;
@ -226,11 +227,7 @@ describe("ConfigService", () => {
// Mock service container
vi.mocked(workos.loadAuthConfig)
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
vi.mocked(serviceContainer.get).mockResolvedValueOnce({
authConfig: { accessToken: "token", organizationId: "org-123" } as any,
isAuthenticated: true,
});
vi.mocked(serviceContainer.get).mockResolvedValueOnce({
vi.mocked(serviceContainer.get).mockResolvedValue({
apiClient: mockApiClient,
});
@ -269,11 +266,7 @@ describe("ConfigService", () => {
vi.mocked(workos.loadAuthConfig)
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
vi.mocked(serviceContainer.get).mockResolvedValueOnce({
authConfig: { accessToken: "token", organizationId: "org-123" } as any,
isAuthenticated: true,
});
vi.mocked(serviceContainer.get).mockResolvedValueOnce({
vi.mocked(serviceContainer.get).mockResolvedValue({
apiClient: null,
});

View file

@ -1,19 +1,20 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { processRule } from "../args.js";
import {
AuthConfig,
loadAuthConfig,
} from "../auth/workos.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import {
ApiClientServiceState,
AuthServiceState,
ConfigServiceState,
SERVICE_NAMES,
} from "./types.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
/**
* Service for managing configuration state and operations
@ -146,7 +147,7 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
return config;
}
let processedRules: string[] = [];
const processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
@ -192,9 +193,6 @@ export class ConfigService extends BaseService<ConfigServiceState> implements Se
try {
// Get current auth and API client state needed for config loading
const authConfig = loadAuthConfig();
const authState = await serviceContainer.get<AuthServiceState>(
SERVICE_NAMES.AUTH
);
const apiClientState = await serviceContainer.get<ApiClientServiceState>(
SERVICE_NAMES.API_CLIENT
);

View file

@ -1,6 +1,8 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { MCPService } from '../mcp.js';
import logger from '../util/logger.js';
import { logger } from '../util/logger.js';
import { MCPServiceState } from './types.js';
/**

View file

@ -1,6 +1,6 @@
import { beforeEach, afterEach, describe, expect, it, vi, test } from 'vitest';
import { beforeEach, afterEach, describe, expect, vi, test } from 'vitest';
import { ModeService } from './ModeService.js';
import { PermissionMode } from '../permissions/types.js';
describe('ModeService', () => {
let modeService: ModeService;

View file

@ -1,7 +1,8 @@
import { PermissionMode } from "../permissions/types.js";
import logger from "../util/logger.js";
import { ToolPermissionService } from "./ToolPermissionService.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { ToolPermissionService } from "./ToolPermissionService.js";
export interface ModeServiceState {
mode: PermissionMode;
@ -70,7 +71,7 @@ export class ModeService extends BaseService<ModeServiceState> {
*/
public switchMode(mode: PermissionMode): void {
const previousMode = this.currentState.mode;
const newState = this.currentState.toolPermissionService.switchMode(mode);
this.currentState.toolPermissionService.switchMode(mode);
this.setState({ mode });

View file

@ -1,10 +1,12 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import { getLlmApi } from '../config.js';
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
import logger from '../util/logger.js';
import { ModelServiceState } from './types.js';
import { getLlmApi } from '../config.js';
import { logger } from '../util/logger.js';
import { BaseService, ServiceWithDependencies } from './BaseService.js';
import { ModelServiceState } from './types.js';
/**
* Service for managing LLM and model state

View file

@ -1,16 +1,17 @@
import { describe, it, expect, beforeEach, vi, test } from 'vitest';
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
import * as openaiAdapters from '@continuedev/openai-adapters';
import { describe, expect, beforeEach, vi, test } from 'vitest';
// Mock dependencies before imports
vi.mock('@continuedev/openai-adapters');
vi.mock('../config.js');
vi.mock('../auth/workos.js');
import { ModelService } from './ModelService.js';
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
import { AuthConfig } from '../auth/workos.js';
import * as config from '../config.js';
import * as workos from '../auth/workos.js';
import * as openaiAdapters from '@continuedev/openai-adapters';
import * as config from '../config.js';
import { ModelService } from './ModelService.js';
describe('ModelService', () => {
let service: ModelService;

View file

@ -1,10 +1,12 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import { getLlmApi } from '../config.js';
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
import logger from '../util/logger.js';
import { ModelServiceState } from './types.js';
import { getLlmApi } from '../config.js';
import { logger } from '../util/logger.js';
import { BaseService, ServiceWithDependencies } from './BaseService.js';
import { ModelServiceState } from './types.js';
/**
* Service for managing LLM and model state

View file

@ -1,4 +1,5 @@
import { describe, expect, test, beforeEach, vi } from 'vitest';
import { ServiceContainer } from './ServiceContainer.js';
describe('ServiceContainer', () => {

View file

@ -1,6 +1,8 @@
import { EventEmitter } from 'events';
import logger from '../util/logger.js';
import { ServiceResult, ServiceState, ServiceEvents } from './types.js';
import { logger } from '../util/logger.js';
import { ServiceResult, ServiceState } from './types.js';
/**
* Central service container that manages service lifecycle and dependencies

View file

@ -1,5 +1,7 @@
import React, { createContext, useContext } from 'react';
import { ServiceContainer } from './ServiceContainer.js';
import { serviceContainer as defaultContainer } from './index.js';
const ServiceContainerContext = createContext<ServiceContainer>(defaultContainer);

View file

@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it } from "vitest";
import { PermissionMode } from "../permissions/types.js";
import { ToolPermissionService } from "./ToolPermissionService.js";
describe("ToolPermissionService - Debug Tool Permissions", () => {

View file

@ -1,5 +1,5 @@
import { vi } from "vitest";
import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js";
import { ToolPermissionService } from "./ToolPermissionService.js";
describe("ToolPermissionService E2E", () => {

View file

@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { ToolPermissionService } from './ToolPermissionService.js';
import { PermissionMode } from '../permissions/types.js';
describe('ToolPermissionService - Mode Functionality', () => {
let service: ToolPermissionService;

View file

@ -1,7 +1,9 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { ToolPermissionService } from './ToolPermissionService.js';
import { checkToolPermission } from '../permissions/permissionChecker.js';
import { ToolPermissionService } from './ToolPermissionService.js';
describe('ToolPermissionService - Real Tool Permission Test', () => {
let service: ToolPermissionService;

View file

@ -1,13 +1,13 @@
import { describe, expect, test, beforeEach, vi } from 'vitest';
import { ToolPermissionService } from "./ToolPermissionService.js";
import { PermissionMode, ToolPermissionPolicy } from '../permissions/types.js';
// Mock modules
vi.mock('../permissions/permissionsYamlLoader.js');
vi.mock('../permissions/precedenceResolver.js');
import * as permissionsYamlLoader from '../permissions/permissionsYamlLoader.js';
import * as precedenceResolver from '../permissions/precedenceResolver.js';
import { ToolPermissionPolicy } from '../permissions/types.js';
import { ToolPermissionService } from "./ToolPermissionService.js";
describe("ToolPermissionService", () => {
let service: ToolPermissionService;

View file

@ -5,7 +5,8 @@ import {
ToolPermissionPolicy,
ToolPermissions,
} from "../permissions/types.js";
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
export interface ToolPermissionServiceState {

View file

@ -1,6 +1,6 @@
import { ServiceContainer } from './ServiceContainer.js';
import { initializeServices } from './index.js';
import { SERVICE_NAMES } from './types.js';
describe('Service Circular Dependencies', () => {
it('should not have circular dependencies in service setup', async () => {

View file

@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
import { serviceContainer } from './ServiceContainer.js';
import type { ToolPermissionServiceState } from './ToolPermissionService.js';
import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
describe('Service Initialization', () => {
beforeEach(() => {
// Clean up service container state

View file

@ -1,8 +1,9 @@
import { vi } from "vitest";
import { initializeServices } from "./index.js";
import { modeService } from "./ModeService.js";
import { initializeServices } from "./index.js";
describe("initializeServices", () => {
let mockModeService: any;

View file

@ -1,10 +1,11 @@
import logger from "../util/logger.js";
import { logger } from "../util/logger.js";
import { ApiClientService } from "./ApiClientService.js";
import { AuthService } from "./AuthService.js";
import { ConfigService } from "./ConfigService.js";
import { MCPServiceWrapper } from "./MCPServiceWrapper.js";
import { modeService } from "./ModeService.js";
import { ModelService } from "./ModelService.js";
import { modeService } from "./ModeService.js";
import { serviceContainer } from "./ServiceContainer.js";
import {
ApiClientServiceState,
@ -28,7 +29,6 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
logger.debug("Initializing service registry");
// Initialize mode service with tool permission overrides
let modeServiceInitialized = false;
if (options.toolPermissionOverrides) {
const overrides = { ...options.toolPermissionOverrides };
@ -49,13 +49,11 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
// If mode is "normal" or undefined, no flags are set
await modeService.initialize(initArgs);
modeServiceInitialized = true;
} else {
// Even if no overrides, we need to initialize with defaults
await modeService.initialize({
isHeadless: options.headless
});
modeServiceInitialized = true;
}
// Register the TOOL_PERMISSIONS service with immediate value

View file

@ -1,6 +1,7 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import { AuthConfig } from "../auth/workos.js";
import { MCPService } from "../mcp.js";
import { PermissionMode, ToolPermissions } from "../permissions/types.js";

View file

@ -1,9 +1,11 @@
import { execSync } from "child_process";
import fs from "fs";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import os from "os";
import path from "path";
import logger from "./util/logger.js";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { logger } from "./util/logger.js";
/**
* Get the terminal process ID by walking up the process tree
@ -54,12 +56,12 @@ function getTerminalProcessId(): string | null {
const nextPid = parseInt(ppid);
if (isNaN(nextPid) || nextPid <= 1) break;
currentPid = nextPid;
} catch (innerError) {
} catch {
// Continue to next iteration if this process lookup fails
break;
}
}
} catch (error) {
} catch {
// Silently fail - this is a fallback mechanism
}
@ -93,7 +95,7 @@ function getTtyPath(): string | null {
return ttyPath.replace("/dev/", "");
}
}
} catch (error) {
} catch {
// Silently fail - this is a fallback mechanism
}

View file

@ -1,3 +1,6 @@
// Import after mocking
import { AssistantUnrolled } from "@continuedev/config-yaml";
import {
afterEach,
beforeEach,
@ -6,13 +9,11 @@ import {
vi,
test,
} from "vitest";
import type { AuthServiceState } from "./services/types.js";
// Import after mocking
import { AssistantUnrolled } from "@continuedev/config-yaml";
import * as workos from "./auth/workos.js";
import * as commands from "./commands/commands.js";
import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
import type { AuthServiceState } from "./services/types.js";
import { handleSlashCommands } from "./slashCommands.js";
// The imports are already mocked via vitest.setup.ts, so we can use them directly

View file

@ -1,5 +1,6 @@
import { type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import {
isAuthenticated,
isAuthenticatedConfig,
@ -11,8 +12,7 @@ import { posthogService } from "./telemetry/posthogService.js";
export async function handleSlashCommands(
input: string,
assistant: AssistantConfig,
onLoginPrompt?: (promptText: string) => Promise<string>
assistant: AssistantConfig
): Promise<{
output?: string;
exit?: boolean;
@ -95,7 +95,7 @@ export async function handleSlashCommands(
exit: true,
output: "Logged out successfully",
};
} catch (error: any) {
} catch {
return {
exit: true,
output: "Logged out successfully",

View file

@ -1,8 +1,9 @@
import { describe, test, expect, beforeEach } from 'vitest';
import { initializeServices, getServiceSync, SERVICE_NAMES } from './services/index.js';
import { serviceContainer } from './services/ServiceContainer.js';
import { getAllTools } from './streamChatResponse.js';
import type { ToolPermissionServiceState } from './services/ToolPermissionService.js';
import { getAllTools } from './streamChatResponse.js';
describe('getAllTools - Tool Filtering', () => {
beforeEach(() => {

View file

@ -1,22 +1,23 @@
import { vi } from 'vitest';
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type {
ChatCompletionChunk,
ChatCompletionMessageParam,
} from "openai/resources/chat/completions.mjs";
import { vi } from 'vitest';
import { toolPermissionManager } from "./permissions/permissionManager.js";
import {
preprocessStreamedToolCalls,
executeStreamedToolCalls,
processStreamingResponse,
} from "./streamChatResponse.js";
import { ToolCall } from "./tools/index.js";
import { PreprocessedToolCall } from "./tools/types.js";
import { toolPermissionManager } from "./permissions/permissionManager.js";
import { readFileTool } from "./tools/readFile.js";
import { searchCodeTool } from "./tools/searchCode.js";
import { PreprocessedToolCall } from "./tools/types.js";
import { writeFileTool } from "./tools/writeFile.js";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { ModelConfig } from "@continuedev/config-yaml";
// Test the chunk processing logic that was identified as buggy
describe("processStreamingResponse - content preservation", () => {

View file

@ -8,8 +8,7 @@ import type {
ChatCompletionTool,
ChatCompletionToolMessageParam,
} from "openai/resources.mjs";
import { getServiceSync, SERVICE_NAMES } from "./services/index.js";
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
import { MCPService } from "./mcp.js";
import {
checkToolPermission,
@ -17,23 +16,24 @@ import {
ToolCallRequest,
} from "./permissions/index.js";
import { toolPermissionManager } from "./permissions/permissionManager.js";
import telemetryService from "./telemetry/telemetryService.js";
import { getServiceSync, SERVICE_NAMES } from "./services/index.js";
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
import { telemetryService } from "./telemetry/telemetryService.js";
import { calculateTokenCost } from "./telemetry/utils.js";
import {
getAllBuiltinTools,
executeToolCall,
getAvailableTools,
getToolDisplayName,
Tool,
ToolCall,
validateToolCallArgsPresent,
} from "./tools/index.js";
import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js";
import {
chatCompletionStreamWithBackoff,
withExponentialBackoff,
} from "./util/exponentialBackoff.js";
import logger from "./util/logger.js";
import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js";
import { logger } from "./util/logger.js";
dotenv.config();
@ -300,7 +300,7 @@ export async function processStreamingResponse(
// Don't notify onToolStart here anymore - wait until after permission check
toolCall.startNotified = true;
} catch (e) {
} catch {
// JSON not complete yet, continue
}
}

View file

@ -1,8 +1,10 @@
import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import pkg from "ignore-walk";
import { Minimatch } from "minimatch";
import * as path from "path";
import { processRule } from "./args.js";
const { WalkerSync } = pkg;
@ -126,7 +128,7 @@ export async function constructSystemMessage(
}
// Process additional rules from --rule flags
let processedRules: string[] = [];
const processedRules: string[] = [];
if (additionalRules && additionalRules.length > 0) {
for (const ruleSpec of additionalRules) {
try {

View file

@ -1,3 +1,5 @@
import os from "os";
import { metrics } from "@opentelemetry/api";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
@ -13,9 +15,9 @@ import {
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 { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
export interface TelemetryConfig {
@ -545,4 +547,3 @@ class TelemetryService {
// Export the singleton instance directly
export const telemetryService = new TelemetryService();
export default telemetryService;

View file

@ -1,6 +1,7 @@
import { diffLines } from "diff";
import path from "path";
import { diffLines } from "diff";
/**
* Calculate lines of code added/removed from a file diff
*/

View file

@ -1,4 +1,5 @@
import { vi } from "vitest";
import { createTestServiceContainer } from '../testServiceContainer.js';
describe('TestServiceContainer', () => {

View file

@ -1,5 +1,8 @@
import { vi } from "vitest";
// Mock BaseLlmApi class to avoid inline class definitions
class MockBaseLlmApi {}
/**
* Mock the constructLlmApi function to return a mock LLM API
*/
@ -38,7 +41,7 @@ export function mockLLMResponse(response: string) {
vi.doMock("@continuedev/openai-adapters", () => ({
constructLlmApi: () => mockApi,
BaseLlmApi: class {},
BaseLlmApi: MockBaseLlmApi,
LLMConfig: {}
}));
@ -82,7 +85,7 @@ export function mockLLMStreamResponse(chunks: string[]) {
vi.doMock("@continuedev/openai-adapters", () => ({
constructLlmApi: () => mockApi,
BaseLlmApi: class {},
BaseLlmApi: MockBaseLlmApi,
LLMConfig: {}
}));
@ -113,7 +116,7 @@ export function mockLLMError(errorMessage: string) {
vi.doMock("@continuedev/openai-adapters", () => ({
constructLlmApi: () => mockApi,
BaseLlmApi: class {},
BaseLlmApi: MockBaseLlmApi,
LLMConfig: {}
}));

View file

@ -1,8 +1,9 @@
import { execaNode, type Subprocess } from "execa";
import fs from "fs/promises";
import os from "os";
import path from "path";
import { execaNode, type Subprocess } from "execa";
export interface CLITestContext {
cliPath: string;
testDir: string;
@ -35,7 +36,7 @@ export async function createTestContext(): Promise<CLITestContext> {
// Ensure the CLI file exists before returning the context
try {
await fs.access(cliPath);
} catch (error) {
} catch {
throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`);
}
@ -53,7 +54,7 @@ export async function cleanupTestContext(
): Promise<void> {
try {
await fs.rm(context.testDir, { recursive: true, force: true });
} catch (error) {
} catch {
// Ignore cleanup errors
}
}
@ -165,7 +166,7 @@ export async function readSession(
const content = await fs.readFile(sessionPath, "utf-8");
return JSON.parse(content);
} catch (error) {
} catch {
return null;
}
}

View file

@ -64,7 +64,7 @@ export function mockOpenAIStream(
return scope.reply(500, { error: { message: "Internal server error" } });
}
return scope.reply(200, (uri, requestBody) => {
return scope.reply(200, () => {
// Return a stream of Server-Sent Events
const events = chunks.map((chunk, index) => {
const data = {

View file

@ -1,6 +1,7 @@
import * as fs from "fs/promises";
import * as http from "http";
import * as path from "path";
import { CLITestContext } from "./cli-helpers.js";
export interface MockLLMServerOptions {
@ -78,7 +79,7 @@ export async function createMockLLMServer(
? (() => {
try {
return JSON.parse(body);
} catch (e) {
} catch {
return body;
}
})()

View file

@ -1,6 +1,8 @@
import { render } from 'ink-testing-library';
import React from 'react';
import { ServiceContainerProvider } from '../services/ServiceContainerContext.js';
import { createTestServiceContainer, TestServiceContainer } from './testServiceContainer.js';
export interface RenderWithServicesOptions {

View file

@ -17,7 +17,6 @@ export function createTestServiceContainer(): TestServiceContainer {
}>();
// Override load instead of register to have more control
const originalLoad = container.load.bind(container);
container.load = async function(serviceName: string) {
// Check if we already have a resolver for this service
const existing = serviceResolvers.get(serviceName);

View file

@ -8,7 +8,7 @@ export const exitTool: Tool = {
parameters: {},
readonly: false,
isBuiltIn: true,
run: async (args: { dirpath: string }): Promise<string> => {
run: async (): Promise<string> => {
process.exit(1);
},
};

View file

@ -1,4 +1,5 @@
import TurndownService from "turndown";
import { Tool } from "./types.js";
const turndownService = new TurndownService({

View file

@ -1,5 +1,7 @@
import { vi } from "vitest";
import { formatToolArgument } from "./formatters.js";
import { formatToolCall } from "./index.js";
describe("formatToolCall", () => {

View file

@ -1,8 +1,9 @@
import { MCPService } from "../mcp.js";
import { getServiceSync, SERVICE_NAMES } from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import { MCPService } from "../mcp.js";
import telemetryService from "../telemetry/telemetryService.js";
import logger from "../util/logger.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
import { formatToolArgument } from "./formatters.js";
@ -51,7 +52,7 @@ function getDynamicTools(): Tool[] {
if (isHeadless) {
dynamicTools.push(exitTool);
}
} catch (error) {
} catch {
// Service not ready yet, no dynamic tools
}
@ -86,7 +87,7 @@ export function extractToolCalls(
arguments: toolCallJson.arguments,
});
}
} catch (e) {
} catch {
logger.error("Failed to parse tool call:", { toolCall: match[1] });
}
}

View file

@ -1,7 +1,8 @@
import * as fs from "fs";
import * as path from "path";
import { Tool } from "./types.js";
import { formatToolArgument } from "./formatters.js";
import { Tool } from "./types.js";
// List files in a directory
export const listFilesTool: Tool = {

View file

@ -1,4 +1,7 @@
import { vi } from 'vitest';
import * as fs from "fs";
import * as diff from "diff";
import { describe, it, expect, beforeEach, vi } from 'vitest';
// Mock fs module
vi.mock("fs", async () => {
@ -18,10 +21,6 @@ vi.mock("diff", () => ({
createTwoFilesPatch: vi.fn(),
}));
// Import mocked modules
import * as fs from "fs";
import * as diff from "diff";
// Get mocked functions using vi.mocked
const mockExistsSync = vi.mocked(fs.existsSync);
const mockReadFileSync = vi.mocked(fs.readFileSync);

View file

@ -1,6 +1,7 @@
import * as fs from "fs";
import { Tool } from "./types.js";
import { formatToolArgument } from "./formatters.js";
import { Tool } from "./types.js";
export const readFileTool: Tool = {
name: "Read",

View file

@ -1,9 +1,11 @@
import { spawn } from "child_process";
import telemetryService from "../telemetry/telemetryService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
isGitCommitCommand,
isPullRequestCommand,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
export const runTerminalCommandTool: Tool = {
@ -41,7 +43,6 @@ export const runTerminalCommandTool: Tool = {
const child = spawn("sh", ["-c", command]);
let stdout = "";
let stderr = "";
let lastOutputTime = Date.now();
let timeoutId: NodeJS.Timeout;
let isResolved = false;
@ -69,13 +70,11 @@ export const runTerminalCommandTool: Tool = {
child.stdout.on("data", (data) => {
stdout += data.toString();
lastOutputTime = Date.now();
resetTimeout();
});
child.stderr.on("data", (data) => {
stderr += data.toString();
lastOutputTime = Date.now();
resetTimeout();
});

View file

@ -1,14 +1,16 @@
import { findSearchMatch } from "./findSearchMatch.js";
import { parseAllSearchReplaceBlocks } from "./parseBlock.js";
import { Tool } from "../types.js";
import { generateDiff } from "../writeFile.js";
import * as fs from "fs";
import telemetryService from "../../telemetry/telemetryService.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../../telemetry/utils.js";
import { Tool } from "../types.js";
import { generateDiff } from "../writeFile.js";
import { findSearchMatch } from "./findSearchMatch.js";
import { parseSearchAndReplaceArgs } from "./parseArgs.js";
import { parseAllSearchReplaceBlocks } from "./parseBlock.js";
export interface SearchAndReplaceInFileArgs {
filepath: string;

View file

@ -1,4 +1,3 @@
import { searchCodeTool } from "./searchCode.js";
// Since we want to test just the interface and not the internals,
// let's create a simplified version of the run function to test the truncation logic

View file

@ -1,6 +1,7 @@
import * as child_process from "child_process";
import * as fs from "fs";
import * as util from "util";
import { Tool } from "./types.js";
const execPromise = util.promisify(child_process.exec);

View file

@ -1,6 +1,7 @@
import * as child_process from "child_process";
import * as fs from "fs";
import * as util from "util";
import { Tool } from "./types.js";
const execPromise = util.promisify(child_process.exec);
@ -41,7 +42,7 @@ export const viewDiffTool: Tool = {
await execPromise("git rev-parse --is-inside-work-tree", {
cwd: repoPath,
});
} catch (error) {
} catch {
return `Error: The specified path is not a git repository: ${repoPath}`;
}

View file

@ -1,11 +1,14 @@
import { createTwoFilesPatch } from "diff";
import * as fs from "fs";
import * as path from "path";
import telemetryService from "../telemetry/telemetryService.js";
import { createTwoFilesPatch } from "diff";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { Tool, ToolCallPreview } from "./types.js";
export function generateDiff(
@ -72,7 +75,7 @@ export const writeFileTool: Tool = {
],
};
}
} catch (e) {
} catch {
// do nothing
}
const lines: string[] = args.content.split("\n");

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