refactor: shared function for constructing llm api

This commit is contained in:
Nate 2025-08-29 10:29:35 -07:00
parent 9f68638e32
commit 728f5b68c1
13 changed files with 192 additions and 175 deletions

View file

@ -18,30 +18,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

View file

@ -84,6 +84,7 @@
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
"prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"semantic-release": "^24.2.7",
@ -15566,6 +15567,93 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prettier-plugin-tailwindcss": {
"version": "0.6.14",
"resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
"integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.21.3"
},
"peerDependencies": {
"@ianvs/prettier-plugin-sort-imports": "*",
"@prettier/plugin-hermes": "*",
"@prettier/plugin-oxc": "*",
"@prettier/plugin-pug": "*",
"@shopify/prettier-plugin-liquid": "*",
"@trivago/prettier-plugin-sort-imports": "*",
"@zackad/prettier-plugin-twig": "*",
"prettier": "^3.0",
"prettier-plugin-astro": "*",
"prettier-plugin-css-order": "*",
"prettier-plugin-import-sort": "*",
"prettier-plugin-jsdoc": "*",
"prettier-plugin-marko": "*",
"prettier-plugin-multiline-arrays": "*",
"prettier-plugin-organize-attributes": "*",
"prettier-plugin-organize-imports": "*",
"prettier-plugin-sort-imports": "*",
"prettier-plugin-style-order": "*",
"prettier-plugin-svelte": "*"
},
"peerDependenciesMeta": {
"@ianvs/prettier-plugin-sort-imports": {
"optional": true
},
"@prettier/plugin-hermes": {
"optional": true
},
"@prettier/plugin-oxc": {
"optional": true
},
"@prettier/plugin-pug": {
"optional": true
},
"@shopify/prettier-plugin-liquid": {
"optional": true
},
"@trivago/prettier-plugin-sort-imports": {
"optional": true
},
"@zackad/prettier-plugin-twig": {
"optional": true
},
"prettier-plugin-astro": {
"optional": true
},
"prettier-plugin-css-order": {
"optional": true
},
"prettier-plugin-import-sort": {
"optional": true
},
"prettier-plugin-jsdoc": {
"optional": true
},
"prettier-plugin-marko": {
"optional": true
},
"prettier-plugin-multiline-arrays": {
"optional": true
},
"prettier-plugin-organize-attributes": {
"optional": true
},
"prettier-plugin-organize-imports": {
"optional": true
},
"prettier-plugin-sort-imports": {
"optional": true
},
"prettier-plugin-style-order": {
"optional": true
},
"prettier-plugin-svelte": {
"optional": true
}
}
},
"node_modules/pretty-format": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",

View file

@ -59,77 +59,78 @@
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
"@workos-inc/node": "^7.45.0",
"chalk": "^5.4.1",
"commander": "^14.0.0",
"core": "file:../../core",
"date-fns": "^4.1.0",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"glob": "^11.0.3",
"gpt-tokenizer": "^3.0.1",
"gradient-string": "^3.0.0",
"ignore": "^7.0.5",
"ignore-walk": "^7.0.0",
"ink": "^6.1.0",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"shell-quote": "^1.8.3",
"swr": "^2.3.4",
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uuid": "^9.0.1",
"winston": "^3.17.0",
"yaml": "^2.8.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@sentry/node": "^9.43.0",
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
"@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/react": "^19.1.8",
"@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@types/turndown": "^5.0.5",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"@workos-inc/node": "^7.45.0",
"chalk": "^5.4.1",
"commander": "^14.0.0",
"conventional-changelog-conventionalcommits": "^9.1.0",
"core": "file:../../core",
"cross-env": "^7.0.3",
"date-fns": "^4.1.0",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
"esbuild": "^0.25.9",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"glob": "^11.0.3",
"gpt-tokenizer": "^3.0.1",
"gradient-string": "^3.0.0",
"happy-dom": "^18.0.1",
"ignore": "^7.0.5",
"ignore-walk": "^7.0.0",
"ink": "^6.1.0",
"ink-testing-library": "^4.0.0",
"jsdom": "^26.1.0",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"nock": "^14.0.5",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
"prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"semantic-release": "^24.2.7",
"shell-quote": "^1.8.3",
"supertest": "^7.1.3",
"swr": "^2.3.4",
"ts-node": "^10.9.2",
"tsx": "^4.20.3",
"vitest": "^3.2.4"
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uuid": "^9.0.1",
"vitest": "^3.2.4",
"winston": "^3.17.0",
"yaml": "^2.8.0"
},
"engine": {
"node": ">=18"

View file

@ -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

View file

@ -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

View file

@ -13,5 +13,4 @@ export const getLlmApi =
) => [any, any]
>();
export const getModel = vi.fn<(config: any, modelName: string) => any>();
export const createLlmApi =
vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();
export const createLlmApi = vi.fn<(model: any, authConfig: any) => any>();

View file

@ -19,6 +19,41 @@ import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./services/MCPService.js";
/**
* Creates an LLM API instance from a ModelConfig and auth configuration
* Handles special logic for continue-proxy provider and constructs the API
*/
export function createLlmApi(
model: ModelConfig,
authConfig: AuthConfig | null,
): BaseLlmApi | null {
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
model.provider === "continue-proxy"
? {
provider: model.provider,
requestOptions: model.requestOptions,
apiBase: model.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (model as any).apiKeyLocation,
orgScopeId: organizationId,
proxyUrl: (model as any).onPremProxyUrl ?? undefined,
},
}
: {
provider: model.provider as any,
apiKey: model.apiKey,
apiBase: model.apiBase,
requestOptions: model.requestOptions,
env: model.env,
};
return constructLlmApi(config);
}
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig,
@ -38,32 +73,7 @@ export function getLlmApi(
);
}
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
model.provider === "continue-proxy"
? {
provider: model.provider,
requestOptions: model.requestOptions,
apiBase: model.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (model as any).apiKeyLocation,
// envSecretLocations: model.env,
orgScopeId: organizationId,
proxyUrl: undefined, // TODO
},
}
: {
provider: model.provider as any,
apiKey: model.apiKey,
apiBase: model.apiBase,
requestOptions: model.requestOptions,
env: model.env,
};
const llmApi = constructLlmApi(config);
const llmApi = createLlmApi(model, authConfig);
if (!llmApi) {
throw new Error(

View file

@ -30,7 +30,7 @@ describe("E2E: Authentication", () => {
authPath,
JSON.stringify({
userId: "test-user",
userEmail: "test@example.com",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh-token",
expiresAt: Date.now() + 3600000,
@ -39,12 +39,12 @@ describe("E2E: Authentication", () => {
);
// Run logout
const result = await runCLI(context, {
const result = await runCLI(context, {
args: ["logout"],
env: {
HOME: context.testDir,
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue")
}
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
},
});
expect(result.exitCode).toBe(0);
@ -59,12 +59,12 @@ describe("E2E: Authentication", () => {
});
it("should handle logout when not logged in", async () => {
const result = await runCLI(context, {
const result = await runCLI(context, {
args: ["logout"],
env: {
HOME: context.testDir,
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue")
}
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
},
});
expect(result.exitCode).toBe(0);

View file

@ -46,16 +46,16 @@ describe("E2E: Resume Flag", () => {
// Verify that a session file was created
const sessionDir = path.join(context.testDir, ".continue", "sessions");
// Ensure session directory exists
try {
await fs.mkdir(sessionDir, { recursive: true });
} catch (error) {
// Directory already exists, continue
}
const sessionFiles = (await fs.readdir(sessionDir)).filter(
f => f.endsWith('.json') && f !== 'sessions.json'
(f) => f.endsWith(".json") && f !== "sessions.json",
);
expect(sessionFiles).toHaveLength(1);
@ -150,16 +150,16 @@ describe("E2E: Resume Flag", () => {
// Verify the first session was saved correctly
const sessionDir = path.join(context.testDir, ".continue", "sessions");
// Ensure session directory exists
try {
await fs.mkdir(sessionDir, { recursive: true });
} catch (error) {
// Directory already exists, continue
}
let sessionFiles = (await fs.readdir(sessionDir)).filter(
f => f.endsWith('.json') && f !== 'sessions.json'
(f) => f.endsWith(".json") && f !== "sessions.json",
);
expect(sessionFiles).toHaveLength(1);
@ -193,7 +193,7 @@ describe("E2E: Resume Flag", () => {
// Check that the session file contains both messages
sessionFiles = (await fs.readdir(sessionDir)).filter(
f => f.endsWith('.json') && f !== 'sessions.json'
(f) => f.endsWith(".json") && f !== "sessions.json",
);
sessionFile = sessionFiles[0];
sessionPath = path.join(sessionDir, sessionFile);

View file

@ -1,9 +1,7 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import * as openaiAdapters from "@continuedev/openai-adapters";
import { describe, expect, beforeEach, vi, test } from "vitest";
// Mock dependencies before imports
vi.mock("@continuedev/openai-adapters");
vi.mock("../config.js");
vi.mock("../auth/workos.js");
@ -81,9 +79,7 @@ describe("ModelService", () => {
test("should initialize with persisted model if valid", async () => {
vi.mocked(workos.getModelName).mockReturnValue("Claude 3");
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
mockLlmApi as any,
);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
const state = await service.initialize(mockAssistant, mockAuthConfig);
@ -152,9 +148,7 @@ describe("ModelService", () => {
await service.initialize(mockAssistant, mockAuthConfig);
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
newLlmApi as any,
);
vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any);
const state = await service.switchModel(1);
@ -204,24 +198,14 @@ describe("ModelService", () => {
]);
await service.initialize(mockAssistant, mockAuthConfig);
vi.mocked(workos.getAccessToken).mockReturnValue("proxy-token");
vi.mocked(workos.getOrganizationId).mockReturnValue("org-123");
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
mockLlmApi as any,
);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
await service.switchModel(0);
expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({
provider: "continue-proxy",
apiBase: "https://proxy.continue.dev",
apiKey: "proxy-token",
env: {
apiKeyLocation: "env.PROXY_KEY",
orgScopeId: "org-123",
proxyUrl: undefined,
},
});
expect(vi.mocked(config.createLlmApi)).toHaveBeenCalledWith(
proxyModel,
mockAuthConfig,
);
});
});
@ -292,9 +276,7 @@ describe("ModelService", () => {
expect(service.getCurrentModelIndex()).toBe(0);
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
mockLlmApi as any,
);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
await service.switchModel(1);
expect(service.getCurrentModelIndex()).toBe(1);
});
@ -392,9 +374,7 @@ describe("ModelService", () => {
service.on("stateChanged", listener);
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
newLlmApi as any,
);
vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any);
await service.switchModel(1);
expect(listener).toHaveBeenCalledWith(
@ -419,7 +399,7 @@ describe("ModelService", () => {
const errorListener = vi.fn();
service.on("error", errorListener);
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any);
vi.mocked(config.createLlmApi).mockReturnValue(null as any);
await expect(service.switchModel(1)).rejects.toThrow(
"Failed to initialize LLM",

View file

@ -1,13 +1,7 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import {
AuthConfig,
getAccessToken,
getModelName,
getOrganizationId,
} from "../auth/workos.js";
import { getLlmApi } from "../config.js";
import { AuthConfig, getModelName } from "../auth/workos.js";
import { createLlmApi, getLlmApi } from "../config.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
@ -89,31 +83,7 @@ export class ModelService
name: (selectedModel as any).name || "unnamed",
});
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
selectedModel.provider === "continue-proxy"
? {
provider: selectedModel.provider,
requestOptions: selectedModel.requestOptions,
apiBase: selectedModel.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (selectedModel as any).apiKeyLocation,
orgScopeId: organizationId,
proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined,
},
}
: {
provider: selectedModel.provider as any,
apiKey: selectedModel.apiKey,
apiBase: selectedModel.apiBase,
requestOptions: selectedModel.requestOptions,
env: selectedModel.env,
};
const llmApi = constructLlmApi(config);
const llmApi = createLlmApi(selectedModel, authConfig);
if (!llmApi) {
throw new Error("Failed to initialize LLM with persisted model");
@ -288,31 +258,7 @@ export class ModelService
});
try {
const accessToken = getAccessToken(authConfig);
const organizationId = getOrganizationId(authConfig);
const config: LLMConfig =
selectedModel.provider === "continue-proxy"
? {
provider: selectedModel.provider,
requestOptions: selectedModel.requestOptions,
apiBase: selectedModel.apiBase,
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (selectedModel as any).apiKeyLocation,
orgScopeId: organizationId,
proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined,
},
}
: {
provider: selectedModel.provider as any,
apiKey: selectedModel.apiKey,
apiBase: selectedModel.apiBase,
requestOptions: selectedModel.requestOptions,
env: selectedModel.env,
};
const llmApi = constructLlmApi(config);
const llmApi = createLlmApi(selectedModel, authConfig);
if (!llmApi) {
throw new Error("Failed to initialize LLM with selected model");

View file

@ -8,14 +8,14 @@ import { fileURLToPath } from "url";
let logger;
try {
// Try to import the compiled logger
const loggerModule = await import('./dist/util/logger.js');
const loggerModule = await import("./dist/util/logger.js");
logger = loggerModule.logger;
} catch {
// Fallback to console if logger not available (e.g., not built yet)
logger = {
info: console.log,
warn: console.warn,
error: console.error
error: console.error,
};
}

View file

@ -12528,6 +12528,7 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz",
"integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==",
"dev": true,
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"