From b26458ea083e770a2070f21d0002a2212aa82fcf Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Aug 2025 11:21:07 -0400 Subject: [PATCH 1/7] Update workflow to respond to @continuedev mentions instead of cubic-dev-ai comments --- .github/workflows/respond-to-cubic-dev-ai.yml | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml index 750ec7de3..bb7e1273f 100644 --- a/.github/workflows/respond-to-cubic-dev-ai.yml +++ b/.github/workflows/respond-to-cubic-dev-ai.yml @@ -1,4 +1,4 @@ -name: Respond to cubic-dev-ai Comments +name: Respond to @continuedev Comments on: issue_comment: @@ -16,29 +16,29 @@ jobs: runs-on: ubuntu-latest steps: - - name: Check if comment is from cubic-dev-ai - id: check-author + - name: Check if comment contains @continuedev + id: check-mention run: | - if [ "${{ github.event.comment.user.login }}" = "cubic-dev-ai" ]; then - echo "is_cubic_dev_ai=true" >> $GITHUB_OUTPUT + if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then + echo "contains_mention=true" >> $GITHUB_OUTPUT else - echo "is_cubic_dev_ai=false" >> $GITHUB_OUTPUT + echo "contains_mention=false" >> $GITHUB_OUTPUT fi - name: Get comment content - if: steps.check-author.outputs.is_cubic_dev_ai == 'true' + if: steps.check-mention.outputs.contains_mention == 'true' id: comment-content run: | # Store the comment body for debugging/logging - echo "Comment from cubic-dev-ai:" + echo "Comment mentioning @continuedev from ${{ github.event.comment.user.login }}:" echo "${{ github.event.comment.body }}" - - name: Respond to cubic-dev-ai comment - if: steps.check-author.outputs.is_cubic_dev_ai == 'true' + - name: Respond to @continuedev mention + if: steps.check-mention.outputs.contains_mention == 'true' uses: actions/github-script@v7 with: script: | - const commentBody = `👋 Thanks for the feedback, @cubic-dev-ai! + const commentBody = `👋 Thanks for mentioning @continuedev, @${{ github.event.comment.user.login }}! I've received your comment: > ${{ github.event.comment.body }} @@ -53,7 +53,7 @@ jobs: }); - name: Log acknowledgement - if: steps.check-author.outputs.is_cubic_dev_ai == 'true' + if: steps.check-mention.outputs.contains_mention == 'true' run: | - echo "✅ Successfully acknowledged comment from cubic-dev-ai on PR #${{ github.event.issue.number }}" + echo "✅ Successfully acknowledged comment mentioning @continuedev from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" echo "Original comment: ${{ github.event.comment.body }}" \ No newline at end of file From a96170cef82c0125703ebae2cb7cdc62a7d3d470 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 12:50:54 -0700 Subject: [PATCH 2/7] Add --org flag to headless mode to allow org selection (#166) * feat: select org * feat: make it possible to use org by slug * improv: clean up * fix: types * improv: comment * fix: add discriminator * improv: comment * fix: types * improv: clean up * test: org flag * improv: clean up * fix: test * improv: clean up * Update src/shared-options.ts Co-authored-by: Patrick Erichsen --------- Co-authored-by: Patrick Erichsen --- src/args.ts | 11 +- src/auth/workos-org.test.ts | 199 ++++++++++++++++++++++++++++++ src/auth/workos.ts | 111 +++++++++++++++-- src/commands/chat.ts | 4 + src/e2e/headless-org-flag.test.ts | 105 ++++++++++++++++ src/services/AuthService.test.ts | 61 ++++++++- src/services/AuthService.ts | 7 +- src/services/index.ts | 7 +- src/services/types.ts | 1 + src/shared-options.ts | 2 + src/ui/OrganizationSelector.tsx | 3 +- src/ui/index.ts | 2 + 12 files changed, 494 insertions(+), 19 deletions(-) create mode 100644 src/auth/workos-org.test.ts create mode 100644 src/e2e/headless-org-flag.test.ts diff --git a/src/args.ts b/src/args.ts index 8031d3909..67b4491ec 100644 --- a/src/args.ts +++ b/src/args.ts @@ -7,6 +7,7 @@ import { env } from "./env.js"; export interface CommandLineArgs { configPath?: string; + organizationSlug?: string; // Organization slug to use for this session prompt?: string; // Optional prompt argument resume?: boolean; // Resume from last session readonly?: boolean; // Start in plan mode (backward compatibility) @@ -143,6 +144,14 @@ export function parseArgs(): CommandLineArgs { result.configPath = args[configIndex + 1]; } + // Get organization slug from --org flag + const orgIndex = args.indexOf("--org"); + if (orgIndex !== -1 && orgIndex + 1 < args.length) { + const orgValue = args[orgIndex + 1]; + // Convert "personal" to undefined right away to simplify downstream logic + result.organizationSlug = orgValue.toLowerCase() === "personal" ? undefined : orgValue; + } + // Get rules from --rule flags (can be specified multiple times) const ruleIndices: number[] = []; for (let i = 0; i < args.length; i++) { @@ -161,7 +170,7 @@ export function parseArgs(): CommandLineArgs { } // Find the last argument that's not a flag or a flag value - const flagsWithValues = ["--config", "--rule", "--format"]; + const flagsWithValues = ["--config", "--org", "--rule", "--format"]; const nonFlagArgs = args.filter((arg, index) => { // Skip flags (starting with --) if (arg.startsWith("--") || arg === "-p") return false; diff --git a/src/auth/workos-org.test.ts b/src/auth/workos-org.test.ts new file mode 100644 index 000000000..ab27597ec --- /dev/null +++ b/src/auth/workos-org.test.ts @@ -0,0 +1,199 @@ +import chalk from "chalk"; +import { describe, expect, test, beforeEach, vi } from "vitest"; + +import { getApiClient } from "../config.js"; + +import { ensureOrganization } from "./workos.js"; +import type { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos.js"; + +// Mock dependencies +vi.mock("../config.js", () => ({ + getApiClient: vi.fn(() => ({ + listOrganizations: vi.fn(), + })), +})); + +vi.mock("fs", () => ({ + default: { + existsSync: vi.fn(() => false), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn(), + unlinkSync: vi.fn(), + }, +})); + +describe("ensureOrganization with CLI organization slug", () => { + const mockAuthConfig: AuthenticatedConfig = { + userId: "user-123", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "refresh-token", + expiresAt: Date.now() + 3600000, + organizationId: null, + }; + + const mockEnvAuthConfig: EnvironmentAuthConfig = { + accessToken: "env-token", + organizationId: null, + }; + + const mockOrganizations = [ + { id: "org-1", name: "Organization One", slug: "org-one" }, + { id: "org-2", name: "Organization Two", slug: "org-two" }, + { id: "org-3", name: "Test Org", slug: "test-org" }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + // Suppress console output during tests + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(console, "info").mockImplementation(() => {}); + }); + + describe("Organization resolution by slug", () => { + test("should resolve organization by exact slug match", async () => { + const apiClient = { + listOrganizations: vi + .fn() + .mockResolvedValue({ organizations: mockOrganizations }), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + const result = await ensureOrganization(mockAuthConfig, true, "org-one"); + + expect(result).toMatchObject({ + organizationId: "org-1", + }); + expect(apiClient.listOrganizations).toHaveBeenCalled(); + }); + + test("should show available organizations when slug not found", async () => { + const apiClient = { + listOrganizations: vi + .fn() + .mockResolvedValue({ organizations: mockOrganizations }), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + const consoleInfoSpy = vi.spyOn(console, "info"); + + await expect( + ensureOrganization(mockAuthConfig, true, "invalid-org") + ).rejects.toThrow('Organization "invalid-org" not found'); + + expect(consoleInfoSpy).toHaveBeenCalledWith( + chalk.yellow("Available organizations:"), + expect.stringContaining("personal") + ); + }); + }); + + describe("Mode restriction", () => { + test("should reject --org flag in interactive mode", async () => { + const consoleErrorSpy = vi.spyOn(console, "error"); + const processExitSpy = vi + .spyOn(process, "exit") + .mockImplementation(() => { + throw new Error("Process exit"); + }); + + await expect( + ensureOrganization(mockAuthConfig, false, "org-one") + ).rejects.toThrow("Process exit"); + + expect(consoleErrorSpy).toHaveBeenCalledWith( + chalk.red( + "The --org flag is only supported in headless mode (with -p/--print flag)" + ) + ); + expect(processExitSpy).toHaveBeenCalledWith(1); + + processExitSpy.mockRestore(); + }); + }); + + describe("Auth type handling", () => { + test("should work with authenticated config and return updated organizationId", async () => { + const apiClient = { + listOrganizations: vi + .fn() + .mockResolvedValue({ organizations: mockOrganizations }), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + const result = await ensureOrganization(mockAuthConfig, true, "test-org"); + + expect(result).toMatchObject({ + userId: "user-123", + organizationId: "org-3", + }); + }); + + test("should work with environment auth config and return updated organizationId", async () => { + const apiClient = { + listOrganizations: vi + .fn() + .mockResolvedValue({ organizations: mockOrganizations }), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + const result = await ensureOrganization( + mockEnvAuthConfig, + true, + "org-two" + ); + + expect(result).toMatchObject({ + accessToken: "env-token", + organizationId: "org-2", + }); + }); + + test("should override existing organization with CLI slug", async () => { + const authWithOrg = { + ...mockAuthConfig, + organizationId: "existing-org", + }; + + const apiClient = { + listOrganizations: vi + .fn() + .mockResolvedValue({ organizations: mockOrganizations }), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + const result = await ensureOrganization(authWithOrg, true, "org-one"); + + expect(result).toMatchObject({ + organizationId: "org-1", + }); + }); + + test("should keep existing organization when no slug provided", async () => { + const authWithOrg = { + ...mockAuthConfig, + organizationId: "existing-org", + }; + + const result = await ensureOrganization(authWithOrg, true); + + expect(result).toMatchObject({ + organizationId: "existing-org", + }); + }); + }); + + describe("Error handling", () => { + test("should handle API errors during organization fetch", async () => { + const apiClient = { + listOrganizations: vi.fn().mockRejectedValue(new Error("API Error")), + }; + vi.mocked(getApiClient).mockReturnValue(apiClient as any); + + await expect( + ensureOrganization(mockAuthConfig, true, "org-one") + ).rejects.toThrow("API Error"); + }); + }); +}); diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 6b2849370..502c6dbcf 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -30,8 +30,15 @@ export interface AuthenticatedConfig { // Represents configuration when using environment variable auth export interface EnvironmentAuthConfig { + /** + * This userId?: undefined; field a trick to help TypeScript differentiate between + * AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is + * a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where + * type guards are involved. + */ + userId?: undefined; accessToken: string; - organizationId: null; // Environment auth always uses personal organization + organizationId: string | null; // Can be set via --org flag in headless mode configUri?: string; // Optional config URI (file:// or slug://owner/slug) modelName?: string; // Name of the selected model } @@ -259,7 +266,11 @@ export function isAuthenticated(): boolean { return true; } - // Check if token is expired + /** + * THIS CODE DOESN'T WORK. + * .catch() will never return in a non-async function. + * It's a hallucination. + **/ if (Date.now() > config.expiresAt) { // Try refreshing the token refreshToken(config.refreshToken).catch(() => { @@ -525,15 +536,75 @@ export async function login(): Promise { return authConfig; } +/** + * Helper function to resolve organization by slug + */ +async function resolveOrganizationBySlug( + apiClient: ReturnType, + organizationSlug: string +): Promise<{ id: string; slug: string }> { + const resp = await apiClient.listOrganizations(); + const organizations = resp.organizations; + + // Find organization by slug (case-insensitive) + const matchedOrg = organizations.find( + (org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase() + ); + + if (matchedOrg) { + return { id: matchedOrg.id, slug: matchedOrg.slug }; + } else { + // Organization not found - show available options + const availableSlugs = organizations + .map((org) => org?.slug) + .filter(Boolean); + const availableOptions = ["personal", ...availableSlugs]; + console.info( + chalk.yellow("Available organizations:"), + availableOptions.join(", ") + ); + + throw new Error(`Organization "${organizationSlug}" not found`); + } +} + /** * Ensures the user has selected an organization, automatically selecting the first one if available */ export async function ensureOrganization( authConfig: AuthConfig, - isHeadless: boolean = false + isHeadless: boolean = false, + cliOrganizationSlug?: string ): Promise { - // If using CONTINUE_API_KEY environment variable, don't require organization selection - if (isEnvironmentAuthConfig(authConfig)) { + // Handle CLI organization slug if provided (undefined means no --org flag or --org personal) + if (cliOrganizationSlug) { + // Only allow --org flag in headless mode + if (!isHeadless) { + console.error( + chalk.red( + "The --org flag is only supported in headless mode (with -p/--print flag)" + ) + ); + process.exit(1); + } + + // For environment auth configs + if (isEnvironmentAuthConfig(authConfig)) { + const apiClient = getApiClient(authConfig.accessToken); + + const resolvedOrg = await resolveOrganizationBySlug( + apiClient, + cliOrganizationSlug + ); + + // Return modified environment auth config with organization ID + return { + ...authConfig, + organizationId: resolvedOrg.id, + }; + } + } else if (isEnvironmentAuthConfig(authConfig)) { + // No CLI organization slug (or "personal" was specified) - return as-is return authConfig; } @@ -543,7 +614,24 @@ export async function ensureOrganization( } // TypeScript now knows authConfig is AuthenticatedConfig - const authenticatedConfig = authConfig; + const authenticatedConfig: AuthenticatedConfig = authConfig; + + // If a CLI organization slug is provided, try to use it (for authenticated configs) + if (cliOrganizationSlug) { + const apiClient = getApiClient(authenticatedConfig.accessToken); + + const resolvedOrg = await resolveOrganizationBySlug( + apiClient, + cliOrganizationSlug + ); + + const updatedConfig: AuthenticatedConfig = { + ...authenticatedConfig, + organizationId: resolvedOrg.id, + }; + saveAuthConfig(updatedConfig); + return updatedConfig; + } // If already have organization ID (including null for personal), return as-is if (authenticatedConfig.organizationId !== undefined) { @@ -630,7 +718,7 @@ export async function ensureOrganization( * Gets the list of available organizations for the user */ export async function listUserOrganizations(): Promise< - { id: string; name: string }[] | null + { id: string; name: string; slug: string }[] | null > { const authConfig = loadAuthConfig(); @@ -647,7 +735,14 @@ export async function listUserOrganizations(): Promise< try { const resp = await apiClient.listOrganizations(); - return resp.organizations || []; + // Map the organizations to include slug field + return ( + resp.organizations?.map((org) => ({ + id: org.id, + name: org.name, + slug: org.slug, + })) || [] + ); } catch { return null; } diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 6afb4e130..65233401f 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -82,6 +82,7 @@ export interface ChatOptions extends ExtendedCommandOptions { rule?: string[]; // Array of rule specifications format?: "json"; // Output format for headless mode silent?: boolean; // Strip tags and excess whitespace + org?: string; // Organization slug to use for this session } export async function initializeChatHistory( @@ -326,6 +327,7 @@ async function runHeadlessMode( await initializeServices({ configPath: options.config, + organizationSlug: options.org, rules: options.rule, headless: true, toolPermissionOverrides: permissionOverrides, @@ -406,6 +408,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // Initialize services with onboarding handled internally const initResult = await initializeServices({ configPath: options.config, + organizationSlug: options.org, rules: options.rule, headless: false, toolPermissionOverrides: permissionOverrides, @@ -424,6 +427,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { prompt, options.resume, options.config, + options.org, options.rule, permissionOverrides, true diff --git a/src/e2e/headless-org-flag.test.ts b/src/e2e/headless-org-flag.test.ts new file mode 100644 index 000000000..d31ec65a9 --- /dev/null +++ b/src/e2e/headless-org-flag.test.ts @@ -0,0 +1,105 @@ +import { + createTestContext, + cleanupTestContext, + runCLI, + createTestConfig, +} from "../test-helpers/cli-helpers.js"; + +describe("E2E: Headless Mode with --org flag", () => { + let context: any; + + const testConfig = `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - model: gpt-4 + provider: openai + apiKey: test-key + roles: + - chat`; + + const testEnv = { + OPENAI_API_KEY: "test-key", + CONTINUE_API_KEY: "test-api-key", + }; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + await cleanupTestContext(context); + }); + + describe("--org flag mode restriction", () => { + it("should fail when --org is used without -p flag (interactive mode)", async () => { + await createTestConfig(context, testConfig); + + const result = await runCLI(context, { + args: [ + "--config", + context.configPath, + "--org", + "my-org", + "Test prompt", + ], + env: testEnv, + expectError: true, + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain( + "--org flag is only supported in headless mode" + ); + }); + + it("should accept --org flag with -p flag (headless mode)", async () => { + await createTestConfig(context, testConfig); + + // This will fail due to missing actual auth, but should get past the flag validation + const result = await runCLI(context, { + args: [ + "-p", + "--config", + context.configPath, + "--org", + "my-org", + "Test prompt", + ], + env: testEnv, + expectError: true, + }); + + // Should fail for a different reason (no actual auth/API), not because of flag validation + expect(result.stderr).not.toContain( + "--org flag is only supported in headless mode" + ); + }); + }); + + describe("--org flag inheritance", () => { + it("should inherit --org flag from parent command", async () => { + await createTestConfig(context, testConfig); + + // Test with chat subcommand + const result = await runCLI(context, { + args: [ + "--org", + "test-org", + "chat", + "-p", + "--config", + context.configPath, + "Test prompt", + ], + env: testEnv, + expectError: true, + }); + + // The org flag should be inherited and work in headless mode + expect(result.stderr).not.toContain( + "--org flag is only supported in headless mode" + ); + }); + }); +}); \ No newline at end of file diff --git a/src/services/AuthService.test.ts b/src/services/AuthService.test.ts index 0ee08a098..1fc84cea5 100644 --- a/src/services/AuthService.test.ts +++ b/src/services/AuthService.test.ts @@ -136,6 +136,59 @@ describe('AuthService', () => { 'Not authenticated - cannot ensure organization' ); }); + + test('should pass organization slug to ensureOrganization in headless mode', async () => { + vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); + vi.mocked(isAuthenticated).mockReturnValue(true); + await service.initialize(); + + const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' }; + vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig); + + const state = await service.ensureOrganization(true, 'org-slug'); + + expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug'); + expect(state).toEqual({ + authConfig: updatedConfig, + isAuthenticated: true, + organizationId: 'org-456' + }); + }); + + test('should handle personal organization slug', async () => { + vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); + vi.mocked(isAuthenticated).mockReturnValue(true); + await service.initialize(); + + const personalConfig = { ...mockAuthConfig, organizationId: null }; + vi.mocked(ensureOrganization).mockResolvedValue(personalConfig); + + const state = await service.ensureOrganization(true, 'personal'); + + expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal'); + expect(state).toEqual({ + authConfig: personalConfig, + isAuthenticated: true, + organizationId: undefined + }); + }); + + test('should work without organization slug parameter', async () => { + vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); + vi.mocked(isAuthenticated).mockReturnValue(true); + await service.initialize(); + + vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig); + + const state = await service.ensureOrganization(false); + + expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined); + expect(state).toEqual({ + authConfig: mockAuthConfig, + isAuthenticated: true, + organizationId: 'org-123' + }); + }); }); describe('switchOrganization()', () => { @@ -189,8 +242,8 @@ describe('AuthService', () => { await service.initialize(); const mockOrgs = [ - { id: 'org-1', name: 'Org 1' }, - { id: 'org-2', name: 'Org 2' } + { id: 'org-1', name: 'Org 1', slug: 'org-1' }, + { id: 'org-2', name: 'Org 2', slug: 'org-2' } ]; vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs); @@ -234,8 +287,8 @@ describe('AuthService', () => { await service.initialize(); vi.mocked(listUserOrganizations).mockResolvedValue([ - { id: 'org-1', name: 'Org 1' }, - { id: 'org-2', name: 'Org 2' } + { id: 'org-1', name: 'Org 1', slug: 'org-1' }, + { id: 'org-2', name: 'Org 2', slug: 'org-2' } ]); const hasMultiple = await service.hasMultipleOrganizations(); diff --git a/src/services/AuthService.ts b/src/services/AuthService.ts index 75320fe4a..71d82e9b7 100644 --- a/src/services/AuthService.ts +++ b/src/services/AuthService.ts @@ -96,7 +96,8 @@ export class AuthService extends BaseService { * Ensure organization is selected, prompting if necessary */ async ensureOrganization( - isHeadless: boolean = false + isHeadless: boolean = false, + cliOrganizationSlug?: string ): Promise { if (!this.currentState.authConfig) { throw new Error("Not authenticated - cannot ensure organization"); @@ -105,11 +106,13 @@ export class AuthService extends BaseService { logger.debug("Ensuring organization is selected", { currentOrgId: this.currentState.organizationId, isHeadless, + cliOrganizationSlug, }); const updatedConfig = await ensureOrganization( this.currentState.authConfig, - isHeadless + isHeadless, + cliOrganizationSlug ); this.setState({ diff --git a/src/services/index.ts b/src/services/index.ts index 7a6e5f1d7..449f44c7a 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -112,11 +112,12 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom serviceContainer.get(SERVICE_NAMES.API_CLIENT), ]); - // Ensure organization is selected if authenticated and not headless + // Ensure organization is selected if authenticated let finalAuthState = authState; - if (authState.authConfig && !options.headless) { + if (authState.authConfig) { finalAuthState = await authService.ensureOrganization( - options.headless ?? false + options.headless ?? false, + options.organizationSlug ); // Update the auth service state in container serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState); diff --git a/src/services/types.ts b/src/services/types.ts index 1ab89049d..e676941b8 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -82,6 +82,7 @@ export const SERVICE_NAMES = { */ export interface ServiceInitOptions { configPath?: string; + organizationSlug?: string; // Organization slug to use for this session rules?: string[]; headless?: boolean; skipOnboarding?: boolean; // Skip onboarding check even in TUI mode diff --git a/src/shared-options.ts b/src/shared-options.ts index fb4c9faa6..7992a1336 100644 --- a/src/shared-options.ts +++ b/src/shared-options.ts @@ -4,6 +4,7 @@ import { Command } from "commander"; export function addCommonOptions(command: Command): Command { return command .option("--config ", "Path to configuration file") + .option("--org ", "Organization slug to use for this session (supported only in headless mode)") .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") .option("-v, --verbose", "Enable verbose logging") @@ -57,6 +58,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { // List of options to inherit from parent if not present in subcommand const inheritableOptions = [ 'config', + 'org', 'readonly', 'auto', 'tools', diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx index 629636c5f..d33701d93 100644 --- a/src/ui/OrganizationSelector.tsx +++ b/src/ui/OrganizationSelector.tsx @@ -41,7 +41,8 @@ const OrganizationSelector: React.FC = ({ const options: Organization[] = [ { id: "personal", - name: "Personal" + name: "Personal", + slug: "personal" }, ...organizations, ]; diff --git a/src/ui/index.ts b/src/ui/index.ts index 20899bff5..ee6d977e0 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -13,6 +13,7 @@ export async function startTUIChat( initialPrompt?: string, resume?: boolean, configPath?: string, + organizationSlug?: string, additionalRules?: string[], toolPermissionOverrides?: { allow?: string[]; @@ -26,6 +27,7 @@ export async function startTUIChat( if (!skipOnboarding) { initializeServices({ configPath, + organizationSlug, rules: additionalRules, headless: false, toolPermissionOverrides, From 33eaa6df4af2a9b95d0202a529dd0ba83cefa03b Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 12:58:23 -0700 Subject: [PATCH 3/7] feat: prettier --- .github/workflows/pr_checks.yml | 3 +++ .prettierignore | 40 +++++++++++++++++++++++++++++++++ .prettierrc | 8 +++++++ package.json | 3 +++ 4 files changed, 54 insertions(+) create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index fce779fb4..845b6528e 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -46,6 +46,9 @@ jobs: - name: Run linting run: npm run lint + - name: Check code formatting + run: npm run format:check + review: uses: ./.github/workflows/continue-review.yaml secrets: diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..f7553b3a2 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,40 @@ +# Dependencies +node_modules/ + +# Build output +dist/ + +# Coverage +coverage/ + +# Logs +*.log +logs/ + +# OS files +.DS_Store +Thumbs.db + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo + +# Lock files +package-lock.json +yarn.lock +pnpm-lock.yaml + +# Test files +*.test.ts +*.test.tsx +*.spec.ts +*.spec.tsx + +# Config files that don't need formatting +.prettierrc +.prettierignore + +# Generated files +*.generated.* \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..354af4b2f --- /dev/null +++ b/.prettierrc @@ -0,0 +1,8 @@ +{ + "tabWidth": 2, + "useTabs": false, + "trailingComma": "all", + "semi": true, + "singleQuote": false, + "bracketSpacing": true +} diff --git a/package.json b/package.json index f8f3bf564..df4d64cb8 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,8 @@ "repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml", "lint": "tsc --noEmit && eslint .", "lint:fix": "eslint . --fix", + "format": "prettier --write .", + "format:check": "prettier --check .", "typecheck": "tsc --noEmit", "watch:logs": "tail -f ~/.continue/logs/cn.log", "prepare": "npm run build", @@ -105,6 +107,7 @@ "happy-dom": "^18.0.1", "ink-testing-library": "^4.0.0", "nock": "^14.0.5", + "prettier": "^3.6.2", "semantic-release": "^24.2.7", "supertest": "^7.1.3", "ts-node": "^10.9.2", From af3527e7d278be64978f4473581283e432d54ddd Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 13:03:39 -0700 Subject: [PATCH 4/7] chore: package-lock --- package-lock.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/package-lock.json b/package-lock.json index 8d9ea5edb..f7e46ef7e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -81,6 +81,7 @@ "happy-dom": "^18.0.1", "ink-testing-library": "^4.0.0", "nock": "^14.0.5", + "prettier": "^3.6.2", "semantic-release": "^24.2.7", "supertest": "^7.1.3", "ts-node": "^10.9.2", @@ -16089,6 +16090,22 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/pretty-ms": { "version": "9.2.0", "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.2.0.tgz", From fcc12bce61e9d21e55f2d0ccf441a70df648848d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 13:05:25 -0700 Subject: [PATCH 5/7] chore: package-lock --- package-lock.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/package-lock.json b/package-lock.json index af7b90423..1ad1db937 100644 --- a/package-lock.json +++ b/package-lock.json @@ -84,6 +84,7 @@ "ink-testing-library": "^4.0.0", "jsdom": "^26.1.0", "nock": "^14.0.5", + "prettier": "^3.6.2", "semantic-release": "^24.2.7", "supertest": "^7.1.3", "ts-node": "^10.9.2", @@ -16145,6 +16146,22 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/pretty-format": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", From fda6c3b508b3821196fcaced969ef4dda8217c8f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 13:05:40 -0700 Subject: [PATCH 6/7] fix: formatting --- .github/workflows/beta-release.yml | 8 +- .github/workflows/respond-to-cubic-dev-ai.yml | 4 +- .github/workflows/stable-release.yml | 16 +- AGENTS.md | 5 - CHANGELOG.md | 129 +++--- docs/command-line-flags.md | 6 +- example-permissions.yaml | 14 +- jest.resolver.cjs | 26 +- jest.resolver.js | 10 +- jest.setup.ts | 4 +- spec/config-loading.md | 2 - spec/modes.md | 14 +- spec/onboarding.md | 3 +- spec/permissions.md | 5 +- src/CLIPlatformClient.ts | 10 +- src/MCPConnection.ts | 13 +- src/__mocks__/args.ts | 4 +- src/__mocks__/auth/workos.ts | 6 +- src/__mocks__/config.ts | 19 +- src/__mocks__/configLoader.ts | 4 +- src/__mocks__/hooks/useService.ts | 2 +- src/__mocks__/logging.ts | 4 +- .../permissions/permissionsYamlLoader.ts | 4 +- .../permissions/precedenceResolver.ts | 6 +- src/__mocks__/services/ServiceContainer.ts | 4 +- .../services/ServiceContainerContext.ts | 12 +- src/__mocks__/services/index.ts | 14 +- src/__mocks__/util/logger.ts | 4 +- src/args.ts | 17 +- src/auth/ensureAuth.ts | 2 +- src/auth/workos.ts | 56 +-- src/commands/BaseCommandOptions.ts | 2 +- src/commands/chat.ts | 38 +- src/commands/commands.ts | 4 +- src/commands/remote-test.ts | 4 +- src/commands/remote.ts | 16 +- src/commands/serve.ts | 42 +- src/compaction.ts | 10 +- src/config.ts | 20 +- src/configLoader.ts | 114 ++++-- src/continueSDK.ts | 4 +- src/e2e/spec.md | 30 +- src/fileTools.ts | 2 +- src/flags/flagProcessor.ts | 21 +- src/flags/flagValidator.ts | 92 +++-- src/freeTrialTransition.ts | 35 +- src/hooks/useService.ts | 66 +-- src/index.ts | 18 +- src/logger.ts | 10 +- src/mcp.ts | 10 +- src/onboarding.ts | 27 +- src/permissions/permissionChecker.ts | 12 +- src/permissions/permissionManager.ts | 2 +- src/permissions/permissionsYamlLoader.ts | 8 +- src/permissions/policyWriter.ts | 27 +- src/permissions/precedenceResolver.ts | 31 +- src/permissions/runtimeOverrides.ts | 2 +- src/sentry.ts | 6 +- src/services/ApiClientService.ts | 13 +- src/services/AuthService.refactored.ts | 16 +- src/services/AuthService.ts | 16 +- src/services/BaseService.ts | 4 +- src/services/ConfigService.ts | 54 +-- src/services/MCPServiceWrapper.ts | 38 +- src/services/ModeService.ts | 44 +- src/services/ModelService.refactored.ts | 119 +++--- src/services/ModelService.ts | 119 +++--- src/services/ServiceContainer.ts | 120 +++--- src/services/ServiceContainerContext.tsx | 19 +- src/services/ToolPermissionService.ts | 12 +- src/services/index.ts | 53 +-- src/services/types.ts | 16 +- src/shared-options.ts | 40 +- src/slashCommands.ts | 9 +- src/streamChatResponse.ts | 62 +-- src/systemMessage.ts | 4 +- src/telemetry/posthogService.ts | 2 +- src/telemetry/telemetryService.ts | 52 +-- src/telemetry/utils.ts | 6 +- src/test-helpers/README.md | 11 +- src/test-helpers/adapter-mocks.ts | 84 ++-- src/test-helpers/cli-helpers.ts | 24 +- src/test-helpers/mock-helpers.ts | 114 +++--- src/test-helpers/mock-llm-server.ts | 18 +- src/test-helpers/renderWithServices.tsx | 23 +- src/test-helpers/testServiceContainer.ts | 92 +++-- src/test-helpers/ui-test-context-minimal.ts | 4 +- src/test-helpers/ui-test-context.ts | 20 +- src/tools/index.ts | 19 +- src/tools/runTerminalCommand.ts | 14 +- src/tools/searchAndReplace/findSearchMatch.ts | 14 +- src/tools/searchAndReplace/index.ts | 8 +- src/tools/searchAndReplace/parseBlock.ts | 4 +- src/tools/types.ts | 2 +- src/tools/writeFile.ts | 12 +- src/ui/AppRoot.tsx | 2 +- src/ui/ColoredDiff.tsx | 14 +- src/ui/FileSearchUI.tsx | 2 +- src/ui/FreeTrialStatus.tsx | 2 +- src/ui/FreeTrialTransitionUI.tsx | 39 +- src/ui/IntroMessage.tsx | 8 +- src/ui/LoadingAnimation.tsx | 7 +- src/ui/MarkdownRenderer.tsx | 384 +++++++++--------- src/ui/ModelSelector.tsx | 10 +- src/ui/OrganizationSelector.tsx | 6 +- src/ui/Selector.tsx | 4 +- src/ui/ServiceDebugger.tsx | 46 ++- src/ui/SlashCommandUI.tsx | 3 +- src/ui/SyntaxHighlighter.ts | 12 +- src/ui/TUIChat.tsx | 54 +-- src/ui/TextBuffer.ts | 4 +- src/ui/Timer.tsx | 2 +- src/ui/UI_TEST_CHECKLIST.md | 12 +- src/ui/UserInput.tsx | 27 +- src/ui/__mocks__/FreeTrialStatus.tsx | 2 +- src/ui/__mocks__/SyntaxHighlighter.ts | 18 +- src/ui/__mocks__/highlightLanguage.js | 6 +- src/ui/__mocks__/lowlight.js | 8 +- src/ui/__tests__/README.md | 39 +- src/ui/__tests__/TUIChat.dualModeHelper.tsx | 27 +- src/ui/__tests__/TUIChat.testHelper.ts | 132 +++--- src/ui/__tests__/mocks/MockApiClient.ts | 10 +- src/ui/__tests__/mocks/MockLlmApi.ts | 2 +- src/ui/__tests__/mocks/MockMCPService.ts | 2 +- src/ui/components/MemoizedMessage.tsx | 12 +- src/ui/components/ModeIndicator.tsx | 24 +- src/ui/components/ToolPermissionSelector.tsx | 6 +- src/ui/context/NavigationContext.tsx | 64 +-- src/ui/hooks/useChat.ts | 47 ++- src/ui/hooks/useMessageRenderer.tsx | 15 +- src/ui/hooks/useModelSelector.ts | 19 +- src/ui/hooks/useOrganizationSelector.ts | 13 +- src/ui/index.ts | 12 +- src/util/apiKeyValidation.ts | 34 +- src/util/consoleOverride.ts | 16 +- src/util/exponentialBackoff.ts | 14 +- src/util/formatError.ts | 22 +- src/util/git.ts | 4 +- src/util/inputHistory.ts | 24 +- src/util/logger.ts | 6 +- src/util/stdin.ts | 2 +- src/util/tokenizer.ts | 8 +- src/util/yamlConfigUpdater.ts | 43 +- src/utils/index.ts | 2 +- src/utils/modelCapability.ts | 10 +- src/version.ts | 6 +- tsconfig.build.json | 4 +- vitest.config.ts | 33 +- vitest.setup.ts | 6 +- 149 files changed, 1993 insertions(+), 1698 deletions(-) diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index 6864b94d2..912dd4d28 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -46,11 +46,11 @@ jobs: echo "Using latest npm version: $LATEST_VERSION" CURRENT_VERSION=$LATEST_VERSION fi - + # Create beta version with current date DATE_SUFFIX=$(date -u +%Y%m%d) BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}" - + echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT @@ -79,9 +79,9 @@ jobs: git config --local user.name "GitHub Action" git tag "v${{ steps.get_version.outputs.beta_version }}" git push origin "v${{ steps.get_version.outputs.beta_version }}" - + # Create GitHub release gh release create "v${{ steps.get_version.outputs.beta_version }}" \ --title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \ --notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \ - --prerelease \ No newline at end of file + --prerelease diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml index bb7e1273f..4c1db1a5f 100644 --- a/.github/workflows/respond-to-cubic-dev-ai.yml +++ b/.github/workflows/respond-to-cubic-dev-ai.yml @@ -14,7 +14,7 @@ jobs: # Only run on pull request comments if: github.event.issue.pull_request runs-on: ubuntu-latest - + steps: - name: Check if comment contains @continuedev id: check-mention @@ -56,4 +56,4 @@ jobs: if: steps.check-mention.outputs.contains_mention == 'true' run: | echo "✅ Successfully acknowledged comment mentioning @continuedev from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" - echo "Original comment: ${{ github.event.comment.body }}" \ No newline at end of file + echo "Original comment: ${{ github.event.comment.body }}" diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index e8a72a8cf..e13c90339 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: beta_version: - description: 'Specific beta version to promote (e.g., 1.2.3-beta.20240115)' + description: "Specific beta version to promote (e.g., 1.2.3-beta.20240115)" required: false type: string @@ -70,10 +70,10 @@ jobs: BETA_VERSION=$CANDIDATE_VERSION echo "Selected beta version for promotion: $BETA_VERSION" fi - + # Extract base version (remove -beta.YYYYMMDD suffix) STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//') - + echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT @@ -83,11 +83,11 @@ jobs: run: | # Download the specific beta version npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }} - + # Extract and verify the package PACKAGE_FILE=$(ls continuedev-cli-*.tgz) tar -xzf "$PACKAGE_FILE" - + echo "Beta package contents verified" ls -la package/ @@ -95,7 +95,7 @@ jobs: run: | # Copy the beta package contents cp -r package/* . - + # Update version to stable (remove beta suffix) npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version @@ -121,7 +121,7 @@ jobs: git config --local user.name "GitHub Action" git tag "v${{ steps.find_beta.outputs.stable_version }}" git push origin "v${{ steps.find_beta.outputs.stable_version }}" - + # Create GitHub release gh release create "v${{ steps.find_beta.outputs.stable_version }}" \ --title "Stable Release v${{ steps.find_beta.outputs.stable_version }}" \ @@ -134,4 +134,4 @@ jobs: run: | # Mark the original beta release as superseded gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \ - --notes "This beta version has been promoted to stable as v${{ steps.find_beta.outputs.stable_version }}." \ No newline at end of file + --notes "This beta version has been promoted to stable as v${{ steps.find_beta.outputs.stable_version }}." diff --git a/AGENTS.md b/AGENTS.md index 936c4e7d7..e4a2cef76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,30 +17,25 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev ### Core Components 1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes: - - **Headless mode**: Non-interactive mode for automation/CI - **TUI mode**: Terminal User Interface using Ink/React - **Standard mode**: Traditional readline-based chat interface 2. **Authentication** (`src/auth/`): WorkOS-based authentication system - - `ensureAuth.ts`: Handles authentication flow - `workos.ts`: WorkOS configuration and token management 3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with: - - API key authentication - Assistant configuration (slug-based) - Organization support 4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components - - `TUIChat.tsx`: Main chat interface component - `UserInput.tsx`: Input handling with multi-line support - `TextBuffer.ts`: Text display utilities 5. **Tools System** (`src/tools/`): Built-in development tools including: - - File operations (read, write, list) - Code search functionality - Terminal command execution diff --git a/CHANGELOG.md b/CHANGELOG.md index ac8aa57ed..fcbb2dec1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,151 +1,134 @@ ## [1.4.2](https://github.com/continuedev/cli/compare/v1.4.1...v1.4.2) (2025-07-17) - ### Bug Fixes -* remove warning ([31b3f67](https://github.com/continuedev/cli/commit/31b3f6707b0f42180c8ae56faf9dfb2f566be5c1)) +- remove warning ([31b3f67](https://github.com/continuedev/cli/commit/31b3f6707b0f42180c8ae56faf9dfb2f566be5c1)) ## [1.4.1](https://github.com/continuedev/cli/compare/v1.4.0...v1.4.1) (2025-07-17) - ### Bug Fixes -* update readme ([0d45e14](https://github.com/continuedev/cli/commit/0d45e14b1be6557ace027cfeadfbf418061a28b0)) +- update readme ([0d45e14](https://github.com/continuedev/cli/commit/0d45e14b1be6557ace027cfeadfbf418061a28b0)) # [1.4.0](https://github.com/continuedev/cli/compare/v1.3.6...v1.4.0) (2025-07-17) - ### Features -* dim user msg text color ([b22429b](https://github.com/continuedev/cli/commit/b22429ba0a101f99b14313345a8a8894caff3081)) +- dim user msg text color ([b22429b](https://github.com/continuedev/cli/commit/b22429ba0a101f99b14313345a8a8894caff3081)) ## [1.3.6](https://github.com/continuedev/cli/compare/v1.3.5...v1.3.6) (2025-07-16) - ### Bug Fixes -* update readme ([01329e4](https://github.com/continuedev/cli/commit/01329e4b4f66d97c93c98e0342f100792f626126)) +- update readme ([01329e4](https://github.com/continuedev/cli/commit/01329e4b4f66d97c93c98e0342f100792f626126)) ## [1.3.5](https://github.com/continuedev/cli/compare/v1.3.4...v1.3.5) (2025-07-16) - ### Bug Fixes -* package.json issues page ([91e1e2e](https://github.com/continuedev/cli/commit/91e1e2e004e86d6fb1df3bbfbbf94f6d46a4adb7)) -* update review.yaml config ([b49ab0d](https://github.com/continuedev/cli/commit/b49ab0d9e54edf8374b113af4752e1c6fba15738)) +- package.json issues page ([91e1e2e](https://github.com/continuedev/cli/commit/91e1e2e004e86d6fb1df3bbfbbf94f6d46a4adb7)) +- update review.yaml config ([b49ab0d](https://github.com/continuedev/cli/commit/b49ab0d9e54edf8374b113af4752e1c6fba15738)) ## [1.3.4](https://github.com/continuedev/cli/compare/v1.3.3...v1.3.4) (2025-07-16) - ### Bug Fixes -* add /clear command to clear chat history ([3782732](https://github.com/continuedev/cli/commit/378273239b32fce735266cb4835512f5c547a86d)) +- add /clear command to clear chat history ([3782732](https://github.com/continuedev/cli/commit/378273239b32fce735266cb4835512f5c547a86d)) ## [1.3.3](https://github.com/continuedev/cli/compare/v1.3.2...v1.3.3) (2025-07-16) - ### Bug Fixes -* update chat history state after streaming and save complete conversation ([936786a](https://github.com/continuedev/cli/commit/936786aee08fcbdde2484896730a0c67f1ebafee)) +- update chat history state after streaming and save complete conversation ([936786a](https://github.com/continuedev/cli/commit/936786aee08fcbdde2484896730a0c67f1ebafee)) ## [1.3.2](https://github.com/continuedev/cli/compare/v1.3.1...v1.3.2) (2025-07-16) - ### Bug Fixes -* remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6)) +- remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6)) ## [1.3.1](https://github.com/continuedev/cli/compare/v1.3.0...v1.3.1) (2025-07-16) - ### Bug Fixes -* type err ([f5f1bca](https://github.com/continuedev/cli/commit/f5f1bca7c6a9f2c4f2842605847d55b765fd3499)) +- type err ([f5f1bca](https://github.com/continuedev/cli/commit/f5f1bca7c6a9f2c4f2842605847d55b765fd3499)) # [1.3.0](https://github.com/continuedev/cli/compare/v1.2.0...v1.3.0) (2025-07-15) - ### Features -* add session management with --resume flag and cn alias ([0096fbc](https://github.com/continuedev/cli/commit/0096fbcc4934d7264d9a7a134908e016e037df1a)) +- add session management with --resume flag and cn alias ([0096fbc](https://github.com/continuedev/cli/commit/0096fbcc4934d7264d9a7a134908e016e037df1a)) # [1.2.0](https://github.com/continuedev/cli/compare/v1.1.0...v1.2.0) (2025-07-14) - ### Bug Fixes -* bg color for diff ([63c9ecf](https://github.com/continuedev/cli/commit/63c9ecf24fcf74f43d07244c963cef04f91baee8)) -* display diff ([fde6098](https://github.com/continuedev/cli/commit/fde6098ef2c4d99a9b9b8d6ffc1299436e0f52c1)) -* improve streaming message handling and display buffering ([d1372b3](https://github.com/continuedev/cli/commit/d1372b3aa2f79221957468fd1decbae2258becc0)) -* remove part of the system message ([daae972](https://github.com/continuedev/cli/commit/daae97242f1fca92f42f8c979df8d9c3f912f69d)) -* truncate diff at 16 lines ([cbb77e3](https://github.com/continuedev/cli/commit/cbb77e35ff19809c1c05760fbdf7c995d85dc72c)) - +- bg color for diff ([63c9ecf](https://github.com/continuedev/cli/commit/63c9ecf24fcf74f43d07244c963cef04f91baee8)) +- display diff ([fde6098](https://github.com/continuedev/cli/commit/fde6098ef2c4d99a9b9b8d6ffc1299436e0f52c1)) +- improve streaming message handling and display buffering ([d1372b3](https://github.com/continuedev/cli/commit/d1372b3aa2f79221957468fd1decbae2258becc0)) +- remove part of the system message ([daae972](https://github.com/continuedev/cli/commit/daae97242f1fca92f42f8c979df8d9c3f912f69d)) +- truncate diff at 16 lines ([cbb77e3](https://github.com/continuedev/cli/commit/cbb77e35ff19809c1c05760fbdf7c995d85dc72c)) ### Features -* add /clear command to clear chat history ([c9c000c](https://github.com/continuedev/cli/commit/c9c000cfab6aa6efe156126f1eafc99349466413)) -* convert absolute paths to relative paths in tool display ([2c722c4](https://github.com/continuedev/cli/commit/2c722c485eea4c3c283fb643193a4b1ffe14bf7f)) +- add /clear command to clear chat history ([c9c000c](https://github.com/continuedev/cli/commit/c9c000cfab6aa6efe156126f1eafc99349466413)) +- convert absolute paths to relative paths in tool display ([2c722c4](https://github.com/continuedev/cli/commit/2c722c485eea4c3c283fb643193a4b1ffe14bf7f)) # [1.1.0](https://github.com/continuedev/cli/compare/v1.0.1...v1.1.0) (2025-07-14) - ### Bug Fixes -* improve streaming message handling and API endpoint ([b822b93](https://github.com/continuedev/cli/commit/b822b938f110af2de2c040f45cd3fca770d9a4a7)) -* use ignore-walk for sys msg ([eb59dcc](https://github.com/continuedev/cli/commit/eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3)) - +- improve streaming message handling and API endpoint ([b822b93](https://github.com/continuedev/cli/commit/b822b938f110af2de2c040f45cd3fca770d9a4a7)) +- use ignore-walk for sys msg ([eb59dcc](https://github.com/continuedev/cli/commit/eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3)) ### Features -* base system message ([25a67cf](https://github.com/continuedev/cli/commit/25a67cf947f786d4cdc36c60e36e303a4e466c87)) +- base system message ([25a67cf](https://github.com/continuedev/cli/commit/25a67cf947f786d4cdc36c60e36e303a4e466c87)) ## [1.0.1](https://github.com/continuedev/cli/compare/v1.0.0...v1.0.1) (2025-07-14) - ### Bug Fixes -* release index.js ([091cfa7](https://github.com/continuedev/cli/commit/091cfa7b64c1591f371e444e602d04fdcbca48d4)) +- release index.js ([091cfa7](https://github.com/continuedev/cli/commit/091cfa7b64c1591f371e444e602d04fdcbca48d4)) # 1.0.0 (2025-07-14) - ### Bug Fixes -* adjust placeholder ([94e6f12](https://github.com/continuedev/cli/commit/94e6f12924ff5ee429a43c53d1810d5519f026bb)) -* adjust waiting message ([454df15](https://github.com/continuedev/cli/commit/454df1554500a530645ef5e7a6a80fea6a27f207)) -* allow multiple consecutive new lines ([423dbdd](https://github.com/continuedev/cli/commit/423dbdd457683260f66eda9024f35dee9c49d5db)) -* backspace on mac ([aa5606f](https://github.com/continuedev/cli/commit/aa5606f65f3284c9ff4d0a02cb1e4611b5cd080c)) -* cursor position ([388eeeb](https://github.com/continuedev/cli/commit/388eeeb37afa7625b954e4dd44cbcd7cf0ab22bb)) -* delete hallucinated tools ([2d4cf55](https://github.com/continuedev/cli/commit/2d4cf55c393121570ff2c4459c6942e124bc88dd)) -* dot shade of green ([8f6ec39](https://github.com/continuedev/cli/commit/8f6ec398ff23ec1d59567cb5b2de92dabd58ab4b)) -* empty assistant message ([5e773f5](https://github.com/continuedev/cli/commit/5e773f52684dc8b267fa33a94b0b707d292a6111)) -* even nicer tool UI ([3716ebc](https://github.com/continuedev/cli/commit/3716ebcdd73a23e021e59a9d162d61915ce31184)) -* more slashcommand UI ([daa4538](https://github.com/continuedev/cli/commit/daa45387725f6b0b9b247ebde63f1f3018052bc2)) -* nicer tool display ([6749e10](https://github.com/continuedev/cli/commit/6749e10daad3fc9238dce6bf5c7309dd610cad2a)) -* option + left/rght ([efa2c43](https://github.com/continuedev/cli/commit/efa2c434d0a5942e9aaf5171c2d1f03c5df3ca51)) -* refactor display name for tools ([837ac2d](https://github.com/continuedev/cli/commit/837ac2d5c33ad0ef6482f8216dd7b3a8ec852fe3)) -* round corners ([a08e217](https://github.com/continuedev/cli/commit/a08e2176a70f5a216f6e03657e9f6522eade99b8)) -* shift+enter for newline ([fa30094](https://github.com/continuedev/cli/commit/fa30094e61dbb2b11f7940b875fc719d06ed3eec)) -* slash command prefix matching ([0a40201](https://github.com/continuedev/cli/commit/0a402010d9ae98a6913b7ceb68b97dfd9772754e)) -* slash command tab ([ee40d8b](https://github.com/continuedev/cli/commit/ee40d8bbb48d502055cad1e811e973598b0bf9bd)) -* stream above input box ([c8945ad](https://github.com/continuedev/cli/commit/c8945adb85c99379039afa02ac4d63f114a6de6b)) -* tool call custom UI ([fa4b98f](https://github.com/continuedev/cli/commit/fa4b98f455db6fe48b4c5810327d0222fade7902)) -* tool name matching ([9792b14](https://github.com/continuedev/cli/commit/9792b1411f713c2615c0d3b82df2c7032d434205)) -* tool ui again ([9c18d28](https://github.com/continuedev/cli/commit/9c18d28cbefed79f316a0b9d219f7ec585455eca)) -* tool UI again ([9d4ea20](https://github.com/continuedev/cli/commit/9d4ea20deb278a7c8d427647b5c1d5cf4d333352)) -* tui no longer completely broken ([8c0fd5e](https://github.com/continuedev/cli/commit/8c0fd5e87e7e8ce59b4b022669d4aba2ba1b8bcf)) - +- adjust placeholder ([94e6f12](https://github.com/continuedev/cli/commit/94e6f12924ff5ee429a43c53d1810d5519f026bb)) +- adjust waiting message ([454df15](https://github.com/continuedev/cli/commit/454df1554500a530645ef5e7a6a80fea6a27f207)) +- allow multiple consecutive new lines ([423dbdd](https://github.com/continuedev/cli/commit/423dbdd457683260f66eda9024f35dee9c49d5db)) +- backspace on mac ([aa5606f](https://github.com/continuedev/cli/commit/aa5606f65f3284c9ff4d0a02cb1e4611b5cd080c)) +- cursor position ([388eeeb](https://github.com/continuedev/cli/commit/388eeeb37afa7625b954e4dd44cbcd7cf0ab22bb)) +- delete hallucinated tools ([2d4cf55](https://github.com/continuedev/cli/commit/2d4cf55c393121570ff2c4459c6942e124bc88dd)) +- dot shade of green ([8f6ec39](https://github.com/continuedev/cli/commit/8f6ec398ff23ec1d59567cb5b2de92dabd58ab4b)) +- empty assistant message ([5e773f5](https://github.com/continuedev/cli/commit/5e773f52684dc8b267fa33a94b0b707d292a6111)) +- even nicer tool UI ([3716ebc](https://github.com/continuedev/cli/commit/3716ebcdd73a23e021e59a9d162d61915ce31184)) +- more slashcommand UI ([daa4538](https://github.com/continuedev/cli/commit/daa45387725f6b0b9b247ebde63f1f3018052bc2)) +- nicer tool display ([6749e10](https://github.com/continuedev/cli/commit/6749e10daad3fc9238dce6bf5c7309dd610cad2a)) +- option + left/rght ([efa2c43](https://github.com/continuedev/cli/commit/efa2c434d0a5942e9aaf5171c2d1f03c5df3ca51)) +- refactor display name for tools ([837ac2d](https://github.com/continuedev/cli/commit/837ac2d5c33ad0ef6482f8216dd7b3a8ec852fe3)) +- round corners ([a08e217](https://github.com/continuedev/cli/commit/a08e2176a70f5a216f6e03657e9f6522eade99b8)) +- shift+enter for newline ([fa30094](https://github.com/continuedev/cli/commit/fa30094e61dbb2b11f7940b875fc719d06ed3eec)) +- slash command prefix matching ([0a40201](https://github.com/continuedev/cli/commit/0a402010d9ae98a6913b7ceb68b97dfd9772754e)) +- slash command tab ([ee40d8b](https://github.com/continuedev/cli/commit/ee40d8bbb48d502055cad1e811e973598b0bf9bd)) +- stream above input box ([c8945ad](https://github.com/continuedev/cli/commit/c8945adb85c99379039afa02ac4d63f114a6de6b)) +- tool call custom UI ([fa4b98f](https://github.com/continuedev/cli/commit/fa4b98f455db6fe48b4c5810327d0222fade7902)) +- tool name matching ([9792b14](https://github.com/continuedev/cli/commit/9792b1411f713c2615c0d3b82df2c7032d434205)) +- tool ui again ([9c18d28](https://github.com/continuedev/cli/commit/9c18d28cbefed79f316a0b9d219f7ec585455eca)) +- tool UI again ([9d4ea20](https://github.com/continuedev/cli/commit/9d4ea20deb278a7c8d427647b5c1d5cf4d333352)) +- tui no longer completely broken ([8c0fd5e](https://github.com/continuedev/cli/commit/8c0fd5e87e7e8ce59b4b022669d4aba2ba1b8bcf)) ### Features -* basic ink tui ([ed536d3](https://github.com/continuedev/cli/commit/ed536d3505167cd15e46ec4dee49847eb87b63a8)) -* better slash command UI ([c62cbdc](https://github.com/continuedev/cli/commit/c62cbdc21e6e93788d8e01c0a97c17ef0c036261)) -* disable PR description ([a5722ba](https://github.com/continuedev/cli/commit/a5722bab8bd7fb925806a767e9f76a4165f5f6b3)) -* esc to interrupt ([5643a53](https://github.com/continuedev/cli/commit/5643a53b5a3440d1e3e2ee41df08524289ad94b2)) -* integrate SDK into CLI ([#1](https://github.com/continuedev/cli/issues/1)) ([597e35b](https://github.com/continuedev/cli/commit/597e35b5be0ab1d1f62b6d9e2ac71e168d06e39c)) -* more spinners ([dccb311](https://github.com/continuedev/cli/commit/dccb31106a43f2c295da3f8a4225a44969cb3ef7)) -* new TextBuffer class for improved keystroke handling ([e7ab301](https://github.com/continuedev/cli/commit/e7ab301dbe3b7e27bd6bb15992f3cf1a3f9694d7)) -* paste ([65f10a1](https://github.com/continuedev/cli/commit/65f10a1a4f2862bf1166d187e49fc732a503f9da)) -* slash command UI and ASCII spinner ([7eefce2](https://github.com/continuedev/cli/commit/7eefce2de39fca9ab51b2d2fb1d0b24286c09404)) -* suppress `console.info` in headless ([8177eef](https://github.com/continuedev/cli/commit/8177eef6a00a06f5c80d4b0ee4c84f00fd156cd5)) -* TUI mode as default ([e73098b](https://github.com/continuedev/cli/commit/e73098b82ed5ea73f6d8d33eab24fdf6c67bb8ec)) +- basic ink tui ([ed536d3](https://github.com/continuedev/cli/commit/ed536d3505167cd15e46ec4dee49847eb87b63a8)) +- better slash command UI ([c62cbdc](https://github.com/continuedev/cli/commit/c62cbdc21e6e93788d8e01c0a97c17ef0c036261)) +- disable PR description ([a5722ba](https://github.com/continuedev/cli/commit/a5722bab8bd7fb925806a767e9f76a4165f5f6b3)) +- esc to interrupt ([5643a53](https://github.com/continuedev/cli/commit/5643a53b5a3440d1e3e2ee41df08524289ad94b2)) +- integrate SDK into CLI ([#1](https://github.com/continuedev/cli/issues/1)) ([597e35b](https://github.com/continuedev/cli/commit/597e35b5be0ab1d1f62b6d9e2ac71e168d06e39c)) +- more spinners ([dccb311](https://github.com/continuedev/cli/commit/dccb31106a43f2c295da3f8a4225a44969cb3ef7)) +- new TextBuffer class for improved keystroke handling ([e7ab301](https://github.com/continuedev/cli/commit/e7ab301dbe3b7e27bd6bb15992f3cf1a3f9694d7)) +- paste ([65f10a1](https://github.com/continuedev/cli/commit/65f10a1a4f2862bf1166d187e49fc732a503f9da)) +- slash command UI and ASCII spinner ([7eefce2](https://github.com/continuedev/cli/commit/7eefce2de39fca9ab51b2d2fb1d0b24286c09404)) +- suppress `console.info` in headless ([8177eef](https://github.com/continuedev/cli/commit/8177eef6a00a06f5c80d4b0ee4c84f00fd156cd5)) +- TUI mode as default ([e73098b](https://github.com/continuedev/cli/commit/e73098b82ed5ea73f6d8d33eab24fdf6c67bb8ec)) diff --git a/docs/command-line-flags.md b/docs/command-line-flags.md index 319eea188..6c718a06d 100644 --- a/docs/command-line-flags.md +++ b/docs/command-line-flags.md @@ -33,7 +33,7 @@ cn --auto -p "fix the failing tests" # Dangerous: will modify files ## Fine-grained Permissions - `--allow ` - Allow specific tools -- `--ask ` - Ask before using tools +- `--ask ` - Ask before using tools - `--exclude ` - Block specific tools ```bash @@ -66,7 +66,7 @@ cn serve --timeout 600 # 10 minute timeout ## Remote Development ```bash -cn remote "help debug this" # Create new remote environment +cn remote "help debug this" # Create new remote environment cn remote --url https://my-server.com "work" # Connect to existing server ``` @@ -94,4 +94,4 @@ cn serve --readonly --port 8080 - Use `--readonly` when you want AI to analyze but not modify code - Use `--auto` only when you trust the AI to make changes - Pipe input works: `cat file.py | cn -p "explain this"` -- `--format json` and `--silent` only work with `-p` \ No newline at end of file +- `--format json` and `--silent` only work with `-p` diff --git a/example-permissions.yaml b/example-permissions.yaml index 05f2e5c83..e7a420785 100644 --- a/example-permissions.yaml +++ b/example-permissions.yaml @@ -3,21 +3,21 @@ # Tools that are automatically allowed without prompting allow: - - Read # or read_file, read, READ - all normalized - - List # or list_files - - Search # or search_code + - Read # or read_file, read, READ - all normalized + - List # or list_files + - Search # or search_code # Tools that require user confirmation before execution ask: - - Write # or write_file - - Terminal # or run_terminal_command, Bash, bash + - Write # or write_file + - Terminal # or run_terminal_command, Bash, bash # Tools that are completely excluded (model won't know they exist) exclude: - - Exit # or exit + - Exit # or exit # You can also use wildcards # allow: # - mcp__* # Allow all MCP tools # exclude: -# - * # Exclude everything else \ No newline at end of file +# - * # Exclude everything else diff --git a/jest.resolver.cjs b/jest.resolver.cjs index 818ecee9b..ac9db7768 100644 --- a/jest.resolver.cjs +++ b/jest.resolver.cjs @@ -1,29 +1,29 @@ // Custom resolver for Jest to handle .js extensions in ESM project -const path = require('path'); -const fs = require('fs'); +const path = require("path"); +const fs = require("fs"); module.exports = (request, options) => { // Call the default resolver const defaultResolver = options.defaultResolver; - + // First try the default resolver try { return defaultResolver(request, options); } catch (e) { // Only continue if module not found - if (!e.message || !e.message.includes('Cannot find module')) { + if (!e.message || !e.message.includes("Cannot find module")) { throw e; } } - + // Handle relative imports - if (request.startsWith('.')) { + if (request.startsWith(".")) { const basePath = options.basedir; const fullPath = path.resolve(basePath, request); - + // Try various extensions - const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']; - + const extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]; + for (const ext of extensions) { const testPath = fullPath + ext; try { @@ -34,10 +34,10 @@ module.exports = (request, options) => { // Continue to next extension } } - + // Also try adding /index with various extensions for (const ext of extensions) { - const testPath = path.join(fullPath, 'index' + ext); + const testPath = path.join(fullPath, "index" + ext); try { if (fs.existsSync(testPath)) { return defaultResolver(testPath, options); @@ -47,7 +47,7 @@ module.exports = (request, options) => { } } } - + // If still not found, throw original error throw new Error(`Cannot find module '${request}'`); -}; \ No newline at end of file +}; diff --git a/jest.resolver.js b/jest.resolver.js index e28f7c266..1e053f75d 100644 --- a/jest.resolver.js +++ b/jest.resolver.js @@ -1,24 +1,24 @@ module.exports = (path, options) => { // Call the default resolver const resolver = options.defaultResolver; - + try { // Try to resolve the path as-is first return resolver(path, options); } catch (error) { // If the path ends with .js and resolution fails, try without the extension - if (path.endsWith('.js')) { + if (path.endsWith(".js")) { const pathWithoutJs = path.slice(0, -3); try { return resolver(pathWithoutJs, options); } catch { // If that also fails, try with .ts extension try { - return resolver(pathWithoutJs + '.ts', options); + return resolver(pathWithoutJs + ".ts", options); } catch { // If that also fails, try with .tsx extension try { - return resolver(pathWithoutJs + '.tsx', options); + return resolver(pathWithoutJs + ".tsx", options); } catch { // If all attempts fail, throw the original error throw error; @@ -28,4 +28,4 @@ module.exports = (path, options) => { } throw error; } -}; \ No newline at end of file +}; diff --git a/jest.setup.ts b/jest.setup.ts index 5e4294d3d..64ae4e9ad 100644 --- a/jest.setup.ts +++ b/jest.setup.ts @@ -32,11 +32,11 @@ afterEach(() => { // Ignore errors when clearing timers } } - + // Reset console overrides to ensure clean state for each test try { resetConsoleOverrides(); } catch (e) { // Ignore errors when resetting console } -}); \ No newline at end of file +}); diff --git a/spec/config-loading.md b/spec/config-loading.md index 0f474b5a7..384b19809 100644 --- a/spec/config-loading.md +++ b/spec/config-loading.md @@ -23,13 +23,11 @@ This document specifies the behavior of the CLI's configuration loading system, **When CLI is invoked, config source is determined in this order:** 1. **CLI `--config` Flag** (highest priority) - - File path (starts with `.`, `/`, `~`): Loads local YAML file - Assistant slug (`owner/package`): Fetches from Continue platform - Overrides any saved preferences 2. **Saved Config URI** (if no `--config` flag) - - Retrieved from authentication config - Converts `file://` URIs back to file paths - Converts `slug://` URIs back to assistant slugs diff --git a/spec/modes.md b/spec/modes.md index c052e1f0b..0bf32c7cf 100644 --- a/spec/modes.md +++ b/spec/modes.md @@ -5,6 +5,7 @@ Modes are a system for managing tool permissions in the CLI. They can be set via ## Available Modes ### `normal` (default) + The default mode that follows configured permission policies from `permissions.yaml` and command-line overrides without any additional restrictions or mode-specific policies. - **UI Indicator:** No indicator shown (clean interface for default behavior) @@ -13,6 +14,7 @@ The default mode that follows configured permission policies from `permissions.y - **Backward compatibility:** Existing configurations work unchanged ### `plan` + Planning mode that **completely overrides all user permissions** to enforce read-only access. This mode absolutely prevents any write operations, file modifications, or command execution, regardless of user configuration. - **Command-line flag:** `--readonly` (for backward compatibility) @@ -22,6 +24,7 @@ Planning mode that **completely overrides all user permissions** to enforce read - **User config ignored:** Any user `--allow` flags for write tools are overridden ### `auto` + Auto mode that **completely overrides all user permissions** to allow everything without asking. This mode provides maximum automation by bypassing all permission policies and restrictions, regardless of user configuration. - **Command-line flag:** `--auto` (starts in auto mode) @@ -33,7 +36,9 @@ Auto mode that **completely overrides all user permissions** to allow everything ## Usage ### Command-Line Initialization + Modes can be set when starting the CLI: + ```bash cn --readonly "Help me analyze this code" # Starts in plan mode cn --auto "Fix all the linting errors" # Starts in auto mode @@ -41,14 +46,17 @@ cn "Let me implement this feature" # Starts in normal mode (default) ``` ### Dynamic Mode Switching + Users can switch modes during chat sessions using: **Keyboard Shortcut:** + - **Shift+Tab** - Cycle through modes: normal → plan → auto → (repeat) ## Implementation Modes are implemented through the permission system: + - **ModeService**: Singleton service managing the current mode and initialization - **ToolPermissionService**: Extended to support mode-specific policies with highest priority - **ModeIndicator**: UI component showing current mode (hidden for normal mode) @@ -56,17 +64,21 @@ Modes are implemented through the permission system: - **Backward compatibility**: Existing `--readonly` flag maps to plan mode ### Mode Policy Priority + **Mode policies completely override all other configurations** when in plan or auto mode: **Plan and Auto modes:** + 1. **Mode policies** (absolute override - ignores everything else) **Normal mode only:** + 1. Command-line overrides (`--allow`, `--ask`, `--exclude`) -2. Permission configuration from `permissions.yaml` +2. Permission configuration from `permissions.yaml` 3. Default tool policies ### Mode-Specific Behaviors + - **normal**: No mode policies applied, uses existing user configuration; shows current directory - **plan**: **Absolute override** - excludes all write tools (Write, Edit, Bash), allows only read tools (Read, Grep, LS); hides current directory - **auto**: **Absolute override** - allows all tools with `*: allow` policy; hides current directory diff --git a/spec/onboarding.md b/spec/onboarding.md index 7bc9dc39d..9b3eaf22e 100644 --- a/spec/onboarding.md +++ b/spec/onboarding.md @@ -8,7 +8,6 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb 1. If the --config flag is provided, load this config 2. Otherwise, we will present the user with two options: - - Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org - Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model @@ -33,4 +32,4 @@ When something in the onboarding flow is done automatically, we should tell the 2. If the user is logged in, look for the first assistant in the selected org 3. If there are no assistants in that org, then look for a local ~/.continue/config.yaml 4. If there is no config.yaml, look for an ANTHROPIC_API_KEY in the environment and manually construct the config object to include just the claude-4-sonnet model with that API key -5. If none of the above, then bring the user to step 3 of the onboarding flow \ No newline at end of file +5. If none of the above, then bring the user to step 3 of the onboarding flow diff --git a/spec/permissions.md b/spec/permissions.md index 8ff9e1fbc..4973a3738 100644 --- a/spec/permissions.md +++ b/spec/permissions.md @@ -19,6 +19,7 @@ There is a default set of permissions for the builtin tools in [`src/permissions 5. Default policies **Note:** Mode policies **completely override all other permission settings** in plan and auto modes. Available modes: + - `normal`: No mode policies (uses existing configuration) - `plan`: **Absolute override** - excludes all write tools, allows only read tools (ignores user config) - `auto`: **Absolute override** - allows all tools without asking (ignores user config) @@ -41,7 +42,7 @@ Each of the `--allow`, `--ask`, and `--exclude` flags allow you to set the permi # Allow Read, Ask Write, and Exclude Bash cn --allow Read --ask Write --exclude Bash -# Start in plan mode (read-only tools only) +# Start in plan mode (read-only tools only) cn --readonly "Help me understand this codebase" # Use mode switching during chat @@ -101,7 +102,7 @@ To use tools that normally require confirmation in headless mode, you must expli # Headless mode with explicit permissions for write operations cn -p --allow write_file "Write a hello world script" -# Headless mode with wildcard permission (allow all tools) +# Headless mode with wildcard permission (allow all tools) cn -p --allow "*" "Write and run a script" # Headless mode with specific restrictions diff --git a/src/CLIPlatformClient.ts b/src/CLIPlatformClient.ts index e919825b2..c1650424d 100644 --- a/src/CLIPlatformClient.ts +++ b/src/CLIPlatformClient.ts @@ -14,12 +14,12 @@ import * as dotenv from "dotenv"; export class CLIPlatformClient implements PlatformClient { constructor( private orgScopeId: string | null, - private readonly apiClient: DefaultApiInterface + private readonly apiClient: DefaultApiInterface, ) {} private findSecretInEnvFile( filePath: string, - secretName: string + secretName: string, ): string | undefined { try { if (!fs.existsSync(filePath)) return undefined; @@ -31,7 +31,7 @@ export class CLIPlatformClient implements PlatformClient { console.warn( `Error reading .env file at ${filePath}: ${ error instanceof Error ? error.message : String(error) - }` + }`, ); return undefined; } @@ -70,7 +70,7 @@ export class CLIPlatformClient implements PlatformClient { } const results: (SecretResult | undefined)[] = new Array(fqsns.length).fill( - undefined + undefined, ); // Try to resolve secrets through the API client first @@ -92,7 +92,7 @@ export class CLIPlatformClient implements PlatformClient { console.warn( `Error resolving FQSNs through API: ${ error instanceof Error ? error.message : String(error) - }` + }`, ); } diff --git a/src/MCPConnection.ts b/src/MCPConnection.ts index 0baaea017..1eb9decff 100644 --- a/src/MCPConnection.ts +++ b/src/MCPConnection.ts @@ -11,14 +11,14 @@ export class MCPConnection { private constructor(public readonly client: Client) {} public static async create( - config: NonNullable[number] + config: NonNullable[number], ) { const client = new Client( { name: "continue-cli-client", version: "1.0.0", }, - { capabilities: {} } + { capabilities: {} }, ); // Construct transport @@ -39,10 +39,13 @@ export class MCPConnection { // Connect and get all prompts and tools const connection = new MCPConnection(client); - logger.debug('Connecting to MCP server', { command: config.command }); + logger.debug("Connecting to MCP server", { command: config.command }); await client.connect(transport); const capabilities = client.getServerCapabilities(); - logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools }); + logger.debug("MCP server capabilities", { + hasPrompts: !!capabilities?.prompts, + hasTools: !!capabilities?.tools, + }); if (capabilities?.prompts) { connection.prompts = (await client.listPrompts()).prompts; @@ -54,4 +57,4 @@ export class MCPConnection { return connection; } -} \ No newline at end of file +} diff --git a/src/__mocks__/args.ts b/src/__mocks__/args.ts index 1f27a96c7..b0d25ffad 100644 --- a/src/__mocks__/args.ts +++ b/src/__mocks__/args.ts @@ -1,3 +1,3 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; -export const processRule = vi.fn<(rule: string) => Promise>(); \ No newline at end of file +export const processRule = vi.fn<(rule: string) => Promise>(); diff --git a/src/__mocks__/auth/workos.ts b/src/__mocks__/auth/workos.ts index 6d42e7050..54fbfdfb7 100644 --- a/src/__mocks__/auth/workos.ts +++ b/src/__mocks__/auth/workos.ts @@ -1,5 +1,5 @@ -import { vi } from 'vitest'; -import type { AuthConfig } from '../../auth/workos.js'; +import { vi } from "vitest"; +import type { AuthConfig } from "../../auth/workos.js"; export const isAuthenticated = vi.fn(() => false); export const isAuthenticatedConfig = vi.fn(() => false); @@ -25,4 +25,4 @@ export const uriToSlug = vi.fn(() => null); export const updateConfigUri = vi.fn(); export const updateModelName = vi.fn(); export const updateAssistantSlug = vi.fn(); -export const updateLocalConfigPath = vi.fn(); \ No newline at end of file +export const updateLocalConfigPath = vi.fn(); diff --git a/src/__mocks__/config.ts b/src/__mocks__/config.ts index d5702d564..8b69b7944 100644 --- a/src/__mocks__/config.ts +++ b/src/__mocks__/config.ts @@ -1,6 +1,17 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; -export const getApiClient = vi.fn<(accessToken: string | null) => any>(() => null); -export const getLlmApi = vi.fn<(config: any, authConfig: any, modelConfig?: any, orgScopeId?: string) => [any, any]>(); +export const getApiClient = vi.fn<(accessToken: string | null) => any>( + () => null, +); +export const getLlmApi = + vi.fn< + ( + config: any, + authConfig: any, + modelConfig?: any, + orgScopeId?: string, + ) => [any, any] + >(); export const getModel = vi.fn<(config: any, modelName: string) => any>(); -export const createLlmApi = vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>(); \ No newline at end of file +export const createLlmApi = + vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>(); diff --git a/src/__mocks__/configLoader.ts b/src/__mocks__/configLoader.ts index 5d1f7c2d0..f99dedb49 100644 --- a/src/__mocks__/configLoader.ts +++ b/src/__mocks__/configLoader.ts @@ -1,3 +1,3 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; -export const loadConfiguration = vi.fn<(options: any) => Promise>(); \ No newline at end of file +export const loadConfiguration = vi.fn<(options: any) => Promise>(); diff --git a/src/__mocks__/hooks/useService.ts b/src/__mocks__/hooks/useService.ts index a0e6f3cbc..d054b7b57 100644 --- a/src/__mocks__/hooks/useService.ts +++ b/src/__mocks__/hooks/useService.ts @@ -18,4 +18,4 @@ export const useServices = vi.fn(() => ({ loading: false, error: null, allReady: true, -})); \ No newline at end of file +})); diff --git a/src/__mocks__/logging.ts b/src/__mocks__/logging.ts index 71c411ca2..19d82d21c 100644 --- a/src/__mocks__/logging.ts +++ b/src/__mocks__/logging.ts @@ -1,4 +1,4 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; export const log = vi.fn(); export const error = vi.fn(); @@ -13,4 +13,4 @@ export const loggers = { cyan: vi.fn(), white: vi.fn(), gray: vi.fn(), -}; \ No newline at end of file +}; diff --git a/src/__mocks__/permissions/permissionsYamlLoader.ts b/src/__mocks__/permissions/permissionsYamlLoader.ts index 055327546..f97702394 100644 --- a/src/__mocks__/permissions/permissionsYamlLoader.ts +++ b/src/__mocks__/permissions/permissionsYamlLoader.ts @@ -1,3 +1,3 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; -export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null); \ No newline at end of file +export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null); diff --git a/src/__mocks__/permissions/precedenceResolver.ts b/src/__mocks__/permissions/precedenceResolver.ts index 8bba6e05d..c516e935e 100644 --- a/src/__mocks__/permissions/precedenceResolver.ts +++ b/src/__mocks__/permissions/precedenceResolver.ts @@ -1,3 +1,5 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; -export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>(() => []); \ No newline at end of file +export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>( + () => [], +); diff --git a/src/__mocks__/services/ServiceContainer.ts b/src/__mocks__/services/ServiceContainer.ts index 159da7886..96032b65f 100644 --- a/src/__mocks__/services/ServiceContainer.ts +++ b/src/__mocks__/services/ServiceContainer.ts @@ -1,4 +1,4 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; export const serviceContainer = { get: vi.fn<(name: string) => any>(), @@ -6,4 +6,4 @@ export const serviceContainer = { has: vi.fn<(name: string) => boolean>(), reset: vi.fn<() => void>(), reload: vi.fn<(name: string) => Promise>(), -}; \ No newline at end of file +}; diff --git a/src/__mocks__/services/ServiceContainerContext.ts b/src/__mocks__/services/ServiceContainerContext.ts index a8a1ae7d7..3933398fb 100644 --- a/src/__mocks__/services/ServiceContainerContext.ts +++ b/src/__mocks__/services/ServiceContainerContext.ts @@ -1,6 +1,6 @@ -import React from 'react'; +import React from "react"; import { vi } from "vitest"; -import { ServiceContainer } from '../../services/ServiceContainer.js'; +import { ServiceContainer } from "../../services/ServiceContainer.js"; // Create a mock service container const mockServiceContainer = { @@ -18,8 +18,12 @@ const mockServiceContainer = { setMaxListeners: vi.fn(), } as unknown as ServiceContainer; -export const ServiceContainerProvider = ({ children }: { children: React.ReactNode }) => { +export const ServiceContainerProvider = ({ + children, +}: { + children: React.ReactNode; +}) => { return React.createElement(React.Fragment, null, children); }; -export const useServiceContainer = vi.fn(() => mockServiceContainer); \ No newline at end of file +export const useServiceContainer = vi.fn(() => mockServiceContainer); diff --git a/src/__mocks__/services/index.ts b/src/__mocks__/services/index.ts index 5587a24dc..7ea28d99b 100644 --- a/src/__mocks__/services/index.ts +++ b/src/__mocks__/services/index.ts @@ -1,4 +1,4 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; export const services = { auth: { @@ -12,9 +12,9 @@ export const services = { export const reloadService = vi.fn(() => Promise.resolve(undefined)); export const SERVICE_NAMES = { - AUTH: 'auth', - API_CLIENT: 'apiClient', - CONFIG: 'config', - MODEL: 'model', - MCP: 'mcp', -}; \ No newline at end of file + AUTH: "auth", + API_CLIENT: "apiClient", + CONFIG: "config", + MODEL: "model", + MCP: "mcp", +}; diff --git a/src/__mocks__/util/logger.ts b/src/__mocks__/util/logger.ts index fe69f919d..90c184456 100644 --- a/src/__mocks__/util/logger.ts +++ b/src/__mocks__/util/logger.ts @@ -1,4 +1,4 @@ -import { vi } from 'vitest'; +import { vi } from "vitest"; const mockLogger: any = { debug: vi.fn(), @@ -10,4 +10,4 @@ const mockLogger: any = { export default mockLogger; export const getLogPath = vi.fn(() => "/mock/log/path"); -export const getSessionId = vi.fn(() => "mock-session-id"); \ No newline at end of file +export const getSessionId = vi.fn(() => "mock-session-id"); diff --git a/src/args.ts b/src/args.ts index 67b4491ec..1d46ee40f 100644 --- a/src/args.ts +++ b/src/args.ts @@ -12,7 +12,7 @@ export interface CommandLineArgs { resume?: boolean; // Resume from last session readonly?: boolean; // Start in plan mode (backward compatibility) rules?: string[]; // Array of rule specifications - format?: 'json'; // Output format for headless mode + format?: "json"; // Output format for headless mode } /** @@ -41,14 +41,14 @@ async function loadRuleFromHub(slug: string): Promise { const parts = slug.split("/"); if (parts.length !== 2) { throw new Error( - `Invalid hub slug format. Expected "owner/package", got: ${slug}` + `Invalid hub slug format. Expected "owner/package", got: ${slug}`, ); } const [ownerSlug, ruleSlug] = parts; const downloadUrl = new URL( `v0/${ownerSlug}/${ruleSlug}/latest/download`, - env.apiBase + env.apiBase, ); try { @@ -65,7 +65,8 @@ async function loadRuleFromHub(slug: string): Promise { // Find the first .md or .txt file (rule content) const ruleFiles = Object.keys(zipContents.files).filter( - (filename) => filename.endsWith(".md") && !zipContents.files[filename].dir + (filename) => + filename.endsWith(".md") && !zipContents.files[filename].dir, ); if (ruleFiles.length === 0) { @@ -128,13 +129,12 @@ export function parseArgs(): CommandLineArgs { result.readonly = true; } - // Get format from --format flag const formatIndex = args.indexOf("--format"); if (formatIndex !== -1 && formatIndex + 1 < args.length) { const formatValue = args[formatIndex + 1]; - if (formatValue === 'json') { - result.format = 'json'; + if (formatValue === "json") { + result.format = "json"; } } @@ -149,7 +149,8 @@ export function parseArgs(): CommandLineArgs { if (orgIndex !== -1 && orgIndex + 1 < args.length) { const orgValue = args[orgIndex + 1]; // Convert "personal" to undefined right away to simplify downstream logic - result.organizationSlug = orgValue.toLowerCase() === "personal" ? undefined : orgValue; + result.organizationSlug = + orgValue.toLowerCase() === "personal" ? undefined : orgValue; } // Get rules from --rule flags (can be specified multiple times) diff --git a/src/auth/ensureAuth.ts b/src/auth/ensureAuth.ts index 8ee8e4402..f3f6636bc 100644 --- a/src/auth/ensureAuth.ts +++ b/src/auth/ensureAuth.ts @@ -7,7 +7,7 @@ import { isAuthenticated, login } from "./workos.js"; * Returns true if authentication is successful, false otherwise */ export async function ensureAuthenticated( - requireAuth: boolean = true + requireAuth: boolean = true, ): Promise { if (isAuthenticated()) { return true; diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 502c6dbcf..b53bc0b70 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -50,7 +50,7 @@ export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null; * Type guard to check if config is authenticated via file-based auth */ export function isAuthenticatedConfig( - config: AuthConfig + config: AuthConfig, ): config is AuthenticatedConfig { return config !== null && "userId" in config; } @@ -59,7 +59,7 @@ export function isAuthenticatedConfig( * Type guard to check if config is authenticated via environment variable */ export function isEnvironmentAuthConfig( - config: AuthConfig + config: AuthConfig, ): config is EnvironmentAuthConfig { return config !== null && !("userId" in config); } @@ -313,7 +313,7 @@ async function requestDeviceAuthorization(): Promise { const startTime = Date.now(); const expirationTime = startTime + expiresIn * 1000; @@ -361,7 +361,7 @@ async function pollForDeviceToken( method: "POST", headers, body: params, - } + }, ); if (response.ok) { @@ -392,21 +392,21 @@ async function pollForDeviceToken( // Log response details for debugging if (response.status === 401) { throw new Error( - "Oops! We had trouble authenticating. Please try again and reach out if the error persists." + "Oops! We had trouble authenticating. Please try again and reach out if the error persists.", ); } if (errorCode === "authorization_pending") { // Continue polling await new Promise((resolve) => - setTimeout(resolve, currentInterval * 1000) + setTimeout(resolve, currentInterval * 1000), ); continue; } else if (errorCode === "slow_down") { // Increase polling interval currentInterval += 5; await new Promise((resolve) => - setTimeout(resolve, currentInterval * 1000) + setTimeout(resolve, currentInterval * 1000), ); continue; } else if (errorCode === "access_denied") { @@ -430,7 +430,7 @@ async function pollForDeviceToken( * Refreshes the access token using a refresh token */ async function refreshToken( - refreshToken: string + refreshToken: string, ): Promise { try { // Load existing config to preserve organizationId and other fields @@ -493,7 +493,7 @@ export async function login(): Promise { // If CONTINUE_API_KEY environment variable exists, use that instead if (process.env.CONTINUE_API_KEY) { console.info( - chalk.green("Using CONTINUE_API_KEY from environment variables") + chalk.green("Using CONTINUE_API_KEY from environment variables"), ); return { accessToken: process.env.CONTINUE_API_KEY, @@ -507,12 +507,14 @@ export async function login(): Promise { const deviceAuth = await requestDeviceAuthorization(); console.info( - chalk.white(`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`) + chalk.white( + `Your authentication code: ${chalk.bold(deviceAuth.user_code)}`, + ), ); console.info( chalk.dim( - `If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}` - ) + `If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`, + ), ); // Try to open the complete verification URL in browser @@ -528,7 +530,7 @@ export async function login(): Promise { const authConfig = await pollForDeviceToken( deviceAuth.device_code, deviceAuth.interval, - deviceAuth.expires_in + deviceAuth.expires_in, ); console.info(chalk.white("✅ Success!")); @@ -541,14 +543,14 @@ export async function login(): Promise { */ async function resolveOrganizationBySlug( apiClient: ReturnType, - organizationSlug: string + organizationSlug: string, ): Promise<{ id: string; slug: string }> { const resp = await apiClient.listOrganizations(); const organizations = resp.organizations; // Find organization by slug (case-insensitive) const matchedOrg = organizations.find( - (org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase() + (org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase(), ); if (matchedOrg) { @@ -561,7 +563,7 @@ async function resolveOrganizationBySlug( const availableOptions = ["personal", ...availableSlugs]; console.info( chalk.yellow("Available organizations:"), - availableOptions.join(", ") + availableOptions.join(", "), ); throw new Error(`Organization "${organizationSlug}" not found`); @@ -574,7 +576,7 @@ async function resolveOrganizationBySlug( export async function ensureOrganization( authConfig: AuthConfig, isHeadless: boolean = false, - cliOrganizationSlug?: string + cliOrganizationSlug?: string, ): Promise { // Handle CLI organization slug if provided (undefined means no --org flag or --org personal) if (cliOrganizationSlug) { @@ -582,8 +584,8 @@ export async function ensureOrganization( if (!isHeadless) { console.error( chalk.red( - "The --org flag is only supported in headless mode (with -p/--print flag)" - ) + "The --org flag is only supported in headless mode (with -p/--print flag)", + ), ); process.exit(1); } @@ -594,7 +596,7 @@ export async function ensureOrganization( const resolvedOrg = await resolveOrganizationBySlug( apiClient, - cliOrganizationSlug + cliOrganizationSlug, ); // Return modified environment auth config with organization ID @@ -622,7 +624,7 @@ export async function ensureOrganization( const resolvedOrg = await resolveOrganizationBySlug( apiClient, - cliOrganizationSlug + cliOrganizationSlug, ); const updatedConfig: AuthenticatedConfig = { @@ -696,7 +698,7 @@ export async function ensureOrganization( } catch (error: any) { console.error( chalk.red("Error fetching organizations:"), - error.response?.data?.message || error.message || error + error.response?.data?.message || error.message || error, ); console.info(chalk.yellow("Continuing without organization selection.")); const updatedConfig: AuthenticatedConfig = { @@ -764,7 +766,7 @@ export function logout(): void { const onboardingFlagPath = path.join( os.homedir(), ".continue", - ".onboarding_complete" + ".onboarding_complete", ); // Remove onboarding completion flag so user will go through onboarding again @@ -775,8 +777,8 @@ export function logout(): void { if (process.env.CONTINUE_API_KEY) { console.info( chalk.yellow( - "Using CONTINUE_API_KEY from environment variables, nothing to log out" - ) + "Using CONTINUE_API_KEY from environment variables, nothing to log out", + ), ); return; } diff --git a/src/commands/BaseCommandOptions.ts b/src/commands/BaseCommandOptions.ts index 5ecde6886..46a5d84d5 100644 --- a/src/commands/BaseCommandOptions.ts +++ b/src/commands/BaseCommandOptions.ts @@ -24,4 +24,4 @@ export interface ExtendedCommandOptions extends BaseCommandOptions { readonly?: boolean; /** Start in auto mode (all tools allowed) */ auto?: boolean; -} \ No newline at end of file +} diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 65233401f..84a7801e9 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -86,7 +86,7 @@ export interface ChatOptions extends ExtendedCommandOptions { } export async function initializeChatHistory( - options: ChatOptions + options: ChatOptions, ): Promise { let chatHistory: ChatCompletionMessageParam[] = []; @@ -108,7 +108,7 @@ export async function initializeChatHistory( rulesSystemMessage, options.rule, options.format, - options.headless + options.headless, ); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); @@ -126,7 +126,7 @@ async function processMessage( isHeadless: boolean, format?: "json", silent?: boolean, - compactionIndex?: number | null + compactionIndex?: number | null, ): Promise<{ compactionIndex?: number | null } | void> { // Check for slash commands in headless mode if (userInput.trim() === "/compact") { @@ -152,7 +152,7 @@ async function processMessage( status: "success", message: "Chat history compacted", historyLength: chatHistory.length, - }) + "\n" + }) + "\n", ); } @@ -163,7 +163,7 @@ async function processMessage( console.error(chalk.red(errorMsg)); } else { safeStdout( - JSON.stringify({ status: "error", message: errorMsg }) + "\n" + JSON.stringify({ status: "error", message: errorMsg }) + "\n", ); } return; @@ -180,8 +180,8 @@ async function processMessage( if (!isHeadless) { console.info( chalk.yellow( - "\nApproaching context limit. Auto-compacting chat history..." - ) + "\nApproaching context limit. Auto-compacting chat history...", + ), ); } else if (format === "json") { safeStdout( @@ -191,9 +191,9 @@ async function processMessage( contextUsage: calculateContextUsagePercentage( countChatHistoryTokens(chatHistory), - model + model, ) + "%", - }) + "\n" + }) + "\n", ); } @@ -210,7 +210,7 @@ async function processMessage( if (!isHeadless) { console.info( - chalk.green("✓ Chat history auto-compacted successfully.") + chalk.green("✓ Chat history auto-compacted successfully."), ); } else if (format === "json") { safeStdout( @@ -218,7 +218,7 @@ async function processMessage( status: "success", message: "Auto-compacted successfully", historyLength: chatHistory.length, - }) + "\n" + }) + "\n", ); } @@ -236,7 +236,7 @@ async function processMessage( JSON.stringify({ status: "warning", message: "Auto-compaction failed, continuing without compaction", - }) + "\n" + }) + "\n", ); } @@ -266,7 +266,7 @@ async function processMessage( historyForLLM, model, llmApi, - abortController + abortController, ); // Append any new messages (assistant/tool) that were added by streamChatResponse @@ -278,7 +278,7 @@ async function processMessage( chatHistory, model, llmApi, - abortController + abortController, ); } @@ -312,7 +312,7 @@ async function processMessage( }); if (!isHeadless) { logger.info( - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) + chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`), ); } } @@ -320,7 +320,7 @@ async function processMessage( async function runHeadlessMode( prompt: string | undefined, - options: ChatOptions + options: ChatOptions, ): Promise { // Initialize services for headless mode const { permissionOverrides } = processCommandFlags(options); @@ -335,7 +335,7 @@ async function runHeadlessMode( // Get required services from the service container const modelState = await serviceContainer.get( - SERVICE_NAMES.MODEL + SERVICE_NAMES.MODEL, ); const { llmApi, model } = modelState; @@ -375,7 +375,7 @@ async function runHeadlessMode( true, options.format, options.silent, - compactionIndex + compactionIndex, ); // Update compaction index if compaction occurred @@ -430,7 +430,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { options.org, options.rule, permissionOverrides, - true + true, ); return; } diff --git a/src/commands/commands.ts b/src/commands/commands.ts index 2342bb751..c7171862e 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -78,7 +78,7 @@ export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [ */ export function getAllSlashCommands( assistant: AssistantConfig, - options: { isRemoteMode?: boolean } = {} + options: { isRemoteMode?: boolean } = {}, ): SlashCommand[] { const { isRemoteMode = false } = options; @@ -105,7 +105,7 @@ export function getAllSlashCommands( * Get assistant prompt commands only */ export function getAssistantSlashCommands( - assistant: AssistantConfig + assistant: AssistantConfig, ): SlashCommand[] { return ( assistant?.prompts?.map((prompt) => ({ diff --git a/src/commands/remote-test.ts b/src/commands/remote-test.ts index 7738b0f8e..e3404c86f 100644 --- a/src/commands/remote-test.ts +++ b/src/commands/remote-test.ts @@ -6,7 +6,7 @@ import { logger } from "../util/logger.js"; export async function remoteTest( prompt?: string, - url: string = "http://localhost:8000" + url: string = "http://localhost:8000", ) { console.info(chalk.white(`Connecting to remote environment at ${url}...`)); @@ -23,7 +23,7 @@ export async function remoteTest( } } catch (error: any) { logger.error( - chalk.red(`Failed to connect to remote environment: ${error.message}`) + chalk.red(`Failed to connect to remote environment: ${error.message}`), ); process.exit(1); } diff --git a/src/commands/remote.ts b/src/commands/remote.ts index 8f4f42c3d..9a966ff2e 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -12,12 +12,12 @@ import { logger } from "../util/logger.js"; export async function remote( prompt: string | undefined, - options: { url?: string } = {} + options: { url?: string } = {}, ) { // If --url is provided, connect directly to that URL if (options.url) { console.info( - chalk.white(`Connecting to remote environment at: ${options.url}`) + chalk.white(`Connecting to remote environment at: ${options.url}`), ); // Record session start @@ -40,7 +40,7 @@ export async function remote( if (!isAuthenticatedConfig(authConfig)) { console.error( - chalk.red("Not authenticated. Please run 'cn login' first.") + chalk.red("Not authenticated. Please run 'cn login' first."), ); process.exit(1); } @@ -64,20 +64,20 @@ export async function remote( if (!response.ok) { const errorText = await response.text(); throw new Error( - `Failed to create remote environment: ${response.status} ${errorText}` + `Failed to create remote environment: ${response.status} ${errorText}`, ); } const result = await response.json(); console.info( - chalk.green("✅ Remote development environment created successfully!") + chalk.green("✅ Remote development environment created successfully!"), ); if (result.url && result.port) { const remoteUrl = result.url; console.info( - chalk.white(`Connecting to remote environment at: ${remoteUrl}`) + chalk.white(`Connecting to remote environment at: ${remoteUrl}`), ); // Record session start @@ -92,12 +92,12 @@ export async function remote( } } else { throw new Error( - "No URL or port returned from remote environment creation" + "No URL or port returned from remote environment creation", ); } } catch (error: any) { logger.error( - chalk.red(`Failed to create remote environment: ${error.message}`) + chalk.red(`Failed to create remote environment: ${error.message}`), ); process.exit(1); } diff --git a/src/commands/serve.ts b/src/commands/serve.ts index e91d8a2ab..6cf428e22 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -6,7 +6,6 @@ import chalk from "chalk"; import express, { Request, Response } from "express"; import type { ChatCompletionMessageParam } from "openai/resources.mjs"; - import { getAssistantSlug } from "../auth/workos.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; @@ -112,8 +111,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { chalk.dim( ` Assistant: ${assistantName}${ assistantSlug ? ` (${assistantSlug})` : "" - }` - ) + }`, + ), ); console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`)); if (options.config) { @@ -122,7 +121,12 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Initialize chat history const chatHistory: ChatCompletionMessageParam[] = []; - const systemMessage = await constructSystemMessage("", options.rule, undefined, true); + const systemMessage = await constructSystemMessage( + "", + options.rule, + undefined, + true, + ); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } @@ -267,7 +271,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // POST /exit - Gracefully shut down the server app.post("/exit", async (_req: Request, res: Response) => { console.log( - chalk.yellow("\nReceived exit request, shutting down server...") + chalk.yellow("\nReceived exit request, shutting down server..."), ); // Respond immediately before shutting down @@ -308,24 +312,24 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { console.log(chalk.dim(" GET /state - Get current agent state")); console.log( chalk.dim( - " POST /message - Send a message (body: { message: string })" - ) + " POST /message - Send a message (body: { message: string })", + ), ); console.log( chalk.dim( - " POST /permission - Approve/reject tool (body: { requestId, approved })" - ) + " POST /permission - Approve/reject tool (body: { requestId, approved })", + ), ); console.log( - chalk.dim(" GET /diff - Get git diff against main branch") + chalk.dim(" GET /diff - Get git diff against main branch"), ); console.log( - chalk.dim(" POST /exit - Gracefully shut down the server") + chalk.dim(" POST /exit - Gracefully shut down the server"), ); console.log( chalk.dim( - `\nServer will shut down after ${timeoutSeconds} seconds of inactivity` - ) + `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`, + ), ); // If initial prompt provided, queue it for processing @@ -357,7 +361,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { state, llmApi, state.currentAbortController, - () => state.shouldInterrupt + () => state.shouldInterrupt, ); // Save session after successful response @@ -407,8 +411,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) { console.log( chalk.yellow( - `\nShutting down due to ${timeoutSeconds} seconds of inactivity` - ) + `\nShutting down due to ${timeoutSeconds} seconds of inactivity`, + ), ); state.serverRunning = false; server.close(() => { @@ -442,7 +446,7 @@ async function streamChatResponseWithInterruption( state: ServerState, llmApi: any, abortController: AbortController, - shouldInterrupt: () => boolean + shouldInterrupt: () => boolean, ): Promise { // Import the original streamChatResponse logic but add interruption checks // Create a wrapper that checks for interruption @@ -557,7 +561,7 @@ async function streamChatResponseWithInterruption( onToolPermissionRequest: ( toolName: string, toolArgs: any, - requestId: string + requestId: string, ) => { // Set pending permission state state.pendingPermission = { @@ -585,7 +589,7 @@ async function streamChatResponseWithInterruption( state.model, llmApi, abortController, - callbacks + callbacks, ); return response || ""; } finally { diff --git a/src/compaction.ts b/src/compaction.ts index 484866476..1034644b3 100644 --- a/src/compaction.ts +++ b/src/compaction.ts @@ -31,7 +31,7 @@ export async function compactChatHistory( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, llmApi: BaseLlmApi, - callbacks?: CompactionCallbacks + callbacks?: CompactionCallbacks, ): Promise { // Create a prompt to summarize the conversation const compactionPrompt: ChatCompletionMessageParam = { @@ -63,7 +63,7 @@ export async function compactChatHistory( model, llmApi, controller, - streamCallbacks + streamCallbacks, ); // Create the compacted history with a special marker @@ -103,13 +103,13 @@ export async function compactChatHistory( * @returns The index of the compaction message, or null if not found */ export function findCompactionIndex( - chatHistory: ChatCompletionMessageParam[] + chatHistory: ChatCompletionMessageParam[], ): number | null { const compactedIndex = chatHistory.findIndex( (msg) => msg.role === "assistant" && typeof msg.content === "string" && - msg.content.startsWith(COMPACTION_MARKER) + msg.content.startsWith(COMPACTION_MARKER), ); return compactedIndex !== -1 ? compactedIndex : null; } @@ -122,7 +122,7 @@ export function findCompactionIndex( */ export function getHistoryForLLM( fullHistory: ChatCompletionMessageParam[], - compactionIndex: number | null + compactionIndex: number | null, ): ChatCompletionMessageParam[] { if (compactionIndex === null || compactionIndex >= fullHistory.length) { return fullHistory; diff --git a/src/config.ts b/src/config.ts index 86b8dd8e8..4654557de 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,8 +1,4 @@ - -import { - AssistantUnrolled, - ModelConfig, -} from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi, constructLlmApi, @@ -25,16 +21,16 @@ import { MCPService } from "./mcp.js"; export function getLlmApi( assistant: AssistantUnrolled, - authConfig: AuthConfig + authConfig: AuthConfig, ): [BaseLlmApi, ModelConfig] { const model = assistant.models?.find( (model) => - model?.roles?.includes("chat") || (model && model.roles === undefined) + model?.roles?.includes("chat") || (model && model.roles === undefined), ); if (!model) { throw new Error( - "No models with the chat role found in the configured assistant" + "No models with the chat role found in the configured assistant", ); } @@ -67,7 +63,7 @@ export function getLlmApi( if (!llmApi) { throw new Error( - "Failed to initialize LLM. Please check your configuration." + "Failed to initialize LLM. Please check your configuration.", ); } @@ -75,19 +71,19 @@ export function getLlmApi( } export function getApiClient( - accessToken: string | undefined | null + accessToken: string | undefined | null, ): DefaultApi { return new DefaultApi( new Configuration({ basePath: env.apiBase.replace(/\/$/, ""), accessToken: accessToken ?? undefined, - }) + }), ); } export async function initialize( authConfig: AuthConfig, - configPath: string | undefined + configPath: string | undefined, ): Promise<{ config: AssistantUnrolled; llmApi: BaseLlmApi; diff --git a/src/configLoader.ts b/src/configLoader.ts index 8484de0fe..310e635de 100644 --- a/src/configLoader.ts +++ b/src/configLoader.ts @@ -29,7 +29,7 @@ export interface ConfigLoadResult { source: ConfigSource; } -export type ConfigSource = +export type ConfigSource = | { type: "cli-flag"; path: string } | { type: "saved-uri"; uri: string } | { type: "user-assistant"; slug: string } @@ -43,17 +43,22 @@ export type ConfigSource = export async function loadConfiguration( authConfig: AuthConfig, cliConfigPath: string | undefined, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const organizationId = getOrganizationId(authConfig); const accessToken = getAccessToken(authConfig); // Step 1: Determine config source using precedence rules const configSource = determineConfigSource(authConfig, cliConfigPath); - + // Step 2: Load configuration from the determined source - const config = await loadFromSource(configSource, accessToken, organizationId, apiClient); - + const config = await loadFromSource( + configSource, + accessToken, + organizationId, + apiClient, + ); + // Step 3: Save config URI for session continuity (only for file-based auth) if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { const uri = getUriFromSource(configSource); @@ -73,7 +78,7 @@ export async function loadConfiguration( */ function determineConfigSource( authConfig: AuthConfig, - cliConfigPath: string | undefined + cliConfigPath: string | undefined, ): ConfigSource { // Priority 1: CLI --config flag if (cliConfigPath) { @@ -94,7 +99,11 @@ function determineConfigSource( return { type: "user-assistant", slug: "" }; // Empty slug means "first available" } else { // Unauthenticated: check for default config.yaml, then fallback to default agent - const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml"); + const defaultConfigPath = path.join( + os.homedir(), + ".continue", + "config.yaml", + ); if (fs.existsSync(defaultConfigPath)) { return { type: "default-config-yaml" }; } @@ -109,32 +118,50 @@ async function loadFromSource( source: ConfigSource, accessToken: string | null, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { try { switch (source.type) { case "cli-flag": - return await loadFromCliFlag(source.path, accessToken, organizationId, apiClient); - + return await loadFromCliFlag( + source.path, + accessToken, + organizationId, + apiClient, + ); + case "saved-uri": - return await loadFromSavedUri(source.uri, accessToken, organizationId, apiClient); - + return await loadFromSavedUri( + source.uri, + accessToken, + organizationId, + apiClient, + ); + case "user-assistant": return await loadUserAssistantWithFallback(organizationId, apiClient); - + case "default-config-yaml": - return await loadDefaultConfigYaml(accessToken, organizationId, apiClient); - + return await loadDefaultConfigYaml( + accessToken, + organizationId, + apiClient, + ); + case "default-agent": return await loadDefaultAgent(organizationId, apiClient); - + default: throw new Error(`Unknown config source type: ${(source as any).type}`); } } catch (error) { // If we're trying user assistants and it fails, fall back to default agent if (source.type === "user-assistant") { - console.warn(chalk.yellow("Failed to load user assistants, falling back to default agent")); + console.warn( + chalk.yellow( + "Failed to load user assistants, falling back to default agent", + ), + ); return await loadDefaultAgent(organizationId, apiClient); } throw error; @@ -149,11 +176,16 @@ async function loadFromCliFlag( configPath: string, accessToken: string | null, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { if (isFilePath(configPath)) { // Load local YAML file - return await loadConfigYaml(configPath, accessToken, organizationId, apiClient); + return await loadConfigYaml( + configPath, + accessToken, + organizationId, + apiClient, + ); } else { // Load assistant slug return await loadAssistantSlug(configPath, organizationId, apiClient); @@ -167,18 +199,23 @@ async function loadFromSavedUri( uri: string, accessToken: string | null, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const filePath = uriToPath(uri); if (filePath) { - return await loadConfigYaml(filePath, accessToken, organizationId, apiClient); + return await loadConfigYaml( + filePath, + accessToken, + organizationId, + apiClient, + ); } - + const slug = uriToSlug(uri); if (slug) { return await loadAssistantSlug(slug, organizationId, apiClient); } - + throw new Error(`Invalid saved config URI: ${uri}`); } @@ -187,7 +224,7 @@ async function loadFromSavedUri( */ async function loadUserAssistantWithFallback( organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const assistants = await apiClient.listAssistants({ alwaysUseProxy: "false", @@ -212,10 +249,15 @@ async function loadUserAssistantWithFallback( async function loadDefaultConfigYaml( accessToken: string | null, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml"); - return await loadConfigYaml(defaultConfigPath, accessToken, organizationId, apiClient); + return await loadConfigYaml( + defaultConfigPath, + accessToken, + organizationId, + apiClient, + ); } /** @@ -223,7 +265,7 @@ async function loadDefaultConfigYaml( */ async function loadDefaultAgent( organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const resp = await apiClient.getAssistant({ ownerSlug: "continuedev", @@ -234,7 +276,7 @@ async function loadDefaultAgent( if (!resp.configResult.config) { throw new Error("Failed to load default agent."); } - + return resp.configResult.config as AssistantUnrolled; } @@ -245,7 +287,7 @@ async function loadConfigYaml( filePath: string, accessToken: string | null, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const unrollResult = await unrollAssistant( { filePath, uriType: "file" }, @@ -261,7 +303,7 @@ async function loadConfigYaml( renderSecrets: true, platformClient: new CLIPlatformClient(organizationId, apiClient), onPremProxyUrl: null, - } + }, ); const errorDetails = unrollResult.errors; @@ -284,11 +326,13 @@ async function loadConfigYaml( async function loadAssistantSlug( slug: string, organizationId: string | null, - apiClient: DefaultApiInterface + apiClient: DefaultApiInterface, ): Promise { const [ownerSlug, packageSlug] = slug.split("/"); if (!ownerSlug || !packageSlug) { - throw new Error(`Invalid assistant slug format. Expected "owner/package", got: ${slug}`); + throw new Error( + `Invalid assistant slug format. Expected "owner/package", got: ${slug}`, + ); } const resp = await apiClient.getAssistant({ @@ -331,8 +375,8 @@ function isFilePath(configPath: string): boolean { function getUriFromSource(source: ConfigSource): string | null { switch (source.type) { case "cli-flag": - return isFilePath(source.path) - ? `file://${source.path}` + return isFilePath(source.path) + ? `file://${source.path}` : `slug://${source.path}`; case "saved-uri": return source.uri; @@ -341,4 +385,4 @@ function getUriFromSource(source: ConfigSource): string | null { default: return null; } -} \ No newline at end of file +} diff --git a/src/continueSDK.ts b/src/continueSDK.ts index 2867176dd..8f18420dd 100644 --- a/src/continueSDK.ts +++ b/src/continueSDK.ts @@ -13,7 +13,7 @@ import { env } from "./env.js"; export async function initializeContinueSDK( apiKey: string | undefined, assistantSlug: string, - organizationId?: string + organizationId?: string, ): Promise { if (!apiKey) { console.error(chalk.red("Error: No API key provided for Continue SDK")); @@ -30,7 +30,7 @@ export async function initializeContinueSDK( } catch (error) { console.error( chalk.red("Error initializing Continue SDK:"), - error instanceof Error ? error.message : String(error) + error instanceof Error ? error.message : String(error), ); throw error; } diff --git a/src/e2e/spec.md b/src/e2e/spec.md index 8267d24bd..4a1c219e3 100644 --- a/src/e2e/spec.md +++ b/src/e2e/spec.md @@ -21,20 +21,20 @@ A typical E2E test follows this structure: ```typescript describe("E2E: Feature", () => { let context: any; - + beforeEach(async () => { context = await createTestContext(); }); - + afterEach(async () => { await cleanupTestContext(context); }); - + it("should do something", async () => { const result = await runCLI(context, { args: ["command", "--flag"], }); - + expect(result.exitCode).toBe(0); expect(result.stdout).toContain("Expected output"); }); @@ -78,9 +78,10 @@ const result = await runCLI(context, { ```typescript // For complex interactive flows -const result = await withInteractiveInput(context, - ["chat"], - ["First input", "Second input"] +const result = await withInteractiveInput( + context, + ["chat"], + ["First input", "Second input"], ); ``` @@ -120,7 +121,7 @@ it("should get response from mock LLM", async () => { const result = await runCLI(context, { args: ["-p", "--config", context.configPath, "Hi"], }); - + expect(result.stdout).toContain("Hello World!"); }); ``` @@ -128,15 +129,16 @@ it("should get response from mock LLM", async () => { ### Advanced Mock LLM Features - **Dynamic responses** based on prompts: + ```typescript mockServer = await setupMockLLMTest(context, { - response: (prompt) => prompt.includes("weather") - ? "It's sunny!" - : "I don't know", + response: (prompt) => + prompt.includes("weather") ? "It's sunny!" : "I don't know", }); ``` - **Non-streaming responses**: + ```typescript mockServer = await setupMockLLMTest(context, { response: "All at once response", @@ -166,7 +168,7 @@ const configPath = await createTestConfig(context, { // Create a mock session await createMockSession(context, [ { role: "user", content: "Hello" }, - { role: "assistant", content: "Hi there!" } + { role: "assistant", content: "Hi there!" }, ]); // Read the session @@ -199,7 +201,7 @@ const result = await runCLI(context, { const result = await withInteractiveInput( context, ["chat"], - ["User input", "/exit"] + ["User input", "/exit"], ); ``` @@ -216,4 +218,4 @@ const result = await runCLI(context, { - Set longer timeouts for complex tests: `}, 30000);` (30 seconds) - Examine the full output: `console.log(result.stdout, result.stderr)` - Check the test directory: `console.log(context.testDir)` -- For intermittent failures, try running the test in isolation \ No newline at end of file +- For intermittent failures, try running the test in isolation diff --git a/src/fileTools.ts b/src/fileTools.ts index 1e7b2c30a..f4401c751 100644 --- a/src/fileTools.ts +++ b/src/fileTools.ts @@ -100,4 +100,4 @@ export function listFiles(dirPath: string): ToolResult { error: error instanceof Error ? error.message : String(error), }; } -} \ No newline at end of file +} diff --git a/src/flags/flagProcessor.ts b/src/flags/flagProcessor.ts index be6bf1394..5a0236934 100644 --- a/src/flags/flagProcessor.ts +++ b/src/flags/flagProcessor.ts @@ -20,19 +20,22 @@ export interface ProcessedFlags { * Converts legacy readonly/auto flags to the new mode system * This logic was previously duplicated in chat.ts lines 168-173 and 259-264 */ -export function convertLegacyModeFlags(readonly?: boolean, auto?: boolean): PermissionMode | undefined { +export function convertLegacyModeFlags( + readonly?: boolean, + auto?: boolean, +): PermissionMode | undefined { if (readonly && auto) { throw new Error("Cannot use both --readonly and --auto flags together"); } - + if (readonly) { return "plan"; } - + if (auto) { return "auto"; } - + return undefined; } @@ -44,7 +47,7 @@ export function buildPermissionOverrides( allow?: string[], ask?: string[], exclude?: string[], - mode?: PermissionMode + mode?: PermissionMode, ): PermissionOverrides { return { allow, @@ -67,17 +70,17 @@ export function processCommandFlags(options: { }): ProcessedFlags { // Convert legacy flags to mode const mode = convertLegacyModeFlags(options.readonly, options.auto); - + // Build permission overrides const permissionOverrides = buildPermissionOverrides( options.allow, options.ask, options.exclude, - mode + mode, ); - + return { mode, permissionOverrides, }; -} \ No newline at end of file +} diff --git a/src/flags/flagValidator.ts b/src/flags/flagValidator.ts index 19e8f6e14..37dbe9769 100644 --- a/src/flags/flagValidator.ts +++ b/src/flags/flagValidator.ts @@ -8,17 +8,17 @@ export interface ValidationOptions { print?: boolean; format?: string; silent?: boolean; - + // Common flags readonly?: boolean; auto?: boolean; config?: string; - + // Permission flags allow?: string[]; ask?: string[]; exclude?: string[]; - + // Command context isRootCommand?: boolean; commandName?: string; @@ -39,14 +39,14 @@ export interface ValidationResult { */ function validateFormatFlag(options: ValidationOptions): ValidationError[] { const errors: ValidationError[] = []; - + if (options.format && !options.print) { errors.push({ - code: 'FORMAT_REQUIRES_PRINT', - message: 'Error: --format flag can only be used with -p/--print flag' + code: "FORMAT_REQUIRES_PRINT", + message: "Error: --format flag can only be used with -p/--print flag", }); } - + return errors; } @@ -55,14 +55,14 @@ function validateFormatFlag(options: ValidationOptions): ValidationError[] { */ function validateSilentFlag(options: ValidationOptions): ValidationError[] { const errors: ValidationError[] = []; - + if (options.silent && !options.print) { errors.push({ - code: 'SILENT_REQUIRES_PRINT', - message: 'Error: --silent flag can only be used with -p/--print flag' + code: "SILENT_REQUIRES_PRINT", + message: "Error: --silent flag can only be used with -p/--print flag", }); } - + return errors; } @@ -71,14 +71,14 @@ function validateSilentFlag(options: ValidationOptions): ValidationError[] { */ function validateFormatValue(options: ValidationOptions): ValidationError[] { const errors: ValidationError[] = []; - - if (options.format && options.format !== 'json') { + + if (options.format && options.format !== "json") { errors.push({ - code: 'INVALID_FORMAT_VALUE', - message: "Error: --format currently only supports 'json'" + code: "INVALID_FORMAT_VALUE", + message: "Error: --format currently only supports 'json'", }); } - + return errors; } @@ -88,14 +88,14 @@ function validateFormatValue(options: ValidationOptions): ValidationError[] { */ function validateModeFlags(options: ValidationOptions): ValidationError[] { const errors: ValidationError[] = []; - + if (options.readonly && options.auto) { errors.push({ - code: 'CONFLICTING_MODE_FLAGS', - message: 'Error: Cannot use both --readonly and --auto flags together' + code: "CONFLICTING_MODE_FLAGS", + message: "Error: Cannot use both --readonly and --auto flags together", }); } - + return errors; } @@ -104,47 +104,49 @@ function validateModeFlags(options: ValidationOptions): ValidationError[] { */ function validateConfigPath(options: ValidationOptions): ValidationError[] { const errors: ValidationError[] = []; - + // Note: We don't check file existence here since the config loader handles that // and provides better error messages. This is just for basic validation. - if (options.config && typeof options.config !== 'string') { + if (options.config && typeof options.config !== "string") { errors.push({ - code: 'INVALID_CONFIG_PATH', - message: 'Error: --config must be a valid path' + code: "INVALID_CONFIG_PATH", + message: "Error: --config must be a valid path", }); } - + return errors; } /** * Validate permission flag combinations */ -function validatePermissionFlags(options: ValidationOptions): ValidationError[] { +function validatePermissionFlags( + options: ValidationOptions, +): ValidationError[] { const errors: ValidationError[] = []; - + // Check for empty permission arrays (likely user error) - if (options.allow?.some(tool => !tool.trim())) { + if (options.allow?.some((tool) => !tool.trim())) { errors.push({ - code: 'EMPTY_ALLOW_TOOL', - message: 'Error: --allow requires a tool name (e.g., --allow readFile)' + code: "EMPTY_ALLOW_TOOL", + message: "Error: --allow requires a tool name (e.g., --allow readFile)", }); } - - if (options.ask?.some(tool => !tool.trim())) { + + if (options.ask?.some((tool) => !tool.trim())) { errors.push({ - code: 'EMPTY_ASK_TOOL', - message: 'Error: --ask requires a tool name (e.g., --ask writeFile)' + code: "EMPTY_ASK_TOOL", + message: "Error: --ask requires a tool name (e.g., --ask writeFile)", }); } - - if (options.exclude?.some(tool => !tool.trim())) { + + if (options.exclude?.some((tool) => !tool.trim())) { errors.push({ - code: 'EMPTY_EXCLUDE_TOOL', - message: 'Error: --exclude requires a tool name (e.g., --exclude Write)' + code: "EMPTY_EXCLUDE_TOOL", + message: "Error: --exclude requires a tool name (e.g., --exclude Write)", }); } - + return errors; } @@ -153,7 +155,7 @@ function validatePermissionFlags(options: ValidationOptions): ValidationError[] */ export function validateFlags(options: ValidationOptions): ValidationResult { const allErrors: ValidationError[] = []; - + // Run all validation functions const validators = [ validateFormatFlag, @@ -163,11 +165,11 @@ export function validateFlags(options: ValidationOptions): ValidationResult { validateConfigPath, validatePermissionFlags, ]; - + for (const validator of validators) { allErrors.push(...validator(options)); } - + return { isValid: allErrors.length === 0, errors: allErrors, @@ -182,10 +184,10 @@ export function handleValidationErrors(errors: ValidationError[]): never { for (const error of errors) { console.error(error.message); } - + if (errors.length > 1) { console.error(`\nFound ${errors.length} validation errors.`); } - + process.exit(1); -} \ No newline at end of file +} diff --git a/src/freeTrialTransition.ts b/src/freeTrialTransition.ts index 514e2f107..52ed3d08e 100644 --- a/src/freeTrialTransition.ts +++ b/src/freeTrialTransition.ts @@ -8,7 +8,10 @@ import open from "open"; import * as readlineSync from "readline-sync"; import { env } from "./env.js"; -import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js"; +import { + isValidAnthropicApiKey, + getApiKeyValidationError, +} from "./util/apiKeyValidation.js"; import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -23,10 +26,10 @@ async function createOrUpdateConfig(apiKey: string): Promise { fs.mkdirSync(configDir, { recursive: true }); } - const existingContent = fs.existsSync(CONFIG_PATH) + const existingContent = fs.existsSync(CONFIG_PATH) ? fs.readFileSync(CONFIG_PATH, "utf8") : ""; - + const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); } @@ -38,7 +41,9 @@ async function createOrUpdateConfig(apiKey: string): Promise { * 2. Provides two specific options for continuing * 3. Returns to the chat without restarting the entire CLI */ -export async function handleMaxedOutFreeTrial(onReload?: () => Promise): Promise { +export async function handleMaxedOutFreeTrial( + onReload?: () => Promise, +): Promise { // Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation console.clear(); @@ -62,16 +67,16 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P console.log(chalk.green("\n✓ Browser opened successfully!")); console.log( chalk.dim( - "After setting up your models subscription, restart the CLI to continue." - ) + "After setting up your models subscription, restart the CLI to continue.", + ), ); } catch { console.log(chalk.yellow("\n⚠ Could not open browser automatically")); console.log(chalk.white(`Please visit: ${modelsUrl}`)); console.log( chalk.dim( - "After setting up your models subscription, restart the CLI to continue." - ) + "After setting up your models subscription, restart the CLI to continue.", + ), ); } @@ -84,13 +89,11 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P chalk.white("\nEnter your Anthropic API key: "), { hideEchoBack: true, - } + }, ); if (!isValidAnthropicApiKey(apiKey)) { - console.log( - chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`) - ); + console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`)); process.exit(1); } @@ -98,7 +101,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P await createOrUpdateConfig(apiKey); console.log(chalk.green(`✓ API key saved successfully!`)); console.log(chalk.green("✓ Switching to local configuration...")); - + // If a reload callback is provided, use it instead of restarting if (onReload) { await onReload(); @@ -112,7 +115,9 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P // Fallback: restart the CLI if no reload callback was provided console.log( - chalk.green("\n🔄 Restarting Continue CLI to resume your conversation...\n") + chalk.green( + "\n🔄 Restarting Continue CLI to resume your conversation...\n", + ), ); // Get the path to the current script @@ -126,7 +131,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise): P { stdio: "inherit", detached: true, - } + }, ); // Unref the child to allow the parent process to exit diff --git a/src/hooks/useService.ts b/src/hooks/useService.ts index c78eff3c3..dcbbd57b8 100644 --- a/src/hooks/useService.ts +++ b/src/hooks/useService.ts @@ -1,7 +1,7 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState } from "react"; -import { useServiceContainer } from '../services/ServiceContainerContext.js'; -import { ServiceResult } from '../services/types.js'; +import { useServiceContainer } from "../services/ServiceContainerContext.js"; +import { ServiceResult } from "../services/types.js"; /** * React hook for consuming services reactively @@ -11,8 +11,8 @@ export function useService(serviceName: string): ServiceResult & { reload: () => Promise; } { const container = useServiceContainer(); - const [result, setResult] = useState>(() => - container.getSync(serviceName) + const [result, setResult] = useState>(() => + container.getSync(serviceName), ); useEffect(() => { @@ -21,7 +21,7 @@ export function useService(serviceName: string): ServiceResult & { setResult(initialResult); // Auto-load if idle - if (initialResult.state === 'idle') { + if (initialResult.state === "idle") { container.load(serviceName).catch(() => { // Error is handled by the service container and will trigger the error event }); @@ -29,33 +29,33 @@ export function useService(serviceName: string): ServiceResult & { // Set up event listeners const onLoading = () => { - setResult(prev => ({ ...prev, state: 'loading', error: null })); + setResult((prev) => ({ ...prev, state: "loading", error: null })); }; const onReady = (value: T) => { setResult({ value, - state: 'ready', + state: "ready", error: null, - lastUpdated: new Date() + lastUpdated: new Date(), }); }; const onError = (error: Error) => { - setResult(prev => ({ + setResult((prev) => ({ ...prev, - state: 'error', + state: "error", error, - lastUpdated: new Date() + lastUpdated: new Date(), })); }; const onChanged = (value: T) => { - setResult(prev => ({ + setResult((prev) => ({ ...prev, value, error: null, - lastUpdated: new Date() + lastUpdated: new Date(), })); }; @@ -80,7 +80,7 @@ export function useService(serviceName: string): ServiceResult & { return { ...result, - reload + reload, }; } @@ -88,10 +88,10 @@ export function useService(serviceName: string): ServiceResult & { * Hook for consuming multiple services */ export function useServices>( - serviceNames: (keyof T)[] -): { - services: Partial; - loading: boolean; + serviceNames: (keyof T)[], +): { + services: Partial; + loading: boolean; error: Error | null; allReady: boolean; } { @@ -108,15 +108,15 @@ export function useServices>( for (const serviceName of serviceNames) { const result = container.getSync(serviceName as string); - - if (result.state === 'loading') { + + if (result.state === "loading") { hasLoading = true; - } else if (result.state === 'error') { + } else if (result.state === "error") { hasError = result.error; - } else if (result.state === 'idle') { + } else if (result.state === "idle") { // Auto-load idle services container.load(serviceName as string).catch(() => {}); - } else if (result.state === 'ready' && result.value !== null) { + } else if (result.state === "ready" && result.value !== null) { newServices[serviceName] = result.value as T[keyof T]; } else { } @@ -132,17 +132,17 @@ export function useServices>( // Set up listeners for all services const listeners: Array<() => void> = []; - + for (const serviceName of serviceNames) { const name = serviceName as string; - + const onAnyChange = () => updateState(); - + container.on(`${name}:loading`, onAnyChange); container.on(`${name}:ready`, onAnyChange); container.on(`${name}:error`, onAnyChange); container.on(`${name}:changed`, onAnyChange); - + listeners.push(() => { container.off(`${name}:loading`, onAnyChange); container.off(`${name}:ready`, onAnyChange); @@ -153,13 +153,13 @@ export function useServices>( // Cleanup return () => { - listeners.forEach(cleanup => cleanup()); + listeners.forEach((cleanup) => cleanup()); }; - }, [serviceNames.join(','), container]); + }, [serviceNames.join(","), container]); - const allReady = serviceNames.every(name => - container.isReady(name as string) + const allReady = serviceNames.every((name) => + container.isReady(name as string), ); return { services, loading, error, allReady }; -} \ No newline at end of file +} diff --git a/src/index.ts b/src/index.ts index 884b1d490..9fcea99b9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,7 +26,7 @@ process.on("unhandledRejection", (reason, promise) => { reason instanceof Error ? reason : new Error(String(reason)), { promise: String(promise), - } + }, ); // Don't exit the process, just log the error }); @@ -42,7 +42,7 @@ const program = new Command(); program .name("cn") .description( - "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output." + "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.", ) .version(getVersion()); @@ -53,11 +53,11 @@ addCommonOptions(program) .option("-p, --print", "Print response and exit (useful for pipes)") .option( "--format ", - "Output format for headless mode (json). Only works with -p/--print flag." + "Output format for headless mode (json). Only works with -p/--print flag.", ) .option( "--silent", - "Strip tags and excess whitespace from output. Only works with -p/--print flag." + "Strip tags and excess whitespace from output. Only works with -p/--print flag.", ) .option("--resume", "Resume from last session") .action(async (prompt, options) => { @@ -94,7 +94,7 @@ addCommonOptions(program) console.log(`Verbose logging enabled (session: ${sessionId})`); console.log(`Logs: ${logPath}`); console.log( - `Filter this session: grep '\\[${sessionId}\\]' ${logPath}` + `Filter this session: grep '\\[${sessionId}\\]' ${logPath}`, ); } logger.debug("Verbose logging enabled"); @@ -117,7 +117,7 @@ addCommonOptions(program) // In headless mode, ensure we have a prompt if (options.print && !prompt) { console.error( - "Error: A prompt is required when using the -p/--print flag.\n" + "Error: A prompt is required when using the -p/--print flag.\n", ); console.error("Usage examples:"); console.error(' cn -p "please review my current git diff"'); @@ -154,7 +154,7 @@ program .description("Launch a remote instance of the cn agent") .option( "--url ", - "Connect directly to the specified URL instead of creating a new remote environment" + "Connect directly to the specified URL instead of creating a new remote environment", ) .action(async (prompt: string | undefined, options) => { await remote(prompt, options); @@ -167,7 +167,7 @@ program .option( "--timeout ", "Inactivity timeout in seconds (default: 300)", - "300" + "300", ) .option("--port ", "Port to run the server on (default: 8000)", "8000") .action(async (prompt, options) => { @@ -204,7 +204,7 @@ try { } catch (error) { console.error(error); sentryService.captureException( - error instanceof Error ? error : new Error(String(error)) + error instanceof Error ? error : new Error(String(error)), ); process.exit(1); } diff --git a/src/logger.ts b/src/logger.ts index 1d4b7840d..d8a868cb6 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -6,15 +6,15 @@ export function configureLogger(isHeadless: boolean): void { if (isHeadless) { // Save the original console.info function const originalConsoleInfo = console.info; - + // Override console.info to be a no-op in headless mode - console.info = function() { + console.info = function () { // Do nothing in headless mode }; - + // Add a method to restore original behavior if needed - (console as any).restoreInfo = function() { + (console as any).restoreInfo = function () { console.info = originalConsoleInfo; }; } -} \ No newline at end of file +} diff --git a/src/mcp.ts b/src/mcp.ts index 9a5a32e79..2119916ff 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -21,13 +21,17 @@ export class MCPService { const service = new MCPService(assistant); if (assistant.mcpServers?.length) { - logger.debug('Creating MCP connections', { serverCount: assistant.mcpServers.length }); + logger.debug("Creating MCP connections", { + serverCount: assistant.mcpServers.length, + }); const connectionPromises = assistant.mcpServers.map((server) => - MCPConnection.create(server) + MCPConnection.create(server), ); const connections = await Promise.all(connectionPromises); service.connections.push(...connections); - logger.debug('MCP connections established', { connectionCount: connections.length }); + logger.debug("MCP connections established", { + connectionCount: connections.length, + }); } // Store the instance and return it diff --git a/src/onboarding.ts b/src/onboarding.ts index af5791ae5..d6fb31844 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -30,7 +30,7 @@ export interface OnboardingResult { } export async function checkHasAcceptableModel( - configPath: string + configPath: string, ): Promise { try { if (!fs.existsSync(configPath)) { @@ -61,7 +61,7 @@ export async function createOrUpdateConfig(apiKey: string): Promise { export async function runOnboardingFlow( configPath: string | undefined, - authConfig: AuthConfig + authConfig: AuthConfig, ): Promise { // Step 1: Check if --config flag is provided if (configPath) { @@ -103,7 +103,7 @@ export async function runOnboardingFlow( chalk.white("\nEnter your Anthropic API key: "), { hideEchoBack: true, - } + }, ); if (!isValidAnthropicApiKey(apiKey)) { @@ -112,7 +112,7 @@ export async function runOnboardingFlow( await createOrUpdateConfig(apiKey); console.log( - chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`) + chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`), ); const result = await initialize(authConfig, CONFIG_PATH); @@ -125,7 +125,7 @@ export async function runOnboardingFlow( export async function runNormalFlow( authConfig: AuthConfig, configPath?: string, - rules?: string[] + rules?: string[], ): Promise { // Step 1: Check if --config flag is provided if (configPath) { @@ -141,7 +141,7 @@ export async function runNormalFlow( const errorMessage = error instanceof Error ? error.message : String(error); throw new Error( - `Failed to load config from "${configPath}": ${errorMessage}` + `Failed to load config from "${configPath}": ${errorMessage}`, ); } } @@ -193,7 +193,7 @@ export async function runNormalFlow( export async function isFirstTime(): Promise { return !fs.existsSync( - path.join(os.homedir(), ".continue", ".onboarding_complete") + path.join(os.homedir(), ".continue", ".onboarding_complete"), ); } @@ -216,7 +216,7 @@ export async function markOnboardingComplete(): Promise { */ async function injectRulesIntoConfig( config: AssistantUnrolled, - rules: string[] + rules: string[], ): Promise { if (!rules || rules.length === 0) { return config; @@ -230,8 +230,8 @@ async function injectRulesIntoConfig( } catch (error: any) { console.warn( chalk.yellow( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}` - ) + `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, + ), ); } } @@ -248,9 +248,8 @@ async function injectRulesIntoConfig( const rulesSection = processedRules.join("\n\n"); if (existingSystemMessage) { - ( - modifiedConfig as any - ).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; + (modifiedConfig as any).systemMessage = + `${existingSystemMessage}\n\n${rulesSection}`; } else { (modifiedConfig as any).systemMessage = rulesSection; } @@ -261,7 +260,7 @@ async function injectRulesIntoConfig( export async function initializeWithOnboarding( authConfig: AuthConfig, configPath: string | undefined, - rules?: string[] + rules?: string[], ): Promise { const firstTime = await isFirstTime(); diff --git a/src/permissions/permissionChecker.ts b/src/permissions/permissionChecker.ts index ad74c91ed..9b2f5d557 100644 --- a/src/permissions/permissionChecker.ts +++ b/src/permissions/permissionChecker.ts @@ -17,7 +17,7 @@ import { export function matchesToolPattern( toolName: string, pattern: string, - toolArguments?: Record + toolArguments?: Record, ): boolean { if (pattern === "*") return true; if (pattern === toolName) return true; @@ -66,7 +66,7 @@ export function matchesToolPattern( */ export function matchesArguments( args: Record, - patterns?: Record + patterns?: Record, ): boolean { if (!patterns) return true; @@ -109,14 +109,14 @@ export function matchesArguments( */ export function checkToolPermission( toolCall: ToolCallRequest, - permissions?: ToolPermissions + permissions?: ToolPermissions, ): PermissionCheckResult { // Get permissions from service if not provided let policies = permissions?.policies; if (!policies) { const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS + SERVICE_NAMES.TOOL_PERMISSIONS, ); // Only use defaults if service is not ready, not registered, or has no value @@ -152,12 +152,12 @@ export function checkToolPermission( */ export function filterExcludedTools( toolNames: string[], - permissions?: ToolPermissions + permissions?: ToolPermissions, ): string[] { return toolNames.filter((toolName) => { const result = checkToolPermission( { name: toolName, arguments: {} }, - permissions + permissions, ); return result.permission !== "exclude"; }); diff --git a/src/permissions/permissionManager.ts b/src/permissions/permissionManager.ts index 4b4c7a3ba..ad9dc60af 100644 --- a/src/permissions/permissionManager.ts +++ b/src/permissions/permissionManager.ts @@ -23,7 +23,7 @@ export class ToolPermissionManager extends EventEmitter { * when the user approves or rejects the request. */ async requestPermission( - toolCall: ToolCallRequest + toolCall: ToolCallRequest, ): Promise { const requestId = `tool-request-${++this.requestCounter}`; diff --git a/src/permissions/permissionsYamlLoader.ts b/src/permissions/permissionsYamlLoader.ts index aea72fc8a..27e30729d 100644 --- a/src/permissions/permissionsYamlLoader.ts +++ b/src/permissions/permissionsYamlLoader.ts @@ -12,7 +12,7 @@ import { PermissionPolicy, ToolPermissionPolicy } from "./types.js"; export const PERMISSIONS_YAML_PATH = path.join( os.homedir(), ".continue", - "permissions.yaml" + "permissions.yaml", ); export interface PermissionsYamlConfig { @@ -44,7 +44,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null { (key) => validKeys.includes(key) && (!parsed[key as keyof PermissionsYamlConfig] || - Array.isArray(parsed[key as keyof PermissionsYamlConfig])) + Array.isArray(parsed[key as keyof PermissionsYamlConfig])), ); if (hasValidStructure) { @@ -79,7 +79,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null { */ export function parseToolPattern( pattern: string, - permission: PermissionPolicy + permission: PermissionPolicy, ): ToolPermissionPolicy { const match = pattern.match(/^([^(]+)(?:\(([^)]*)\))?$/); if (!match) { @@ -123,7 +123,7 @@ export function parseToolPattern( * Converts permissions YAML config to ToolPermissionPolicy array */ export function yamlConfigToPolicies( - config: PermissionsYamlConfig + config: PermissionsYamlConfig, ): ToolPermissionPolicy[] { const policies: ToolPermissionPolicy[] = []; diff --git a/src/permissions/policyWriter.ts b/src/permissions/policyWriter.ts index d21b4a629..6ba079896 100644 --- a/src/permissions/policyWriter.ts +++ b/src/permissions/policyWriter.ts @@ -4,7 +4,11 @@ import * as yaml from "yaml"; import { logger } from "../util/logger.js"; -import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js"; +import { + PERMISSIONS_YAML_PATH, + PermissionsYamlConfig, + loadPermissionsYaml, +} from "./permissionsYamlLoader.js"; import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; /** @@ -14,7 +18,7 @@ import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; */ export function generatePolicyRule(toolName: string, toolArgs: any): string { const normalizedName = normalizeToolName(toolName); - + // For Bash tool, create command-specific policies if (normalizedName === "Bash" && toolArgs?.command) { const command = toolArgs.command.trim(); @@ -26,7 +30,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string { return `Bash(${commandName}*)`; } } - + // For all other tools, return the display name return getDisplayName(normalizedName); } @@ -38,33 +42,36 @@ export async function addPolicyToYaml(policyRule: string): Promise { try { // Load existing config or create empty one const config: PermissionsYamlConfig = loadPermissionsYaml() || {}; - + // Ensure allow array exists if (!config.allow) { config.allow = []; } - + // Add the policy if it doesn't already exist if (!config.allow.includes(policyRule)) { config.allow.push(policyRule); - + // Write the updated config back to the file const yamlContent = yaml.stringify(config); - + // Add header comment const finalContent = `# Continue CLI Permissions Configuration # This file is managed by the Continue CLI and should not be edited manually. # Use the TUI to modify permissions interactively. ${yamlContent}`; - + await fs.promises.writeFile(PERMISSIONS_YAML_PATH, finalContent, "utf-8"); logger.info(`Added policy rule to permissions.yaml: ${policyRule}`); } else { logger.debug(`Policy rule already exists: ${policyRule}`); } } catch (error) { - logger.error("Failed to add policy to permissions.yaml", { error, policyRule }); + logger.error("Failed to add policy to permissions.yaml", { + error, + policyRule, + }); throw error; } -} \ No newline at end of file +} diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index 2a4c54d71..65a769ec9 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -1,7 +1,10 @@ import { logger } from "../util/logger.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; -import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js"; +import { + loadPermissionsYaml, + yamlConfigToPolicies, +} from "./permissionsYamlLoader.js"; import { normalizeToolName } from "./toolNameMapping.js"; import { ToolPermissionPolicy } from "./types.js"; @@ -23,15 +26,17 @@ export interface PermissionSources { /** * Resolves permission policies from all sources according to precedence rules. * This function implements the clean precedence logic from the specification: - * + * * 1. Command line flags (highest) * 2. Permissions in config.yaml (when implemented) * 3. Permissions in ~/.continue/permissions.yaml * 4. Default policies (lowest) - * + * * Earlier sources completely override later ones on a per-tool basis. */ -export function resolvePermissionPrecedence(sources: PermissionSources): ToolPermissionPolicy[] { +export function resolvePermissionPrecedence( + sources: PermissionSources, +): ToolPermissionPolicy[] { const layers: { name: string; policies: ToolPermissionPolicy[]; @@ -41,7 +46,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer if (sources.useDefaults !== false) { layers.push({ name: "defaults", - policies: [...DEFAULT_TOOL_POLICIES] + policies: [...DEFAULT_TOOL_POLICIES], }); } @@ -53,7 +58,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer if (yamlPolicies.length > 0) { layers.push({ name: "personal-settings", - policies: yamlPolicies + policies: yamlPolicies, }); } } @@ -63,7 +68,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer if (sources.configPermissions) { layers.push({ name: "config", - policies: sources.configPermissions + policies: sources.configPermissions, }); } @@ -73,7 +78,7 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer if (cliPolicies.length > 0) { layers.push({ name: "cli-flags", - policies: cliPolicies + policies: cliPolicies, }); } } @@ -82,8 +87,8 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer const combinedPolicies = combineLayersWithPrecedence(layers); logger.debug("Resolved permission precedence", { - layers: layers.map(l => ({ name: l.name, count: l.policies.length })), - totalPolicies: combinedPolicies.length + layers: layers.map((l) => ({ name: l.name, count: l.policies.length })), + totalPolicies: combinedPolicies.length, }); return combinedPolicies; @@ -128,7 +133,9 @@ function commandLineFlagsToPolicies(flags: { * Combines permission layers with proper precedence. * Higher precedence layers come later in the array and are prepended to the result. */ -function combineLayersWithPrecedence(layers: Array<{ name: string; policies: ToolPermissionPolicy[] }>): ToolPermissionPolicy[] { +function combineLayersWithPrecedence( + layers: Array<{ name: string; policies: ToolPermissionPolicy[] }>, +): ToolPermissionPolicy[] { // Start with empty array let combined: ToolPermissionPolicy[] = []; @@ -141,4 +148,4 @@ function combineLayersWithPrecedence(layers: Array<{ name: string; policies: Too } return combined; -} \ No newline at end of file +} diff --git a/src/permissions/runtimeOverrides.ts b/src/permissions/runtimeOverrides.ts index f9725839a..d776d2b9f 100644 --- a/src/permissions/runtimeOverrides.ts +++ b/src/permissions/runtimeOverrides.ts @@ -47,4 +47,4 @@ export function setRuntimePermissionOverrides(overrides: { export function getRuntimePermissionOverrides(): ToolPermissionPolicy[] | null { return runtimeOverrides; -} \ No newline at end of file +} diff --git a/src/sentry.ts b/src/sentry.ts index f515374bb..0028b9b1e 100644 --- a/src/sentry.ts +++ b/src/sentry.ts @@ -37,10 +37,10 @@ class SentryService { release: getVersion(), sampleRate: parseFloat(process.env.SENTRY_SAMPLE_RATE || "1.0"), profilesSampleRate: parseFloat( - process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0" + process.env.SENTRY_PROFILES_SAMPLE_RATE || "1.0", ), tracesSampleRate: parseFloat( - process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0" + process.env.SENTRY_TRACES_SAMPLE_RATE || "1.0", ), }; } @@ -98,7 +98,7 @@ class SentryService { public captureMessage( message: string, level: "info" | "warning" | "error" | "debug" | "fatal" = "info", - context?: Record + context?: Record, ) { if (!this.isEnabled()) return; diff --git a/src/services/ApiClientService.ts b/src/services/ApiClientService.ts index f27242232..b2dc8910d 100644 --- a/src/services/ApiClientService.ts +++ b/src/services/ApiClientService.ts @@ -9,9 +9,12 @@ import { ApiClientServiceState } from "./types.js"; * Service for managing API client state * Provides access to the Continue SDK API client */ -export class ApiClientService extends BaseService implements ServiceWithDependencies { +export class ApiClientService + extends BaseService + implements ServiceWithDependencies +{ constructor() { - super('ApiClientService', { + super("ApiClientService", { apiClient: null, }); } @@ -20,7 +23,7 @@ export class ApiClientService extends BaseService impleme * Declare dependencies on other services */ getDependencies(): string[] { - return ['auth']; + return ["auth"]; } /** @@ -51,7 +54,7 @@ export class ApiClientService extends BaseService impleme return this.getState(); } catch (error: any) { logger.error("Failed to update ApiClientService:", error); - this.emit('error', error); + this.emit("error", error); throw error; } } @@ -62,4 +65,4 @@ export class ApiClientService extends BaseService impleme override isReady(): boolean { return super.isReady() && this.currentState.apiClient !== null; } -} \ No newline at end of file +} diff --git a/src/services/AuthService.refactored.ts b/src/services/AuthService.refactored.ts index da9e77927..0a3a79653 100644 --- a/src/services/AuthService.refactored.ts +++ b/src/services/AuthService.refactored.ts @@ -19,7 +19,7 @@ import { AuthServiceState } from "./types.js"; */ export class AuthService extends BaseService { constructor() { - super('AuthService', { + super("AuthService", { authConfig: null, isAuthenticated: false, }); @@ -69,7 +69,7 @@ export class AuthService extends BaseService { return this.getState(); } catch (error: any) { logger.error("Login failed:", error); - this.emit('error', error); + this.emit("error", error); throw error; } } @@ -96,7 +96,7 @@ export class AuthService extends BaseService { * Ensure organization is selected, prompting if necessary */ async ensureOrganization( - isHeadless: boolean = false + isHeadless: boolean = false, ): Promise { if (!this.currentState.authConfig) { throw new Error("Not authenticated - cannot ensure organization"); @@ -109,7 +109,7 @@ export class AuthService extends BaseService { const updatedConfig = await ensureOrganization( this.currentState.authConfig, - isHeadless + isHeadless, ); this.setState({ @@ -129,14 +129,14 @@ export class AuthService extends BaseService { * Switch to a different organization */ async switchOrganization( - organizationId: string | null + organizationId: string | null, ): Promise { if ( !this.currentState.authConfig || !("userId" in this.currentState.authConfig) ) { throw new Error( - "Not authenticated with file-based auth - cannot switch organizations" + "Not authenticated with file-based auth - cannot switch organizations", ); } @@ -182,7 +182,7 @@ export class AuthService extends BaseService { return await listUserOrganizations(); } catch (error: any) { logger.error("Failed to list organizations:", error); - this.emit('error', error); + this.emit("error", error); return null; } } @@ -202,4 +202,4 @@ export class AuthService extends BaseService { logger.debug("Refreshing auth state from disk"); return this.reload(); } -} \ No newline at end of file +} diff --git a/src/services/AuthService.ts b/src/services/AuthService.ts index 71d82e9b7..90a2f7347 100644 --- a/src/services/AuthService.ts +++ b/src/services/AuthService.ts @@ -19,7 +19,7 @@ import { AuthServiceState } from "./types.js"; */ export class AuthService extends BaseService { constructor() { - super('AuthService', { + super("AuthService", { authConfig: null, isAuthenticated: false, }); @@ -69,7 +69,7 @@ export class AuthService extends BaseService { return this.getState(); } catch (error: any) { logger.error("Login failed:", error); - this.emit('error', error); + this.emit("error", error); throw error; } } @@ -97,7 +97,7 @@ export class AuthService extends BaseService { */ async ensureOrganization( isHeadless: boolean = false, - cliOrganizationSlug?: string + cliOrganizationSlug?: string, ): Promise { if (!this.currentState.authConfig) { throw new Error("Not authenticated - cannot ensure organization"); @@ -112,7 +112,7 @@ export class AuthService extends BaseService { const updatedConfig = await ensureOrganization( this.currentState.authConfig, isHeadless, - cliOrganizationSlug + cliOrganizationSlug, ); this.setState({ @@ -132,14 +132,14 @@ export class AuthService extends BaseService { * Switch to a different organization */ async switchOrganization( - organizationId: string | null + organizationId: string | null, ): Promise { if ( !this.currentState.authConfig || !("userId" in this.currentState.authConfig) ) { throw new Error( - "Not authenticated with file-based auth - cannot switch organizations" + "Not authenticated with file-based auth - cannot switch organizations", ); } @@ -185,7 +185,7 @@ export class AuthService extends BaseService { return await listUserOrganizations(); } catch (error: any) { logger.error("Failed to list organizations:", error); - this.emit('error', error); + this.emit("error", error); return null; } } @@ -205,4 +205,4 @@ export class AuthService extends BaseService { logger.debug("Refreshing auth state from disk"); return this.reload(); } -} \ No newline at end of file +} diff --git a/src/services/BaseService.ts b/src/services/BaseService.ts index bfbdb1108..b29ec7b1c 100644 --- a/src/services/BaseService.ts +++ b/src/services/BaseService.ts @@ -60,7 +60,7 @@ export abstract class BaseService extends EventEmitter { const previousState = this.currentState; this.currentState = { ...this.currentState, ...newState }; // Only log state updates if not in production to avoid circular reference issues - if (process.env.NODE_ENV !== 'production') { + if (process.env.NODE_ENV !== "production") { logger.debug(`${this.serviceName} state updated`); } this.emit("stateChanged", this.currentState, previousState); @@ -103,7 +103,7 @@ export interface ServiceWithDependencies { * Helper to check if a service has dependencies */ export function hasDependencies( - service: any + service: any, ): service is ServiceWithDependencies { return !!service && typeof service.getDependencies === "function"; } diff --git a/src/services/ConfigService.ts b/src/services/ConfigService.ts index 6e131633b..c1fc706a9 100644 --- a/src/services/ConfigService.ts +++ b/src/services/ConfigService.ts @@ -2,10 +2,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import { processRule } from "../args.js"; -import { - AuthConfig, - loadAuthConfig, -} from "../auth/workos.js"; +import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; @@ -20,9 +17,12 @@ import { * Service for managing configuration state and operations * Handles loading configs from files or assistant slugs */ -export class ConfigService extends BaseService implements ServiceWithDependencies { +export class ConfigService + extends BaseService + implements ServiceWithDependencies +{ constructor() { - super('ConfigService', { + super("ConfigService", { config: null, configPath: undefined, }); @@ -43,12 +43,12 @@ export class ConfigService extends BaseService implements Se configPath: string | undefined, organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[] + rules?: string[], ): Promise { // Use the new streamlined config loader const { loadConfiguration } = await import("../configLoader.js"); const result = await loadConfiguration(authConfig, configPath, apiClient); - + let config = result.config; // Inject rules if provided @@ -59,7 +59,7 @@ export class ConfigService extends BaseService implements Se // Config URI persistence is now handled by the streamlined loader logger.debug("ConfigService initialized successfully"); - + return { config, configPath, @@ -74,7 +74,7 @@ export class ConfigService extends BaseService implements Se authConfig: AuthConfig, organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[] + rules?: string[], ): Promise { logger.debug("Switching configuration", { from: this.currentState.configPath, @@ -84,8 +84,12 @@ export class ConfigService extends BaseService implements Se try { // Use the new streamlined config loader const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration(authConfig, newConfigPath, apiClient); - + const result = await loadConfiguration( + authConfig, + newConfigPath, + apiClient, + ); + let config = result.config; // Inject rules if provided @@ -107,7 +111,7 @@ export class ConfigService extends BaseService implements Se return this.getState(); } catch (error: any) { logger.error("Failed to switch configuration:", error); - this.emit('error', error); + this.emit("error", error); throw error; } } @@ -119,7 +123,7 @@ export class ConfigService extends BaseService implements Se authConfig: AuthConfig, organizationId: string | null, apiClient: DefaultApiInterface, - rules?: string[] + rules?: string[], ): Promise { if (!this.currentState.configPath) { throw new Error("No configuration path available for reload"); @@ -132,7 +136,7 @@ export class ConfigService extends BaseService implements Se authConfig, organizationId, apiClient, - rules + rules, ); } @@ -141,7 +145,7 @@ export class ConfigService extends BaseService implements Se */ private async injectRulesIntoConfig( config: AssistantUnrolled, - rules: string[] + rules: string[], ): Promise { if (!rules || rules.length === 0) { return config; @@ -170,9 +174,8 @@ export class ConfigService extends BaseService implements Se const rulesSection = processedRules.join("\n\n"); if (existingSystemMessage) { - ( - modifiedConfig as any - ).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; + (modifiedConfig as any).systemMessage = + `${existingSystemMessage}\n\n${rulesSection}`; } else { (modifiedConfig as any).systemMessage = rulesSection; } @@ -194,7 +197,7 @@ export class ConfigService extends BaseService implements Se // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); const apiClientState = await serviceContainer.get( - SERVICE_NAMES.API_CLIENT + SERVICE_NAMES.API_CLIENT, ); if (!apiClientState.apiClient) { @@ -204,9 +207,9 @@ export class ConfigService extends BaseService implements Se // Load the new configuration using streamlined loader const { loadConfiguration } = await import("../configLoader.js"); const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClientState.apiClient + authConfig, + newConfigPath, + apiClientState.apiClient, ); // Update internal state @@ -230,9 +233,8 @@ export class ConfigService extends BaseService implements Se }); } catch (error: any) { logger.error("Failed to update configuration path:", error); - this.emit('error', error); + this.emit("error", error); throw error; } } - -} \ No newline at end of file +} diff --git a/src/services/MCPServiceWrapper.ts b/src/services/MCPServiceWrapper.ts index 8d584c5a1..1235f6fb0 100644 --- a/src/services/MCPServiceWrapper.ts +++ b/src/services/MCPServiceWrapper.ts @@ -1,9 +1,9 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { MCPService } from '../mcp.js'; -import { logger } from '../util/logger.js'; +import { MCPService } from "../mcp.js"; +import { logger } from "../util/logger.js"; -import { MCPServiceState } from './types.js'; +import { MCPServiceState } from "./types.js"; /** * Service wrapper for managing MCP service state @@ -11,30 +11,30 @@ import { MCPServiceState } from './types.js'; */ export class MCPServiceWrapper { private currentState: MCPServiceState = { - mcpService: null + mcpService: null, }; /** * Initialize the MCP service wrapper */ async initialize(assistant: AssistantUnrolled): Promise { - logger.debug('Initializing MCPServiceWrapper'); - + logger.debug("Initializing MCPServiceWrapper"); + try { const mcpService = await MCPService.create(assistant); this.currentState = { - mcpService + mcpService, }; - logger.debug('MCPServiceWrapper initialized successfully', { + logger.debug("MCPServiceWrapper initialized successfully", { toolCount: mcpService.getTools().length, - promptCount: mcpService.getPrompts().length + promptCount: mcpService.getPrompts().length, }); return this.currentState; } catch (error: any) { - logger.error('Failed to initialize MCPServiceWrapper:', error); + logger.error("Failed to initialize MCPServiceWrapper:", error); throw error; } } @@ -51,26 +51,26 @@ export class MCPServiceWrapper { * Note: This creates a new MCP service since the original is a singleton */ async update(assistant: AssistantUnrolled): Promise { - logger.debug('Updating MCPServiceWrapper'); - + logger.debug("Updating MCPServiceWrapper"); + try { // Clear the existing singleton instance to force recreation (MCPService as any).instance = null; - + const mcpService = await MCPService.create(assistant); this.currentState = { - mcpService + mcpService, }; - logger.debug('MCPServiceWrapper updated successfully', { + logger.debug("MCPServiceWrapper updated successfully", { toolCount: mcpService.getTools().length, - promptCount: mcpService.getPrompts().length + promptCount: mcpService.getPrompts().length, }); return this.currentState; } catch (error: any) { - logger.error('Failed to update MCPServiceWrapper:', error); + logger.error("Failed to update MCPServiceWrapper:", error); throw error; } } @@ -92,7 +92,7 @@ export class MCPServiceWrapper { return { toolCount: this.currentState.mcpService.getTools().length, - promptCount: this.currentState.mcpService.getPrompts().length + promptCount: this.currentState.mcpService.getPrompts().length, }; } -} \ No newline at end of file +} diff --git a/src/services/ModeService.ts b/src/services/ModeService.ts index 3e26aa5de..b066af870 100644 --- a/src/services/ModeService.ts +++ b/src/services/ModeService.ts @@ -18,11 +18,11 @@ export class ModeService extends BaseService { private constructor() { const toolPermissionService = new ToolPermissionService(); - super('ModeService', { + super("ModeService", { mode: "normal", - toolPermissionService + toolPermissionService, }); - + // Increase max listeners since ModeService is a singleton that can have // multiple subscribers (UI components, tests, etc.) this.setMaxListeners(100); @@ -49,9 +49,9 @@ export class ModeService extends BaseService { // Convert legacy flags to mode let mode: PermissionMode = "normal"; if (args.readonly) { - mode = "plan"; // Legacy flag maps directly to plan mode + mode = "plan"; // Legacy flag maps directly to plan mode } else if (args.auto) { - mode = "auto"; // Auto flag maps to auto mode + mode = "auto"; // Auto flag maps to auto mode } this.currentState.toolPermissionService.initializeSync({ @@ -59,14 +59,14 @@ export class ModeService extends BaseService { ask: args.ask, exclude: args.exclude, mode, - isHeadless: args.isHeadless + isHeadless: args.isHeadless, }); logger.debug(`ModeService initialized with mode: ${mode}`); return { mode, - toolPermissionService: this.currentState.toolPermissionService + toolPermissionService: this.currentState.toolPermissionService, }; } @@ -76,14 +76,14 @@ export class ModeService extends BaseService { public switchMode(mode: PermissionMode): void { const previousMode = this.currentState.mode; this.currentState.toolPermissionService.switchMode(mode); - + this.setState({ mode }); - + logger.info(`Switched to ${mode} mode`); - + // Emit mode change event for immediate UI updates if (previousMode !== mode) { - this.emit('modeChanged', mode, previousMode); + this.emit("modeChanged", mode, previousMode); } } @@ -104,11 +104,23 @@ export class ModeService extends BaseService { /** * Get available modes with descriptions */ - public getAvailableModes(): Array<{ mode: PermissionMode; description: string }> { + public getAvailableModes(): Array<{ + mode: PermissionMode; + description: string; + }> { return [ - { mode: "normal", description: "Default mode - follows configured permission policies" }, - { mode: "plan", description: "Planning mode - only allow read-only tools for analysis" }, - { mode: "auto", description: "Automatically allow all tools without asking" } + { + mode: "normal", + description: "Default mode - follows configured permission policies", + }, + { + mode: "plan", + description: "Planning mode - only allow read-only tools for analysis", + }, + { + mode: "auto", + description: "Automatically allow all tools without asking", + }, ]; } @@ -129,4 +141,4 @@ export class ModeService extends BaseService { } // Export singleton instance -export const modeService = ModeService.getInstance(); \ No newline at end of file +export const modeService = ModeService.getInstance(); diff --git a/src/services/ModelService.refactored.ts b/src/services/ModelService.refactored.ts index a2d0d58f4..9a4b5d4c9 100644 --- a/src/services/ModelService.refactored.ts +++ b/src/services/ModelService.refactored.ts @@ -1,26 +1,34 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; -import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js'; -import { getLlmApi } from '../config.js'; -import { logger } from '../util/logger.js'; +import { + AuthConfig, + getAccessToken, + getOrganizationId, + getModelName, +} from "../auth/workos.js"; +import { getLlmApi } from "../config.js"; +import { logger } from "../util/logger.js"; -import { BaseService, ServiceWithDependencies } from './BaseService.js'; -import { ModelServiceState } from './types.js'; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { ModelServiceState } from "./types.js"; /** * Service for managing LLM and model state * Extends BaseService and implements ServiceWithDependencies */ -export class ModelService extends BaseService implements ServiceWithDependencies { +export class ModelService + extends BaseService + implements ServiceWithDependencies +{ private availableModels: ModelConfig[] = []; private assistant: AssistantUnrolled | null = null; private authConfig: AuthConfig | null = null; constructor() { - super('ModelService', { + super("ModelService", { llmApi: null, - model: null + model: null, }); } @@ -28,7 +36,7 @@ export class ModelService extends BaseService implements Serv * Declare dependencies on other services */ getDependencies(): string[] { - return ['auth', 'config']; + return ["auth", "config"]; } /** @@ -36,14 +44,14 @@ export class ModelService extends BaseService implements Serv */ async doInitialize( assistant: AssistantUnrolled, - authConfig: AuthConfig + authConfig: AuthConfig, ): Promise { this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter((model) => - model && model.roles?.includes("chat") + this.availableModels = (assistant.models?.filter( + (model) => model && model.roles?.includes("chat"), ) || []) as ModelConfig[]; - + // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); if (persistedModelName) { @@ -57,7 +65,7 @@ export class ModelService extends BaseService implements Serv const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, - model + model, }; } } else { @@ -65,7 +73,7 @@ export class ModelService extends BaseService implements Serv const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, - model + model, }; } } @@ -75,34 +83,34 @@ export class ModelService extends BaseService implements Serv */ async update( assistant: AssistantUnrolled, - authConfig: AuthConfig + authConfig: AuthConfig, ): Promise { - logger.debug('Updating ModelService'); - + logger.debug("Updating ModelService"); + try { this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter((model) => - model && model.roles?.includes("chat") + this.availableModels = (assistant.models?.filter( + (model) => model && model.roles?.includes("chat"), ) || []) as ModelConfig[]; - + const [llmApi, model] = getLlmApi(assistant, authConfig); this.setState({ llmApi, - model + model, }); - logger.debug('ModelService updated successfully', { + logger.debug("ModelService updated successfully", { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed', - availableModels: this.availableModels.length + modelName: (model as any).name || "unnamed", + availableModels: this.availableModels.length, }); return this.getState(); } catch (error: any) { - logger.error('Failed to update ModelService:', error); - this.emit('error', error); + logger.error("Failed to update ModelService:", error); + this.emit("error", error); throw error; } } @@ -111,9 +119,11 @@ export class ModelService extends BaseService implements Serv * Override isReady to check for required state */ override isReady(): boolean { - return super.isReady() && - this.currentState.llmApi !== null && - this.currentState.model !== null; + return ( + super.isReady() && + this.currentState.llmApi !== null && + this.currentState.model !== null + ); } /** @@ -126,18 +136,22 @@ export class ModelService extends BaseService implements Serv return { provider: this.currentState.model.provider, - name: (this.currentState.model as any).name || 'unnamed' + name: (this.currentState.model as any).name || "unnamed", }; } /** * Get list of available chat models */ - getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> { + getAvailableChatModels(): Array<{ + provider: string; + name: string; + index: number; + }> { return this.availableModels.map((model, index) => ({ provider: model.provider, - name: (model as any).name || (model as any).model || 'unnamed', - index + name: (model as any).name || (model as any).model || "unnamed", + index, })); } @@ -146,18 +160,20 @@ export class ModelService extends BaseService implements Serv */ async switchModel(modelIndex: number): Promise { if (!this.assistant || !this.authConfig) { - throw new Error('ModelService not initialized'); + throw new Error("ModelService not initialized"); } if (modelIndex < 0 || modelIndex >= this.availableModels.length) { - throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`); + throw new Error( + `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`, + ); } const selectedModel = this.availableModels[modelIndex]; - logger.debug('Switching to model', { + logger.debug("Switching to model", { modelIndex, provider: selectedModel.provider, - name: (selectedModel as any).name || 'unnamed' + name: (selectedModel as any).name || "unnamed", }); try { @@ -188,23 +204,23 @@ export class ModelService extends BaseService implements Serv const llmApi = constructLlmApi(config); if (!llmApi) { - throw new Error('Failed to initialize LLM with selected model'); + throw new Error("Failed to initialize LLM with selected model"); } this.setState({ llmApi, - model: selectedModel + model: selectedModel, }); - logger.debug('Model switched successfully', { + logger.debug("Model switched successfully", { modelProvider: selectedModel.provider, - modelName: (selectedModel as any).name || 'unnamed' + modelName: (selectedModel as any).name || "unnamed", }); return this.getState(); } catch (error: any) { - logger.error('Failed to switch model:', error); - this.emit('error', error); + logger.error("Failed to switch model:", error); + this.emit("error", error); throw error; } } @@ -217,9 +233,10 @@ export class ModelService extends BaseService implements Serv return -1; } - return this.availableModels.findIndex(model => - model.provider === this.currentState.model?.provider && - (model as any).name === (this.currentState.model as any).name + return this.availableModels.findIndex( + (model) => + model.provider === this.currentState.model?.provider && + (model as any).name === (this.currentState.model as any).name, ); } @@ -227,15 +244,15 @@ export class ModelService extends BaseService implements Serv * Get model index by name and provider */ getModelIndexByName(modelName: string, provider?: string): number { - return this.availableModels.findIndex(model => { + return this.availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; const nameMatches = name === modelName; - + if (provider) { return nameMatches && model.provider === provider; } - + return nameMatches; }); } -} \ No newline at end of file +} diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts index 93e854087..66465e129 100644 --- a/src/services/ModelService.ts +++ b/src/services/ModelService.ts @@ -1,26 +1,34 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; -import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js'; -import { getLlmApi } from '../config.js'; -import { logger } from '../util/logger.js'; +import { + AuthConfig, + getAccessToken, + getOrganizationId, + getModelName, +} from "../auth/workos.js"; +import { getLlmApi } from "../config.js"; +import { logger } from "../util/logger.js"; -import { BaseService, ServiceWithDependencies } from './BaseService.js'; -import { ModelServiceState } from './types.js'; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { ModelServiceState } from "./types.js"; /** * Service for managing LLM and model state * Depends on auth config and assistant config */ -export class ModelService extends BaseService implements ServiceWithDependencies { +export class ModelService + extends BaseService + implements ServiceWithDependencies +{ private availableModels: ModelConfig[] = []; private assistant: AssistantUnrolled | null = null; private authConfig: AuthConfig | null = null; constructor() { - super('ModelService', { + super("ModelService", { llmApi: null, - model: null + model: null, }); } @@ -28,7 +36,7 @@ export class ModelService extends BaseService implements Serv * Declare dependencies on other services */ getDependencies(): string[] { - return ['auth', 'config']; + return ["auth", "config"]; } /** @@ -36,14 +44,14 @@ export class ModelService extends BaseService implements Serv */ async doInitialize( assistant: AssistantUnrolled, - authConfig: AuthConfig + authConfig: AuthConfig, ): Promise { this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter((model) => - model && model.roles?.includes("chat") + this.availableModels = (assistant.models?.filter( + (model) => model && model.roles?.includes("chat"), ) || []) as ModelConfig[]; - + // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); if (persistedModelName) { @@ -57,7 +65,7 @@ export class ModelService extends BaseService implements Serv const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, - model + model, }; } } else { @@ -65,7 +73,7 @@ export class ModelService extends BaseService implements Serv const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, - model + model, }; } } @@ -75,34 +83,34 @@ export class ModelService extends BaseService implements Serv */ async update( assistant: AssistantUnrolled, - authConfig: AuthConfig + authConfig: AuthConfig, ): Promise { - logger.debug('Updating ModelService'); - + logger.debug("Updating ModelService"); + try { this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter((model) => - model && model.roles?.includes("chat") + this.availableModels = (assistant.models?.filter( + (model) => model && model.roles?.includes("chat"), ) || []) as ModelConfig[]; - + const [llmApi, model] = getLlmApi(assistant, authConfig); this.setState({ llmApi, - model + model, }); - logger.debug('ModelService updated successfully', { + logger.debug("ModelService updated successfully", { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed', - availableModels: this.availableModels.length + modelName: (model as any).name || "unnamed", + availableModels: this.availableModels.length, }); return this.getState(); } catch (error: any) { - logger.error('Failed to update ModelService:', error); - this.emit('error', error); + logger.error("Failed to update ModelService:", error); + this.emit("error", error); throw error; } } @@ -111,9 +119,11 @@ export class ModelService extends BaseService implements Serv * Override isReady to check for required state */ override isReady(): boolean { - return super.isReady() && - this.currentState.llmApi !== null && - this.currentState.model !== null; + return ( + super.isReady() && + this.currentState.llmApi !== null && + this.currentState.model !== null + ); } /** @@ -126,18 +136,22 @@ export class ModelService extends BaseService implements Serv return { provider: this.currentState.model.provider, - name: (this.currentState.model as any).name || 'unnamed' + name: (this.currentState.model as any).name || "unnamed", }; } /** * Get list of available chat models */ - getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> { + getAvailableChatModels(): Array<{ + provider: string; + name: string; + index: number; + }> { return this.availableModels.map((model, index) => ({ provider: model.provider, - name: (model as any).name || (model as any).model || 'unnamed', - index + name: (model as any).name || (model as any).model || "unnamed", + index, })); } @@ -146,18 +160,20 @@ export class ModelService extends BaseService implements Serv */ async switchModel(modelIndex: number): Promise { if (!this.assistant || !this.authConfig) { - throw new Error('ModelService not initialized'); + throw new Error("ModelService not initialized"); } if (modelIndex < 0 || modelIndex >= this.availableModels.length) { - throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`); + throw new Error( + `Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`, + ); } const selectedModel = this.availableModels[modelIndex]; - logger.debug('Switching to model', { + logger.debug("Switching to model", { modelIndex, provider: selectedModel.provider, - name: (selectedModel as any).name || 'unnamed' + name: (selectedModel as any).name || "unnamed", }); try { @@ -188,23 +204,23 @@ export class ModelService extends BaseService implements Serv const llmApi = constructLlmApi(config); if (!llmApi) { - throw new Error('Failed to initialize LLM with selected model'); + throw new Error("Failed to initialize LLM with selected model"); } this.setState({ llmApi, - model: selectedModel + model: selectedModel, }); - logger.debug('Model switched successfully', { + logger.debug("Model switched successfully", { modelProvider: selectedModel.provider, - modelName: (selectedModel as any).name || 'unnamed' + modelName: (selectedModel as any).name || "unnamed", }); return this.getState(); } catch (error: any) { - logger.error('Failed to switch model:', error); - this.emit('error', error); + logger.error("Failed to switch model:", error); + this.emit("error", error); throw error; } } @@ -217,9 +233,10 @@ export class ModelService extends BaseService implements Serv return -1; } - return this.availableModels.findIndex(model => - model.provider === this.currentState.model?.provider && - (model as any).name === (this.currentState.model as any).name + return this.availableModels.findIndex( + (model) => + model.provider === this.currentState.model?.provider && + (model as any).name === (this.currentState.model as any).name, ); } @@ -227,15 +244,15 @@ export class ModelService extends BaseService implements Serv * Get model index by name and provider */ getModelIndexByName(modelName: string, provider?: string): number { - return this.availableModels.findIndex(model => { + return this.availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; const nameMatches = name === modelName; - + if (provider) { return nameMatches && model.provider === provider; } - + return nameMatches; }); } -} \ No newline at end of file +} diff --git a/src/services/ServiceContainer.ts b/src/services/ServiceContainer.ts index af085cb78..bb3054d15 100644 --- a/src/services/ServiceContainer.ts +++ b/src/services/ServiceContainer.ts @@ -1,8 +1,8 @@ -import { EventEmitter } from 'events'; +import { EventEmitter } from "events"; -import { logger } from '../util/logger.js'; +import { logger } from "../util/logger.js"; -import { ServiceResult, ServiceState } from './types.js'; +import { ServiceResult, ServiceState } from "./types.js"; /** * Central service container that manages service lifecycle and dependencies @@ -23,20 +23,20 @@ export class ServiceContainer extends EventEmitter { * Register a service factory with optional dependencies */ register( - serviceName: string, + serviceName: string, factory: () => Promise, - deps: string[] = [] + deps: string[] = [], ): void { this.factories.set(serviceName, factory); this.dependencies.set(serviceName, deps); - + // Only initialize with idle state if the service doesn't already exist // This prevents overwriting services that were registered with registerValue if (!this.services.has(serviceName)) { this.services.set(serviceName, { value: null, - state: 'idle', - error: null + state: "idle", + error: null, }); } @@ -47,25 +47,22 @@ export class ServiceContainer extends EventEmitter { * Register a service with an immediate value (no factory needed) * Used when the service is already initialized */ - registerValue( - serviceName: string, - value: T - ): void { + registerValue(serviceName: string, value: T): void { // Set the service as ready with the provided value this.services.set(serviceName, { value, - state: 'ready', + state: "ready", error: null, - lastUpdated: new Date() + lastUpdated: new Date(), }); // Emit ready event this.emit(`${serviceName}:ready`, value); logger.debug(`Registered service with immediate value: ${serviceName}`, { - state: 'ready', + state: "ready", hasValue: value !== null, - serviceMapSize: this.services.size + serviceMapSize: this.services.size, }); } @@ -78,8 +75,8 @@ export class ServiceContainer extends EventEmitter { logger.warn(`Service not found: ${serviceName}`); return { value: null, - state: 'error', - error: new Error(`Service '${serviceName}' not registered`) + state: "error", + error: new Error(`Service '${serviceName}' not registered`), }; } return result; @@ -90,12 +87,12 @@ export class ServiceContainer extends EventEmitter { */ async get(serviceName: string): Promise { const current = this.getSync(serviceName); - - if (current.state === 'ready' && current.value !== null) { + + if (current.state === "ready" && current.value !== null) { return current.value; } - if (current.state === 'loading') { + if (current.state === "loading") { // Wait for loading to complete return new Promise((resolve, reject) => { const onReady = (value: T) => { @@ -103,7 +100,7 @@ export class ServiceContainer extends EventEmitter { this.off(`${serviceName}:error`, onError); resolve(value); }; - + const onError = (error: Error) => { this.off(`${serviceName}:ready`, onReady); this.off(`${serviceName}:error`, onError); @@ -125,31 +122,33 @@ export class ServiceContainer extends EventEmitter { async load(serviceName: string): Promise { const factory = this.factories.get(serviceName); if (!factory) { - const error = new Error(`No factory registered for service '${serviceName}'`); + const error = new Error( + `No factory registered for service '${serviceName}'`, + ); this.setServiceError(serviceName, error); throw error; } // Check if already loading const current = this.services.get(serviceName); - if (current?.state === 'loading') { + if (current?.state === "loading") { return this.get(serviceName); } logger.debug(`Loading service: ${serviceName}`); - this.setServiceState(serviceName, 'loading'); + this.setServiceState(serviceName, "loading"); try { // Load dependencies first const deps = this.dependencies.get(serviceName) || []; - await Promise.all(deps.map(dep => this.load(dep))); + await Promise.all(deps.map((dep) => this.load(dep))); // Load the service const value = await factory(); - + this.setServiceValue(serviceName, value); logger.debug(`Service loaded successfully: ${serviceName}`); - + return value; } catch (error: any) { logger.error(`Failed to load service '${serviceName}':`, error); @@ -163,27 +162,27 @@ export class ServiceContainer extends EventEmitter { */ async reload(serviceName: string): Promise { logger.debug(`Reloading service: ${serviceName}`); - + // Find all services that depend on this one (recursively) const dependents = this.findAllDependents(serviceName); - + logger.debug(`Found dependents for ${serviceName}:`, dependents); // Reset this service and all dependents to ensure fresh reload this.resetService(serviceName); - dependents.forEach(dep => this.resetService(dep)); + dependents.forEach((dep) => this.resetService(dep)); // Now reload ALL services that were reset, starting with the root service // This ensures proper dependency order and that all dependents get reloaded const allToReload = [serviceName, ...dependents]; - + // Reset ALL services first to ensure clean state - allToReload.forEach(name => this.resetService(name)); - + allToReload.forEach((name) => this.resetService(name)); + // Load all services in dependency order - starting with the root service // will naturally load its dependents when they're requested const results = await Promise.all( - allToReload.map(name => this.load(name)) + allToReload.map((name) => this.load(name)), ); // Return the value of the primary service that was reloaded @@ -228,7 +227,7 @@ export class ServiceContainer extends EventEmitter { */ isReady(serviceName: string): boolean { const result = this.services.get(serviceName); - return result?.state === 'ready' && result.value !== null; + return result?.state === "ready" && result.value !== null; } /** @@ -236,7 +235,7 @@ export class ServiceContainer extends EventEmitter { */ isLoading(serviceName: string): boolean { const result = this.services.get(serviceName); - return result?.state === 'loading'; + return result?.state === "loading"; } /** @@ -244,22 +243,25 @@ export class ServiceContainer extends EventEmitter { * This eagerly loads all services rather than waiting for them to be requested */ async initializeAll(): Promise { - logger.debug('Initializing all registered services'); - + logger.debug("Initializing all registered services"); + // Get all registered service names const serviceNames = Array.from(this.factories.keys()); - + // Load all services in parallel (dependencies will be handled by load()) await Promise.all( - serviceNames.map(name => - this.load(name).catch(error => { + serviceNames.map((name) => + this.load(name).catch((error) => { logger.error(`Failed to initialize service ${name}:`, error); // Don't throw - let individual services fail without breaking others - }) - ) + }), + ), + ); + + logger.debug( + "All services initialization complete", + this.getServiceStates(), ); - - logger.debug('All services initialization complete', this.getServiceStates()); } /** @@ -277,7 +279,11 @@ export class ServiceContainer extends EventEmitter { * Private helper methods */ private setServiceState(serviceName: string, state: ServiceState): void { - const current = this.services.get(serviceName) || { value: null, state: 'idle', error: null }; + const current = this.services.get(serviceName) || { + value: null, + state: "idle", + error: null, + }; const updated = { ...current, state, lastUpdated: new Date() }; this.services.set(serviceName, updated); this.emit(`${serviceName}:${state}`); @@ -286,11 +292,11 @@ export class ServiceContainer extends EventEmitter { private setServiceValue(serviceName: string, value: T): void { const result: ServiceResult = { value, - state: 'ready', + state: "ready", error: null, - lastUpdated: new Date() + lastUpdated: new Date(), }; - + this.services.set(serviceName, result); this.emit(`${serviceName}:ready`, value); this.emit(`${serviceName}:changed`, value); @@ -299,11 +305,11 @@ export class ServiceContainer extends EventEmitter { private setServiceError(serviceName: string, error: Error): void { const result: ServiceResult = { value: null, - state: 'error', + state: "error", error, - lastUpdated: new Date() + lastUpdated: new Date(), }; - + this.services.set(serviceName, result); this.emit(`${serviceName}:error`, error); } @@ -311,13 +317,13 @@ export class ServiceContainer extends EventEmitter { private resetService(serviceName: string): void { const result: ServiceResult = { value: null, - state: 'idle', - error: null + state: "idle", + error: null, }; - + this.services.set(serviceName, result); } } // Global singleton instance -export const serviceContainer = new ServiceContainer(); \ No newline at end of file +export const serviceContainer = new ServiceContainer(); diff --git a/src/services/ServiceContainerContext.tsx b/src/services/ServiceContainerContext.tsx index 630018309..38a4eeb84 100644 --- a/src/services/ServiceContainerContext.tsx +++ b/src/services/ServiceContainerContext.tsx @@ -1,15 +1,16 @@ -import React, { createContext, useContext } from 'react'; +import React, { createContext, useContext } from "react"; -import { ServiceContainer } from './ServiceContainer.js'; +import { ServiceContainer } from "./ServiceContainer.js"; -import { serviceContainer as defaultContainer } from './index.js'; +import { serviceContainer as defaultContainer } from "./index.js"; -const ServiceContainerContext = createContext(defaultContainer); +const ServiceContainerContext = + createContext(defaultContainer); -export function ServiceContainerProvider({ - children, - container = defaultContainer -}: { +export function ServiceContainerProvider({ + children, + container = defaultContainer, +}: { children: React.ReactNode; container?: ServiceContainer; }) { @@ -22,4 +23,4 @@ export function ServiceContainerProvider({ export function useServiceContainer() { return useContext(ServiceContainerContext); -} \ No newline at end of file +} diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts index 1ec8d29ca..70bff797b 100644 --- a/src/services/ToolPermissionService.ts +++ b/src/services/ToolPermissionService.ts @@ -165,7 +165,7 @@ export class ToolPermissionService extends BaseService { +export async function initializeServices( + options: ServiceInitOptions = {}, +): Promise { logger.debug("Initializing service registry"); - + let wasOnboarded = false; - + // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!options.headless && !options.skipOnboarding) { const authConfig = loadAuthConfig(); const onboardingResult = await initializeWithOnboarding( authConfig, options.configPath, - options.rules + options.rules, ); wasOnboarded = onboardingResult.wasOnboarded; } @@ -48,15 +50,15 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom // Initialize mode service with tool permission overrides if (options.toolPermissionOverrides) { const overrides = { ...options.toolPermissionOverrides }; - + // Convert mode to boolean flags for ModeService const initArgs: Parameters[0] = { allow: overrides.allow, ask: overrides.ask, exclude: overrides.exclude, - isHeadless: options.headless + isHeadless: options.headless, }; - + // Only set the boolean flag that corresponds to the mode if (overrides.mode === "plan") { initArgs.readonly = true; @@ -64,15 +66,15 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom initArgs.auto = true; } // If mode is "normal" or undefined, no flags are set - + await modeService.initialize(initArgs); } else { // Even if no overrides, we need to initialize with defaults await modeService.initialize({ - isHeadless: options.headless + isHeadless: options.headless, }); } - + // Register the TOOL_PERMISSIONS service with immediate value // Since ToolPermissionService is already initialized synchronously in ModeService, // we can register it as a ready value instead of a factory @@ -80,28 +82,28 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom logger.debug("Registering TOOL_PERMISSIONS with state:", { currentMode: toolPermissionState.currentMode, isHeadless: toolPermissionState.isHeadless, - policyCount: toolPermissionState.permissions.policies.length + policyCount: toolPermissionState.permissions.policies.length, }); serviceContainer.registerValue( SERVICE_NAMES.TOOL_PERMISSIONS, - toolPermissionState + toolPermissionState, ); serviceContainer.register( SERVICE_NAMES.AUTH, () => authService.initialize(), - [] // No dependencies + [], // No dependencies ); serviceContainer.register( SERVICE_NAMES.API_CLIENT, async () => { const authState = await serviceContainer.get( - SERVICE_NAMES.AUTH + SERVICE_NAMES.AUTH, ); return apiClientService.initialize(authState.authConfig); }, - [SERVICE_NAMES.AUTH] // Depends on auth + [SERVICE_NAMES.AUTH], // Depends on auth ); serviceContainer.register( @@ -117,7 +119,7 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom if (authState.authConfig) { finalAuthState = await authService.ensureOrganization( options.headless ?? false, - options.organizationSlug + options.organizationSlug, ); // Update the auth service state in container serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState); @@ -131,8 +133,11 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom // otherwise use initial options.configPath (for first initialization) // IMPORTANT: Always prefer explicit --config flag over saved state const currentState = configService.getState(); - let configPath = options.configPath || - (currentState.configPath !== undefined ? currentState.configPath : undefined); + let configPath = + options.configPath || + (currentState.configPath !== undefined + ? currentState.configPath + : undefined); // If no config path is available, check for saved config URI in auth config if (!configPath) { @@ -152,10 +157,10 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom configPath, finalAuthState.organizationId || null, apiClientState.apiClient, - options.rules + options.rules, ); }, - [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT] // Depends on auth and API client + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client ); serviceContainer.register( @@ -172,14 +177,14 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom return modelService.initialize(configState.config, authState.authConfig); }, - [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH] // Depends on config and auth + [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth ); serviceContainer.register( SERVICE_NAMES.MCP, async () => { const configState = await serviceContainer.get( - SERVICE_NAMES.CONFIG + SERVICE_NAMES.CONFIG, ); if (!configState.config) { @@ -188,7 +193,7 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom return mcpServiceWrapper.initialize(configState.config); }, - [SERVICE_NAMES.CONFIG] // Depends on config + [SERVICE_NAMES.CONFIG], // Depends on config ); // Eagerly initialize all services to ensure they're ready when needed @@ -196,7 +201,7 @@ export async function initializeServices(options: ServiceInitOptions = {}): Prom await serviceContainer.initializeAll(); logger.debug("Service registry initialized"); - + return { wasOnboarded }; } diff --git a/src/services/types.ts b/src/services/types.ts index e676941b8..32bb4085d 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -9,7 +9,7 @@ import { PermissionMode, ToolPermissions } from "../permissions/types.js"; /** * Service lifecycle states */ -export type ServiceState = 'idle' | 'loading' | 'ready' | 'error'; +export type ServiceState = "idle" | "loading" | "ready" | "error"; /** * Generic service result with state tracking @@ -69,12 +69,12 @@ export interface ToolPermissionServiceState { * Service names as constants to prevent typos */ export const SERVICE_NAMES = { - AUTH: 'auth', - CONFIG: 'config', - MODEL: 'model', - MCP: 'mcp', - API_CLIENT: 'apiClient', - TOOL_PERMISSIONS: 'toolPermissions' + AUTH: "auth", + CONFIG: "config", + MODEL: "model", + MCP: "mcp", + API_CLIENT: "apiClient", + TOOL_PERMISSIONS: "toolPermissions", } as const; /** @@ -99,4 +99,4 @@ export interface ServiceInitOptions { */ export interface ServiceInitResult { wasOnboarded?: boolean; -} \ No newline at end of file +} diff --git a/src/shared-options.ts b/src/shared-options.ts index 7992a1336..a3fe38772 100644 --- a/src/shared-options.ts +++ b/src/shared-options.ts @@ -4,7 +4,10 @@ import { Command } from "commander"; export function addCommonOptions(command: Command): Command { return command .option("--config ", "Path to configuration file") - .option("--org ", "Organization slug to use for this session (supported only in headless mode)") + .option( + "--org ", + "Organization slug to use for this session (supported only in headless mode)", + ) .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") .option("-v, --verbose", "Enable verbose logging") @@ -16,7 +19,7 @@ export function addCommonOptions(command: Command): Command { array.push(value); return array; }, - [] as string[] + [] as string[], ) .option( "--allow ", @@ -26,7 +29,7 @@ export function addCommonOptions(command: Command): Command { array.push(value); return array; }, - [] as string[] + [] as string[], ) .option( "--ask ", @@ -36,7 +39,7 @@ export function addCommonOptions(command: Command): Command { array.push(value); return array; }, - [] as string[] + [] as string[], ) .option( "--exclude ", @@ -46,7 +49,7 @@ export function addCommonOptions(command: Command): Command { array.push(value); return array; }, - [] as string[] + [] as string[], ); } @@ -57,23 +60,26 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { // List of options to inherit from parent if not present in subcommand const inheritableOptions = [ - 'config', - 'org', - 'readonly', - 'auto', - 'tools', - 'verbose', - 'rule', - 'allow', - 'ask', - 'exclude' + "config", + "org", + "readonly", + "auto", + "tools", + "verbose", + "rule", + "allow", + "ask", + "exclude", ]; for (const optName of inheritableOptions) { - if (parentOpts[optName] !== undefined && mergedOptions[optName] === undefined) { + if ( + parentOpts[optName] !== undefined && + mergedOptions[optName] === undefined + ) { mergedOptions[optName] = parentOpts[optName]; } } return mergedOptions; -} \ No newline at end of file +} diff --git a/src/slashCommands.ts b/src/slashCommands.ts index f0bd9f31b..360a48185 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -12,7 +12,7 @@ import { posthogService } from "./telemetry/posthogService.js"; export async function handleSlashCommands( input: string, - assistant: AssistantConfig + assistant: AssistantConfig, ): Promise<{ output?: string; exit?: boolean; @@ -30,7 +30,10 @@ export async function handleSlashCommands( const allCommands = getAllSlashCommands(assistant); const helpMessage = [ chalk.cyan("Slash commands:"), - ...allCommands.map((cmd) => `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`), + ...allCommands.map( + (cmd) => + `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`, + ), ].join("\n"); posthogService.capture("useSlashCommand", { name: "help", @@ -195,7 +198,7 @@ export async function handleSlashCommands( } default: const assistantPrompt = assistant.prompts?.find( - (prompt) => prompt?.name === command + (prompt) => prompt?.name === command, ); if (assistantPrompt) { const newInput = assistantPrompt.prompt + args.join(" "); diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index a38296beb..9e93e59f0 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -49,7 +49,7 @@ export function getAllTools() { // Check if the ToolPermissionService is ready const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS + SERVICE_NAMES.TOOL_PERMISSIONS, ); let allowedToolNames: string[]; @@ -57,16 +57,16 @@ export function getAllTools() { // Filter out excluded tools based on permissions allowedToolNames = filterExcludedTools( allToolNames, - serviceResult.value.permissions + serviceResult.value.permissions, ); } else { // Service not ready - this is a critical error since tools should only be // requested after services are properly initialized logger.error( - "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue" + "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", ); throw new Error( - "ToolPermissionService not initialized. Services must be initialized before requesting tools." + "ToolPermissionService not initialized. Services must be initialized before requesting tools.", ); } @@ -74,7 +74,7 @@ export function getAllTools() { // Filter builtin tools const allowedBuiltinTools = allBuiltinTools.filter((tool) => - allowedToolNamesSet.has(tool.name) + allowedToolNamesSet.has(tool.name), ); const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ @@ -92,7 +92,7 @@ export function getAllTools() { description: param.description, items: param.items, }, - ]) + ]), ), required: Object.entries(tool.parameters) .filter(([_, param]) => param.required) @@ -104,7 +104,7 @@ export function getAllTools() { // Add filtered MCP tools const mcpTools = MCPService.getInstance()?.getTools() ?? []; const allowedMcpTools = mcpTools.filter((tool) => - allowedToolNamesSet.has(tool.name) + allowedToolNamesSet.has(tool.name), ); allTools.push( @@ -115,7 +115,7 @@ export function getAllTools() { description: tool.description, parameters: tool.inputSchema, }, - })) + })), ); return allTools; @@ -131,11 +131,11 @@ export interface StreamCallbacks { toolName: string, toolArgs: any, requestId: string, - preview?: ToolCallPreview[] + preview?: ToolCallPreview[], ) => void; } function getDefaultCompletionOptions( - opts?: CompletionOptions + opts?: CompletionOptions, ): Partial { if (!opts) return {}; return { @@ -155,7 +155,7 @@ export async function processStreamingResponse( abortController: AbortController, callbacks?: StreamCallbacks, isHeadless?: boolean, - tools?: ChatCompletionTool[] + tools?: ChatCompletionTool[], ): Promise<{ content: string; finalContent: string; // Added field for final content only @@ -179,7 +179,7 @@ export async function processStreamingResponse( tools, ...getDefaultCompletionOptions(model.defaultCompletionOptions), }, - abortController.signal + abortController.signal, ); }; @@ -194,7 +194,7 @@ export async function processStreamingResponse( try { const streamWithBackoff = withExponentialBackoff( streamFactory, - abortController.signal + abortController.signal, ); let chunkCount = 0; @@ -213,7 +213,7 @@ export async function processStreamingResponse( firstTokenTime - requestStartTime, model.model, "time_to_first_token", - (tools?.length || 0) > 0 + (tools?.length || 0) > 0, ); } @@ -332,7 +332,7 @@ export async function processStreamingResponse( totalDuration, model.model, "total_response_time", - (tools?.length || 0) > 0 + (tools?.length || 0) > 0, ); // Log API request event @@ -343,7 +343,7 @@ export async function processStreamingResponse( undefined, // no error inputTokens, outputTokens, - cost + cost, ); logger.debug("Stream complete", { @@ -363,7 +363,7 @@ export async function processStreamingResponse( model.model, errorDuration, false, // failed - error.message || String(error) + error.message || String(error), ); if (error.name === "AbortError" || abortController?.signal.aborted) { @@ -413,7 +413,7 @@ export async function processStreamingResponse( */ export async function preprocessStreamedToolCalls( toolCalls: ToolCall[], - callbacks?: StreamCallbacks + callbacks?: StreamCallbacks, ): Promise<{ preprocessedCalls: PreprocessedToolCall[]; errorChatEntries: ChatCompletionToolMessageParam[]; @@ -468,7 +468,7 @@ export async function preprocessStreamedToolCalls( toolCall.name, false, duration, - errorMessage + errorMessage, ); // Add error to chat history @@ -495,7 +495,7 @@ export async function preprocessStreamedToolCalls( export async function executeStreamedToolCalls( preprocessedCalls: PreprocessedToolCall[], callbacks?: StreamCallbacks, - isHeadless?: boolean + isHeadless?: boolean, ): Promise<{ hasRejection: boolean; chatHistoryEntries: ChatCompletionToolMessageParam[]; @@ -541,13 +541,13 @@ export async function executeStreamedToolCalls( const tool = allBuiltinTools.find((t) => t.name === toolCall.name); const toolName = tool?.displayName || toolCall.name; console.error( - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.` + `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, ); console.error( - `If you want to allow this tool, use --allow ${toolName}.` + `If you want to allow this tool, use --allow ${toolName}.`, ); console.error( - `If you don't want the tool to be included, use --exclude ${toolName}.` + `If you don't want the tool to be included, use --exclude ${toolName}.`, ); process.exit(1); @@ -570,21 +570,21 @@ export async function executeStreamedToolCalls( if (event.toolCall.name === toolCall.name) { toolPermissionManager.off( "permissionRequested", - handlePermissionRequested + handlePermissionRequested, ); // Notify UI about permission request callbacks.onToolPermissionRequest!( event.toolCall.name, event.toolCall.arguments, event.requestId, - event.toolCall.preview + event.toolCall.preview, ); } }; toolPermissionManager.on( "permissionRequested", - handlePermissionRequested + handlePermissionRequested, ); // Request permission using the proper API @@ -667,7 +667,7 @@ export async function streamChatResponse( model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, - callbacks?: StreamCallbacks + callbacks?: StreamCallbacks, ) { logger.debug("streamChatResponse called", { model, @@ -676,7 +676,7 @@ export async function streamChatResponse( }); const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS + SERVICE_NAMES.TOOL_PERMISSIONS, ); const isHeadless = serviceResult.value?.isHeadless ?? false; const tools = getAllTools(); @@ -701,7 +701,7 @@ export async function streamChatResponse( abortController, callbacks, isHeadless, - tools + tools, ); fullResponse += content; @@ -756,12 +756,12 @@ export async function streamChatResponse( await executeStreamedToolCalls( preprocessedCalls, callbacks, - isHeadless + isHeadless, ); if (isHeadless && hasRejection) { logger.debug( - "Tool call rejected in headless mode - returning current content" + "Tool call rejected in headless mode - returning current content", ); return finalResponse || content || fullResponse; } diff --git a/src/systemMessage.ts b/src/systemMessage.ts index 2a032ec15..cb947a27f 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -107,7 +107,7 @@ export async function constructSystemMessage( rulesSystemMessage: string, additionalRules?: string[], format?: "json", - headless?: boolean + headless?: boolean, ): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; @@ -136,7 +136,7 @@ export async function constructSystemMessage( processedRules.push(processedRule); } catch (error: any) { console.warn( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}` + `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, ); } } diff --git a/src/telemetry/posthogService.ts b/src/telemetry/posthogService.ts index 8ea9484f7..c5a76b722 100644 --- a/src/telemetry/posthogService.ts +++ b/src/telemetry/posthogService.ts @@ -24,7 +24,7 @@ export class PosthogService { "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { host: "https://app.posthog.com", - } + }, ); } } else { diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index c3e5a6929..c3165e181 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -110,13 +110,13 @@ class TelemetryService { `${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` || "http://localhost:4318/v1/metrics", headers: this.parseHeaders( - process.env.OTEL_EXPORTER_OTLP_HEADERS || "" + process.env.OTEL_EXPORTER_OTLP_HEADERS || "", ), }), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000" + process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", ), - }) + }), ); break; case "console": @@ -124,9 +124,9 @@ class TelemetryService { new PeriodicExportingMetricReader({ exporter: new ConsoleMetricExporter(), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000" + process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", ), - }) + }), ); break; } @@ -175,7 +175,7 @@ class TelemetryService { { description: "Count of CLI sessions started", unit: "count", - } + }, ); this.linesOfCodeCounter = this.meter.createCounter( @@ -183,7 +183,7 @@ class TelemetryService { { description: "Count of lines of code modified", unit: "count", - } + }, ); this.pullRequestCounter = this.meter.createCounter( @@ -191,7 +191,7 @@ class TelemetryService { { description: "Number of pull requests created", unit: "count", - } + }, ); this.commitCounter = this.meter.createCounter("continue.cli.commit.count", { @@ -214,7 +214,7 @@ class TelemetryService { { description: "Count of code editing tool permission decisions", unit: "count", - } + }, ); this.activeTimeCounter = this.meter.createCounter( @@ -222,7 +222,7 @@ class TelemetryService { { description: "Total active time in seconds", unit: "s", - } + }, ); // Additional Continue CLI specific metrics @@ -231,7 +231,7 @@ class TelemetryService { { description: "Authentication attempts", unit: "{attempt}", - } + }, ); this.mcpConnectionsGauge = this.meter.createObservableGauge( @@ -239,7 +239,7 @@ class TelemetryService { { description: "Active MCP connections", unit: "{connection}", - } + }, ); this.startupTimeHistogram = this.meter.createHistogram( @@ -247,7 +247,7 @@ class TelemetryService { { description: "Time from CLI start to ready state", unit: "ms", - } + }, ); this.responseTimeHistogram = this.meter.createHistogram( @@ -255,7 +255,7 @@ class TelemetryService { { description: "LLM response time metrics", unit: "ms", - } + }, ); } @@ -265,7 +265,7 @@ class TelemetryService { } private getStandardAttributes( - additionalAttributes: Record = {} + additionalAttributes: Record = {}, ) { const attributes: Record = { ...additionalAttributes }; @@ -319,7 +319,7 @@ class TelemetryService { public recordLinesOfCodeModified( type: "added" | "removed", count: number, - language?: string + language?: string, ) { if (!this.isEnabled()) return; @@ -352,7 +352,7 @@ class TelemetryService { public recordTokenUsage( tokens: number, type: "input" | "output" | "cacheRead" | "cacheCreation", - model: string + model: string, ) { if (!this.isEnabled()) return; @@ -362,7 +362,7 @@ class TelemetryService { public recordCodeEditDecision( tool: string, decision: "accept" | "reject", - language?: string + language?: string, ) { if (!this.isEnabled()) return; @@ -391,26 +391,26 @@ class TelemetryService { this.activeTimeCounter.add( this.totalActiveTime / 1000, - this.getStandardAttributes() + this.getStandardAttributes(), ); } } public recordAuthAttempt( result: "success" | "failure" | "cancelled", - method: "workos" | "token" + method: "workos" | "token", ) { if (!this.isEnabled()) return; this.authAttemptsCounter.add( 1, - this.getStandardAttributes({ result, method }) + this.getStandardAttributes({ result, method }), ); } public recordMCPConnection( serverName: string, - status: "connected" | "disconnected" | "error" + status: "connected" | "disconnected" | "error", ) { if (!this.isEnabled()) return; @@ -425,7 +425,7 @@ class TelemetryService { public recordStartupTime( timeMs: number, mode?: "tui" | "headless" | "standard", - coldStart?: boolean + coldStart?: boolean, ) { if (!this.isEnabled()) return; @@ -440,7 +440,7 @@ class TelemetryService { timeMs: number, model: string, metricType: "time_to_first_token" | "total_response_time", - hasTools?: boolean + hasTools?: boolean, ) { if (!this.isEnabled()) return; @@ -478,7 +478,7 @@ class TelemetryService { error?: string, decision?: "accept" | "reject", source?: string, - toolParameters?: string + toolParameters?: string, ) { if (!this.isEnabled()) return; @@ -506,7 +506,7 @@ class TelemetryService { error?: string, inputTokens?: number, outputTokens?: number, - costUsd?: number + costUsd?: number, ) { if (!this.isEnabled()) return; diff --git a/src/telemetry/utils.ts b/src/telemetry/utils.ts index 43aaa92c7..6f968033a 100644 --- a/src/telemetry/utils.ts +++ b/src/telemetry/utils.ts @@ -7,7 +7,7 @@ import { diffLines } from "diff"; */ export function calculateLinesOfCodeDiff( oldContent: string, - newContent: string + newContent: string, ): { added: number; removed: number } { const diff = diffLines(oldContent, newContent); let added = 0; @@ -119,7 +119,7 @@ export function isPullRequestCommand(command: string): boolean { export function calculateTokenCost( inputTokens: number, outputTokens: number, - model: string + model: string, ): number { // Pricing per 1K tokens (these are approximate and should be updated) const pricingMap: Record = { @@ -134,7 +134,7 @@ export function calculateTokenCost( // Find pricing for model (case insensitive partial match) const modelKey = Object.keys(pricingMap).find((key) => - model.toLowerCase().includes(key.toLowerCase()) + model.toLowerCase().includes(key.toLowerCase()), ); if (!modelKey) { diff --git a/src/test-helpers/README.md b/src/test-helpers/README.md index 583a40099..f9902fd4d 100644 --- a/src/test-helpers/README.md +++ b/src/test-helpers/README.md @@ -9,7 +9,10 @@ The `mock-llm-server.ts` module provides utilities for creating mock LLM servers ### Basic Usage ```typescript -import { setupMockLLMTest, cleanupMockLLMServer } from "../test-helpers/mock-llm-server.js"; +import { + setupMockLLMTest, + cleanupMockLLMServer, +} from "../test-helpers/mock-llm-server.js"; describe("My Test", () => { let context: any; @@ -87,13 +90,17 @@ expect(mockServer.requests[0].body.messages[0].content).toBe("User prompt"); ### API Reference #### `setupMockLLMTest(context, options)` + Sets up a complete test environment with mock LLM server, config file, and skips onboarding. #### `createMockLLMServer(options)` + Creates just the mock server without test environment setup. #### `createMockLLMConfig(mockServer, modelName)` + Generates a config YAML string for the mock server. #### `cleanupMockLLMServer(mockServer)` -Properly shuts down the mock server. \ No newline at end of file + +Properly shuts down the mock server. diff --git a/src/test-helpers/adapter-mocks.ts b/src/test-helpers/adapter-mocks.ts index 0213cb7c8..a8b0a4b7b 100644 --- a/src/test-helpers/adapter-mocks.ts +++ b/src/test-helpers/adapter-mocks.ts @@ -13,38 +13,42 @@ export function mockLLMResponse(response: string) { const words = response.split(" "); for (const word of words) { yield { - choices: [{ - delta: { - content: word + " " - } - }] + choices: [ + { + delta: { + content: word + " ", + }, + }, + ], }; } }, - + chatCompletion: async () => ({ - choices: [{ - message: { - role: "assistant", - content: response - } - }] + choices: [ + { + message: { + role: "assistant", + content: response, + }, + }, + ], }), - + // Add any other methods that might be used completionStream: async function* () { yield response; }, - + completion: async () => response, }; vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, BaseLlmApi: MockBaseLlmApi, - LLMConfig: {} + LLMConfig: {}, })); - + return mockApi; } @@ -56,39 +60,43 @@ export function mockLLMStreamResponse(chunks: string[]) { chatCompletionStream: async function* () { for (const chunk of chunks) { yield { - choices: [{ - delta: { - content: chunk - } - }] + choices: [ + { + delta: { + content: chunk, + }, + }, + ], }; } }, - + chatCompletion: async () => ({ - choices: [{ - message: { - role: "assistant", - content: chunks.join("") - } - }] + choices: [ + { + message: { + role: "assistant", + content: chunks.join(""), + }, + }, + ], }), - + completionStream: async function* () { for (const chunk of chunks) { yield chunk; } }, - + completion: async () => chunks.join(""), }; vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, BaseLlmApi: MockBaseLlmApi, - LLMConfig: {} + LLMConfig: {}, })); - + return mockApi; } @@ -100,15 +108,15 @@ export function mockLLMError(errorMessage: string) { chatCompletionStream: async function* () { throw new Error(errorMessage); }, - + chatCompletion: async () => { throw new Error(errorMessage); }, - + completionStream: async function* () { throw new Error(errorMessage); }, - + completion: async () => { throw new Error(errorMessage); }, @@ -117,9 +125,9 @@ export function mockLLMError(errorMessage: string) { vi.doMock("@continuedev/openai-adapters", () => ({ constructLlmApi: () => mockApi, BaseLlmApi: MockBaseLlmApi, - LLMConfig: {} + LLMConfig: {}, })); - + return mockApi; } @@ -128,4 +136,4 @@ export function mockLLMError(errorMessage: string) { */ export function clearLLMMocks() { vi.unmock("@continuedev/openai-adapters"); -} \ No newline at end of file +} diff --git a/src/test-helpers/cli-helpers.ts b/src/test-helpers/cli-helpers.ts index 341af220a..5d1ffc75f 100644 --- a/src/test-helpers/cli-helpers.ts +++ b/src/test-helpers/cli-helpers.ts @@ -37,7 +37,9 @@ export async function createTestContext(): Promise { try { await fs.access(cliPath); } catch { - throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`); + throw new Error( + `CLI file not found at ${cliPath}. Please run 'npm run build' first.`, + ); } return { @@ -50,7 +52,7 @@ export async function createTestContext(): Promise { * Cleans up test context */ export async function cleanupTestContext( - context: CLITestContext + context: CLITestContext, ): Promise { try { await fs.rm(context.testDir, { recursive: true, force: true }); @@ -64,7 +66,7 @@ export async function cleanupTestContext( */ export async function runCLI( context: CLITestContext, - options: CLIRunOptions = {} + options: CLIRunOptions = {}, ): Promise { const { args = [], @@ -85,7 +87,7 @@ export async function runCLI( HOMEDRIVE: path.parse(context.testDir).root, HOMEPATH: path.relative( path.parse(context.testDir).root, - context.testDir + context.testDir, ), ...env, }, @@ -121,7 +123,7 @@ export async function runCLI( */ export async function createTestConfig( context: CLITestContext, - config: any + config: any, ): Promise { const configPath = path.join(context.testDir, "test-config.yaml"); const configContent = @@ -139,7 +141,7 @@ export async function createTestConfig( export async function createTestRule( context: CLITestContext, ruleName: string, - content: string + content: string, ): Promise { const rulePath = path.join(context.testDir, `${ruleName}.md`); await fs.writeFile(rulePath, content); @@ -150,7 +152,7 @@ export async function createTestRule( * Reads the session file if it exists */ export async function readSession( - context: CLITestContext + context: CLITestContext, ): Promise { try { const sessionDir = path.join(context.testDir, ".continue", "sessions"); @@ -176,7 +178,7 @@ export async function readSession( */ export async function createMockSession( context: CLITestContext, - messages: any[] + messages: any[], ): Promise { const sessionDir = path.join(context.testDir, ".continue", "sessions"); await fs.mkdir(sessionDir, { recursive: true }); @@ -203,7 +205,7 @@ export async function createMockSession( export function waitForPattern( proc: Subprocess, pattern: RegExp | string, - timeout: number = 5000 + timeout: number = 5000, ): Promise { return new Promise((resolve, reject) => { let output = ""; @@ -236,7 +238,7 @@ export function waitForPattern( export async function withInteractiveInput( context: CLITestContext, args: string[], - inputs: string[] + inputs: string[], ): Promise { const proc = execaNode(context.cliPath, args, { cwd: context.testDir, @@ -249,7 +251,7 @@ export async function withInteractiveInput( HOMEDRIVE: path.parse(context.testDir).root, HOMEPATH: path.relative( path.parse(context.testDir).root, - context.testDir + context.testDir, ), }, }); diff --git a/src/test-helpers/mock-helpers.ts b/src/test-helpers/mock-helpers.ts index 91f09b5f3..d90c469ff 100644 --- a/src/test-helpers/mock-helpers.ts +++ b/src/test-helpers/mock-helpers.ts @@ -12,13 +12,15 @@ export interface MockAPIOptions { */ export function mockOpenAIChat( response: string, - options: MockAPIOptions = {} + options: MockAPIOptions = {}, ): nock.Scope { - const { baseURL = "https://api.openai.com", delay = 0, error = false } = options; + const { + baseURL = "https://api.openai.com", + delay = 0, + error = false, + } = options; - const scope = nock(baseURL) - .post("/v1/chat/completions") - .delay(delay); + const scope = nock(baseURL).post("/v1/chat/completions").delay(delay); if (error) { return scope.reply(500, { error: { message: "Internal server error" } }); @@ -52,46 +54,52 @@ export function mockOpenAIChat( */ export function mockOpenAIStream( chunks: string[], - options: MockAPIOptions = {} + options: MockAPIOptions = {}, ): nock.Scope { - const { baseURL = "https://api.openai.com", delay = 0, error = false } = options; + const { + baseURL = "https://api.openai.com", + delay = 0, + error = false, + } = options; - const scope = nock(baseURL) - .post("/v1/chat/completions") - .delay(delay); + const scope = nock(baseURL).post("/v1/chat/completions").delay(delay); if (error) { return scope.reply(500, { error: { message: "Internal server error" } }); } - return scope.reply(200, () => { - // Return a stream of Server-Sent Events - const events = chunks.map((chunk, index) => { - const data = { - id: `chatcmpl-test`, - object: "chat.completion.chunk", - created: Date.now(), - model: "gpt-4", - choices: [ - { - index: 0, - delta: { - content: chunk, + return scope.reply( + 200, + () => { + // Return a stream of Server-Sent Events + const events = chunks.map((chunk, index) => { + const data = { + id: `chatcmpl-test`, + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-4", + choices: [ + { + index: 0, + delta: { + content: chunk, + }, + finish_reason: index === chunks.length - 1 ? "stop" : null, }, - finish_reason: index === chunks.length - 1 ? "stop" : null, - }, - ], - }; - return `data: ${JSON.stringify(data)}\n\n`; - }); - - events.push("data: [DONE]\n\n"); - return events.join(""); - }, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", - }); + ], + }; + return `data: ${JSON.stringify(data)}\n\n`; + }); + + events.push("data: [DONE]\n\n"); + return events.join(""); + }, + { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + ); } /** @@ -113,10 +121,15 @@ export function mockWorkOSAuth(options: { // Mock token exchange nock("https://api.workos.com") .post("/user_management/authenticate") - .reply(error ? 401 : 200, error ? { error: "Invalid credentials" } : { - access_token: accessToken, - user: userInfo, - }); + .reply( + error ? 401 : 200, + error + ? { error: "Invalid credentials" } + : { + access_token: accessToken, + user: userInfo, + }, + ); // Mock get user info nock("https://api.workos.com") @@ -128,9 +141,14 @@ export function mockWorkOSAuth(options: { nock("https://api.workos.com") .get("/user_management/organizations") .matchHeader("authorization", `Bearer ${accessToken}`) - .reply(error ? 401 : 200, error ? { error: "Unauthorized" } : { - data: organizations, - }); + .reply( + error ? 401 : 200, + error + ? { error: "Unauthorized" } + : { + data: organizations, + }, + ); } /** @@ -150,7 +168,9 @@ export function createMockConfig(overrides: any = {}): any { /** * Creates mock chat messages */ -export function createMockMessages(count: number = 2): ChatCompletionMessageParam[] { +export function createMockMessages( + count: number = 2, +): ChatCompletionMessageParam[] { const messages: ChatCompletionMessageParam[] = [ { role: "system", content: "You are a helpful assistant." }, ]; @@ -158,7 +178,7 @@ export function createMockMessages(count: number = 2): ChatCompletionMessagePara for (let i = 0; i < count; i++) { messages.push( { role: "user", content: `Test message ${i + 1}` }, - { role: "assistant", content: `Test response ${i + 1}` } + { role: "assistant", content: `Test response ${i + 1}` }, ); } @@ -170,4 +190,4 @@ export function createMockMessages(count: number = 2): ChatCompletionMessagePara */ export function cleanupMocks(): void { nock.cleanAll(); -} \ No newline at end of file +} diff --git a/src/test-helpers/mock-llm-server.ts b/src/test-helpers/mock-llm-server.ts index 292416338..f08508fd4 100644 --- a/src/test-helpers/mock-llm-server.ts +++ b/src/test-helpers/mock-llm-server.ts @@ -33,7 +33,7 @@ export interface MockLLMServer { * @returns A promise that resolves to the mock server instance */ export async function createMockLLMServer( - options: MockLLMServerOptions = {} + options: MockLLMServerOptions = {}, ): Promise { const { response = "Hello World!", @@ -55,7 +55,7 @@ export async function createMockLLMServer( res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader( "Access-Control-Allow-Headers", - "Content-Type, Authorization" + "Content-Type, Authorization", ); if (req.method === "OPTIONS") { @@ -115,7 +115,7 @@ export async function createMockLLMServer( // Properly escape JSON content const escapedContent = JSON.stringify(content).slice(1, -1); res.write( - `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n` + `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`, ); }); } else { @@ -123,7 +123,7 @@ export async function createMockLLMServer( // Properly escape JSON content const escapedContent = JSON.stringify(responseText).slice(1, -1); res.write( - `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n` + `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`, ); } @@ -188,7 +188,7 @@ export async function createMockLLMServer( */ export function createMockLLMConfig( mockServer: MockLLMServer, - modelName: string = "gpt-4" + modelName: string = "gpt-4", ): string { return `name: Test Assistant version: 1.0.0 @@ -212,7 +212,7 @@ models: */ export async function setupMockLLMTest( context: CLITestContext, - options: MockLLMServerOptions = {} + options: MockLLMServerOptions = {}, ): Promise { // Create mock server const mockServer = await createMockLLMServer(options); @@ -227,7 +227,7 @@ export async function setupMockLLMTest( const onboardingFlagPath = path.join( context.testDir, ".continue", - ".onboarding_complete" + ".onboarding_complete", ); await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true }); await fs.writeFile(onboardingFlagPath, new Date().toISOString()); @@ -240,7 +240,7 @@ export async function setupMockLLMTest( * @param mockServer The mock server to clean up */ export async function cleanupMockLLMServer( - mockServer: MockLLMServer + mockServer: MockLLMServer, ): Promise { return new Promise((resolve) => { if (!mockServer?.server) { @@ -273,7 +273,7 @@ export async function cleanupMockLLMServer( } resolveOnce(); }); - + // Force close after a short timeout setTimeout(() => { if (mockServer.server.listening) { diff --git a/src/test-helpers/renderWithServices.tsx b/src/test-helpers/renderWithServices.tsx index 64e4b46ac..78e715e82 100644 --- a/src/test-helpers/renderWithServices.tsx +++ b/src/test-helpers/renderWithServices.tsx @@ -1,9 +1,12 @@ -import { render } from 'ink-testing-library'; -import React from 'react'; +import { render } from "ink-testing-library"; +import React from "react"; -import { ServiceContainerProvider } from '../services/ServiceContainerContext.js'; +import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; -import { createTestServiceContainer, TestServiceContainer } from './testServiceContainer.js'; +import { + createTestServiceContainer, + TestServiceContainer, +} from "./testServiceContainer.js"; export interface RenderWithServicesOptions { services?: Record; @@ -23,25 +26,25 @@ export interface RenderWithServicesResult { export function renderWithServices( ui: React.ReactElement, - options?: RenderWithServicesOptions + options?: RenderWithServicesOptions, ): RenderWithServicesResult { const container = options?.container || createTestServiceContainer(); - + // Register default services if provided if (options?.services) { Object.entries(options.services).forEach(([name, value]) => { container.register(name, () => Promise.resolve(value)); }); } - + const rendered = render( {ui} - + , ); - + return { ...rendered, container, }; -} \ No newline at end of file +} diff --git a/src/test-helpers/testServiceContainer.ts b/src/test-helpers/testServiceContainer.ts index 5e8913eb9..e8d52fb44 100644 --- a/src/test-helpers/testServiceContainer.ts +++ b/src/test-helpers/testServiceContainer.ts @@ -1,5 +1,5 @@ -import { ServiceContainer } from '../services/ServiceContainer.js'; -import { ServiceState } from '../services/types.js'; +import { ServiceContainer } from "../services/ServiceContainer.js"; +import { ServiceState } from "../services/types.js"; export interface TestServiceContainer extends ServiceContainer { waitForReady(...serviceNames: string[]): Promise; @@ -10,108 +10,112 @@ export interface TestServiceContainer extends ServiceContainer { export function createTestServiceContainer(): TestServiceContainer { const container = new ServiceContainer() as TestServiceContainer; - const serviceResolvers = new Map void; - reject: (error: Error) => void; - promise?: Promise; - }>(); - + const serviceResolvers = new Map< + string, + { + resolve: (value: any) => void; + reject: (error: Error) => void; + promise?: Promise; + } + >(); + // Override load instead of register to have more control - container.load = async function(serviceName: string) { + container.load = async function (serviceName: string) { // Check if we already have a resolver for this service const existing = serviceResolvers.get(serviceName); if (existing && existing.promise) { return existing.promise; } - + // Create a controllable promise let promiseResolve: (value: any) => void; let promiseReject: (error: Error) => void; - + const promise = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); - - serviceResolvers.set(serviceName, { - resolve: promiseResolve!, - reject: promiseReject!, - promise + + serviceResolvers.set(serviceName, { + resolve: promiseResolve!, + reject: promiseReject!, + promise, }); - + // Update service state to loading const currentState = container.getSync(serviceName); - if (currentState.state === 'idle' || currentState.state === 'error') { + if (currentState.state === "idle" || currentState.state === "error") { container.emit(`${serviceName}:loading`); // Manually update the internal state (we'll need to expose this) (container as any).services.set(serviceName, { value: null, - state: 'loading' as ServiceState, - error: null + state: "loading" as ServiceState, + error: null, }); } - + return promise; }; - + // Helper to resolve a service on demand - container.resolveService = function(name, value) { + container.resolveService = function (name, value) { const resolver = serviceResolvers.get(name); if (resolver) { // Update internal state (container as any).services.set(name, { value, - state: 'ready' as ServiceState, + state: "ready" as ServiceState, error: null, - lastUpdated: new Date() + lastUpdated: new Date(), }); - + // Emit ready event container.emit(`${name}:ready`, value); - + // Resolve the promise resolver.resolve(value); } }; - + // Helper to reject a service - container.rejectService = function(name, error) { + container.rejectService = function (name, error) { const resolver = serviceResolvers.get(name); if (resolver) { // Update internal state (container as any).services.set(name, { value: null, - state: 'error' as ServiceState, + state: "error" as ServiceState, error, - lastUpdated: new Date() + lastUpdated: new Date(), }); - + // Emit error event container.emit(`${name}:error`, error); - + // Reject the promise resolver.reject(error); } }; - + // Wait for specific services to be ready - container.waitForReady = async function(...names) { - const promises = names.map(name => - new Promise(resolve => { - container.once(`${name}:ready`, () => resolve()); - container.once(`${name}:error`, () => resolve()); - }) + container.waitForReady = async function (...names) { + const promises = names.map( + (name) => + new Promise((resolve) => { + container.once(`${name}:ready`, () => resolve()); + container.once(`${name}:error`, () => resolve()); + }), ); await Promise.all(promises); }; - + // Wait for a specific service and return its value - container.waitForService = async function(name) { + container.waitForService = async function (name) { return new Promise((resolve) => { container.once(`${name}:ready`, (value) => resolve(value)); container.once(`${name}:error`, (error) => resolve(error)); }); }; - + return container; -} \ No newline at end of file +} diff --git a/src/test-helpers/ui-test-context-minimal.ts b/src/test-helpers/ui-test-context-minimal.ts index 128f0ded8..142019d2d 100644 --- a/src/test-helpers/ui-test-context-minimal.ts +++ b/src/test-helpers/ui-test-context-minimal.ts @@ -56,6 +56,6 @@ export function createMinimalTestContext() { return { cleanup: () => { vi.clearAllMocks(); - } + }, }; -} \ No newline at end of file +} diff --git a/src/test-helpers/ui-test-context.ts b/src/test-helpers/ui-test-context.ts index 7ea69ae53..092f16098 100644 --- a/src/test-helpers/ui-test-context.ts +++ b/src/test-helpers/ui-test-context.ts @@ -11,14 +11,16 @@ export interface UITestContext { /** * Creates a test context with common UI mocks for TUI components */ -export function createUITestContext(options: { - serviceValue?: any; - serviceState?: "idle" | "loading" | "ready" | "error"; - services?: Record; - allServicesReady?: boolean; - chatMessages?: any[]; - isWaitingForResponse?: boolean; -} = {}): UITestContext { +export function createUITestContext( + options: { + serviceValue?: any; + serviceState?: "idle" | "loading" | "ready" | "error"; + services?: Record; + allServicesReady?: boolean; + chatMessages?: any[]; + isWaitingForResponse?: boolean; + } = {}, +): UITestContext { const { serviceValue = null, serviceState = "idle", @@ -101,4 +103,4 @@ export function createMinimalTestContext(): { cleanup: () => void } { }; return { cleanup }; -} \ No newline at end of file +} diff --git a/src/tools/index.ts b/src/tools/index.ts index 17141a360..47b65cc17 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -42,11 +42,11 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; // Get dynamic tools based on current state function getDynamicTools(): Tool[] { const dynamicTools: Tool[] = []; - + // Add headless-specific tools if in headless mode try { const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS + SERVICE_NAMES.TOOL_PERMISSIONS, ); const isHeadless = serviceResult.value?.isHeadless ?? false; if (isHeadless) { @@ -55,7 +55,7 @@ function getDynamicTools(): Tool[] { } catch { // Service not ready yet, no dynamic tools } - + return dynamicTools; } @@ -71,7 +71,7 @@ export function getToolDisplayName(toolName: string): string { } export function extractToolCalls( - response: string + response: string, ): Array<{ name: string; arguments: Record }> { const toolCallRegex = /([\s\S]*?)<\/tool>/g; const matches = [...response.matchAll(toolCallRegex)]; @@ -112,7 +112,6 @@ function convertInputSchemaToParameters(inputSchema: any): ToolParameters { } export async function getAvailableTools() { - // Load MCP tools const mcpTools: Tool[] = MCPService.getInstance() @@ -135,7 +134,7 @@ export async function getAvailableTools() { } export async function executeToolCall( - toolCall: PreprocessedToolCall + toolCall: PreprocessedToolCall, ): Promise { const startTime = Date.now(); @@ -148,7 +147,7 @@ export async function executeToolCall( // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args // Preprocessed arg names may be different const result = await toolCall.tool.run( - toolCall.preprocessResult?.args ?? toolCall.arguments + toolCall.preprocessResult?.args ?? toolCall.arguments, ); const duration = Date.now() - startTime; @@ -159,7 +158,7 @@ export async function executeToolCall( undefined, // no error undefined, // no decision undefined, // no source - JSON.stringify(toolCall.arguments) + JSON.stringify(toolCall.arguments), ); logger.debug("Tool execution completed", { @@ -179,7 +178,7 @@ export async function executeToolCall( errorMessage, undefined, // no decision undefined, // no source - JSON.stringify(toolCall.arguments) + JSON.stringify(toolCall.arguments), ); return `Error executing tool "${toolCall.name}": ${errorMessage}`; @@ -194,7 +193,7 @@ export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { toolCall.arguments[paramName] === null) ) { throw new Error( - `Required parameter "${paramName}" missing for tool "${toolCall.name}"` + `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, ); } } diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index 3c32f13e5..999bbd3c2 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -46,9 +46,10 @@ export const runTerminalCommandTool: Tool = { let timeoutId: NodeJS.Timeout; let isResolved = false; - const TIMEOUT_MS = process.env.NODE_ENV === 'test' && process.env.TEST_TERMINAL_TIMEOUT - ? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10) - : 30000; // 30 seconds default, configurable for tests + const TIMEOUT_MS = + process.env.NODE_ENV === "test" && process.env.TEST_TERMINAL_TIMEOUT + ? parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10) + : 30000; // 30 seconds default, configurable for tests const resetTimeout = () => { if (timeoutId) { @@ -60,7 +61,8 @@ export const runTerminalCommandTool: Tool = { child.kill(); const output = stdout + (stderr ? `\nStderr: ${stderr}` : ""); resolve( - output + `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]` + output + + `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`, ); }, TIMEOUT_MS); }; @@ -81,7 +83,7 @@ export const runTerminalCommandTool: Tool = { child.on("close", (code) => { if (isResolved) return; isResolved = true; - + if (timeoutId) { clearTimeout(timeoutId); } @@ -111,7 +113,7 @@ export const runTerminalCommandTool: Tool = { child.on("error", (error) => { if (isResolved) return; isResolved = true; - + if (timeoutId) { clearTimeout(timeoutId); } diff --git a/src/tools/searchAndReplace/findSearchMatch.ts b/src/tools/searchAndReplace/findSearchMatch.ts index bb731e6a5..9597d5070 100644 --- a/src/tools/searchAndReplace/findSearchMatch.ts +++ b/src/tools/searchAndReplace/findSearchMatch.ts @@ -21,7 +21,7 @@ export interface SearchMatchResult extends BasicMatchResult { */ type MatchStrategy = ( fileContent: string, - searchContent: string + searchContent: string, ) => BasicMatchResult | null; /** @@ -29,7 +29,7 @@ type MatchStrategy = ( */ function exactMatch( fileContent: string, - searchContent: string + searchContent: string, ): BasicMatchResult | null { const exactIndex = fileContent.indexOf(searchContent); if (exactIndex !== -1) { @@ -46,7 +46,7 @@ function exactMatch( */ function trimmedMatch( fileContent: string, - searchContent: string + searchContent: string, ): BasicMatchResult | null { const trimmedSearchContent = searchContent.trim(); const trimmedIndex = fileContent.indexOf(trimmedSearchContent); @@ -65,7 +65,7 @@ function trimmedMatch( */ function whitespaceIgnoredMatch( fileContent: string, - searchContent: string + searchContent: string, ): BasicMatchResult | null { // Remove all whitespace (spaces, tabs, newlines, etc.) const strippedFileContent = fileContent.replace(/\s/g, ""); @@ -171,7 +171,7 @@ function jaroSimilarity(s1: string, s2: string): number { function jaroWinklerSimilarity( s1: string, s2: string, - prefixScale = 0.1 + prefixScale = 0.1, ): number { const jaroSim = jaroSimilarity(s1, s2); @@ -198,7 +198,7 @@ function jaroWinklerSimilarity( function findFuzzyMatch( fileContent: string, searchContent: string, - threshold: number = 0.9 + threshold: number = 0.9, ): BasicMatchResult | null { const searchLines = searchContent.split("\n"); const fileLines = fileContent.split("\n"); @@ -296,7 +296,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ */ export function findSearchMatch( fileContent: string, - searchContent: string + searchContent: string, ): SearchMatchResult | null { const trimmedSearchContent = searchContent.trim(); diff --git a/src/tools/searchAndReplace/index.ts b/src/tools/searchAndReplace/index.ts index 86e27552b..ddcffc7a7 100644 --- a/src/tools/searchAndReplace/index.ts +++ b/src/tools/searchAndReplace/index.ts @@ -125,7 +125,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a if (!match) { throw new Error( - `Search content not found in block ${i + 1}:\n${searchContent}` + `Search content not found in block ${i + 1}:\n${searchContent}`, ); } @@ -162,7 +162,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a // Get lines for telemetry const { added, removed } = calculateLinesOfCodeDiff( args.oldContent, - args.newContent + args.newContent, ); const language = getLanguageFromFilePath(args.filepath); @@ -173,7 +173,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a telemetryService.recordLinesOfCodeModified( "removed", removed, - language + language, ); } @@ -183,7 +183,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a throw new Error( `Error: failed to edit ${args.filepath}:\n ${ error instanceof Error ? error.message : String(error) - }` + }`, ); } }, diff --git a/src/tools/searchAndReplace/parseBlock.ts b/src/tools/searchAndReplace/parseBlock.ts index 8bc4088c0..64fa901a2 100644 --- a/src/tools/searchAndReplace/parseBlock.ts +++ b/src/tools/searchAndReplace/parseBlock.ts @@ -28,7 +28,7 @@ export interface SearchReplaceBlockResult { * @returns ParseResult with completion status and extracted content */ export function parseSearchReplaceBlock( - content: string + content: string, ): SearchReplaceBlockResult { const lines = content.split("\n"); @@ -99,7 +99,7 @@ export function parseSearchReplaceBlock( * @throws Error if any malformed blocks are encountered */ export function parseAllSearchReplaceBlocks( - content: string + content: string, ): SearchReplaceBlockResult[] { const blocks: SearchReplaceBlockResult[] = []; const lines = content.split("\n"); diff --git a/src/tools/types.ts b/src/tools/types.ts index 48758e46f..e70c96e7b 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -44,4 +44,4 @@ export interface ToolCall { export interface PreprocessedToolCall extends ToolCall { tool: Tool; preprocessResult?: PreprocessToolCallResult; -} \ No newline at end of file +} diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index 9a3b3a770..2d3ad8377 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -14,7 +14,7 @@ import { Tool, ToolCallPreview } from "./types.js"; export function generateDiff( oldContent: string, newContent: string, - filePath: string + filePath: string, ): string { return createTwoFilesPatch( filePath, @@ -23,7 +23,7 @@ export function generateDiff( newContent, undefined, undefined, - { context: 3 } + { context: 3 }, ); } @@ -58,7 +58,7 @@ export const writeFileTool: Tool = { newContent, undefined, undefined, - { context: 2 } + { context: 2 }, ); return { @@ -124,7 +124,7 @@ export const writeFileTool: Tool = { if (oldContent) { const { added, removed } = calculateLinesOfCodeDiff( oldContent, - args.content + args.content, ); const language = getLanguageFromFilePath(args.filepath); @@ -135,7 +135,7 @@ export const writeFileTool: Tool = { telemetryService.recordLinesOfCodeModified( "removed", removed, - language + language, ); } @@ -148,7 +148,7 @@ export const writeFileTool: Tool = { telemetryService.recordLinesOfCodeModified( "added", lineCount, - language + language, ); return `Successfully created file: ${args.filepath}`; diff --git a/src/ui/AppRoot.tsx b/src/ui/AppRoot.tsx index 84dd2094a..8f2c1c193 100644 --- a/src/ui/AppRoot.tsx +++ b/src/ui/AppRoot.tsx @@ -21,4 +21,4 @@ export const AppRoot: React.FC = (props) => { ); -}; \ No newline at end of file +}; diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index 40b13c239..ecc7c34e9 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -85,7 +85,7 @@ function useWordLevelDiff(oldContent: string, newContent: string) { function renderWordLevelContent( changes: Change[], - showType: "removed" | "added" + showType: "removed" | "added", ): React.ReactNode { const segments: React.ReactNode[] = []; @@ -96,7 +96,7 @@ function renderWordLevelContent( segments.push( {change.value} - + , ); } else if (!change.added) { // Unchanged text - no special styling @@ -108,7 +108,7 @@ function renderWordLevelContent( segments.push( {change.value} - + , ); } else if (!change.removed) { // Unchanged text - no special styling @@ -125,8 +125,8 @@ const WordLevelDiffGroup: React.FC<{ delLines: DiffLine[]; addLines: DiffLine[]; }> = ({ groupIndex, delLines, addLines }) => { - const oldContent = delLines.map(l => l.content).join('\n'); - const newContent = addLines.map(l => l.content).join('\n'); + const oldContent = delLines.map((l) => l.content).join("\n"); + const newContent = addLines.map((l) => l.content).join("\n"); const changes = useWordLevelDiff(oldContent, newContent); return ( @@ -163,7 +163,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ } const displayableLines = parsedLines.filter( - (l) => l.type !== "hunk" && l.type !== "other" + (l) => l.type !== "hunk" && l.type !== "other", ); const truncatedLines = displayableLines.slice(0, 16); @@ -193,7 +193,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ } else { // Single type, treat as individual lines currentGroup.forEach((l) => - groupedLines.push({ type: "single", lines: [l] }) + groupedLines.push({ type: "single", lines: [l] }), ); } } else { diff --git a/src/ui/FileSearchUI.tsx b/src/ui/FileSearchUI.tsx index 0fb65c15d..74dfb51c1 100644 --- a/src/ui/FileSearchUI.tsx +++ b/src/ui/FileSearchUI.tsx @@ -263,7 +263,7 @@ export async function throttledGlob( patterns: string[], options: GlobOptionsWithFileTypesFalse, batchSize = 100, - delay = 20 + delay = 20, ): Promise { return new Promise((resolve, reject) => { const allMatches: string[] = []; diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx index ecd1e42e4..5a2c7c78d 100644 --- a/src/ui/FreeTrialStatus.tsx +++ b/src/ui/FreeTrialStatus.tsx @@ -25,7 +25,7 @@ const FreeTrialStatus: React.FC = ({ model, }) => { const [status, setStatus] = useState( - null + null, ); const [loading, setLoading] = useState(true); diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx index 83db00016..c4bcf7021 100644 --- a/src/ui/FreeTrialTransitionUI.tsx +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -9,7 +9,10 @@ import useSWR from "swr"; import { listUserOrganizations } from "../auth/workos.js"; import { env } from "../env.js"; -import { isValidAnthropicApiKey, getApiKeyValidationError } from "../util/apiKeyValidation.js"; +import { + isValidAnthropicApiKey, + getApiKeyValidationError, +} from "../util/apiKeyValidation.js"; import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; import { useNavigation } from "./context/NavigationContext.js"; @@ -30,10 +33,10 @@ async function createOrUpdateConfig(apiKey: string): Promise { fs.mkdirSync(configDir, { recursive: true }); } - const existingContent = fs.existsSync(CONFIG_PATH) + const existingContent = fs.existsSync(CONFIG_PATH) ? fs.readFileSync(CONFIG_PATH, "utf8") : ""; - + const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); } @@ -50,7 +53,7 @@ const FreeTrialTransitionUI: React.FC = ({ const [errorMessage, setErrorMessage] = useState(""); const [successMessage, setSuccessMessage] = useState(""); const [wasModelsSetup, setWasModelsSetup] = useState(false); - + // Fetch organizations using SWR const { data: organizations } = useSWR( "organizations", @@ -59,9 +62,9 @@ const FreeTrialTransitionUI: React.FC = ({ revalidateOnFocus: false, revalidateOnReconnect: false, shouldRetryOnError: false, - } + }, ); - + const hasOrganizations = organizations && organizations.length > 0; useInput((input, key) => { @@ -116,12 +119,12 @@ const FreeTrialTransitionUI: React.FC = ({ try { await open(modelsUrl); setSuccessMessage( - `Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.` + `Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.`, ); setCurrentStep("success"); } catch { setErrorMessage( - `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.` + `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.`, ); setCurrentStep("error"); } @@ -131,10 +134,10 @@ const FreeTrialTransitionUI: React.FC = ({ setWasModelsSetup(false); // This is not models setup } else if (selectedOption === 3) { // Option 3: Switch to different configuration - navigateTo('config'); + navigateTo("config"); } else if (selectedOption === 4 && hasOrganizations) { // Option 4: Switch to organization - navigateTo('organization'); + navigateTo("organization"); } }; @@ -144,7 +147,7 @@ const FreeTrialTransitionUI: React.FC = ({ try { await createOrUpdateConfig(apiKey); setSuccessMessage( - "✓ API key saved successfully! Switching to local configuration..." + "✓ API key saved successfully! Switching to local configuration...", ); setCurrentStep("success"); @@ -155,7 +158,7 @@ const FreeTrialTransitionUI: React.FC = ({ }, 1000); } catch (error) { setErrorMessage( - `❌ Error saving API key: ${error}. Press Enter to try again.` + `❌ Error saving API key: ${error}. Press Enter to try again.`, ); setCurrentStep("error"); } @@ -179,19 +182,23 @@ const FreeTrialTransitionUI: React.FC = ({ (recommended) - {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API key + {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API + key - {selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different configuration + {selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different + configuration {hasOrganizations && ( - {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization profile + {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization + profile )} - Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, Enter to confirm + Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, + Enter to confirm ); diff --git a/src/ui/IntroMessage.tsx b/src/ui/IntroMessage.tsx index cbf5f378a..5e7a10e49 100644 --- a/src/ui/IntroMessage.tsx +++ b/src/ui/IntroMessage.tsx @@ -30,7 +30,7 @@ const IntroMessage: React.FC = ({ const commandLineRules = args.rules || []; const configRules = config.rules?.map((rule: any) => - typeof rule === "string" ? rule : rule?.name || "Unknown" + typeof rule === "string" ? rule : rule?.name || "Unknown", ) || []; const allRules = [...commandLineRules, ...configRules]; @@ -54,7 +54,9 @@ const IntroMessage: React.FC = ({ {!modelCapable && ( <> - + )} @@ -108,4 +110,4 @@ const IntroMessage: React.FC = ({ ); }; -export { IntroMessage }; \ No newline at end of file +export { IntroMessage }; diff --git a/src/ui/LoadingAnimation.tsx b/src/ui/LoadingAnimation.tsx index 8954c7d64..fc11bec1f 100644 --- a/src/ui/LoadingAnimation.tsx +++ b/src/ui/LoadingAnimation.tsx @@ -1,8 +1,6 @@ import { Text } from "ink"; import React, { useEffect, useState } from "react"; - - const BRAILLE_BY_DENSITY: { [key: number]: string[] } = { 0: ["⠀"], // No dots 1: ["⠁", "⠂", "⠄", "⠈", "⠐", "⠠", "⡀", "⢀"], // 1 dot @@ -20,13 +18,13 @@ const generateDensityFrame = (dotCount: number): string => { const chars = BRAILLE_BY_DENSITY[Math.min(8, Math.max(0, dotCount))]; return Array.from( { length: 3 }, - () => chars[Math.floor(Math.random() * chars.length)] + () => chars[Math.floor(Math.random() * chars.length)], ).join(""); }; // Helper function to generate eased static fade animation with full timing control const generateEasedStaticFade = ( - timingCurve: number[] = [3, 3, 2, 1, 1, 1, 2, 3, 3] + timingCurve: number[] = [3, 3, 2, 1, 1, 1, 2, 3, 3], ): string[] => { const frames: string[] = []; @@ -66,7 +64,6 @@ const STATIC_FADE = [ ...generateEasedStaticFade(TIMING_CURVE), ]; - const SPINNER: string | string[] = STATIC_FADE; interface LoadingAnimationProps { diff --git a/src/ui/MarkdownRenderer.tsx b/src/ui/MarkdownRenderer.tsx index 008009876..12d4d17bc 100644 --- a/src/ui/MarkdownRenderer.tsx +++ b/src/ui/MarkdownRenderer.tsx @@ -1,7 +1,12 @@ import { Text } from "ink"; import React from "react"; -import { highlightCode, detectLanguage, SyntaxHighlighterTheme, defaultTheme } from "./SyntaxHighlighter.js"; +import { + highlightCode, + detectLanguage, + SyntaxHighlighterTheme, + defaultTheme, +} from "./SyntaxHighlighter.js"; interface MarkdownRendererProps { content: string | null | undefined; @@ -13,204 +18,213 @@ interface MarkdownPattern { render: (content: string, key: string) => React.ReactNode; } -const MarkdownRenderer: React.FC = React.memo(({ content, theme = defaultTheme }) => { - const patterns: MarkdownPattern[] = [ - { - regex: /```(?:(\w+)\n)?([\s\S]*?)```/g, - render: (_content, _key) => { - // content here is the captured group, but we need to parse the full match - return null; // This will be handled separately +const MarkdownRenderer: React.FC = React.memo( + ({ content, theme = defaultTheme }) => { + const patterns: MarkdownPattern[] = [ + { + regex: /```(?:(\w+)\n)?([\s\S]*?)```/g, + render: (_content, _key) => { + // content here is the captured group, but we need to parse the full match + return null; // This will be handled separately + }, + }, + { + regex: /^(#{1,6})\s+(.+)$/gm, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /\*\*(.+?)\*\*/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /\*([^\s*][^*]*[^\s*]|[^\s*])\*/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /_([^_]+)_/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /~~([^~]+)~~/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /`([^`\n]+)`/g, + render: (content, key) => ( + + {content} + + ), }, - }, - { - regex: /^(#{1,6})\s+(.+)$/gm, - render: (content, key) => ( - - {content} - - ), - }, - { - regex: /\*\*(.+?)\*\*/g, - render: (content, key) => ( - - {content} - - ), - }, - { - regex: /\*([^\s*][^*]*[^\s*]|[^\s*])\*/g, - render: (content, key) => ( - - {content} - - ), - }, - { - regex: /_([^_]+)_/g, - render: (content, key) => ( - - {content} - - ), - }, - { - regex: /~~([^~]+)~~/g, - render: (content, key) => ( - - {content} - - ), - }, - { - regex: /`([^`\n]+)`/g, - render: (content, key) => ( - - {content} - - ), - }, - ]; - - const renderMarkdown = (text: string | null | undefined) => { - const parts: React.ReactNode[] = []; - - // Handle null/undefined text - if (!text) { - return parts; - } - - let currentIndex = 0; - - // First, handle code blocks separately - const codeBlockRegex = /```(?:(\w+)\n)?([\s\S]*?)```/g; - const codeBlocks: Array<{ - index: number; - length: number; - language: string; - code: string; - }> = []; - - let codeMatch; - while ((codeMatch = codeBlockRegex.exec(text)) !== null) { - const language = codeMatch[1] || detectLanguage(codeMatch[2]); - codeBlocks.push({ - index: codeMatch.index, - length: codeMatch[0].length, - language, - code: codeMatch[2].trim() - }); - } - - // Find all matches for other patterns (excluding code blocks) - const allMatches: Array<{ - index: number; - length: number; - content: string; - render: (content: string, key: string) => React.ReactNode; - }> = []; - - patterns.slice(1).forEach((pattern) => { // Skip the first pattern (code blocks) - let match: RegExpExecArray | null; - const regex = new RegExp(pattern.regex.source, pattern.regex.flags); - - while ((match = regex.exec(text)) !== null) { - // Skip if this match is inside a code block - const isInCodeBlock = codeBlocks.some(block => - match!.index >= block.index && match!.index < block.index + block.length - ); - - if (!isInCodeBlock) { - allMatches.push({ - index: match.index, - length: match[0].length, - content: match[2] || match[1], // Use second capture group for headings, first for others - render: pattern.render, - }); - } - } - }); - - // Combine code blocks and other matches - const combinedMatches: Array<{ - index: number; - length: number; - type: 'code' | 'other'; - content?: string; - render?: (content: string, key: string) => React.ReactNode; - language?: string; - code?: string; - }> = [ - ...codeBlocks.map(block => ({ - index: block.index, - length: block.length, - type: 'code' as const, - language: block.language, - code: block.code - })), - ...allMatches.map(match => ({ - index: match.index, - length: match.length, - type: 'other' as const, - content: match.content, - render: match.render - })) ]; - // Sort matches by index to process them in order - combinedMatches.sort((a, b) => a.index - b.index); + const renderMarkdown = (text: string | null | undefined) => { + const parts: React.ReactNode[] = []; - // Process matches, avoiding overlaps - const processedMatches: typeof combinedMatches = []; - for (const match of combinedMatches) { - const overlaps = processedMatches.some( - (processed) => - (match.index >= processed.index && - match.index < processed.index + processed.length) || - (processed.index >= match.index && - processed.index < match.index + match.length) - ); - - if (!overlaps) { - processedMatches.push(match); - } - } - - // Render the text with formatting - processedMatches.forEach((match, idx) => { - // Add text before this match - if (match.index > currentIndex) { - parts.push(text.slice(currentIndex, match.index)); + // Handle null/undefined text + if (!text) { + return parts; } - // Add the formatted match - if (match.type === 'code') { - const highlightedCode = highlightCode(match.code!, match.language!, theme); - parts.push( - - {highlightedCode} - + let currentIndex = 0; + + // First, handle code blocks separately + const codeBlockRegex = /```(?:(\w+)\n)?([\s\S]*?)```/g; + const codeBlocks: Array<{ + index: number; + length: number; + language: string; + code: string; + }> = []; + + let codeMatch; + while ((codeMatch = codeBlockRegex.exec(text)) !== null) { + const language = codeMatch[1] || detectLanguage(codeMatch[2]); + codeBlocks.push({ + index: codeMatch.index, + length: codeMatch[0].length, + language, + code: codeMatch[2].trim(), + }); + } + + // Find all matches for other patterns (excluding code blocks) + const allMatches: Array<{ + index: number; + length: number; + content: string; + render: (content: string, key: string) => React.ReactNode; + }> = []; + + patterns.slice(1).forEach((pattern) => { + // Skip the first pattern (code blocks) + let match: RegExpExecArray | null; + const regex = new RegExp(pattern.regex.source, pattern.regex.flags); + + while ((match = regex.exec(text)) !== null) { + // Skip if this match is inside a code block + const isInCodeBlock = codeBlocks.some( + (block) => + match!.index >= block.index && + match!.index < block.index + block.length, + ); + + if (!isInCodeBlock) { + allMatches.push({ + index: match.index, + length: match[0].length, + content: match[2] || match[1], // Use second capture group for headings, first for others + render: pattern.render, + }); + } + } + }); + + // Combine code blocks and other matches + const combinedMatches: Array<{ + index: number; + length: number; + type: "code" | "other"; + content?: string; + render?: (content: string, key: string) => React.ReactNode; + language?: string; + code?: string; + }> = [ + ...codeBlocks.map((block) => ({ + index: block.index, + length: block.length, + type: "code" as const, + language: block.language, + code: block.code, + })), + ...allMatches.map((match) => ({ + index: match.index, + length: match.length, + type: "other" as const, + content: match.content, + render: match.render, + })), + ]; + + // Sort matches by index to process them in order + combinedMatches.sort((a, b) => a.index - b.index); + + // Process matches, avoiding overlaps + const processedMatches: typeof combinedMatches = []; + for (const match of combinedMatches) { + const overlaps = processedMatches.some( + (processed) => + (match.index >= processed.index && + match.index < processed.index + processed.length) || + (processed.index >= match.index && + processed.index < match.index + match.length), ); - } else { - parts.push(match.render!(match.content!, `format-${idx}-${match.index}`)); + + if (!overlaps) { + processedMatches.push(match); + } } - currentIndex = match.index + match.length; - }); + // Render the text with formatting + processedMatches.forEach((match, idx) => { + // Add text before this match + if (match.index > currentIndex) { + parts.push(text.slice(currentIndex, match.index)); + } - // Add remaining text - if (currentIndex < text.length) { - parts.push(text.slice(currentIndex)); - } + // Add the formatted match + if (match.type === "code") { + const highlightedCode = highlightCode( + match.code!, + match.language!, + theme, + ); + parts.push( + {highlightedCode}, + ); + } else { + parts.push( + match.render!(match.content!, `format-${idx}-${match.index}`), + ); + } - return parts; - }; + currentIndex = match.index + match.length; + }); - return {renderMarkdown(content)}; -}); + // Add remaining text + if (currentIndex < text.length) { + parts.push(text.slice(currentIndex)); + } + + return parts; + }; + + return {renderMarkdown(content)}; + }, +); MarkdownRenderer.displayName = "MarkdownRenderer"; export { MarkdownRenderer }; export type { SyntaxHighlighterTheme }; -export { defaultTheme }; \ No newline at end of file +export { defaultTheme }; diff --git a/src/ui/ModelSelector.tsx b/src/ui/ModelSelector.tsx index 34829173d..c9a79fe25 100644 --- a/src/ui/ModelSelector.tsx +++ b/src/ui/ModelSelector.tsx @@ -29,7 +29,7 @@ const ModelSelector: React.FC = ({ try { const availableModels = services.model.getAvailableChatModels(); const currentIndex = services.model.getCurrentModelIndex(); - + if (availableModels.length === 0) { setError("No chat models available in the configuration"); setLoading(false); @@ -64,7 +64,11 @@ const ModelSelector: React.FC = ({ loading={loading} error={error} loadingMessage="Loading available models..." - currentId={currentModelIndex >= 0 && models[currentModelIndex] ? models[currentModelIndex].id : null} + currentId={ + currentModelIndex >= 0 && models[currentModelIndex] + ? models[currentModelIndex].id + : null + } onSelect={onSelect} onCancel={onCancel} onNavigate={setSelectedIndex} @@ -72,4 +76,4 @@ const ModelSelector: React.FC = ({ ); }; -export { ModelSelector }; \ No newline at end of file +export { ModelSelector }; diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx index d33701d93..dfa535090 100644 --- a/src/ui/OrganizationSelector.tsx +++ b/src/ui/OrganizationSelector.tsx @@ -39,10 +39,10 @@ const OrganizationSelector: React.FC = ({ } const options: Organization[] = [ - { - id: "personal", + { + id: "personal", name: "Personal", - slug: "personal" + slug: "personal", }, ...organizations, ]; diff --git a/src/ui/Selector.tsx b/src/ui/Selector.tsx index 5d3b7c65c..ba82abce1 100644 --- a/src/ui/Selector.tsx +++ b/src/ui/Selector.tsx @@ -21,7 +21,7 @@ interface SelectorProps { renderOption?: ( option: T, isSelected: boolean, - isCurrent: boolean + isCurrent: boolean, ) => ReactNode; } @@ -97,7 +97,7 @@ export function Selector({ const defaultRenderOption = ( option: T, isSelected: boolean, - isCurrent: boolean + isCurrent: boolean, ) => ( = ({ const getServiceDetails = (serviceName: string, service: any) => { switch (serviceName) { case "auth": - return service?.authConfig ? `User: ${service.authConfig.email || 'unknown'}` : "No auth config"; + return service?.authConfig + ? `User: ${service.authConfig.email || "unknown"}` + : "No auth config"; case "config": return service?.config ? `Agent: ${service.config.name}` : "No config"; case "model": return service?.model ? `Model: ${service.model.name}` : "No model"; case "mcp": - return service?.mcpService ? `Tools: ${service.mcpService.getTools()?.length || 0}` : "No MCP service"; + return service?.mcpService + ? `Tools: ${service.mcpService.getTools()?.length || 0}` + : "No MCP service"; case "apiClient": return service?.apiClient ? "API client ready" : "No API client"; default: @@ -56,31 +60,37 @@ const ServiceDebugger: React.FC = ({ }; return ( - - 🔧 Service Debug Info + + + 🔧 Service Debug Info + - + Overall Status: Loading: {loading ? "🟡 Yes" : "✅ No"} All Ready: {allReady ? "✅ Yes" : "❌ No"} Services Loading: {servicesLoading ? "🟡 Yes" : "✅ No"} - - {error && ( - Error: {String(error)} - )} - + + {error && Error: {String(error)}} + {servicesError && ( Services Error: {String(servicesError)} )} - + Individual Services: - + {["auth", "config", "model", "mcp", "apiClient"].map((serviceName) => { const service = services[serviceName as keyof typeof services]; const status = getServiceStatus(serviceName, service); const details = getServiceDetails(serviceName, service); - + return ( @@ -88,22 +98,20 @@ const ServiceDebugger: React.FC = ({ {details && ( - - {details} - + {details} )} ); })} - + Intro Message Conditions: Services ready: {allReady ? "✅" : "❌"} Has config: {services.config?.config ? "✅" : "❌"} Has model: {services.model?.model ? "✅" : "❌"} Has MCP service: {services.mcp?.mcpService ? "✅" : "❌"} - + Comment out this component when debugging is complete @@ -112,4 +120,4 @@ const ServiceDebugger: React.FC = ({ ); }; -export { ServiceDebugger }; \ No newline at end of file +export { ServiceDebugger }; diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 55f673669..ad0cbb8d2 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -17,7 +17,6 @@ const SlashCommandUI: React.FC = ({ selectedIndex, isRemoteMode = false, }) => { - // Memoize the slash commands to prevent excessive re-renders const allCommands = useMemo(() => { if (assistant || isRemoteMode) { @@ -79,4 +78,4 @@ const SlashCommandUI: React.FC = ({ ); }; -export { SlashCommandUI }; \ No newline at end of file +export { SlashCommandUI }; diff --git a/src/ui/SyntaxHighlighter.ts b/src/ui/SyntaxHighlighter.ts index 35931b1de..7fd3b60b8 100644 --- a/src/ui/SyntaxHighlighter.ts +++ b/src/ui/SyntaxHighlighter.ts @@ -82,7 +82,7 @@ const tokenColorMap: Record = { export function highlightCode( code: string, language: string = "javascript", - theme: SyntaxHighlighterTheme = defaultTheme + theme: SyntaxHighlighterTheme = defaultTheme, ): React.ReactNode[] { try { // Create lowlight instance with common languages @@ -97,7 +97,7 @@ export function highlightCode( function processNode( node: any, - parentColor: string = theme.default + parentColor: string = theme.default, ): React.ReactNode { if (node.type === "text") { const text = node.value; @@ -108,7 +108,7 @@ export function highlightCode( key: `text-${keyCounter++}`, color: parentColor, }, - text + text, ); } return null; @@ -155,7 +155,7 @@ export function highlightCode( key: `element-${keyCounter++}`, color, }, - textContent + textContent, ); } } @@ -197,7 +197,7 @@ export function highlightCode( React.createElement( Text, { key: "error-fallback", color: theme.default }, - code + code, ), ]; } @@ -230,7 +230,7 @@ export function detectLanguage(code: string): string { ]; // Check patterns line by line for multiline code - const lines = code.split('\n'); + const lines = code.split("\n"); for (const line of lines) { for (const pattern of patterns) { if (pattern.regex.test(line)) { diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 5eb754992..9c88dddb3 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -33,7 +33,6 @@ import { Timer } from "./Timer.js"; import { UpdateNotification } from "./UpdateNotification.js"; import { UserInput } from "./UserInput.js"; - interface TUIChatProps { // Remote mode props remoteUrl?: string; @@ -78,10 +77,7 @@ const TUIChat: React.FC = ({ }, [remoteUrl]); // Get all services reactively - only in normal mode - const { - services, - allReady: allServicesReady, - } = useServices<{ + const { services, allReady: allServicesReady } = useServices<{ auth: AuthServiceState; config: ConfigServiceState; model: ModelServiceState; @@ -90,14 +86,19 @@ const TUIChat: React.FC = ({ }>(["auth", "config", "model", "mcp", "apiClient"]); // Use navigation context - const { state: navState, navigateTo, closeCurrentScreen, isScreenActive } = useNavigation(); + const { + state: navState, + navigateTo, + closeCurrentScreen, + isScreenActive, + } = useNavigation(); // State for intro message display const [showIntroMessage, setShowIntroMessage] = useState(false); // State for current mode (for hiding cwd in plan/auto modes) const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode() + modeService.getCurrentMode(), ); // Listen for mode changes to update UI @@ -106,9 +107,9 @@ const TUIChat: React.FC = ({ setCurrentMode(newMode); }; - modeService.on('modeChanged', handleModeChange); + modeService.on("modeChanged", handleModeChange); return () => { - modeService.off('modeChanged', handleModeChange); + modeService.off("modeChanged", handleModeChange); }; }, []); @@ -146,7 +147,7 @@ const TUIChat: React.FC = ({ // Custom login prompt handler for TUI const handleLoginPrompt = (promptText: string): Promise => { return new Promise((resolve) => { - navigateTo('login', { text: promptText, resolve }); + navigateTo("login", { text: promptText, resolve }); }); }; @@ -186,9 +187,9 @@ const TUIChat: React.FC = ({ initialPrompt, resume, additionalRules, - onShowOrgSelector: () => navigateTo('organization'), - onShowConfigSelector: () => navigateTo('config'), - onShowModelSelector: () => navigateTo('model'), + onShowOrgSelector: () => navigateTo("organization"), + onShowConfigSelector: () => navigateTo("config"), + onShowModelSelector: () => navigateTo("model"), onLoginPrompt: handleLoginPrompt, onReload: handleReload, // Remote mode configuration @@ -219,12 +220,10 @@ const TUIChat: React.FC = ({ }, }); - // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = - navState.currentScreen !== 'chat' || - !!activePermissionRequest; + navState.currentScreen !== "chat" || !!activePermissionRequest; return ( @@ -270,7 +269,7 @@ const TUIChat: React.FC = ({ )} {/* Login prompt - shows above input when active */} - {isScreenActive('login') && navState.screenData && ( + {isScreenActive("login") && navState.screenData && ( = ({ )} {/* Organization selector - shows above input when active */} - {isScreenActive('organization') && ( + {isScreenActive("organization") && ( = ({ )} {/* Config selector - shows above input when active */} - {isScreenActive('config') && ( + {isScreenActive("config") && ( = ({ )} {/* Model selector - shows above input when active */} - {isScreenActive('model') && ( + {isScreenActive("model") && ( = ({ )} {/* Free trial transition UI - replaces input when active */} - {isScreenActive('free-trial') && ( + {isScreenActive("free-trial") && ( )} {/* Input area - only show when showing chat screen */} - {isScreenActive('chat') && ( + {isScreenActive("chat") && ( <> {/* Show permission selector when there's an active permission request */} {activePermissionRequest ? ( @@ -358,7 +357,7 @@ const TUIChat: React.FC = ({ > {/* Only show cwd in normal mode to save space in plan/auto modes */} - {currentMode === 'normal' && ( + {currentMode === "normal" && ( <> {repoURlText} @@ -374,9 +373,12 @@ const TUIChat: React.FC = ({ apiClient={services.apiClient?.apiClient || undefined} model={services.model.model} onTransitionStateChange={(shouldShow) => { - if (shouldShow && navState.currentScreen === 'chat') { - navigateTo('free-trial'); - } else if (!shouldShow && navState.currentScreen === 'free-trial') { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if ( + !shouldShow && + navState.currentScreen === "free-trial" + ) { closeCurrentScreen(); } }} diff --git a/src/ui/TextBuffer.ts b/src/ui/TextBuffer.ts index 65cebac0f..0e0d0fc01 100644 --- a/src/ui/TextBuffer.ts +++ b/src/ui/TextBuffer.ts @@ -56,7 +56,7 @@ export class TextBuffer { private findWordBoundary( position: number, - direction: "left" | "right" + direction: "left" | "right", ): number { if (direction === "left") { // Find start of current word or previous word @@ -199,7 +199,7 @@ export class TextBuffer { this.moveWordRight(); return true; } - + // Handle option+left/right as characters (on Mac, option+arrow sends character codes) if (input === "b") { this.moveWordLeft(); diff --git a/src/ui/Timer.tsx b/src/ui/Timer.tsx index dc72904a9..87744ce92 100644 --- a/src/ui/Timer.tsx +++ b/src/ui/Timer.tsx @@ -22,4 +22,4 @@ const Timer: React.FC = ({ startTime, color = "gray" }) => { return {elapsed}s; }; -export { Timer }; \ No newline at end of file +export { Timer }; diff --git a/src/ui/UI_TEST_CHECKLIST.md b/src/ui/UI_TEST_CHECKLIST.md index a1070bc1a..ce78fa674 100644 --- a/src/ui/UI_TEST_CHECKLIST.md +++ b/src/ui/UI_TEST_CHECKLIST.md @@ -3,6 +3,7 @@ ## ✅ Simple Tests (Priority 1) ### Message Display Tests + - [ ] Empty chat displays correctly (no messages) - [ ] Single user message displays with correct formatting (● indicator) - [ ] Single assistant message displays with correct formatting (● indicator) @@ -10,12 +11,14 @@ - [ ] System messages display with correct styling (gray, italic) ### User Input Tests + - [ ] Input field shows typed text - [ ] Input field clears after pressing Enter - [ ] Input field handles special characters - [ ] Input prompt shows correctly ("cn>" or custom) ### Loading State Tests + - [ ] Loading spinner appears when `isLoading` is true - [ ] Loading spinner disappears when `isLoading` is false - [ ] Loading text displays correctly @@ -23,6 +26,7 @@ ## 📝 Medium Complexity Tests (Priority 2) ### Tool Execution Display Tests + - [ ] Tool start indicator (○) displays correctly - [ ] Tool name displays next to indicator - [ ] Tool arguments display correctly @@ -32,6 +36,7 @@ - [ ] Tool result expands when selected ### Markdown Rendering Tests + - [ ] Bold text renders correctly - [ ] Italic text renders correctly - [ ] Code blocks render with syntax highlighting @@ -40,6 +45,7 @@ - [ ] Lists render correctly ### Component Visibility Tests + - [ ] Config selector shows when multiple configs available - [ ] Organization selector shows when multiple orgs available - [ ] Scroll indicators appear for long content @@ -48,24 +54,28 @@ ## 🔧 Complex Tests (Priority 3) ### State Transition Tests + - [ ] Message transitions from streaming to complete - [ ] Tool execution transitions through states (start → result) - [ ] Error states display and recover correctly - [ ] Focus changes between input and selectors ### Scrolling and Navigation Tests + - [ ] Chat scrolls to bottom on new messages - [ ] PageUp/PageDown scroll through history - [ ] Home/End jump to top/bottom - [ ] Scroll position maintains during updates ### Error Handling Tests + - [ ] API errors display user-friendly messages - [ ] Tool errors display correctly - [ ] Network errors handle gracefully - [ ] Invalid input errors display ### Integration Tests + - [ ] Full conversation flow works correctly - [ ] Tool execution integrates with message display - [ ] Config switching updates UI correctly @@ -77,4 +87,4 @@ 2. **Use minimal mocking** - Only mock what's necessary (API calls) 3. **Test user-visible behavior** - Not implementation details 4. **Keep tests focused** - One behavior per test -5. **Use descriptive test names** - Should explain what's being tested \ No newline at end of file +5. **Use descriptive test names** - Should explain what's being tested diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 072c7e950..719d82cbb 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -75,12 +75,12 @@ const UserInput: React.FC = ({ const currentIndex = modes.indexOf(currentMode); const nextIndex = (currentIndex + 1) % modes.length; const nextMode = modes[nextIndex]; - + modeService.switchMode(nextMode); - + // Reload the tool permissions service to ensure the service container has the latest state await reloadService(SERVICE_NAMES.TOOL_PERMISSIONS); - + // Show a brief indicator of the mode change // This will be reflected in the ModeIndicator component return nextMode; @@ -93,7 +93,7 @@ const UserInput: React.FC = ({ const trimmedText = text.trimStart(); const beforeCursor = trimmedText.slice( 0, - cursor - (text.length - trimmedText.length) + cursor - (text.length - trimmedText.length), ); // Only show if cursor is after the slash and before any whitespace @@ -110,10 +110,7 @@ const UserInput: React.FC = ({ const restOfText = text.slice(cursor); // Only hide if there's a space or newline immediately after cursor // Don't hide just because we're at the end - user might want to see the suggestion - if ( - restOfText.startsWith(" ") || - restOfText.startsWith("\n") - ) { + if (restOfText.startsWith(" ") || restOfText.startsWith("\n")) { setShowSlashCommands(false); return; } @@ -170,7 +167,7 @@ const UserInput: React.FC = ({ const allCommands = getSlashCommands(); return allCommands .filter((cmd) => - cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase()) + cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase()), ) .sort((a, b) => { const aStartsWith = a.name @@ -252,7 +249,7 @@ const UserInput: React.FC = ({ // Handle Shift+Tab to cycle through modes if (key.tab && key.shift && !showSlashCommands && !showFileSearch) { - cycleModes().catch(error => { + cycleModes().catch((error) => { logger.error("Failed to cycle modes:", error); }); return; @@ -291,14 +288,14 @@ const UserInput: React.FC = ({ if (key.upArrow) { setSelectedCommandIndex((prev) => - prev > 0 ? prev - 1 : filteredCommands.length - 1 + prev > 0 ? prev - 1 : filteredCommands.length - 1, ); return; } if (key.downArrow) { setSelectedCommandIndex((prev) => - prev < filteredCommands.length - 1 ? prev + 1 : 0 + prev < filteredCommands.length - 1 ? prev + 1 : 0, ); return; } @@ -324,14 +321,14 @@ const UserInput: React.FC = ({ setSelectedFileIndex((prev) => prev > 0 ? prev - 1 - : Math.max(0, Math.min(currentFiles.length - 1, 9)) + : Math.max(0, Math.min(currentFiles.length - 1, 9)), ); return; } if (key.downArrow) { setSelectedFileIndex((prev) => - prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0 + prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0, ); return; } @@ -549,4 +546,4 @@ const UserInput: React.FC = ({ ); }; -export { UserInput }; \ No newline at end of file +export { UserInput }; diff --git a/src/ui/__mocks__/FreeTrialStatus.tsx b/src/ui/__mocks__/FreeTrialStatus.tsx index 517dcf3f7..2359e7f5d 100644 --- a/src/ui/__mocks__/FreeTrialStatus.tsx +++ b/src/ui/__mocks__/FreeTrialStatus.tsx @@ -8,4 +8,4 @@ const FreeTrialStatus: React.FC = () => { export { FreeTrialStatus }; export function isModelUsingFreeTrial(): boolean { return false; -} \ No newline at end of file +} diff --git a/src/ui/__mocks__/SyntaxHighlighter.ts b/src/ui/__mocks__/SyntaxHighlighter.ts index 041f75b44..abf08ff9e 100644 --- a/src/ui/__mocks__/SyntaxHighlighter.ts +++ b/src/ui/__mocks__/SyntaxHighlighter.ts @@ -1,4 +1,4 @@ -import React from 'react'; +import React from "react"; export interface SyntaxHighlighterTheme { keyword: string; @@ -9,19 +9,19 @@ export interface SyntaxHighlighterTheme { } export const defaultTheme: SyntaxHighlighterTheme = { - keyword: 'blue', - string: 'green', - comment: 'gray', - number: 'yellow', - operator: 'cyan', + keyword: "blue", + string: "green", + comment: "gray", + number: "yellow", + operator: "cyan", }; export function highlightCode(code: string): React.ReactNode[] { // Mock implementation that just returns the code as plain text - return [React.createElement('ink-text', { key: 'mock-code' }, code)]; + return [React.createElement("ink-text", { key: "mock-code" }, code)]; } export function detectLanguage(): string { // Mock implementation - return 'javascript'; -} \ No newline at end of file + return "javascript"; +} diff --git a/src/ui/__mocks__/highlightLanguage.js b/src/ui/__mocks__/highlightLanguage.js index c123584e1..07707d044 100644 --- a/src/ui/__mocks__/highlightLanguage.js +++ b/src/ui/__mocks__/highlightLanguage.js @@ -1,7 +1,7 @@ // Mock for highlight.js language modules export default function mockLanguage() { return { - keywords: 'mock keywords', - contains: [] + keywords: "mock keywords", + contains: [], }; -} \ No newline at end of file +} diff --git a/src/ui/__mocks__/lowlight.js b/src/ui/__mocks__/lowlight.js index cb2e9f752..e9e799e0b 100644 --- a/src/ui/__mocks__/lowlight.js +++ b/src/ui/__mocks__/lowlight.js @@ -5,10 +5,10 @@ export function createLowlight() { return { register: () => {}, highlight: (lang, code) => ({ - children: [{ type: 'text', value: code }] + children: [{ type: "text", value: code }], }), highlightAuto: (code) => ({ - children: [{ type: 'text', value: code }] - }) + children: [{ type: "text", value: code }], + }), }; -} \ No newline at end of file +} diff --git a/src/ui/__tests__/README.md b/src/ui/__tests__/README.md index 5e0c79833..fe195d779 100644 --- a/src/ui/__tests__/README.md +++ b/src/ui/__tests__/README.md @@ -9,17 +9,22 @@ The testing framework ensures that the TUI behaves consistently whether running ## Key Components ### 1. Mock Remote Server (`mockRemoteServer.ts`) + A mock Express server that simulates the `cn serve` endpoints: + - `GET /state` - Returns current chat state - `POST /message` - Receives user messages and can simulate responses ### 2. Test Helper (`TUIChat.testHelper.ts`) + Provides utilities for writing tests that work in both modes: + - `runTest()` - Run a single test in specified mode(s) - `runTestSuite()` - Run a test suite in specified mode(s) - Helper functions for common operations ### 3. Test Files + - `TUIChat.basic.test.tsx` - Basic UI and layout tests - `TUIChat.messages.test.tsx` - Message handling tests - `TUIChat.remote.test.tsx` - Remote-specific behavior tests @@ -28,16 +33,17 @@ Provides utilities for writing tests that work in both modes: ## Writing Tests ### Basic Test (runs in both modes) + ```typescript import { runTest } from "./TUIChat.testHelper.js"; runTest("my test name", async (ctx) => { const { renderResult, mode, server } = ctx; - + // Your test code here const frame = renderResult.lastFrame(); expect(frame).toContain("Expected content"); - + // Mode-specific logic if needed if (mode === "remote" && server) { // Remote-specific assertions @@ -46,6 +52,7 @@ runTest("my test name", async (ctx) => { ``` ### Test Suite (runs all tests in both modes) + ```typescript import { runTestSuite } from "./TUIChat.testHelper.js"; @@ -53,7 +60,7 @@ runTestSuite("My Test Suite", () => { runTest("test 1", async (ctx) => { // Test code }); - + runTest("test 2", async (ctx) => { // Test code }); @@ -61,6 +68,7 @@ runTestSuite("My Test Suite", () => { ``` ### Mode-Specific Tests + ```typescript // Remote-only test runTest( @@ -68,39 +76,41 @@ runTest( async (ctx) => { // This only runs in remote mode }, - { mode: "remote" } + { mode: "remote" }, ); // Normal-only test runTest( - "local-specific behavior", + "local-specific behavior", async (ctx) => { // This only runs in normal mode }, - { mode: "normal" } + { mode: "normal" }, ); ``` ## Helper Functions ### `sendMessage(ctx, message, waitTime?)` + Sends a message and waits for it to be processed: + ```typescript await sendMessage(ctx, "Hello world"); ``` ### `waitForServerState(server, predicate, timeout?)` + Waits for server state to match a condition (remote mode only): + ```typescript -await waitForServerState( - server, - state => state.messages.length > 0, - 5000 -); +await waitForServerState(server, (state) => state.messages.length > 0, 5000); ``` ### `expectRemoteMode(frame)` / `expectNormalMode(frame)` + Verify mode-specific UI indicators: + ```typescript if (mode === "remote") { expectRemoteMode(frame); @@ -112,6 +122,7 @@ if (mode === "remote") { ## Server Setup For tests that need specific server behavior: + ```typescript runTest( "test with custom server", @@ -124,8 +135,8 @@ runTest( // Custom response logic server.simulateResponse(`Echo: ${msg}`); }); - } - } + }, + }, ); ``` @@ -155,4 +166,4 @@ npm test -- --coverage - Tests output the current mode in brackets: `[NORMAL MODE]` or `[REMOTE MODE]` - Server state can be inspected with `server.getState()` - Use `console.log(renderResult.lastFrame())` to see the current UI state -- Mock server runs on a random port to avoid conflicts \ No newline at end of file +- Mock server runs on a random port to avoid conflicts diff --git a/src/ui/__tests__/TUIChat.dualModeHelper.tsx b/src/ui/__tests__/TUIChat.dualModeHelper.tsx index 4db481274..3b5021ab0 100644 --- a/src/ui/__tests__/TUIChat.dualModeHelper.tsx +++ b/src/ui/__tests__/TUIChat.dualModeHelper.tsx @@ -4,11 +4,11 @@ import React from "react"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; -export type TestMode = 'local' | 'remote'; +export type TestMode = "local" | "remote"; // Dummy test to satisfy Jest -describe('TUIChat dual mode helper', () => { - it('exports helper functions', () => { +describe("TUIChat dual mode helper", () => { + it("exports helper functions", () => { expect(testBothModes).toBeDefined(); expect(renderInMode).toBeDefined(); expect(testSingleMode).toBeDefined(); @@ -20,8 +20,8 @@ describe('TUIChat dual mode helper', () => { * This creates two test suites - one for each mode */ export function testBothModes( - name: string, - testFn: (mode: TestMode) => void | Promise + name: string, + testFn: (mode: TestMode) => void | Promise, ) { describe(`${name} [LOCAL MODE]`, () => { let context: any; @@ -38,7 +38,7 @@ export function testBothModes( }); it("works in local mode", async () => { - await testFn('local'); + await testFn("local"); }); }); @@ -57,7 +57,7 @@ export function testBothModes( }); it("works in remote mode", async () => { - await testFn('remote'); + await testFn("remote"); }); }); } @@ -67,9 +67,12 @@ export function testBothModes( */ export function renderInMode(mode: TestMode, props?: any) { return render( - mode === 'remote' - ? React.createElement(AppRoot, { remoteUrl: "http://localhost:3000", ...props }) - : React.createElement(AppRoot, props) + mode === "remote" + ? React.createElement(AppRoot, { + remoteUrl: "http://localhost:3000", + ...props, + }) + : React.createElement(AppRoot, props), ) as ReturnType; // Explicit type to avoid TypeScript issues } @@ -79,7 +82,7 @@ export function renderInMode(mode: TestMode, props?: any) { export function testSingleMode( name: string, mode: TestMode, - testFn: () => void | Promise + testFn: () => void | Promise, ) { describe(`${name} [${mode.toUpperCase()} MODE ONLY]`, () => { let context: any; @@ -99,4 +102,4 @@ export function testSingleMode( await testFn(); }); }); -} \ No newline at end of file +} diff --git a/src/ui/__tests__/TUIChat.testHelper.ts b/src/ui/__tests__/TUIChat.testHelper.ts index 1d8af2799..2c2cc1e3b 100644 --- a/src/ui/__tests__/TUIChat.testHelper.ts +++ b/src/ui/__tests__/TUIChat.testHelper.ts @@ -46,7 +46,7 @@ export interface TestOptions { export function runTest( name: string, testFn: (ctx: TestContext) => void | Promise, - options: TestOptions = {} + options: TestOptions = {}, ) { const { mode = "both", serverSetup, props = {} } = options; const modes = mode === "both" ? ["normal", "remote"] : [mode]; @@ -89,7 +89,7 @@ export function runTest( let renderResult: RenderResult | null = null; try { renderResult = render( - React.createElement(TUIChat, { remoteUrl, ...props }) + React.createElement(TUIChat, { remoteUrl, ...props }), ) as RenderResult; await testFn({ @@ -124,35 +124,38 @@ export function runTest( allReady: true, }); - mockUseService.mockImplementation((serviceName: string) => ({ - value: (() => { - switch (serviceName) { - case "auth": - return { authConfig: null, isAuthenticated: false }; - case "config": - return { config: mockAssistant }; - case "model": - return { - llmApi: new MockLlmApi(), - model: { provider: "test", name: "test" }, - }; - case "mcp": - return { mcpService: new MockMCPService() }; - case "apiClient": - return { apiClient: new MockApiClient() }; - default: - return null; - } - })(), - state: "ready" as const, - error: null, - reload: vi.fn(() => Promise.resolve()), - } as any)); + mockUseService.mockImplementation( + (serviceName: string) => + ({ + value: (() => { + switch (serviceName) { + case "auth": + return { authConfig: null, isAuthenticated: false }; + case "config": + return { config: mockAssistant }; + case "model": + return { + llmApi: new MockLlmApi(), + model: { provider: "test", name: "test" }, + }; + case "mcp": + return { mcpService: new MockMCPService() }; + case "apiClient": + return { apiClient: new MockApiClient() }; + default: + return null; + } + })(), + state: "ready" as const, + error: null, + reload: vi.fn(() => Promise.resolve()), + }) as any, + ); let renderResult: RenderResult | null = null; try { renderResult = render( - React.createElement(TUIChat, { ...props }) + React.createElement(TUIChat, { ...props }), ) as RenderResult; await testFn({ @@ -180,7 +183,7 @@ export function runTest( export function runTestSuite( suiteName: string, suiteFn: () => void, - defaultOptions: TestOptions = {} + defaultOptions: TestOptions = {}, ) { const modes = defaultOptions.mode === "both" || !defaultOptions.mode @@ -204,7 +207,7 @@ export function runTestSuite( global.runTest = ( name: string, testFn: any, - options: TestOptions = {} + options: TestOptions = {}, ) => { // If test specifies a mode, only run if it matches current mode const testMode = options.mode || "both"; @@ -241,7 +244,7 @@ export function runTestSuite( React.createElement(TUIChat, { remoteUrl, ...options.props, - }) + }), ) as RenderResult; await testFn({ @@ -276,35 +279,38 @@ export function runTestSuite( allReady: true, }); - mockUseService.mockImplementation((serviceName: string) => ({ - value: (() => { - switch (serviceName) { - case "auth": - return { authConfig: null, isAuthenticated: false }; - case "config": - return { config: mockAssistant }; - case "model": - return { - llmApi: new MockLlmApi(), - model: { provider: "test", name: "test" }, - }; - case "mcp": - return { mcpService: new MockMCPService() }; - case "apiClient": - return { apiClient: new MockApiClient() }; - default: - return null; - } - })(), - state: "ready" as const, - error: null, - reload: vi.fn(() => Promise.resolve()), - } as any)); + mockUseService.mockImplementation( + (serviceName: string) => + ({ + value: (() => { + switch (serviceName) { + case "auth": + return { authConfig: null, isAuthenticated: false }; + case "config": + return { config: mockAssistant }; + case "model": + return { + llmApi: new MockLlmApi(), + model: { provider: "test", name: "test" }, + }; + case "mcp": + return { mcpService: new MockMCPService() }; + case "apiClient": + return { apiClient: new MockApiClient() }; + default: + return null; + } + })(), + state: "ready" as const, + error: null, + reload: vi.fn(() => Promise.resolve()), + }) as any, + ); let renderResult: RenderResult | null = null; try { renderResult = render( - React.createElement(TUIChat, { ...options.props }) + React.createElement(TUIChat, { ...options.props }), ) as RenderResult; await testFn({ @@ -345,7 +351,7 @@ export function runTestSuite( export async function waitForServerState( server: MockRemoteServer, predicate: (state: any) => boolean, - timeout: number = 5000 + timeout: number = 5000, ): Promise { const startTime = Date.now(); @@ -359,7 +365,7 @@ export async function waitForServerState( const finalState = (server as any).state || {}; throw new Error( - `Timeout waiting for server state: ${JSON.stringify(finalState)}` + `Timeout waiting for server state: ${JSON.stringify(finalState)}`, ); } @@ -369,7 +375,7 @@ export async function waitForServerState( export async function sendMessage( ctx: TestContext, message: string, - waitTime: number = 100 + waitTime: number = 100, ): Promise { const { renderResult } = ctx; @@ -383,15 +389,15 @@ export async function sendMessage( ctx.server, (state) => state.messages?.some?.( - (m: any) => m.content === message && m.role === "user" + (m: any) => m.content === message && m.role === "user", ), - 2000 + 2000, ); } catch (error) { // If waiting fails, continue anyway - the server might be slow console.warn( "Warning: Message might not have been processed by server:", - error + error, ); } // Extra wait for UI to poll and update @@ -428,8 +434,8 @@ declare global { var runTest: ( name: string, testFn: (ctx: TestContext) => void | Promise, - options?: TestOptions + options?: TestOptions, ) => void; } -global.runTest = runTest; \ No newline at end of file +global.runTest = runTest; diff --git a/src/ui/__tests__/mocks/MockApiClient.ts b/src/ui/__tests__/mocks/MockApiClient.ts index 41184578b..d619a6256 100644 --- a/src/ui/__tests__/mocks/MockApiClient.ts +++ b/src/ui/__tests__/mocks/MockApiClient.ts @@ -12,8 +12,8 @@ export class MockApiClient { } async getAssistant() { // Return a minimal assistant config - return { - configResult: { + return { + configResult: { config: { name: "test-assistant", models: [ @@ -26,8 +26,8 @@ export class MockApiClient { systemMessage: "You are a helpful assistant", tools: [], mcpServers: [], - } - } + }, + }, }; } async listOrganizations() { @@ -36,4 +36,4 @@ export class MockApiClient { async syncSecrets() { return []; } -} \ No newline at end of file +} diff --git a/src/ui/__tests__/mocks/MockLlmApi.ts b/src/ui/__tests__/mocks/MockLlmApi.ts index da19ee2ff..fdd5649aa 100644 --- a/src/ui/__tests__/mocks/MockLlmApi.ts +++ b/src/ui/__tests__/mocks/MockLlmApi.ts @@ -35,4 +35,4 @@ export class MockLlmApi { async fimComplete() { throw new Error("Not implemented"); } -} \ No newline at end of file +} diff --git a/src/ui/__tests__/mocks/MockMCPService.ts b/src/ui/__tests__/mocks/MockMCPService.ts index c1ca17860..dc918f585 100644 --- a/src/ui/__tests__/mocks/MockMCPService.ts +++ b/src/ui/__tests__/mocks/MockMCPService.ts @@ -18,4 +18,4 @@ export class MockMCPService { isInitialized() { return true; } -} \ No newline at end of file +} diff --git a/src/ui/components/MemoizedMessage.tsx b/src/ui/components/MemoizedMessage.tsx index addbbcf32..35e94cda6 100644 --- a/src/ui/components/MemoizedMessage.tsx +++ b/src/ui/components/MemoizedMessage.tsx @@ -67,7 +67,15 @@ export const MemoizedMessage = memo( // Special rendering for compaction messages if (message.messageType === "compaction") { return ( - + ); } @@ -98,7 +106,7 @@ export const MemoizedMessage = memo( nextProps.message.permissionRequestId && prevProps.index === nextProps.index ); - } + }, ); MemoizedMessage.displayName = "MemoizedMessage"; diff --git a/src/ui/components/ModeIndicator.tsx b/src/ui/components/ModeIndicator.tsx index ee95160bf..b84915c09 100644 --- a/src/ui/components/ModeIndicator.tsx +++ b/src/ui/components/ModeIndicator.tsx @@ -10,7 +10,7 @@ interface ModeIndicatorProps { const ModeIndicator: React.FC = ({ mode }) => { const [currentMode, setCurrentMode] = useState( - mode || modeService.getCurrentMode() + mode || modeService.getCurrentMode(), ); // Update mode when it changes (for cases where mode prop is not provided) @@ -21,33 +21,33 @@ const ModeIndicator: React.FC = ({ mode }) => { setCurrentMode(newMode); }; - modeService.on('modeChanged', handleModeChange); - + modeService.on("modeChanged", handleModeChange); + // Set initial mode setCurrentMode(modeService.getCurrentMode()); return () => { - modeService.off('modeChanged', handleModeChange); + modeService.off("modeChanged", handleModeChange); }; } else if (mode !== currentMode) { setCurrentMode(mode); } }, [mode]); - + // Don't show indicator for normal mode to keep it clean - if (currentMode === 'normal') { + if (currentMode === "normal") { return null; } // Get mode display info const getModeDisplay = (mode: PermissionMode) => { switch (mode) { - case 'plan': - return { text: 'plan', color: 'blue' }; - case 'auto': - return { text: 'auto', color: 'green' }; + case "plan": + return { text: "plan", color: "blue" }; + case "auto": + return { text: "auto", color: "green" }; default: - return { text: mode, color: 'dim' }; + return { text: mode, color: "dim" }; } }; @@ -60,4 +60,4 @@ const ModeIndicator: React.FC = ({ mode }) => { ); }; -export { ModeIndicator }; \ No newline at end of file +export { ModeIndicator }; diff --git a/src/ui/components/ToolPermissionSelector.tsx b/src/ui/components/ToolPermissionSelector.tsx index 9be8e88d4..1ab6c36bc 100644 --- a/src/ui/components/ToolPermissionSelector.tsx +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -22,7 +22,7 @@ interface ToolPermissionSelectorProps { onResponse: ( requestId: string, approved: boolean, - createPolicy?: boolean + createPolicy?: boolean, ) => void; } @@ -53,7 +53,7 @@ export const ToolPermissionSelector: React.FC = ({ onResponse( requestId, selectedOption.approved, - selectedOption.createPolicy + selectedOption.createPolicy, ); return; } @@ -80,7 +80,7 @@ export const ToolPermissionSelector: React.FC = ({ setSelectedIndex(Math.max(0, selectedIndex - 1)); } else if (key.downArrow) { setSelectedIndex( - Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1) + Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1), ); } diff --git a/src/ui/context/NavigationContext.tsx b/src/ui/context/NavigationContext.tsx index ad74c9c26..70f4e2e48 100644 --- a/src/ui/context/NavigationContext.tsx +++ b/src/ui/context/NavigationContext.tsx @@ -1,16 +1,22 @@ -import React, { createContext, useContext, useReducer, useCallback, ReactNode } from 'react'; +import React, { + createContext, + useContext, + useReducer, + useCallback, + ReactNode, +} from "react"; /** * Navigation screens for the UI * Only one screen can be active at a time */ -export type NavigationScreen = - | 'chat' // Normal chat interface - | 'organization' // Organization selector - | 'config' // Config selector - | 'model' // Model selector - | 'free-trial' // Free trial transition UI - | 'login'; // Login prompt +export type NavigationScreen = + | "chat" // Normal chat interface + | "organization" // Organization selector + | "config" // Config selector + | "model" // Model selector + | "free-trial" // Free trial transition UI + | "login"; // Login prompt interface NavigationState { currentScreen: NavigationScreen; @@ -22,23 +28,26 @@ interface NavigationState { * Navigation actions */ type NavigationAction = - | { type: 'NAVIGATE_TO'; screen: NavigationScreen; data?: any } - | { type: 'CLOSE_SCREEN' }; + | { type: "NAVIGATE_TO"; screen: NavigationScreen; data?: any } + | { type: "CLOSE_SCREEN" }; /** * Navigation reducer - handles all state transitions deterministically */ -function navigationReducer(state: NavigationState, action: NavigationAction): NavigationState { +function navigationReducer( + state: NavigationState, + action: NavigationAction, +): NavigationState { switch (action.type) { - case 'NAVIGATE_TO': + case "NAVIGATE_TO": return { currentScreen: action.screen, screenData: action.data ?? null, }; - case 'CLOSE_SCREEN': + case "CLOSE_SCREEN": return { - currentScreen: 'chat', + currentScreen: "chat", screenData: null, }; @@ -50,21 +59,23 @@ function navigationReducer(state: NavigationState, action: NavigationAction): Na interface NavigationContextValue { // Current navigation state state: NavigationState; - + // Navigation methods navigateTo: (screen: NavigationScreen, data?: any) => void; closeCurrentScreen: () => void; - + // Check if a specific screen is active isScreenActive: (screen: NavigationScreen) => boolean; } -const NavigationContext = createContext(undefined); +const NavigationContext = createContext( + undefined, +); export function useNavigation() { const context = useContext(NavigationContext); if (!context) { - throw new Error('useNavigation must be used within NavigationProvider'); + throw new Error("useNavigation must be used within NavigationProvider"); } return context; } @@ -75,21 +86,24 @@ interface NavigationProviderProps { export function NavigationProvider({ children }: NavigationProviderProps) { const [state, dispatch] = useReducer(navigationReducer, { - currentScreen: 'chat', + currentScreen: "chat", screenData: null, }); const navigateTo = useCallback((screen: NavigationScreen, data?: any) => { - dispatch({ type: 'NAVIGATE_TO', screen, data }); + dispatch({ type: "NAVIGATE_TO", screen, data }); }, []); const closeCurrentScreen = useCallback(() => { - dispatch({ type: 'CLOSE_SCREEN' }); + dispatch({ type: "CLOSE_SCREEN" }); }, []); - const isScreenActive = useCallback((screen: NavigationScreen): boolean => { - return state.currentScreen === screen; - }, [state.currentScreen]); + const isScreenActive = useCallback( + (screen: NavigationScreen): boolean => { + return state.currentScreen === screen; + }, + [state.currentScreen], + ); const value: NavigationContextValue = { state, @@ -103,4 +117,4 @@ export function NavigationProvider({ children }: NavigationProviderProps) { {children} ); -} \ No newline at end of file +} diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index e20a56998..6d634694b 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -70,8 +70,8 @@ export function useChat({ // Load previous session if resume flag is used // If no session loaded or not resuming, we'll need to add system message // We can't make this async, so we'll handle it in the useEffect - return resume ? loadSession() ?? [] : []; - } + return resume ? (loadSession() ?? []) : []; + }, ); const [messages, setMessages] = useState(() => { @@ -91,7 +91,7 @@ export function useChat({ const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); const [responseStartTime, setResponseStartTime] = useState( - null + null, ); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = @@ -99,7 +99,7 @@ export function useChat({ const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( // If we're resuming and found a saved session, we're already initialized // If we're in remote mode, we're initialized (will be populated by polling) - isRemoteMode || (resume && loadSession() !== null) + isRemoteMode || (resume && loadSession() !== null), ); // Capture initial rules to prevent re-initialization when rules change @@ -162,7 +162,7 @@ export function useChat({ prevMsg.toolName !== msg.toolName || prevMsg.toolResult !== msg.toolResult ); - } + }, ); // Only update if there are actual changes @@ -189,7 +189,7 @@ export function useChat({ prevMsg.role !== msg.role || prevMsg.content !== msg.content ); - } + }, ); return hasChanged ? newChatHistory : prevChatHistory; @@ -338,10 +338,7 @@ export function useChat({ // Handle slash commands (skip in remote mode except for /exit which we handled above) if (!isRemoteMode && assistant) { - const commandResult = await handleSlashCommands( - message, - assistant - ); + const commandResult = await handleSlashCommands(message, assistant); if (commandResult) { if (commandResult.exit) { exit(); @@ -360,7 +357,7 @@ export function useChat({ if (commandResult.clear) { const systemMessage = chatHistory.find( - (msg) => msg.role === "system" + (msg) => msg.role === "system", ); const newHistory = systemMessage ? [systemMessage] : []; setChatHistory(newHistory); @@ -421,7 +418,7 @@ export function useChat({ if (attachedFiles.length > 0) { const fileContents = attachedFiles .map( - (file) => `\n\n\n${file.content}\n` + (file) => `\n\n\n${file.content}\n`, ) .join(""); messageContent = `${message}${fileContents}`; @@ -468,7 +465,7 @@ export function useChat({ // Check if auto-compacting is needed BEFORE adding user message let currentCompactionIndex = compactionIndex; let currentChatHistory = chatHistory; - + if (model && shouldAutoCompact(chatHistory, model)) { logger.info("Auto-compacting triggered in TUI mode"); @@ -485,14 +482,14 @@ export function useChat({ if (!llmApi) { throw new Error("LLM API is not available for auto-compaction"); } - + // Compact the history WITHOUT the current user message const result = await compactChatHistory(chatHistory, model, llmApi); // Update local variables immediately currentChatHistory = result.compactedHistory; currentCompactionIndex = result.compactionIndex; - + // Update state setChatHistory(result.compactedHistory); setCompactionIndex(result.compactionIndex); @@ -630,7 +627,7 @@ export function useChat({ toolName: string, toolArgs: any, requestId: string, - toolCallPreview?: ToolCallPreview[] + toolCallPreview?: ToolCallPreview[], ) => { // Set the active permission request to show the selector setActivePermissionRequest({ @@ -647,9 +644,15 @@ export function useChat({ if (model && llmApi) { // Use currentCompactionIndex which has the updated value after potential auto-compaction - if (currentCompactionIndex !== null && currentCompactionIndex !== undefined) { + if ( + currentCompactionIndex !== null && + currentCompactionIndex !== undefined + ) { // When using compaction, we need to send a subset but capture the full history - const historyForLLM = getHistoryForLLM(newHistory, currentCompactionIndex); + const historyForLLM = getHistoryForLLM( + newHistory, + currentCompactionIndex, + ); const originalLength = historyForLLM.length; await streamChatResponse( @@ -657,7 +660,7 @@ export function useChat({ model, llmApi, controller, - streamCallbacks + streamCallbacks, ); // Append any new messages (assistant/tool) that were added by streamChatResponse @@ -670,7 +673,7 @@ export function useChat({ model, llmApi, controller, - streamCallbacks + streamCallbacks, ); } } @@ -856,7 +859,7 @@ export function useChat({ const handleToolPermissionResponse = async ( requestId: string, approved: boolean, - createPolicy?: boolean + createPolicy?: boolean, ) => { // Capture the current permission request before clearing it const currentRequest = activePermissionRequest; @@ -873,7 +876,7 @@ export function useChat({ const policyRule = generatePolicyRule( currentRequest.toolName, - currentRequest.toolArgs + currentRequest.toolArgs, ); await addPolicyToYaml(policyRule); diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx index 888b03cce..bc86c63a2 100644 --- a/src/ui/hooks/useMessageRenderer.tsx +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -4,15 +4,12 @@ import { MemoizedMessage } from "../components/MemoizedMessage.js"; import { DisplayMessage } from "../types.js"; export function useMessageRenderer() { - const renderMessage = useCallback((message: DisplayMessage, index: number) => { - return ( - - ); - }, []); + const renderMessage = useCallback( + (message: DisplayMessage, index: number) => { + return ; + }, + [], + ); return { renderMessage }; } diff --git a/src/ui/hooks/useModelSelector.ts b/src/ui/hooks/useModelSelector.ts index 6cc729196..f4ebf9bf4 100644 --- a/src/ui/hooks/useModelSelector.ts +++ b/src/ui/hooks/useModelSelector.ts @@ -1,5 +1,9 @@ import { updateModelName } from "../../auth/workos.js"; -import { services, serviceContainer, SERVICE_NAMES } from "../../services/index.js"; +import { + services, + serviceContainer, + SERVICE_NAMES, +} from "../../services/index.js"; import { ModelServiceState } from "../../services/types.js"; import { useNavigation } from "../context/NavigationContext.js"; @@ -31,16 +35,19 @@ export function useModelSelector({ try { await services.model.switchModel(model.index); const modelInfo = services.model.getModelInfo(); - + // Update the service container to trigger re-renders const currentState = services.model.getState(); - serviceContainer.set(SERVICE_NAMES.MODEL, currentState); - + serviceContainer.set( + SERVICE_NAMES.MODEL, + currentState, + ); + // Persist the model choice using the actual model name if (modelInfo?.name) { updateModelName(modelInfo.name); } - + onMessage({ role: "system", content: `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`, @@ -63,4 +70,4 @@ export function useModelSelector({ return { handleModelSelect, }; -} \ No newline at end of file +} diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts index df5f23306..98daead95 100644 --- a/src/ui/hooks/useOrganizationSelector.ts +++ b/src/ui/hooks/useOrganizationSelector.ts @@ -1,6 +1,4 @@ -import { - isAuthenticatedConfig, -} from "../../auth/workos.js"; +import { isAuthenticatedConfig } from "../../auth/workos.js"; import { services, reloadService } from "../../services/index.js"; import { SERVICE_NAMES } from "../../services/types.js"; import { useNavigation } from "../context/NavigationContext.js"; @@ -22,7 +20,7 @@ export function useOrganizationSelector({ const handleOrganizationSelect = async ( organizationId: string | null, - organizationName: string + organizationName: string, ) => { try { // Check if user is authenticated @@ -30,8 +28,7 @@ export function useOrganizationSelector({ if (!authState.isAuthenticated || !authState.authConfig) { onMessage({ role: "system", - content: - "Organization switching not available - not authenticated", + content: "Organization switching not available - not authenticated", messageType: "system" as const, }); return; @@ -72,7 +69,7 @@ export function useOrganizationSelector({ content: `Successfully switched to organization: ${organizationName}`, messageType: "system" as const, }); - + // Close the organization selector closeCurrentScreen(); } catch (error: any) { @@ -82,7 +79,7 @@ export function useOrganizationSelector({ content: `Failed to switch organization: ${error.message}`, messageType: "system" as const, }); - + // Close selector even on error closeCurrentScreen(); } diff --git a/src/ui/index.ts b/src/ui/index.ts index ee6d977e0..e64cb3091 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -21,7 +21,7 @@ export async function startTUIChat( exclude?: string[]; mode?: PermissionMode; }, - skipOnboarding?: boolean + skipOnboarding?: boolean, ) { // Initialize services only if not already done (skipOnboarding means already initialized) if (!skipOnboarding) { @@ -44,8 +44,8 @@ export async function startTUIChat( initialPrompt, resume, additionalRules, - }) - }) + }), + }), ); // Handle cleanup @@ -59,7 +59,7 @@ export async function startTUIChat( export async function startRemoteTUIChat( remoteUrl: string, - initialPrompt?: string + initialPrompt?: string, ) { // Start the TUI in remote mode - no services needed const { unmount } = render( @@ -67,8 +67,8 @@ export async function startRemoteTUIChat( children: React.createElement(AppRoot, { remoteUrl, initialPrompt, - }) - }) + }), + }), ); // Handle cleanup diff --git a/src/util/apiKeyValidation.ts b/src/util/apiKeyValidation.ts index cf438b093..f6fbd896c 100644 --- a/src/util/apiKeyValidation.ts +++ b/src/util/apiKeyValidation.ts @@ -3,13 +3,15 @@ * @param apiKey The API key to validate * @returns true if the API key is valid, false otherwise */ -export function isValidAnthropicApiKey(apiKey: string | null | undefined): boolean { - if (!apiKey || typeof apiKey !== 'string') { +export function isValidAnthropicApiKey( + apiKey: string | null | undefined, +): boolean { + if (!apiKey || typeof apiKey !== "string") { return false; } - + // Anthropic API keys must start with "sk-ant-" and have additional characters - return apiKey.startsWith('sk-ant-') && apiKey.length > 'sk-ant-'.length; + return apiKey.startsWith("sk-ant-") && apiKey.length > "sk-ant-".length; } /** @@ -17,18 +19,20 @@ export function isValidAnthropicApiKey(apiKey: string | null | undefined): boole * @param apiKey The API key that failed validation * @returns A descriptive error message */ -export function getApiKeyValidationError(apiKey: string | null | undefined): string { - if (!apiKey || typeof apiKey !== 'string') { - return 'API key is required'; +export function getApiKeyValidationError( + apiKey: string | null | undefined, +): string { + if (!apiKey || typeof apiKey !== "string") { + return "API key is required"; } - - if (!apiKey.startsWith('sk-ant-')) { + + if (!apiKey.startsWith("sk-ant-")) { return 'API key must start with "sk-ant-"'; } - - if (apiKey.length <= 'sk-ant-'.length) { - return 'API key is too short'; + + if (apiKey.length <= "sk-ant-".length) { + return "API key is too short"; } - - return 'Invalid API key format'; -} \ No newline at end of file + + return "Invalid API key format"; +} diff --git a/src/util/consoleOverride.ts b/src/util/consoleOverride.ts index 5f7743115..24ee2e5d0 100644 --- a/src/util/consoleOverride.ts +++ b/src/util/consoleOverride.ts @@ -20,7 +20,7 @@ let isHeadlessMode = false; */ export function configureConsoleForHeadless(headless: boolean): void { isHeadlessMode = headless; - + if (headless && !originalConsole) { // Backup original console methods originalConsole = { @@ -33,10 +33,10 @@ export function configureConsoleForHeadless(headless: boolean): void { // Override console methods to suppress output in headless mode console.log = () => {}; // Suppress all console.log - console.info = () => {}; // Suppress all console.info + 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); @@ -48,7 +48,7 @@ export function configureConsoleForHeadless(headless: boolean): void { console.warn = originalConsole.warn; console.error = originalConsole.error; console.debug = originalConsole.debug; - + originalConsole = null; } } @@ -62,7 +62,7 @@ export function safeStdout(message: string): void { } /** - * Safe stderr output that bypasses console overrides + * Safe stderr output that bypasses console overrides * Use this for error messages that should always be visible */ export function safeStderr(message: string): void { @@ -81,7 +81,7 @@ export function withOriginalConsole(fn: () => T): T { // Temporarily restore const tempConsole = { ...console }; Object.assign(console, originalConsole); - + try { return fn(); } finally { @@ -108,8 +108,8 @@ export function resetConsoleOverrides(): void { console.warn = originalConsole.warn; console.error = originalConsole.error; console.debug = originalConsole.debug; - + originalConsole = null; } isHeadlessMode = false; -} \ No newline at end of file +} diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index 7ab424bec..d594b488c 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -69,7 +69,7 @@ function isRetryableError(error: any): boolean { */ function calculateDelay( attempt: number, - options: Required + options: Required, ): number { const baseDelay = options.initialDelay * Math.pow(options.backoffMultiplier, attempt); @@ -90,7 +90,7 @@ export async function chatCompletionStreamWithBackoff( llmApi: BaseLlmApi, params: ChatCompletionCreateParamsStreaming, abortSignal: AbortSignal, - options: ExponentialBackoffOptions = {} + options: ExponentialBackoffOptions = {}, ): Promise> { const opts = { ...DEFAULT_OPTIONS, ...options }; let lastError: any; @@ -128,7 +128,7 @@ export async function chatCompletionStreamWithBackoff( warn( `Retrying LLM API call (attempt ${attempt + 1 - opts.hiddenRetries}/${ opts.maxRetries + 1 - opts.hiddenRetries - }) after ${delay}ms delay. Error: ${err.message}` + }) after ${delay}ms delay. Error: ${err.message}`, ); } @@ -141,7 +141,7 @@ export async function chatCompletionStreamWithBackoff( error( `LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${ lastError.message - }` + }`, ); throw lastError; } @@ -153,7 +153,7 @@ export async function chatCompletionStreamWithBackoff( export async function* withExponentialBackoff( generatorFactory: () => Promise>, abortSignal: AbortSignal, - options: ExponentialBackoffOptions = {} + options: ExponentialBackoffOptions = {}, ): AsyncGenerator { const opts = { ...DEFAULT_OPTIONS, ...options }; let lastError: any; @@ -208,7 +208,7 @@ export async function* withExponentialBackoff( warn( `Retrying request (${attempt + 1 - opts.hiddenRetries}/${ opts.maxRetries + 1 - opts.hiddenRetries - }). Error: ${formatError(err)}` + }). Error: ${formatError(err)}`, ); } @@ -222,7 +222,7 @@ export async function* withExponentialBackoff( error( `Failed after ${opts.maxRetries + 1} attempts. Last error: ${ lastError.message - }` + }`, ); throw lastError; } diff --git a/src/util/formatError.ts b/src/util/formatError.ts index 85e555ce5..177ac2ef0 100644 --- a/src/util/formatError.ts +++ b/src/util/formatError.ts @@ -5,12 +5,12 @@ export function formatError(error: any): string { if (error instanceof Error) { return error.message; } - - if (typeof error === 'string') { + + if (typeof error === "string") { return error; } - - if (error && typeof error === 'object') { + + if (error && typeof error === "object") { // Try to extract common error properties if (error.message) { return error.message; @@ -24,22 +24,22 @@ export function formatError(error: any): string { if (error.description) { return error.description; } - + // For API errors, try to extract meaningful info if (error.status && error.error && error.error.message) { return `HTTP ${error.status}: ${error.error.message}`; } - + // For network errors if (error.code && error.syscall) { return `Network error: ${error.code} in ${error.syscall}`; } - + // For errors with an errors array if (error.errors && Array.isArray(error.errors)) { - return error.errors.join(', '); + return error.errors.join(", "); } - + // Try to JSON stringify if possible try { return JSON.stringify(error); @@ -48,6 +48,6 @@ export function formatError(error: any): string { return `An error occurred: ${Object.prototype.toString.call(error)}`; } } - + return String(error); -} \ No newline at end of file +} diff --git a/src/util/git.ts b/src/util/git.ts index 02c1605fd..c15927848 100644 --- a/src/util/git.ts +++ b/src/util/git.ts @@ -23,7 +23,7 @@ export function getGitRemoteUrl(remote: string = "origin"): string | null { */ export function isGitRepo(): boolean { try { - execSync("git rev-parse --is-inside-work-tree", { + execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore", cwd: process.cwd(), }); @@ -44,4 +44,4 @@ export function getRepoUrl(): string { const remoteUrl = getGitRemoteUrl(); return remoteUrl || process.cwd(); -} \ No newline at end of file +} diff --git a/src/util/inputHistory.ts b/src/util/inputHistory.ts index f6c528273..6f646cda4 100644 --- a/src/util/inputHistory.ts +++ b/src/util/inputHistory.ts @@ -1,8 +1,8 @@ -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import fs from "fs"; +import os from "os"; +import path from "path"; -const HISTORY_FILE = path.join(os.homedir(), '.continue', 'input_history.json'); +const HISTORY_FILE = path.join(os.homedir(), ".continue", "input_history.json"); const MAX_HISTORY_SIZE = 1000; export interface InputHistoryEntry { @@ -13,7 +13,7 @@ export interface InputHistoryEntry { export class InputHistory { private history: InputHistoryEntry[] = []; private currentIndex: number = -1; - private originalInput: string = ''; + private originalInput: string = ""; constructor() { this.loadHistory(); @@ -27,11 +27,11 @@ export class InputHistory { } if (fs.existsSync(HISTORY_FILE)) { - const data = fs.readFileSync(HISTORY_FILE, 'utf8'); + const data = fs.readFileSync(HISTORY_FILE, "utf8"); this.history = JSON.parse(data); } } catch (error) { - console.error('Failed to load input history:', error); + console.error("Failed to load input history:", error); this.history = []; } } @@ -45,7 +45,7 @@ export class InputHistory { fs.writeFileSync(HISTORY_FILE, JSON.stringify(this.history, null, 2)); } catch (error) { - console.error('Failed to save input history:', error); + console.error("Failed to save input history:", error); } } @@ -53,12 +53,12 @@ export class InputHistory { if (!text.trim()) return; // Remove duplicate if it exists - this.history = this.history.filter(entry => entry.text !== text); + this.history = this.history.filter((entry) => entry.text !== text); // Add new entry at the beginning this.history.unshift({ text, - timestamp: Date.now() + timestamp: Date.now(), }); // Limit history size @@ -99,7 +99,7 @@ export class InputHistory { resetNavigation(): void { this.currentIndex = -1; - this.originalInput = ''; + this.originalInput = ""; } getHistory(): InputHistoryEntry[] { @@ -111,4 +111,4 @@ export class InputHistory { this.resetNavigation(); this.saveHistory(); } -} \ No newline at end of file +} diff --git a/src/util/logger.ts b/src/util/logger.ts index 183a7148e..31862308c 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -80,7 +80,7 @@ const logFormat = printf( } return msg; - } + }, ); // Track headless mode @@ -92,7 +92,7 @@ const winstonLogger = winston.createLogger({ format: combine( errors({ stack: true }), timestamp({ format: "YYYY-MM-DD HH:mm:ss.SSS" }), - logFormat + logFormat, ), transports: [ // File transport for all logs @@ -135,7 +135,7 @@ export const logger = { sentryService.captureMessage( `${message}: ${String(error)}`, "error", - meta + meta, ); } else { winstonLogger.error(message, meta); diff --git a/src/util/stdin.ts b/src/util/stdin.ts index b1de966bf..b5eae1ffa 100644 --- a/src/util/stdin.ts +++ b/src/util/stdin.ts @@ -30,4 +30,4 @@ export function readStdinSync(): string | null { } catch { return null; } -} \ No newline at end of file +} diff --git a/src/util/tokenizer.ts b/src/util/tokenizer.ts index a2ff9dfd6..7dc53e809 100644 --- a/src/util/tokenizer.ts +++ b/src/util/tokenizer.ts @@ -28,7 +28,7 @@ export function getModelContextLimit(model: ModelConfig): number { * @returns The estimated token count */ export function countMessageTokens( - message: ChatCompletionMessageParam + message: ChatCompletionMessageParam, ): number { try { let tokenCount = 0; @@ -86,7 +86,7 @@ export function countMessageTokens( * @returns The estimated total token count */ export function countChatHistoryTokens( - chatHistory: ChatCompletionMessageParam[] + chatHistory: ChatCompletionMessageParam[], ): number { let totalTokens = 0; @@ -108,7 +108,7 @@ export function countChatHistoryTokens( */ export function calculateContextUsagePercentage( tokenCount: number, - model: ModelConfig + model: ModelConfig, ): number { const limit = getModelContextLimit(model); return Math.min(100, Math.round((tokenCount / limit) * 100)); @@ -122,7 +122,7 @@ export function calculateContextUsagePercentage( */ export function shouldAutoCompact( chatHistory: ChatCompletionMessageParam[], - model: ModelConfig + model: ModelConfig, ): boolean { const tokenCount = countChatHistoryTokens(chatHistory); const limit = getModelContextLimit(model); diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts index ee63bb2ed..738f075cf 100644 --- a/src/util/yamlConfigUpdater.ts +++ b/src/util/yamlConfigUpdater.ts @@ -17,12 +17,15 @@ export interface ConfigStructure { /** * Updates or adds an Anthropic Claude model configuration in a YAML string while preserving comments and formatting. * This is a pure function that takes a YAML string and returns a modified YAML string. - * + * * @param yamlContent - The original YAML content as a string (can be empty) * @param apiKey - The Anthropic API key to set * @returns The updated YAML content as a string with comments preserved */ -export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): string { +export function updateAnthropicModelInYaml( + yamlContent: string, + apiKey: string, +): string { const newModel: ModelConfig = { uses: "anthropic/claude-4-sonnet", with: { @@ -41,47 +44,47 @@ export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): schema: "v1", models: [newModel], }; - - const newDoc = parseDocument(''); - Object.keys(defaultConfig).forEach(key => - newDoc.set(key, (defaultConfig as any)[key]) + + const newDoc = parseDocument(""); + Object.keys(defaultConfig).forEach((key) => + newDoc.set(key, (defaultConfig as any)[key]), ); return newDoc.toString(); } - // Convert to JS, filter models, and recreate + // Convert to JS, filter models, and recreate const config = doc.toJS() as any; - + // Make sure models array exists if (!config.models) { config.models = []; } - + // Filter out existing anthropic models - config.models = config.models.filter((model: any) => - !model || model.uses !== "anthropic/claude-4-sonnet" + config.models = config.models.filter( + (model: any) => !model || model.uses !== "anthropic/claude-4-sonnet", ); - + // Add the new anthropic model config.models.push(newModel); - + // Update the models array while preserving comments and structure - doc.set('models', config.models); + doc.set("models", config.models); return doc.toString(); } catch { // If parsing fails completely, create a new config const defaultConfig: ConfigStructure = { name: "Local Config", - version: "1.0.0", + version: "1.0.0", schema: "v1", models: [newModel], }; - - const doc = parseDocument(''); - Object.keys(defaultConfig).forEach(key => - doc.set(key, (defaultConfig as any)[key]) + + const doc = parseDocument(""); + Object.keys(defaultConfig).forEach((key) => + doc.set(key, (defaultConfig as any)[key]), ); return doc.toString(); } -} \ No newline at end of file +} diff --git a/src/utils/index.ts b/src/utils/index.ts index 25312b3d7..6e25560eb 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1 +1 @@ -export { isModelCapable } from './modelCapability.js'; \ No newline at end of file +export { isModelCapable } from "./modelCapability.js"; diff --git a/src/utils/modelCapability.ts b/src/utils/modelCapability.ts index 72588e1e3..1dca2417f 100644 --- a/src/utils/modelCapability.ts +++ b/src/utils/modelCapability.ts @@ -1,10 +1,14 @@ /** * Determines if a model is recommended for use with `cn` */ -export function isModelCapable(provider: string, name: string, model?: string): boolean { +export function isModelCapable( + provider: string, + name: string, + model?: string, +): boolean { // Check both name and model properties const normalizedName = name.toLowerCase(); - const normalizedModel = model ? model.toLowerCase() : ''; + const normalizedModel = model ? model.toLowerCase() : ""; const patterns = [/gemini/, /claude/, /gpt/, /o\d/, /kimi/, /qwen/]; @@ -18,4 +22,4 @@ export function isModelCapable(provider: string, name: string, model?: string): } return false; -} \ No newline at end of file +} diff --git a/src/version.ts b/src/version.ts index bf0906fc4..7363b920d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -18,12 +18,12 @@ export function getVersion(): string { } export async function getLatestVersion( - signal?: AbortSignal + signal?: AbortSignal, ): Promise { try { const response = await fetch( "https://registry.npmjs.org/@continuedev/cli/latest", - { signal } + { signal }, ); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); @@ -42,7 +42,7 @@ export async function getLatestVersion( export function compareVersions( current: string, - latest: string + latest: string, ): "newer" | "same" | "older" { if (current === "unknown" || latest === "unknown") { return "same"; diff --git a/tsconfig.build.json b/tsconfig.build.json index 3d549c7da..90ab61a16 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -4,7 +4,7 @@ "exclude": [ "src/**/*.test.ts", "src/**/*.test.tsx", - "src/**/*.spec.ts", + "src/**/*.spec.ts", "src/**/*.spec.tsx", "src/**/*.vitest.ts", "src/**/*.vitest.tsx", @@ -12,4 +12,4 @@ "src/**/__tests__/**/*", "src/**/__mocks__/**/*" ] -} \ No newline at end of file +} diff --git a/vitest.config.ts b/vitest.config.ts index d393f2a0a..81b6c4b7f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,32 +1,27 @@ -import { defineConfig } from 'vitest/config'; +import { defineConfig } from "vitest/config"; export default defineConfig({ test: { globals: true, - environment: 'node', - setupFiles: ['./vitest.setup.ts'], - exclude: [ - '**/node_modules/**', - '**/dist/**', - '**/*.e2e.*', - '**/e2e/**', - ], + environment: "node", + setupFiles: ["./vitest.setup.ts"], + exclude: ["**/node_modules/**", "**/dist/**", "**/*.e2e.*", "**/e2e/**"], coverage: { - reporter: ['text', 'json', 'html'], + reporter: ["text", "json", "html"], exclude: [ - 'node_modules/', - 'dist/', - '**/*.test.ts', - '**/*.spec.ts', - '**/test-helpers/**', - '**/types/**', - '**/__mocks__/**', + "node_modules/", + "dist/", + "**/*.test.ts", + "**/*.spec.ts", + "**/test-helpers/**", + "**/types/**", + "**/__mocks__/**", ], }, testTimeout: 30000, hookTimeout: 30000, }, resolve: { - extensions: ['.js', '.ts', '.tsx', '.json'], + extensions: [".js", ".ts", ".tsx", ".json"], }, -}); \ No newline at end of file +}); diff --git a/vitest.setup.ts b/vitest.setup.ts index 86715ac60..0a8dd66dc 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -7,18 +7,18 @@ process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; // Mock the 'open' package to prevent browser opening during tests vi.mock("open", () => ({ - default: vi.fn().mockResolvedValue(undefined) + default: vi.fn().mockResolvedValue(undefined), })); // Set up global afterEach hook to clear all timers and reset console afterEach(() => { // Clear vitest timers vi.clearAllTimers(); - + // Reset console overrides to ensure clean state for each test try { resetConsoleOverrides(); } catch { // Ignore errors when resetting console } -}); \ No newline at end of file +}); From d0dfb8675688d8bcfd2f8465c6548927ff4fa314 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 8 Aug 2025 13:23:42 -0700 Subject: [PATCH 7/7] improv: checks --- .github/workflows/pr_checks.yml | 44 ++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index 845b6528e..700498b82 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -10,6 +10,42 @@ permissions: issues: write jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Run linting + run: npm run lint + + format-check: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Check code formatting + run: npm run format:check + test: strategy: matrix: @@ -43,12 +79,6 @@ jobs: shell: bash run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**' - - name: Run linting - run: npm run lint - - - name: Check code formatting - run: npm run format:check - review: uses: ./.github/workflows/continue-review.yaml secrets: @@ -68,6 +98,8 @@ jobs: if: always() runs-on: ubuntu-latest needs: + - lint + - format-check - test steps: