Merge branch 'main' of https://github.com/continuedev/continue into uinstinct/non-whitespace

This commit is contained in:
Dallin Romney 2026-02-03 17:45:48 -08:00
commit 2a717dde88
68 changed files with 4785 additions and 2365 deletions

View file

@ -1,202 +0,0 @@
name: PR Compliance Checks
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
conventional-commits:
name: Validate Conventional Commits
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
continue-on-error: true
permissions:
pull-requests: write
issues: write
contents: read
steps:
- name: Validate PR title format
id: pr-title-check
run: |
PR_TITLE="${{ github.event.pull_request.title }}"
echo "Checking PR title: $PR_TITLE"
# Regex pattern for conventional commits
PATTERN="^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?!?: .+"
if [[ $PR_TITLE =~ $PATTERN ]]; then
echo "✅ PR title follows conventional commit format"
echo "valid=true" >> $GITHUB_OUTPUT
else
echo "❌ PR title does not follow conventional commit format"
echo "valid=false" >> $GITHUB_OUTPUT
# Don't exit with failure - just mark as invalid for comment
fi
- name: Add PR title guidance comment
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v8
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('PR Title Format')
);
if (!botComment) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: [
"## ⚠️ PR Title Format",
"",
"Your PR title doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend using this format for better project organization.",
"",
"### Expected Format:",
"```",
"<type>[optional scope]: <description>",
"```",
"",
"### Examples:",
"- `feat: add changelog generation support`",
"- `fix: resolve login redirect issue`",
"- `docs: update README with new instructions`",
"- `chore: update dependencies`",
"",
"### Valid Types:",
"`feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`",
"",
"This helps with:",
"- 📝 Automatic changelog generation",
"- 🚀 Automated semantic versioning",
"- 📊 Better project history tracking",
"",
"*This is a non-blocking warning - your PR can still be merged without fixing this.*"
].join('\n')
});
}
- name: Ensure job always succeeds
if: always()
run: echo "✅ Conventional commits check completed (warning only)"
security-audit:
name: Security Audit
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
permissions:
security-events: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Fix vulnerabilities
run: npm audit fix
- name: Run npm audit
run: npm audit --audit-level=moderate
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
# Use this for any files that we want to be certain exist
# Basically creates a forcing function to discuss were anyone to want to remove them
file-validation:
name: Required Files Check
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Check required files
run: |
required_files=(
"package.json"
"package-lock.json"
"README.md"
"LICENSE"
".gitignore"
"tsconfig.json"
"SECURITY.md"
"CONTRIBUTING.md"
".nvmrc"
".prettierrc"
".prettierignore"
)
missing_files=()
for file in "${required_files[@]}"; do
if [[ ! -f "$file" ]]; then
missing_files+=("$file")
fi
done
if [[ ${#missing_files[@]} -gt 0 ]]; then
echo "❌ Missing required files:"
printf '%s\n' "${missing_files[@]}"
exit 1
else
echo "✅ All required files present"
fi
compliance-summary:
name: Compliance Summary
runs-on: ubuntu-latest
needs: [conventional-commits, security-audit, file-validation]
if: always() && !github.event.pull_request.draft
steps:
- name: Check compliance status
run: |
echo "## 🔍 Compliance Check Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ needs.conventional-commits.result }}" == "success" ]]; then
echo "✅ Conventional Commits: PASSED" >> $GITHUB_STEP_SUMMARY
elif [[ "${{ needs.conventional-commits.result }}" == "failure" ]]; then
echo "⚠️ Conventional Commits: WARNING (non-blocking)" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Conventional Commits: SKIPPED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.security-audit.result }}" == "success" ]]; then
echo "✅ Security Audit: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Security Audit: FAILED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.file-validation.result }}" == "success" ]]; then
echo "✅ File Validation: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ File Validation: FAILED" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "📊 **Overall Status**: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY

View file

@ -1,28 +0,0 @@
name: Continue General Review
on:
push:
branches:
- main
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-code-review:
name: Continue General Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
continue-agent: "empty-agent"

View file

@ -1,9 +1,9 @@
import {
AssistantUnrolled,
AssistantUnrolledNonNullable,
BLOCK_TYPES,
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
@ -145,8 +145,8 @@ async function loadConfigYaml(options: {
}
}
if (config && isAssistantUnrolledNonNullable(config)) {
errors.push(...validateConfigYaml(config));
if (config) {
errors.push(...validateConfigYaml(nonNullifyConfigYaml(config)));
}
if (errors?.some((error) => error.fatal)) {
@ -165,15 +165,30 @@ async function loadConfigYaml(options: {
};
}
function nonNullifyConfigYaml(
unrolledAssistant: AssistantUnrolled,
): AssistantUnrolledNonNullable {
return {
...unrolledAssistant,
data: unrolledAssistant.data?.filter((k) => !!k),
context: unrolledAssistant.context?.filter((k) => !!k),
docs: unrolledAssistant.docs?.filter((k) => !!k),
mcpServers: unrolledAssistant.mcpServers?.filter((k) => !!k),
models: unrolledAssistant.models?.filter((k) => !!k),
prompts: unrolledAssistant.prompts?.filter((k) => !!k),
rules: unrolledAssistant.rules?.filter((k) => !!k).map((k) => k!),
};
}
export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
unrolledAssistant: AssistantUnrolled;
ide: IDE;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { config, ide, ideInfo, uniqueId, llmLogger } = options;
let { unrolledAssistant, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -203,22 +218,10 @@ export async function configYamlToContinueConfig(options: {
subagent: null,
},
rules: [],
requestOptions: { ...config.requestOptions },
requestOptions: { ...unrolledAssistant.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
if (!isAssistantUnrolledNonNullable(config)) {
return {
config: continueConfig,
errors: [
{
message:
"Failed to load config due to missing blocks, see which blocks are missing below",
fatal: true,
},
],
};
}
const config = nonNullifyConfigYaml(unrolledAssistant);
for (const rule of config.rules ?? []) {
const convertedRule = convertYamlRuleToContinueRule(rule);
@ -255,9 +258,30 @@ export async function configYamlToContinueConfig(options: {
continueConfig.slashCommands?.push(slashCommand);
}
} catch (e) {
// If the file is in a rules directory, we can provide a more helpful error message
// because we know it's likely a rule definition
const isRuleFile =
file.path.toLowerCase().includes("/rules/") ||
file.path.toLowerCase().includes("\\rules\\");
let message = `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`;
if (isRuleFile) {
const isYamlError =
e instanceof Error &&
(e.name?.includes("YAML") || e.message.includes("flow sequence"));
const prefix = isYamlError
? "Failed to parse rule definition"
: "Failed to process rule definition";
const errorDetails = e instanceof Error ? e.message : String(e);
message = `${prefix} ${file.path}: ${errorDetails}`;
}
localErrors.push({
fatal: false,
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
message,
});
}
});
@ -447,7 +471,7 @@ export async function loadContinueConfigFromYaml(options: {
const { config: continueConfig, errors: localErrors } =
await configYamlToContinueConfig({
config: configYamlResult.config,
unrolledAssistant: configYamlResult.config,
ide,
ideInfo,
uniqueId,

View file

@ -67,6 +67,12 @@ async function modelConfigToBaseLLM({
baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
basePlanSystemMessage: model.chatOptions?.basePlanSystemMessage,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
toolOverrides: model.chatOptions?.toolOverrides
? Object.entries(model.chatOptions.toolOverrides).map(([name, o]) => ({
name,
...o,
}))
: undefined,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),

14
core/index.d.ts vendored
View file

@ -2,6 +2,7 @@ import {
DataDestination,
ModelRole,
PromptTemplates,
ToolOverrideConfig,
} from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
@ -290,6 +291,7 @@ export interface BaseSessionMetadata {
title: string;
dateCreated: string;
workspaceDirectory: string;
messageCount?: number;
}
export interface RangeInFile {
@ -694,6 +696,9 @@ export interface LLMOptions {
sourceFile?: string;
isFromAutoDetect?: boolean;
/** Tool overrides for this model */
toolOverrides?: ToolOverride[];
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -1141,6 +1146,15 @@ export interface Tool {
) => ToolPolicy;
}
/**
* Configuration for overriding built-in tool prompts.
* Extends ToolOverrideConfig with required name for array usage.
*/
export type ToolOverride = ToolOverrideConfig & {
/** Tool name to override (matches function.name, e.g., "read_file") */
name: string;
};
interface ToolChoice {
type: "function";
function: {

View file

@ -70,6 +70,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"groq",
"gemini",
"docker",
"nous",
// TODO add these, change to inverted logic so only the ones that need templating are hardcoded
// Asksage.ts
// Azure.ts
@ -365,6 +366,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "deepseek";
}
if (lower.includes("hermes")) {
return "chatml";
}
if (lower.includes("ninja") || lower.includes("openchat")) {
return "openchat";
}

View file

@ -18,6 +18,7 @@ import {
import { renderChatMessage } from "../util/messageContent.js";
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
import { DEFAULT_PRUNING_LENGTH } from "./constants.js";
import { getAdjustedTokenCountFromModel } from "./getAdjustedTokenCount.js";
import llamaTokenizer from "./llamaTokenizer.js";
interface Encoding {
encode: Tiktoken["encode"];
@ -114,8 +115,9 @@ function countTokens(
modelName = "llama2",
): number {
const encoding = encodingForModel(modelName);
let baseTokens = 0;
if (Array.isArray(content)) {
return content.reduce((acc, part) => {
baseTokens = content.reduce((acc, part) => {
return (
acc +
(part.type === "text"
@ -124,8 +126,9 @@ function countTokens(
);
}, 0);
} else {
return encoding.encode(content ?? "", "all", []).length;
baseTokens = encoding.encode(content ?? "", "all", []).length;
}
return getAdjustedTokenCountFromModel(baseTokens, modelName);
}
// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10

View file

@ -0,0 +1,48 @@
import { getAdjustedTokenCountFromModel } from "./getAdjustedTokenCount";
describe("getAdjustedTokenCountFromModel", () => {
it("should return base tokens for non-special models", () => {
expect(getAdjustedTokenCountFromModel(100, "gpt-4")).toBe(100);
expect(getAdjustedTokenCountFromModel(100, "llama2")).toBe(100);
expect(getAdjustedTokenCountFromModel(100, "random-model")).toBe(100);
});
it("should apply multiplier for Claude models", () => {
expect(getAdjustedTokenCountFromModel(100, "claude-3-opus")).toBe(123);
expect(getAdjustedTokenCountFromModel(100, "claude-3.5-sonnet")).toBe(123);
expect(getAdjustedTokenCountFromModel(100, "CLAUDE-2")).toBe(123);
expect(getAdjustedTokenCountFromModel(50, "claude")).toBe(62); // 50 * 1.23 = 61.5, ceiled to 62
});
it("should apply multiplier for Gemini models", () => {
expect(getAdjustedTokenCountFromModel(100, "gemini-pro")).toBe(118);
expect(getAdjustedTokenCountFromModel(100, "gemini-1.5-pro")).toBe(118);
expect(getAdjustedTokenCountFromModel(100, "GEMINI-flash")).toBe(118);
expect(getAdjustedTokenCountFromModel(50, "gemini")).toBe(59); // 50 * 1.18 = 59
});
it("should apply multiplier for Mistral family models", () => {
expect(getAdjustedTokenCountFromModel(100, "mistral-large")).toBe(126);
expect(getAdjustedTokenCountFromModel(100, "mixtral-8x7b")).toBe(126);
expect(getAdjustedTokenCountFromModel(100, "devstral")).toBe(126);
expect(getAdjustedTokenCountFromModel(100, "CODESTRAL")).toBe(126);
expect(getAdjustedTokenCountFromModel(50, "mistral")).toBe(63); // 50 * 1.26 = 63
});
it("should handle edge cases", () => {
expect(getAdjustedTokenCountFromModel(0, "claude")).toBe(0);
expect(getAdjustedTokenCountFromModel(1, "gemini")).toBe(2); // 1 * 1.18 = 1.18, ceiled to 2
expect(getAdjustedTokenCountFromModel(1000, "mixtral")).toBe(1260);
});
it("should handle empty or undefined model names", () => {
expect(getAdjustedTokenCountFromModel(100, "")).toBe(100);
expect(getAdjustedTokenCountFromModel(100, undefined as any)).toBe(100);
});
it("should be case-insensitive", () => {
expect(getAdjustedTokenCountFromModel(100, "ClAuDe-3-OpUs")).toBe(123);
expect(getAdjustedTokenCountFromModel(100, "GeMiNi-PrO")).toBe(118);
expect(getAdjustedTokenCountFromModel(100, "MiXtRaL")).toBe(126);
});
});

View file

@ -0,0 +1,38 @@
// Importing a bunch of tokenizers can be very resource intensive (MB-scale per tokenizer)
// Using token counting APIs (e.g. for anthropic) can be complicated and unreliable in many environments
// So for now we will just use super fast gpt-tokenizer and apply safety buffers
// I'm using rough estimates from this article to apply safety buffers to common tokenizers
// which will have HIGHER token counts than gpt. Roughly using token ratio from article + 10%
// https://medium.com/@disparate-ai/not-all-tokens-are-created-equal-7347d549af4d
const ANTHROPIC_TOKEN_MULTIPLIER = 1.23;
const GEMINI_TOKEN_MULTIPLIER = 1.18;
const MISTRAL_TOKEN_MULTIPLIER = 1.26;
/**
* Adjusts token count based on model-specific tokenizer differences.
* Since we use llama tokenizer (~= gpt tokenizer) for all models, we apply
* multipliers for models known to have higher token counts.
*
* @param baseTokens - Token count from llama/gpt tokenizer
* @param modelName - Name of the model
* @returns Adjusted token count with safety buffer
*/
export function getAdjustedTokenCountFromModel(
baseTokens: number,
modelName: string,
): number {
let multiplier = 1;
const lowerModelName = modelName?.toLowerCase() ?? "";
if (lowerModelName.includes("claude")) {
multiplier = ANTHROPIC_TOKEN_MULTIPLIER;
} else if (lowerModelName.includes("gemini")) {
multiplier = GEMINI_TOKEN_MULTIPLIER;
} else if (
lowerModelName.includes("stral") ||
lowerModelName.includes("mixtral")
) {
// Mistral family models: mistral, mixtral, codestral, devstral, etc
multiplier = MISTRAL_TOKEN_MULTIPLIER;
}
return Math.ceil(baseTokens * multiplier);
}

View file

@ -28,6 +28,7 @@ import {
RequestOptions,
TabAutocompleteOptions,
TemplateType,
ToolOverride,
Usage,
} from "../index.js";
import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
@ -65,6 +66,8 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { applyToolOverrides } from "../tools/applyToolOverrides.js";
export class LLMError extends Error {
constructor(
message: string,
@ -90,6 +93,7 @@ export abstract class BaseLLM implements ILLM {
// Provider capabilities (overridable by subclasses)
protected supportsReasoningField: boolean = false;
protected supportsReasoningDetailsField: boolean = false;
protected supportsReasoningContentField: boolean = false;
get providerName(): string {
return (this.constructor as typeof BaseLLM).providerName;
@ -196,6 +200,9 @@ export abstract class BaseLLM implements ILLM {
isFromAutoDetect?: boolean;
/** Tool overrides for this model */
toolOverrides?: ToolOverride[];
lastRequestId: string | undefined;
private _llmOptions: LLMOptions;
@ -303,6 +310,7 @@ export abstract class BaseLLM implements ILLM {
this.autocompleteOptions = options.autocompleteOptions;
this.sourceFile = options.sourceFile;
this.isFromAutoDetect = options.isFromAutoDetect;
this.toolOverrides = options.toolOverrides;
}
get contextLength() {
@ -1111,8 +1119,28 @@ export abstract class BaseLLM implements ILLM {
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog> {
this.lastRequestId = undefined;
// Apply per-model tool overrides if configured
let effectiveTools = options.tools;
if (this.toolOverrides?.length && options.tools?.length) {
const { tools: overriddenTools, errors } = applyToolOverrides(
options.tools,
this.toolOverrides,
);
effectiveTools = overriddenTools;
// Log any warnings for unknown tool names
for (const error of errors) {
if (!error.fatal) {
console.warn(`Tool override warning: ${error.message}`);
}
}
}
// Use effectiveTools for the rest of this method
const optionsWithOverrides = { ...options, tools: effectiveTools };
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
this._parseCompletionOptions(optionsWithOverrides);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
@ -1130,7 +1158,7 @@ export abstract class BaseLLM implements ILLM {
knownContextLength: this._contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
tools: optionsWithOverrides.tools,
});
messages = compiledChatMessages;
@ -1182,6 +1210,7 @@ export abstract class BaseLLM implements ILLM {
let body = toChatBody(messages, completionOptions, {
includeReasoningField: this.supportsReasoningField,
includeReasoningDetailsField: this.supportsReasoningDetailsField,
includeReasoningContentField: this.supportsReasoningContentField,
});
body = this.modifyChatBody(body);

View file

@ -407,7 +407,7 @@ class Anthropic extends BaseLLM {
): AsyncGenerator<ChatMessage> {
if (!this.apiKey || this.apiKey === "") {
throw new Error(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
"Request not sent. You have an Anthropic model configured in your config.yaml, but the API key is not set.",
);
}

View file

@ -488,7 +488,7 @@ describe("Anthropic", () => {
},
}),
).rejects.toThrow(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
"Request not sent. You have an Anthropic model configured in your config.yaml, but the API key is not set.",
);
});
});

View file

@ -6,8 +6,9 @@ import OpenAI from "./OpenAI.js";
class Deepseek extends OpenAI {
static providerName = "deepseek";
protected supportsReasoningField = true;
protected supportsReasoningField = false;
protected supportsReasoningDetailsField = false;
protected supportsReasoningContentField = true;
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.deepseek.com/",
model: "deepseek-coder",

13
core/llm/llms/Nous.ts Normal file
View file

@ -0,0 +1,13 @@
import { LLMOptions } from "../..";
import OpenAI from "./OpenAI";
class Nous extends OpenAI {
static providerName = "nous";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://inference-api.nousresearch.com/v1",
useLegacyCompletionsEndpoint: false,
};
}
export default Nous;

View file

@ -4,6 +4,12 @@ import {
} from "openai/resources/index";
import { streamSse } from "@continuedev/fetch";
import {
ResponseCreateParamsBase,
ResponseInputItem,
ResponseInputMessageContentList,
Tool as ResponsesTool,
} from "openai/resources/responses/responses.mjs";
import {
ChatMessage,
CompletionOptions,
@ -19,13 +25,6 @@ import {
toChatBody,
toResponsesInput,
} from "../openaiTypeConverters.js";
import {
ResponseInput,
ResponseInputItem,
ResponseInputMessageContentList,
ResponseCreateParamsBase,
Tool as ResponsesTool,
} from "openai/resources/responses/responses.mjs";
const NON_CHAT_MODELS = [
"text-davinci-002",
@ -279,6 +278,7 @@ class OpenAI extends BaseLLM {
const finalOptions = toChatBody(messages, options, {
includeReasoningField: this.supportsReasoningField,
includeReasoningDetailsField: this.supportsReasoningDetailsField,
includeReasoningContentField: this.supportsReasoningContentField,
});
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());

View file

@ -43,6 +43,7 @@ import Moonshot from "./Moonshot";
import Msty from "./Msty";
import NCompass from "./NCompass";
import Nebius from "./Nebius";
import Nous from "./Nous";
import Novita from "./Novita";
import Nvidia from "./Nvidia";
import Ollama from "./Ollama";
@ -114,6 +115,7 @@ export const LLMClasses = [
Cerebras,
Asksage,
Nebius,
Nous,
Venice,
VertexAI,
xAI,

View file

@ -0,0 +1,511 @@
import { toResponsesInput } from "./openaiTypeConverters";
import { ChatMessage } from "..";
import type { ResponseInputItem } from "openai/resources/responses/responses.mjs";
// Types for test assertions (simplified from OpenAI types)
type FunctionCallItem = {
type: "function_call";
id: string;
name: string;
arguments: string;
call_id: string;
};
type FunctionCallOutputItem = {
type: "function_call_output";
call_id: string;
output: string;
};
type MessageItem = {
role: string;
content: unknown;
};
// Helper functions for filtering results
function getFunctionCalls(items: ResponseInputItem[]): FunctionCallItem[] {
return items.filter(
(item) => (item as { type?: string }).type === "function_call",
) as unknown as FunctionCallItem[];
}
function getFunctionCallOutputs(
items: ResponseInputItem[],
): FunctionCallOutputItem[] {
return items.filter(
(item) => (item as { type?: string }).type === "function_call_output",
) as unknown as FunctionCallOutputItem[];
}
function getMessagesByRole(
items: ResponseInputItem[],
role: string,
): MessageItem[] {
return items.filter((item) => {
const msg = item as { role?: string; type?: string };
return msg.role === role && (!msg.type || msg.type === "message");
}) as unknown as MessageItem[];
}
describe("openaiTypeConverters", () => {
describe("toResponsesInput", () => {
describe("tool calls handling - OpenAI Responses API", () => {
it("should emit function_call items when fc_ ID is in metadata", () => {
const messages: ChatMessage[] = [
{
role: "user",
content: "List files in current directory",
},
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_abc123",
type: "function",
function: {
name: "filesystem_list_directory",
arguments: '{"path": "."}',
},
},
],
metadata: { responsesOutputItemId: "fc_abc123" },
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(1);
expect(functionCalls[0].id).toBe("fc_abc123");
expect(functionCalls[0].call_id).toBe("call_abc123");
expect(functionCalls[0].name).toBe("filesystem_list_directory");
});
it("should NOT emit function_call when no fc_ ID in metadata", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "I'll help.",
toolCalls: [
{
id: "call_xyz",
type: "function",
function: {
name: "some_tool",
arguments: "{}",
},
},
],
// No metadata with fc_ ID
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(0);
// Text should still be emitted
const assistantMessages = getMessagesByRole(result, "assistant");
expect(assistantMessages.length).toBe(1);
});
it("should emit text content alongside tool calls", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "Let me help you with that.",
toolCalls: [
{
id: "call_xyz",
type: "function",
function: {
name: "some_tool",
arguments: "{}",
},
},
],
metadata: { responsesOutputItemId: "fc_xyz" },
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
const assistantMessages = getMessagesByRole(result, "assistant");
expect(functionCalls.length).toBe(1);
expect(assistantMessages.length).toBe(1);
expect(assistantMessages[0].content).toBe("Let me help you with that.");
});
});
describe("function_call_output handling", () => {
it("should emit function_call_output for tool role messages", () => {
const messages: ChatMessage[] = [
{
role: "tool",
content: '{"files": ["a.txt", "b.txt"]}',
toolCallId: "call_abc123",
} as ChatMessage,
];
const result = toResponsesInput(messages);
const outputs = getFunctionCallOutputs(result);
expect(outputs.length).toBe(1);
expect(outputs[0].call_id).toBe("call_abc123");
});
});
// Complete conversation flow tests (moved out of describe block to reduce nesting)
it("should handle full tool call cycle with fc_ IDs", () => {
const messages: ChatMessage[] = [
{
role: "user",
content: "List files",
},
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_list",
type: "function",
function: {
name: "list_files",
arguments: "{}",
},
},
],
metadata: { responsesOutputItemId: "fc_list" },
} as ChatMessage,
{
role: "tool",
content: '["file1.txt", "file2.txt"]',
toolCallId: "call_list",
} as ChatMessage,
];
const result = toResponsesInput(messages);
const userMsgs = getMessagesByRole(result, "user");
const functionCalls = getFunctionCalls(result);
const functionOutputs = getFunctionCallOutputs(result);
expect(userMsgs.length).toBe(1);
expect(functionCalls.length).toBe(1);
expect(functionOutputs.length).toBe(1);
expect(functionCalls[0].id).toBe("fc_list");
expect(functionCalls[0].call_id).toBe("call_list");
expect(functionOutputs[0].call_id).toBe("call_list");
});
it("should handle parallel tool calls merged into ONE message with responsesOutputItemIds array", () => {
// This is the REAL scenario: streaming parallel tool calls get merged into
// ONE ChatMessage with multiple toolCalls and an array of fc_ IDs
const messages: ChatMessage[] = [
{
role: "user",
content: "Read these 3 files",
},
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_001",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.py"}',
},
},
{
id: "call_002",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.js"}',
},
},
{
id: "call_003",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.ts"}',
},
},
],
metadata: {
// Array of fc_ IDs, one per tool call
responsesOutputItemIds: ["fc_001", "fc_002", "fc_003"],
responsesOutputItemId: "fc_003", // Also keep last one for backwards compat
},
} as ChatMessage,
// Tool results
{
role: "tool",
content: "# Python code",
toolCallId: "call_001",
} as ChatMessage,
{
role: "tool",
content: "// JS code",
toolCallId: "call_002",
} as ChatMessage,
{
role: "tool",
content: "// TS code",
toolCallId: "call_003",
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(3);
// Verify each function_call has correct fc_ ID and call_id
expect(functionCalls[0].id).toBe("fc_001");
expect(functionCalls[0].call_id).toBe("call_001");
expect(functionCalls[1].id).toBe("fc_002");
expect(functionCalls[1].call_id).toBe("call_002");
expect(functionCalls[2].id).toBe("fc_003");
expect(functionCalls[2].call_id).toBe("call_003");
const functionOutputs = getFunctionCallOutputs(result);
expect(functionOutputs.length).toBe(3);
});
it("should handle 3 parallel tool calls when each has its own fc_ ID (separate messages)", () => {
// Legacy scenario: Each function_call from OpenAI creates a separate ChatMessage
const messages: ChatMessage[] = [
{
role: "user",
content: "Read these 3 files",
},
// First tool call
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_001",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.py"}',
},
},
],
metadata: { responsesOutputItemId: "fc_001" },
} as ChatMessage,
// Second tool call
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_002",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.js"}',
},
},
],
metadata: { responsesOutputItemId: "fc_002" },
} as ChatMessage,
// Third tool call
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_003",
type: "function",
function: {
name: "read_file",
arguments: '{"path":"test.ts"}',
},
},
],
metadata: { responsesOutputItemId: "fc_003" },
} as ChatMessage,
// Tool results
{
role: "tool",
content: "# Python code",
toolCallId: "call_001",
} as ChatMessage,
{
role: "tool",
content: "// JS code",
toolCallId: "call_002",
} as ChatMessage,
{
role: "tool",
content: "// TS code",
toolCallId: "call_003",
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(3);
const fcIds = functionCalls.map((fc) => fc.id);
expect(fcIds).toContain("fc_001");
expect(fcIds).toContain("fc_002");
expect(fcIds).toContain("fc_003");
const functionOutputs = getFunctionCallOutputs(result);
expect(functionOutputs.length).toBe(3);
});
describe("edge cases", () => {
it("should handle empty messages array", () => {
const result = toResponsesInput([]);
expect(result).toEqual([]);
});
it("should handle assistant message with empty toolCalls array", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "No tools needed",
toolCalls: [],
metadata: { responsesOutputItemId: "fc_empty" },
} as ChatMessage,
];
const result = toResponsesInput(messages);
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(0);
// Should emit as regular message instead
const assistantMessages = getMessagesByRole(result, "assistant");
expect(assistantMessages.length).toBe(1);
});
it("should handle assistant message with undefined metadata", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "Hello",
toolCalls: [
{
id: "call_test",
type: "function",
function: {
name: "test_tool",
arguments: "{}",
},
},
],
// metadata is undefined
} as ChatMessage,
];
const result = toResponsesInput(messages);
// Should not emit function_call without fc_ ID
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(0);
});
it("should handle more toolCalls than responsesOutputItemIds", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_001",
type: "function",
function: { name: "tool1", arguments: "{}" },
},
{
id: "call_002",
type: "function",
function: { name: "tool2", arguments: "{}" },
},
{
id: "call_003",
type: "function",
function: { name: "tool3", arguments: "{}" },
},
],
metadata: {
// Only 2 IDs for 3 tool calls
responsesOutputItemIds: ["fc_001", "fc_002"],
},
} as ChatMessage,
];
const result = toResponsesInput(messages);
// Should only emit 2 function_calls (matching the available IDs)
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(2);
expect(functionCalls[0].id).toBe("fc_001");
expect(functionCalls[1].id).toBe("fc_002");
});
it("should handle toolCall with missing function name", () => {
const messages: ChatMessage[] = [
{
role: "assistant",
content: "",
toolCalls: [
{
id: "call_001",
type: "function",
function: { name: "", arguments: "{}" }, // Empty name
},
],
metadata: { responsesOutputItemIds: ["fc_001"] },
} as ChatMessage,
];
const result = toResponsesInput(messages);
// Should skip tool calls with empty name
const functionCalls = getFunctionCalls(result);
expect(functionCalls.length).toBe(0);
});
it("should handle user message with various content types", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Simple string" },
{
role: "user",
content: [{ type: "text", text: "Array content" }],
} as ChatMessage,
];
const result = toResponsesInput(messages);
const userMessages = getMessagesByRole(result, "user");
expect(userMessages.length).toBe(2);
});
it("should handle system message (converted to developer role)", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "You are a helpful assistant" },
];
const result = toResponsesInput(messages);
const devMessages = getMessagesByRole(result, "developer");
expect(devMessages.length).toBe(1);
});
});
});
});

View file

@ -40,6 +40,7 @@ import {
function appendReasoningFieldsIfSupported(
msg: ChatCompletionAssistantMessageParam & {
reasoning?: string;
reasoning_content?: string;
reasoning_details?: any[];
},
options: CompletionOptions,
@ -47,13 +48,16 @@ function appendReasoningFieldsIfSupported(
providerFlags?: {
includeReasoningField?: boolean;
includeReasoningDetailsField?: boolean;
includeReasoningContentField?: boolean;
},
) {
if (!prevMessage || prevMessage.role !== "thinking") return;
const includeReasoning = !!providerFlags?.includeReasoningField;
const includeReasoningDetails = !!providerFlags?.includeReasoningDetailsField;
if (!includeReasoning && !includeReasoningDetails) return;
const includeReasoningContent = !!providerFlags?.includeReasoningContentField;
if (!includeReasoning && !includeReasoningDetails && !includeReasoningContent)
return;
const reasoningDetailsValue =
prevMessage.reasoning_details ||
@ -84,6 +88,9 @@ function appendReasoningFieldsIfSupported(
if (includeReasoning) {
msg.reasoning = prevMessage.content as string;
}
if (includeReasoningContent) {
msg.reasoning_content = prevMessage.content as string;
}
}
export function toChatMessage(
@ -93,6 +100,7 @@ export function toChatMessage(
providerFlags?: {
includeReasoningField?: boolean;
includeReasoningDetailsField?: boolean;
includeReasoningContentField?: boolean;
},
): ChatCompletionMessageParam | null {
if (message.role === "tool") {
@ -117,6 +125,7 @@ export function toChatMessage(
// Base assistant message
const msg: ChatCompletionAssistantMessageParam & {
reasoning?: string;
reasoning_content?: string;
reasoning_details?: {
[key: string]: any;
signature?: string | undefined;
@ -191,6 +200,7 @@ export function toChatBody(
providerFlags?: {
includeReasoningField?: boolean;
includeReasoningDetailsField?: boolean;
includeReasoningContentField?: boolean;
},
): ChatCompletionCreateParams {
const params: ChatCompletionCreateParams = {
@ -774,6 +784,90 @@ function toResponseInputContentList(
return list;
}
/**
* Emits function_call items for each tool call that has a corresponding fc_ ID.
* Extracted to reduce cyclomatic complexity in toResponsesInput.
*/
function emitFunctionCallsFromToolCalls(
toolCalls: ToolCallDelta[],
respIds: string[],
input: ResponseInput,
): void {
for (let i = 0; i < toolCalls.length; i++) {
const tc = toolCalls[i];
const fcId = respIds[i];
if (!fcId) continue; // Skip if no fc_ ID for this tool call
const name = tc?.function?.name as string | undefined;
const args = tc?.function?.arguments as string | undefined;
const call_id = tc?.id as string | undefined;
if (name && call_id) {
const functionCallItem: ResponseFunctionToolCall = {
id: fcId,
type: "function_call",
name,
arguments: typeof args === "string" ? args : "{}",
call_id,
};
input.push(functionCallItem);
}
}
}
/**
* Converts a thinking message's reasoning_details into a ResponseReasoningItem.
* Extracted to reduce cyclomatic complexity in toResponsesInput.
*/
function convertThinkingMessageToReasoningItem(
msg: ThinkingChatMessage,
): ResponseReasoningItem | undefined {
const details = msg.reasoning_details ?? [];
if (!details.length) return undefined;
let id: string | undefined;
let summaryText = "";
let encrypted: string | undefined;
let reasoningText = "";
for (const raw of details as Array<Record<string, unknown>>) {
const d = raw as {
type?: string;
id?: string;
text?: string;
encrypted_content?: string;
};
if (d.type === "reasoning_id" && d.id) id = d.id;
else if (d.type === "encrypted_content" && d.encrypted_content)
encrypted = d.encrypted_content;
else if (d.type === "summary_text" && typeof d.text === "string")
summaryText += d.text;
else if (d.type === "reasoning_text" && typeof d.text === "string")
reasoningText += d.text;
}
if (!id) return undefined;
const reasoningItem: ResponseReasoningItem = {
id,
type: "reasoning",
summary: [],
} as ResponseReasoningItem;
if (summaryText) {
reasoningItem.summary = [{ type: "summary_text", text: summaryText }];
}
if (reasoningText) {
reasoningItem.content = [{ type: "reasoning_text", text: reasoningText }];
}
if (encrypted) {
reasoningItem.encrypted_content = encrypted;
}
return reasoningItem;
}
export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
const input: ResponseInput = [];
@ -817,21 +911,25 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
| string
| undefined;
const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined;
// Get array of fc_ IDs for parallel tool calls, fallback to single respId
// NOTE: responsesOutputItemIds is accumulated in sessionSlice.ts during streaming.
// We rely on OpenAI streaming events arriving in order, so respIds[i] corresponds
// to toolCalls[i] by position. See: https://platform.openai.com/docs/guides/function-calling
const respIds =
(msg.metadata?.responsesOutputItemIds as string[] | undefined) ||
(respId ? [respId] : []);
if (respId && Array.isArray(toolCalls) && toolCalls.length > 0) {
// Emit full function_call output item
const tc = toolCalls[0];
const name = tc?.function?.name as string | undefined;
const args = tc?.function?.arguments as string | undefined;
const call_id = tc?.id as string | undefined;
const functionCallItem: ResponseFunctionToolCall = {
id: respId,
type: "function_call",
name: name || "",
arguments: typeof args === "string" ? args : "{}",
call_id: call_id || respId,
};
input.push(functionCallItem);
if (
Array.isArray(toolCalls) &&
toolCalls.length > 0 &&
respIds.length > 0
) {
// Emit function_call for EACH tool call (supports parallel tool calls)
emitFunctionCallsFromToolCalls(toolCalls, respIds, input);
// Also emit text content if present alongside tool calls
if (text && text.trim()) {
pushMessage("assistant", text);
}
} else if (respId) {
// Emit full assistant output message item
const outputMessageItem: ResponseOutputMessage = {
@ -869,48 +967,11 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
break;
}
case "thinking": {
const details = (msg as ThinkingChatMessage).reasoning_details ?? [];
if (details.length) {
let id: string | undefined;
let summaryText = "";
let encrypted: string | undefined;
let reasoningText = "";
for (const raw of details as Array<Record<string, unknown>>) {
const d = raw as {
type?: string;
id?: string;
text?: string;
encrypted_content?: string;
};
if (d.type === "reasoning_id" && d.id) id = d.id;
else if (d.type === "encrypted_content" && d.encrypted_content)
encrypted = d.encrypted_content;
else if (d.type === "summary_text" && typeof d.text === "string")
summaryText += d.text;
else if (d.type === "reasoning_text" && typeof d.text === "string")
reasoningText += d.text;
}
if (id) {
const reasoningItem: ResponseReasoningItem = {
id,
type: "reasoning",
summary: [],
} as ResponseReasoningItem;
if (summaryText) {
reasoningItem.summary = [
{ type: "summary_text", text: summaryText },
];
}
if (reasoningText) {
reasoningItem.content = [
{ type: "reasoning_text", text: reasoningText },
];
}
if (encrypted) {
reasoningItem.encrypted_content = encrypted;
}
input.push(reasoningItem as ResponseInputItem);
}
const reasoningItem = convertThinkingMessageToReasoningItem(
msg as ThinkingChatMessage,
);
if (reasoningItem) {
input.push(reasoningItem as ResponseInputItem);
}
break;
}

1350
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -57,7 +57,7 @@
"@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.931.0",
"@aws-sdk/client-sagemaker-runtime": "^3.894.0",
"@aws-sdk/credential-providers": "^3.931.0",
"@aws-sdk/credential-providers": "^3.974.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "file:../packages/fetch",

View file

@ -0,0 +1,69 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { Tool, ToolOverride } from "..";
export interface ApplyToolOverridesResult {
tools: Tool[];
errors: ConfigValidationError[];
}
/**
* Applies tool overrides from config to the list of tools.
* Overrides can modify tool descriptions, display titles, action phrases,
* system message descriptions, or disable tools entirely.
*/
export function applyToolOverrides(
tools: Tool[],
overrides: ToolOverride[] | undefined,
): ApplyToolOverridesResult {
if (!overrides?.length) {
return { tools, errors: [] };
}
const errors: ConfigValidationError[] = [];
const toolsByName = new Map(tools.map((t) => [t.function.name, t]));
for (const override of overrides) {
const tool = toolsByName.get(override.name);
if (!tool) {
errors.push({
fatal: false,
message: `Tool override "${override.name}" does not match any known tool. Available tools: ${Array.from(toolsByName.keys()).join(", ")}`,
});
continue;
}
if (override.disabled) {
toolsByName.delete(override.name);
continue;
}
const updatedTool: Tool = {
...tool,
function: {
...tool.function,
description: override.description ?? tool.function.description,
},
displayTitle: override.displayTitle ?? tool.displayTitle,
wouldLikeTo: override.wouldLikeTo ?? tool.wouldLikeTo,
isCurrently: override.isCurrently ?? tool.isCurrently,
hasAlready: override.hasAlready ?? tool.hasAlready,
};
if (override.systemMessageDescription) {
updatedTool.systemMessageDescription = {
prefix:
override.systemMessageDescription.prefix ??
tool.systemMessageDescription?.prefix ??
"",
exampleArgs:
override.systemMessageDescription.exampleArgs ??
tool.systemMessageDescription?.exampleArgs,
};
}
toolsByName.set(override.name, updatedTool);
}
return { tools: Array.from(toolsByName.values()), errors };
}

View file

@ -0,0 +1,185 @@
import { describe, expect, it } from "vitest";
import { Tool, ToolOverride } from "..";
import { applyToolOverrides } from "./applyToolOverrides";
const mockTool = (name: string, description: string): Tool => ({
type: "function",
displayTitle: name,
readonly: true,
group: "test",
function: { name, description },
});
describe("applyToolOverrides", () => {
it("should return tools unchanged when no overrides provided", () => {
const tools = [mockTool("read_file", "Read a file")];
const result = applyToolOverrides(tools, undefined);
expect(result.tools).toEqual(tools);
expect(result.errors).toHaveLength(0);
});
it("should return tools unchanged when empty overrides array provided", () => {
const tools = [mockTool("read_file", "Read a file")];
const result = applyToolOverrides(tools, []);
expect(result.tools).toEqual(tools);
expect(result.errors).toHaveLength(0);
});
it("should override description when specified", () => {
const tools = [mockTool("read_file", "Original description")];
const overrides: ToolOverride[] = [
{ name: "read_file", description: "New description" },
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].function.description).toBe("New description");
expect(result.errors).toHaveLength(0);
});
it("should override displayTitle when specified", () => {
const tools = [mockTool("read_file", "Read a file")];
const overrides: ToolOverride[] = [
{ name: "read_file", displayTitle: "Custom Read File" },
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].displayTitle).toBe("Custom Read File");
});
it("should override action phrases when specified", () => {
const tools = [mockTool("read_file", "Read a file")];
tools[0].wouldLikeTo = "read {{{ filepath }}}";
tools[0].isCurrently = "reading {{{ filepath }}}";
tools[0].hasAlready = "read {{{ filepath }}}";
const overrides: ToolOverride[] = [
{
name: "read_file",
wouldLikeTo: "open {{{ filepath }}}",
isCurrently: "opening {{{ filepath }}}",
hasAlready: "opened {{{ filepath }}}",
},
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].wouldLikeTo).toBe("open {{{ filepath }}}");
expect(result.tools[0].isCurrently).toBe("opening {{{ filepath }}}");
expect(result.tools[0].hasAlready).toBe("opened {{{ filepath }}}");
});
it("should disable tools when disabled: true", () => {
const tools = [
mockTool("read_file", "Read"),
mockTool("write_file", "Write"),
];
const overrides: ToolOverride[] = [{ name: "read_file", disabled: true }];
const result = applyToolOverrides(tools, overrides);
expect(result.tools).toHaveLength(1);
expect(result.tools[0].function.name).toBe("write_file");
expect(result.errors).toHaveLength(0);
});
it("should warn when override references unknown tool", () => {
const tools = [mockTool("read_file", "Read")];
const overrides: ToolOverride[] = [
{ name: "unknown_tool", description: "test" },
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools).toHaveLength(1);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].message).toContain("unknown_tool");
expect(result.errors[0].fatal).toBe(false);
});
it("should preserve unmodified fields", () => {
const tools = [mockTool("read_file", "Original")];
tools[0].readonly = true;
tools[0].group = "Built-In";
const overrides: ToolOverride[] = [
{ name: "read_file", description: "New description" },
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].readonly).toBe(true);
expect(result.tools[0].group).toBe("Built-In");
expect(result.tools[0].displayTitle).toBe("read_file");
});
it("should override systemMessageDescription", () => {
const tools = [mockTool("read_file", "Read")];
tools[0].systemMessageDescription = {
prefix: "old prefix",
exampleArgs: [["filepath", "/old/path"]],
};
const overrides: ToolOverride[] = [
{
name: "read_file",
systemMessageDescription: {
prefix: "new prefix",
exampleArgs: [["filepath", "/new/path"]],
},
},
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].systemMessageDescription?.prefix).toBe("new prefix");
expect(result.tools[0].systemMessageDescription?.exampleArgs).toEqual([
["filepath", "/new/path"],
]);
});
it("should partially override systemMessageDescription", () => {
const tools = [mockTool("read_file", "Read")];
tools[0].systemMessageDescription = {
prefix: "old prefix",
exampleArgs: [["filepath", "/old/path"]],
};
const overrides: ToolOverride[] = [
{
name: "read_file",
systemMessageDescription: {
prefix: "new prefix",
// exampleArgs not specified - should preserve original
},
},
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools[0].systemMessageDescription?.prefix).toBe("new prefix");
expect(result.tools[0].systemMessageDescription?.exampleArgs).toEqual([
["filepath", "/old/path"],
]);
});
it("should apply multiple overrides", () => {
const tools = [
mockTool("read_file", "Read"),
mockTool("write_file", "Write"),
mockTool("delete_file", "Delete"),
];
const overrides: ToolOverride[] = [
{ name: "read_file", description: "Custom read" },
{ name: "write_file", disabled: true },
{ name: "delete_file", displayTitle: "Remove File" },
];
const result = applyToolOverrides(tools, overrides);
expect(result.tools).toHaveLength(2);
expect(result.tools[0].function.description).toBe("Custom read");
expect(result.tools[1].displayTitle).toBe("Remove File");
expect(result.errors).toHaveLength(0);
});
it("should not mutate original tools array", () => {
const tools = [mockTool("read_file", "Original")];
const originalDescription = tools[0].function.description;
const overrides: ToolOverride[] = [
{ name: "read_file", description: "New description" },
];
const result = applyToolOverrides(tools, overrides);
// Original should be unchanged
expect(tools[0].function.description).toBe(originalDescription);
// Result should have new description
expect(result.tools[0].function.description).toBe("New description");
});
});

View file

@ -141,10 +141,14 @@ export class HistoryManager {
}
let found = false;
const messageCount = session.history.filter(
(item) => item.message.role === "assistant",
).length;
for (const sessionMetadata of sessionsList) {
if (sessionMetadata.sessionId === session.sessionId) {
sessionMetadata.title = session.title;
sessionMetadata.workspaceDirectory = session.workspaceDirectory;
sessionMetadata.messageCount = messageCount;
found = true;
break;
}
@ -156,6 +160,7 @@ export class HistoryManager {
title: session.title,
dateCreated: String(Date.now()),
workspaceDirectory: session.workspaceDirectory,
messageCount,
};
sessionsList.push(sessionMetadata);
}

View file

@ -0,0 +1,95 @@
---
title: Nous Research
slug: ../nous
---
<Tip>
**Discover Nous Research Hermes models for advanced reasoning and instruction following**
</Tip>
<Info>
You can get an API key from the [Nous Research Portal](https://portal.nousresearch.com/).
</Info>
## Available Models
| Model | Context Length | Description |
|-------|----------------|-------------|
| `Hermes-4.3-36B` | 128k | Compact reasoning model with thinking capabilities |
| `Hermes-4-70B` | 128k | Large reasoning model with 128k context |
| `Hermes-4-405B` | 128k | Flagship reasoning model |
| `Hermes-3-Llama-3.1-70B` | 32k | Instruction-tuned on Llama 3.1 70B |
| `Hermes-3-Llama-3.1-405B` | 32k | Instruction-tuned on Llama 3.1 405B |
## Configuration
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
name: My Config
version: 0.0.1
schema: v1
models:
- name: Hermes 4.3 36B
provider: nous
model: Hermes-4.3-36B
apiKey: <YOUR_NOUS_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Hermes 4.3 36B",
"provider": "nous",
"model": "Hermes-4.3-36B",
"apiKey": "<YOUR_NOUS_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
## Reasoning Mode
Hermes 4 and DeepHermes models support reasoning with chain-of-thought. To enable reasoning, use the following system prompt:
```
You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside <think> </think> tags, and then provide your solution or response to the problem.
```
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
name: My Config
version: 0.0.1
schema: v1
models:
- name: Hermes 4.3 36B (Reasoning)
provider: nous
model: Hermes-4.3-36B
apiKey: <YOUR_NOUS_API_KEY>
systemMessage: |
You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside <think> </think> tags, and then provide your solution or response to the problem.
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Hermes 4.3 36B (Reasoning)",
"provider": "nous",
"model": "Hermes-4.3-36B",
"apiKey": "<YOUR_NOUS_API_KEY>",
"systemMessage": "You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside <think> </think> tags, and then provide your solution or response to the problem."
}
]
}
```
</Tab>
</Tabs>

View file

@ -198,6 +198,7 @@
"customize/model-providers/more/llamastack",
"customize/model-providers/more/mimo",
"customize/model-providers/more/mistral",
"customize/model-providers/more/nous",
"customize/model-providers/more/nvidia",
"customize/model-providers/more/together",
"customize/model-providers/more/xAI"

View file

@ -3,6 +3,8 @@ title: "What is Continue?"
description: "Run agents as CI checks on every PR"
---
<video autoPlay muted loop playsInline className="rounded-xl" src="https://continue.dev/videos/demo.mp4" />
Continue lets you create agents that review every pull request. Each agent runs as a GitHub check: green if the code looks good, red with a suggested diff if not.
Agents are markdown prompts describing the standards you want to enforce. They can be defined at [continue.dev](https://continue.dev/agents) or in your repo at `.continue/agents/`.

View file

@ -1,5 +1,5 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
import tsParser from "@typescript-eslint/parser";
import importPlugin from "eslint-plugin-import";
import unusedImports from "eslint-plugin-unused-imports";
@ -40,7 +40,7 @@ export default [
"error",
{ max: 500, skipBlankLines: true, skipComments: true },
],
complexity: ["error", { max: 20 }],
complexity: ["error", { max: 30 }],
// "max-lines-per-function": [
// "error",
// { max: 150, skipBlankLines: true, skipComments: true },

View file

@ -2,7 +2,7 @@ import { type AssistantConfig } from "@continuedev/sdk";
// Export command functions
export { chat } from "./chat.js";
export { check } from "./check.js";
export { review } from "./review.js";
export { login } from "./login.js";
export { logout } from "./logout.js";
export { listSessionsCommand } from "./ls.js";

View file

@ -7,38 +7,38 @@ import { configureConsoleForHeadless } from "../init.js";
import { logger } from "../util/logger.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import type { CheckState } from "./check/CheckProgress.js";
import { CheckProgress } from "./check/CheckProgress.js";
import type { WorkerConfig, WorkerResult } from "./check/checkWorker.js";
import type { DiffContext } from "./check/diffContext.js";
import { computeDiffContext } from "./check/diffContext.js";
import type { CheckResult } from "./check/renderReport.js";
import { renderReport } from "./check/renderReport.js";
import { resolveChecks } from "./check/resolveChecks.js";
import { createWorktree, cleanupWorktree } from "./check/worktree.js";
import type { DiffContext } from "./review/diffContext.js";
import { computeDiffContext } from "./review/diffContext.js";
import type { ReviewResult } from "./review/renderReport.js";
import { renderReport } from "./review/renderReport.js";
import { resolveReviews } from "./review/resolveReviews.js";
import { ReviewProgress } from "./review/ReviewProgress.js";
import type { ReviewState } from "./review/ReviewProgress.js";
import type { WorkerConfig, WorkerResult } from "./review/reviewWorker.js";
import { createWorktree, cleanupWorktree } from "./review/worktree.js";
export interface CheckOptions extends ExtendedCommandOptions {
export interface ReviewOptions extends ExtendedCommandOptions {
base?: string;
format?: string;
fix?: boolean;
patch?: boolean;
failFast?: boolean;
checkAgents?: string[];
reviewAgents?: string[];
}
/**
* Run a single check in a forked worker process.
* Run a single review in a forked worker process.
*/
async function runCheckInWorker(
async function runReviewInWorker(
agentSource: string,
worktreePath: string,
diffContext: DiffContext,
options: CheckOptions,
options: ReviewOptions,
): Promise<WorkerResult> {
return new Promise<WorkerResult>((resolve, _reject) => {
// Fork the current CLI entry point with the internal worker flag
const workerPath = process.argv[1];
const child = fork(workerPath, ["--internal-check-worker"], {
const child = fork(workerPath, ["--internal-review-worker"], {
stdio: ["pipe", "pipe", "pipe", "ipc"],
env: {
...process.env,
@ -58,7 +58,7 @@ async function runCheckInWorker(
patch: "",
agentOutput: "",
duration: 0,
error: "Check timed out after 5 minutes",
error: "Review timed out after 5 minutes",
});
}
},
@ -79,7 +79,7 @@ async function runCheckInWorker(
verbose: options.verbose,
},
};
child.send({ type: "run-check", config });
child.send({ type: "run-review", config });
} else if (msg.type === "result" && msg.result) {
if (!settled) {
settled = true;
@ -135,7 +135,7 @@ async function runCheckInWorker(
/**
* Apply patches to the real working tree (--fix mode).
*/
function applyPatches(results: CheckResult[]): void {
function applyPatches(results: ReviewResult[]): void {
const patchResults = results.filter(
(r) => r.status === "fail" && r.patch.trim(),
);
@ -179,35 +179,37 @@ function applyPatches(results: CheckResult[]): void {
}
/**
* Mount the Ink live progress UI or fall back to static logs.
* Mutable props bag for the live Ink UI so we can update it progressively.
*/
interface LiveUIProps {
checks: ReviewState[];
baseBranch?: string;
changedFileCount?: number;
loading?: boolean;
}
/**
* Mount the Ink live progress UI or return a no-op for non-TTY / special modes.
*/
async function mountProgressUI(
checkStates: CheckState[],
diffContext: DiffContext,
options: CheckOptions,
): Promise<{ rerender?: () => void; unmount?: () => void }> {
props: LiveUIProps,
options: ReviewOptions,
): Promise<{ rerender: () => void; unmount: () => void }> {
const useLiveUI =
process.stdout.isTTY && !options.patch && options.format !== "json";
if (!useLiveUI) {
console.log(
chalk.dim(
`Running ${checkStates.length} check${checkStates.length > 1 ? "s" : ""}: ${checkStates.map((c) => c.name).join(", ")}`,
),
);
return {};
return {
rerender: () => {},
unmount: () => {},
};
}
const { render } = await import("ink");
const props = {
checks: checkStates,
baseBranch: diffContext.baseBranch,
changedFileCount: diffContext.changedFiles.length,
};
const instance = render(React.createElement(CheckProgress, props));
const instance = render(React.createElement(ReviewProgress, props));
return {
rerender: () =>
instance.rerender(React.createElement(CheckProgress, props)),
instance.rerender(React.createElement(ReviewProgress, props)),
unmount: () => instance.unmount(),
};
}
@ -216,9 +218,9 @@ async function mountProgressUI(
* Output results and exit with appropriate code.
*/
function outputResultsAndExit(
results: CheckResult[],
results: ReviewResult[],
diffContext: DiffContext,
options: CheckOptions,
options: ReviewOptions,
checksFromHub: boolean,
): void {
const format = options.format === "json" ? "json" : "text";
@ -254,20 +256,30 @@ function outputResultsAndExit(
}
/**
* Main check command handler.
* Main review command handler.
*/
export async function check(options: CheckOptions = {}): Promise<void> {
export async function review(options: ReviewOptions = {}): Promise<void> {
configureConsoleForHeadless(false);
if (options.verbose) {
logger.setLevel("debug");
}
// Step 1: Check for changes
console.log(chalk.dim("Computing diff..."));
// Mount the live UI immediately with a loading state
const uiProps: LiveUIProps = {
checks: [],
loading: true,
};
const { rerender, unmount: unmountUI } = await mountProgressUI(
uiProps,
options,
);
// Step 1: Compute diff
const diffContext = computeDiffContext(options.base);
if (!diffContext.diff.trim() && diffContext.changedFiles.length === 0) {
unmountUI();
console.log(
chalk.yellow(
"No changes detected. Make some changes or specify a different base branch with --base.",
@ -276,64 +288,60 @@ export async function check(options: CheckOptions = {}): Promise<void> {
process.exit(0);
}
console.log(
chalk.dim(
`Found ${diffContext.changedFiles.length} changed files against ${diffContext.baseBranch}`,
),
);
// Update UI with diff info (still loading reviews)
uiProps.baseBranch = diffContext.baseBranch;
uiProps.changedFileCount = diffContext.changedFiles.length;
rerender();
// Step 2: Resolve checks
console.log(chalk.dim("Resolving checks..."));
const checks = await resolveChecks(options.checkAgents);
// Step 2: Resolve reviews
const reviews = await resolveReviews(options.reviewAgents);
if (checks.length === 0) {
if (reviews.length === 0) {
unmountUI();
console.log(
chalk.yellow("\nNo checks found. To add checks:\n") +
chalk.yellow("\nNo reviews found. To add reviews:\n") +
chalk.dim(
" 1. Create .continue/agents/my-check.md with agent instructions\n",
" 1. Create .continue/agents/my-review.md with agent instructions\n",
) +
chalk.dim(
" 2. Or specify an agent: cn check --agent org/agent-name\n",
" 2. Or specify an agent: cn review --review-agents org/agent-name\n",
) +
chalk.dim(" 3. Or configure checks on https://continue.dev\n"),
chalk.dim(" 3. Or configure reviews on https://continue.dev\n"),
);
process.exit(0);
}
const checksFromHub = checks.some((c) => c.sourceType === "hub");
const checksFromHub = reviews.some((c) => c.sourceType === "hub");
// Build mutable state for the live UI
const checkStates: CheckState[] = checks.map((c) => ({
// Build mutable state for the live UI and stop loading
const reviewStates: ReviewState[] = reviews.map((c) => ({
name: c.name,
status: "pending" as const,
}));
uiProps.checks = reviewStates;
uiProps.loading = false;
rerender();
const { rerender, unmount: unmountUI } = await mountProgressUI(
checkStates,
diffContext,
options,
);
// Step 3: Create worktrees and run reviews
const results: ReviewResult[] = [];
// Step 3: Create worktrees and run checks
const results: CheckResult[] = [];
const runSingleCheck = async (
resolvedCheck: (typeof checks)[number],
const runSingleReview = async (
resolvedReview: (typeof reviews)[number],
i: number,
): Promise<CheckResult> => {
): Promise<ReviewResult> => {
const startTime = Date.now();
let worktreePath: string | null = null;
try {
// Mark as running
checkStates[i].status = "running";
checkStates[i].startTime = Date.now();
rerender?.();
reviewStates[i].status = "running";
reviewStates[i].startTime = Date.now();
rerender();
worktreePath = await createWorktree(i);
const workerResult = await runCheckInWorker(
resolvedCheck.source,
const workerResult = await runReviewInWorker(
resolvedReview.source,
worktreePath,
diffContext,
options,
@ -345,31 +353,33 @@ export async function check(options: CheckOptions = {}): Promise<void> {
? ("fail" as const)
: ("pass" as const);
const duration = (Date.now() - startTime) / 1000;
// Mark as complete
checkStates[i].status = status;
checkStates[i].duration = workerResult.duration;
rerender?.();
reviewStates[i].status = status;
reviewStates[i].duration = duration;
rerender();
return {
agent: resolvedCheck.source,
name: resolvedCheck.name,
agent: resolvedReview.source,
name: resolvedReview.name,
status,
patch: workerResult.patch,
output: workerResult.agentOutput,
duration: workerResult.duration,
duration,
error: workerResult.error,
};
} catch (e: any) {
const duration = (Date.now() - startTime) / 1000;
// Mark as error
checkStates[i].status = "error";
checkStates[i].duration = duration;
rerender?.();
reviewStates[i].status = "error";
reviewStates[i].duration = duration;
rerender();
return {
agent: resolvedCheck.source,
name: resolvedCheck.name,
agent: resolvedReview.source,
name: resolvedReview.name,
status: "error" as const,
patch: "",
output: "",
@ -384,8 +394,8 @@ export async function check(options: CheckOptions = {}): Promise<void> {
};
if (options.failFast) {
for (let i = 0; i < checks.length; i++) {
const result = await runSingleCheck(checks[i], i);
for (let i = 0; i < reviews.length; i++) {
const result = await runSingleReview(reviews[i], i);
results.push(result);
if (result.status === "fail" || result.status === "error") {
break;
@ -393,7 +403,7 @@ export async function check(options: CheckOptions = {}): Promise<void> {
}
} else {
const settled = await Promise.allSettled(
checks.map((resolvedCheck, i) => runSingleCheck(resolvedCheck, i)),
reviews.map((resolvedReview, i) => runSingleReview(resolvedReview, i)),
);
for (const result of settled) {
if (result.status === "fulfilled") {
@ -402,6 +412,6 @@ export async function check(options: CheckOptions = {}): Promise<void> {
}
}
unmountUI?.();
unmountUI();
outputResultsAndExit(results, diffContext, options, checksFromHub);
}

View file

@ -3,20 +3,21 @@ import React, { useEffect, useState } from "react";
import { LoadingAnimation } from "../../ui/LoadingAnimation.js";
export interface CheckState {
export interface ReviewState {
name: string;
status: "pending" | "running" | "pass" | "fail" | "error";
startTime?: number;
duration?: number;
}
interface CheckProgressProps {
checks: CheckState[];
baseBranch: string;
changedFileCount: number;
interface ReviewProgressProps {
checks: ReviewState[];
baseBranch?: string;
changedFileCount?: number;
loading?: boolean;
}
function StatusIndicator({ status }: { status: CheckState["status"] }) {
function StatusIndicator({ status }: { status: ReviewState["status"] }) {
switch (status) {
case "pending":
return <Text dimColor>{"◌ Pending"}</Text>;
@ -36,7 +37,7 @@ function StatusIndicator({ status }: { status: CheckState["status"] }) {
}
}
function ElapsedTime({ check }: { check: CheckState }) {
function ElapsedTime({ check }: { check: ReviewState }) {
const [, setTick] = useState(0);
useEffect(() => {
@ -62,31 +63,37 @@ function ElapsedTime({ check }: { check: CheckState }) {
const COL_NAME = 22;
const COL_STATUS = 16;
export const CheckProgress: React.FC<CheckProgressProps> = ({
export const ReviewProgress: React.FC<ReviewProgressProps> = ({
checks,
baseBranch,
changedFileCount,
loading,
}) => {
return (
<Box flexDirection="column" paddingTop={1} paddingBottom={1}>
<Box gap={1}>
<Text bold>cn check</Text>
<Text dimColor>─</Text>
<Text>
{checks.length} check{checks.length === 1 ? "" : "s"} against{" "}
{baseBranch}
</Text>
<Text dimColor>─</Text>
<Text>
{changedFileCount} changed file{changedFileCount === 1 ? "" : "s"}
</Text>
<Text bold>cn review</Text>
{baseBranch ? (
<>
<Text dimColor>─</Text>
<Text>
{checks.length} review{checks.length === 1 ? "" : "s"} against{" "}
{baseBranch}
</Text>
<Text dimColor>─</Text>
<Text>
{changedFileCount} changed file
{changedFileCount === 1 ? "" : "s"}
</Text>
</>
) : null}
</Box>
<Box flexDirection="column" marginTop={1}>
<Box>
<Box width={COL_NAME}>
<Text bold dimColor>
Check
Review
</Text>
</Box>
<Box width={COL_STATUS}>
@ -101,17 +108,24 @@ export const CheckProgress: React.FC<CheckProgressProps> = ({
<Text dimColor>{"─".repeat(COL_NAME + COL_STATUS + 6)}</Text>
{checks.map((check, i) => (
<Box key={i}>
<Box width={COL_NAME}>
<Text>{check.name}</Text>
</Box>
<Box width={COL_STATUS}>
<StatusIndicator status={check.status} />
</Box>
<ElapsedTime check={check} />
{loading && checks.length === 0 ? (
<Box>
<LoadingAnimation color="cyan" />
<Text dimColor>{" Loading reviews…"}</Text>
</Box>
))}
) : (
checks.map((check, i) => (
<Box key={i}>
<Box width={COL_NAME}>
<Text>{check.name}</Text>
</Box>
<Box width={COL_STATUS}>
<StatusIndicator status={check.status} />
</Box>
<ElapsedTime check={check} />
</Box>
))
)}
</Box>
</Box>
);

View file

@ -1,6 +1,6 @@
import chalk from "chalk";
export interface CheckResult {
export interface ReviewResult {
/** Agent slug or local path */
agent: string;
/** Display name */
@ -25,10 +25,10 @@ export interface RenderOptions {
}
/**
* Render the check results report.
* Render the review results report.
*/
export function renderReport(
results: CheckResult[],
results: ReviewResult[],
options: RenderOptions,
): string {
if (options.format === "json") {
@ -38,7 +38,7 @@ export function renderReport(
}
function renderJsonReport(
results: CheckResult[],
results: ReviewResult[],
_options: RenderOptions,
): string {
const passed = results.filter((r) => r.status === "pass").length;
@ -47,7 +47,7 @@ function renderJsonReport(
return JSON.stringify(
{
checks: results.map((r) => ({
reviews: results.map((r) => ({
agent: r.agent,
name: r.name,
status: r.status,
@ -69,29 +69,21 @@ function renderJsonReport(
}
function renderTextReport(
results: CheckResult[],
results: ReviewResult[],
options: RenderOptions,
): string {
const isTTY = process.stdout.isTTY;
const lines: string[] = [];
lines.push(isTTY ? chalk.bold("# Check Results") : "# Check Results");
lines.push("");
lines.push(
`Checked against \`${options.baseBranch}...HEAD\` (${options.changedFileCount} files changed)`,
const failedResults = results.filter(
(r) => r.status === "fail" || r.status === "error",
);
lines.push("");
for (const result of results) {
// Only output details for failures/errors — passes are already in the table
for (const result of failedResults) {
const durationStr = `(${result.duration.toFixed(1)}s)`;
if (result.status === "pass") {
const header = isTTY
? chalk.green(`## ✓ ${result.name}`) + " " + chalk.dim(durationStr)
: `## ✓ ${result.name} ${durationStr}`;
lines.push(header);
lines.push("No issues found.");
} else if (result.status === "error") {
if (result.status === "error") {
const header = isTTY
? chalk.red(`## ✗ ${result.name}`) + " " + chalk.dim(durationStr)
: `## ✗ ${result.name} ${durationStr}`;
@ -120,28 +112,19 @@ function renderTextReport(
lines.push("");
}
// Summary
lines.push("---");
const failed = results.filter(
(r) => r.status === "fail" || r.status === "error",
).length;
const total = results.length;
if (failed === 0) {
const summary = `**All ${total} checks passed.**`;
lines.push(isTTY ? chalk.green(summary) : summary);
} else {
const summary = `**${failed} of ${total} checks failed.**`;
if (failedResults.length > 0) {
lines.push("---");
const summary = `**${failedResults.length} of ${results.length} reviews failed.**`;
lines.push(isTTY ? chalk.red(summary) : summary);
lines.push("");
}
// Migration nudge
lines.push("");
if (options.checksFromHub) {
lines.push(
isTTY
? chalk.dim("These checks also run on your PRs via Continue CI.")
: "These checks also run on your PRs via Continue CI.",
? chalk.dim("These reviews also run on your PRs via Continue CI.")
: "These reviews also run on your PRs via Continue CI.",
);
} else {
lines.push(

View file

@ -6,8 +6,8 @@ import { loadAuthConfig, getAccessToken } from "../../auth/workos.js";
import { env } from "../../env.js";
import { logger } from "../../util/logger.js";
export interface ResolvedCheck {
/** Display name for the check */
export interface ResolvedReview {
/** Display name for the review */
name: string;
/** Hub slug (org/agent) or local file path */
source: string;
@ -16,14 +16,14 @@ export interface ResolvedCheck {
}
/**
* Determine which checks to run, using three sources in order:
* Determine which reviews to run, using three sources in order:
* 1. CLI --agent flags (highest priority)
* 2. Hub API (if logged in and no --agent flags)
* 3. Local .continue/agents/*.md (fallback)
*/
export async function resolveChecks(
export async function resolveReviews(
agentFlags?: string[],
): Promise<ResolvedCheck[]> {
): Promise<ResolvedReview[]> {
// Source 1: CLI --agent flags
if (agentFlags && agentFlags.length > 0) {
return agentFlags.map((agent) => ({
@ -34,24 +34,24 @@ export async function resolveChecks(
}
// Source 2: Hub API (silent failure if not logged in)
const hubChecks = await resolveFromHub();
if (hubChecks.length > 0) {
return hubChecks;
const hubReviews = await resolveFromHub();
if (hubReviews.length > 0) {
return hubReviews;
}
// Source 3: Local .continue/agents/*.md
const localChecks = resolveFromLocal();
if (localChecks.length > 0) {
return localChecks;
const localReviews = resolveFromLocal();
if (localReviews.length > 0) {
return localReviews;
}
return [];
}
/**
* Try to resolve checks from the hub API based on the current repo.
* Try to resolve reviews from the hub API based on the current repo.
*/
async function resolveFromHub(): Promise<ResolvedCheck[]> {
async function resolveFromHub(): Promise<ResolvedReview[]> {
try {
const authConfig = loadAuthConfig();
if (!authConfig) {
@ -88,7 +88,7 @@ async function resolveFromHub(): Promise<ResolvedCheck[]> {
});
if (!response.ok) {
logger.debug(`Hub check resolution returned ${response.status}`);
logger.debug(`Hub review resolution returned ${response.status}`);
return [];
}
@ -101,15 +101,15 @@ async function resolveFromHub(): Promise<ResolvedCheck[]> {
sourceType: "hub" as const,
}));
} catch (e) {
logger.debug("Hub check resolution failed", { error: e });
logger.debug("Hub review resolution failed", { error: e });
return [];
}
}
/**
* Resolve checks from local .continue/agents/*.md files.
* Resolve reviews from local .continue/agents/*.md files.
*/
function resolveFromLocal(): ResolvedCheck[] {
function resolveFromLocal(): ResolvedReview[] {
const agentsDir = path.join(process.cwd(), ".continue", "agents");
if (!fs.existsSync(agentsDir)) {
return [];

View file

@ -1,5 +1,5 @@
/**
* Check worker - runs in a forked process.
* Review worker - runs in a forked process.
*
* Receives configuration via IPC, initializes services,
* runs the agent in the worktree, then captures the diff
@ -44,12 +44,18 @@ export interface WorkerResult {
}
/**
* Build the check prompt that gets prepended to the agent's own instructions.
* Build the review prompt that gets prepended to the agent's own instructions.
*/
function buildCheckPrompt(diffContext: DiffContext): string {
function buildReviewPrompt(diffContext: DiffContext): string {
const fileList = diffContext.changedFiles.map((f) => `- ${f}`).join("\n");
let prompt = `You are running as a local code check. Review and fix the following changes.
let prompt = `You are a code review agent. Your job is to review ONLY the changed lines in the diff below and check them against your review rules.
## Scope — READ THIS CAREFULLY
- You MUST only review the files and lines shown in the diff.
- Do NOT read, scan, or report on files outside the diff.
- Do NOT report pre-existing issues in unchanged code — even in files that appear in the diff, only the changed lines are in scope.
- If you need surrounding context to understand a change, you may read that file, but you must NOT flag issues in the unchanged parts.
## Changes (base: ${diffContext.baseBranch})
### Changed files
@ -62,15 +68,16 @@ ${diffContext.diff || "(no diff available)"}
`;
if (diffContext.truncated) {
prompt += `\nNote: The diff was truncated due to size. Use Read and Search tools to inspect the full files.\n`;
prompt += `\nNote: The diff was truncated due to size. You may use Read tool to view the full content of the changed files listed above — but do NOT explore beyond them.\n`;
}
prompt += `
## Context
## Rules
- You are in a temporary worktree. Dependencies (node_modules, etc.) are not installed.
- Focus on source code analysis and edits.
- Make any edits you think are needed to fix issues. Your changes will be captured as suggestions.
- If there are no issues, simply say so and exit.
- ONLY flag issues that exist in the changed lines of the diff.
- ONLY make edits to files listed in the changed files above, and only to fix violations of your specific review rules in the changed code.
- Do NOT make general improvements, refactoring, documentation changes, or style fixes.
- If there are no violations in the changed code, do NOT edit any files. State that no issues were found and exit.
`;
return prompt;
@ -91,16 +98,16 @@ function loadLocalAgentInstructions(filePath: string): string {
* Entry point for the forked worker process.
* Listens for IPC messages from the orchestrator.
*/
export async function runCheckWorker(): Promise<void> {
export async function runReviewWorker(): Promise<void> {
if (typeof process.send !== "function") {
console.error(
"Error: check worker must be run as a forked process (via cn check).",
"Error: review worker must be run as a forked process (via cn review).",
);
process.exit(1);
}
process.on("message", async (msg: { type: string; config: WorkerConfig }) => {
if (msg.type !== "run-check") return;
if (msg.type !== "run-review") return;
const { config } = msg;
const startTime = Date.now();
@ -131,8 +138,8 @@ export async function runCheckWorker(): Promise<void> {
throw new Error("Failed to initialize model service");
}
// Build the check prompt
const checkPrompt = buildCheckPrompt(config.diffContext);
// Build the review prompt
const reviewPrompt = buildReviewPrompt(config.diffContext);
// Load agent-specific instructions if it's a local file
let agentInstructions = "";
@ -151,7 +158,7 @@ export async function runCheckWorker(): Promise<void> {
if (agentInstructions) {
promptParts.push(`## Agent Instructions\n\n${agentInstructions}`);
}
promptParts.push(checkPrompt);
promptParts.push(reviewPrompt);
const userMessage = promptParts.join("\n\n");
chatHistorySvc.addUserMessage(userMessage);

View file

@ -1,31 +1,32 @@
import { execSync } from "child_process";
import { exec, execSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { promisify } from "util";
import { logger } from "../../util/logger.js";
const execAsync = promisify(exec);
/**
* Create a git worktree that mirrors the user's current working tree state.
* The worktree gets committed + staged + unstaged + untracked changes.
*/
export async function createWorktree(index: number): Promise<string> {
const tmpDir = os.tmpdir();
const worktreePath = path.join(tmpDir, `cn-check-${Date.now()}-${index}`);
const worktreePath = path.join(tmpDir, `cn-review-${Date.now()}-${index}`);
// Create the worktree at HEAD (detached)
execSync(`git worktree add "${worktreePath}" HEAD --detach`, {
stdio: ["pipe", "pipe", "pipe"],
});
await execAsync(`git worktree add "${worktreePath}" HEAD --detach`);
// Apply uncommitted changes (staged + unstaged) to the worktree
try {
const diff = execSync("git diff HEAD", {
encoding: "utf-8",
const { stdout: diff } = await execAsync("git diff HEAD", {
maxBuffer: 10 * 1024 * 1024,
stdio: ["pipe", "pipe", "pipe"],
});
if (diff.trim()) {
// execAsync (promisified exec) doesn't support `input`, use execSync for apply.
// This is fine: the apply targets the isolated worktree, so it won't contend.
execSync(`git -C "${worktreePath}" apply --allow-empty -`, {
input: diff,
stdio: ["pipe", "pipe", "pipe"],
@ -39,16 +40,12 @@ export async function createWorktree(index: number): Promise<string> {
// Copy untracked files to the worktree
try {
const untrackedOutput = execSync(
const { stdout: untrackedOutput } = await execAsync(
"git ls-files --others --exclude-standard",
{
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
},
).trim();
);
if (untrackedOutput) {
const untrackedFiles = untrackedOutput.split("\n");
if (untrackedOutput.trim()) {
const untrackedFiles = untrackedOutput.trim().split("\n");
const cwd = process.cwd();
for (const file of untrackedFiles) {
const srcPath = path.join(cwd, file);
@ -68,6 +65,12 @@ export async function createWorktree(index: number): Promise<string> {
logger.debug("Could not copy untracked files to worktree", { error: e });
}
// Commit the initial state so captureWorktreeDiff only captures agent changes
await execAsync(`git -C "${worktreePath}" add -A`);
await execAsync(
`git -C "${worktreePath}" commit -m "cn-review: user working tree state (staged + unstaged + untracked)" --allow-empty --no-verify`,
);
return worktreePath;
}
@ -96,9 +99,7 @@ export function captureWorktreeDiff(worktreePath: string): string {
*/
export async function cleanupWorktree(worktreePath: string): Promise<void> {
try {
execSync(`git worktree remove "${worktreePath}" --force`, {
stdio: ["pipe", "pipe", "pipe"],
});
await execAsync(`git worktree remove "${worktreePath}" --force`);
} catch (e) {
logger.debug("Could not remove worktree, attempting manual cleanup", {
worktreePath,
@ -107,10 +108,7 @@ export async function cleanupWorktree(worktreePath: string): Promise<void> {
// Manual cleanup as fallback
try {
fs.rmSync(worktreePath, { recursive: true, force: true });
// Prune the worktree entry
execSync("git worktree prune", {
stdio: ["pipe", "pipe", "pipe"],
});
await execAsync("git worktree prune");
} catch {
// Best effort
}

View file

@ -377,7 +377,9 @@ async function loadDefaultConfig(
});
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
throw new Error(
`Failed to load default agent. Body:\n${JSON.stringify(resp)}`,
);
}
let apiConfig = resp.configResult.config as AssistantUnrolled;
if (injectBlocks.length > 0) {

View file

@ -6,12 +6,12 @@ import "./init.js";
import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { check } from "./commands/check.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { listSessionsCommand } from "./commands/ls.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { review } from "./commands/review.js";
import { serve } from "./commands/serve.js";
import {
handleValidationErrors,
@ -420,20 +420,20 @@ program
await remoteTest(prompt, options.url);
});
// Check subcommand
// Review subcommand
program
.command("check")
.description("Run AI-powered checks on your changes")
.command("review")
.description("Run AI-powered reviews on your changes")
.option("--base <ref>", "Base git ref to diff against (default: auto-detect)")
.option("--format <format>", "Output format")
.option("--fix", "Automatically apply suggested fixes")
.option("--patch", "Show patches")
.option("--fail-fast", "Stop on first failure")
.option("--check-agents <agents...>", "Specific check agents to run")
.option("--review-agents <agents...>", "Specific review agents to run")
.option("--verbose", "Enable verbose logging")
.action(async (options) => {
await posthogService.capture("cliCommand", { command: "check" });
await check(options);
await posthogService.capture("cliCommand", { command: "review" });
await review(options);
});
// Handle unknown commands
@ -444,10 +444,12 @@ program.on("command:*", () => {
});
export async function runCli(): Promise<void> {
// Handle internal worker subprocess for cn check
if (process.argv.includes("--internal-check-worker")) {
const { runCheckWorker } = await import("./commands/check/checkWorker.js");
await runCheckWorker();
// Handle internal worker subprocess for cn review
if (process.argv.includes("--internal-review-worker")) {
const { runReviewWorker } = await import(
"./commands/review/reviewWorker.js"
);
await runReviewWorker();
return;
}

View file

@ -29,6 +29,12 @@ vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
StreamableHTTPClientTransport: vi.fn(),
}));
vi.mock("https", () => ({
Agent: vi.fn().mockImplementation(() => ({
rejectUnauthorized: false,
})),
}));
describe("MCPService", () => {
let mcpService: MCPService;
let mockAssistant: AssistantConfig;
@ -211,5 +217,206 @@ describe("MCPService", () => {
mcpService.initialize(defaultAssistant),
).resolves.not.toThrow();
});
it("should create HttpsAgent when verifySsl is false for SSE transport", async () => {
const { SSEClientTransport } = await import(
"@modelcontextprotocol/sdk/client/sse.js"
);
const { Agent: HttpsAgent } = await import("https");
const sseAssistant: AssistantConfig = {
name: "sse-assistant",
version: "1.0.0",
mcpServers: [
{
name: "sse-server",
type: "sse",
url: "https://example.com/sse",
requestOptions: {
verifySsl: false,
},
},
],
} as AssistantConfig;
await mcpService.initialize(sseAssistant);
expect(SSEClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
eventSourceInit: expect.objectContaining({
fetch: expect.any(Function),
}),
requestInit: expect.objectContaining({
agent: expect.any(Object),
}),
}),
);
expect(HttpsAgent).toHaveBeenCalledWith({
rejectUnauthorized: false,
});
});
it("should not create HttpsAgent when verifySsl is true for SSE transport", async () => {
const { SSEClientTransport } = await import(
"@modelcontextprotocol/sdk/client/sse.js"
);
const { Agent: HttpsAgent } = await import("https");
const sseAssistant: AssistantConfig = {
name: "sse-assistant",
version: "1.0.0",
mcpServers: [
{
name: "sse-server",
type: "sse",
url: "https://example.com/sse",
requestOptions: {
verifySsl: true,
},
},
],
} as AssistantConfig;
await mcpService.initialize(sseAssistant);
expect(SSEClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
eventSourceInit: expect.objectContaining({
fetch: expect.any(Function),
}),
requestInit: expect.objectContaining({
headers: {},
}),
}),
);
expect(SSEClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.not.objectContaining({
requestInit: expect.objectContaining({
agent: expect.anything(),
}),
}),
);
expect(HttpsAgent).not.toHaveBeenCalled();
});
it("should create HttpsAgent when verifySsl is false for streamable-http transport", async () => {
const { StreamableHTTPClientTransport } = await import(
"@modelcontextprotocol/sdk/client/streamableHttp.js"
);
const { Agent: HttpsAgent } = await import("https");
const httpAssistant: AssistantConfig = {
name: "http-assistant",
version: "1.0.0",
mcpServers: [
{
name: "http-server",
type: "streamable-http",
url: "https://example.com/http",
requestOptions: {
verifySsl: false,
},
},
],
} as AssistantConfig;
await mcpService.initialize(httpAssistant);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
requestInit: expect.objectContaining({
agent: expect.any(Object),
}),
}),
);
expect(HttpsAgent).toHaveBeenCalledWith({
rejectUnauthorized: false,
});
});
it("should not create HttpsAgent when verifySsl is true for streamable-http transport", async () => {
const { StreamableHTTPClientTransport } = await import(
"@modelcontextprotocol/sdk/client/streamableHttp.js"
);
const { Agent: HttpsAgent } = await import("https");
const httpAssistant: AssistantConfig = {
name: "http-assistant",
version: "1.0.0",
mcpServers: [
{
name: "http-server",
type: "streamable-http",
url: "https://example.com/http",
requestOptions: {
verifySsl: true,
},
},
],
} as AssistantConfig;
await mcpService.initialize(httpAssistant);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
requestInit: expect.objectContaining({
headers: {},
}),
}),
);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.not.objectContaining({
requestInit: expect.objectContaining({
agent: expect.anything(),
}),
}),
);
expect(HttpsAgent).not.toHaveBeenCalled();
});
it("should not create HttpsAgent when verifySsl is not specified", async () => {
const { StreamableHTTPClientTransport } = await import(
"@modelcontextprotocol/sdk/client/streamableHttp.js"
);
const { Agent: HttpsAgent } = await import("https");
const httpAssistant: AssistantConfig = {
name: "http-assistant",
version: "1.0.0",
mcpServers: [
{
name: "http-server",
type: "streamable-http",
url: "https://example.com/http",
},
],
} as AssistantConfig;
await mcpService.initialize(httpAssistant);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
requestInit: expect.objectContaining({
headers: {},
}),
}),
);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
expect.any(URL),
expect.not.objectContaining({
requestInit: expect.objectContaining({
agent: expect.anything(),
}),
}),
);
expect(HttpsAgent).not.toHaveBeenCalled();
});
});
});

View file

@ -1,14 +1,6 @@
import { decodeFQSN, getTemplateVariables } from "@continuedev/config-yaml";
import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import {
HttpMcpServer,
SseMcpServer,
StdioMcpServer,
} from "node_modules/@continuedev/config-yaml/dist/schemas/mcp/index.js";
import { isAuthenticated, loadAuthConfig } from "src/auth/workos.js";
@ -17,6 +9,11 @@ import { getErrorString } from "../util/error.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import {
constructHttpTransport,
constructSseTransport,
constructStdioTransport,
} from "./mcpTransports.js";
import { isAuthError } from "./mcpUtils.js";
import { serviceContainer } from "./ServiceContainer.js";
import {
@ -472,7 +469,7 @@ Org-level secrets can only be used for MCP by Background Agents (https://docs.co
if ("command" in serverConfig) {
// STDIO: no need to check type, just if command is present
const transport = this.constructStdioTransport(serverConfig, connection);
const transport = constructStdioTransport(serverConfig, connection);
await client.connect(transport, {});
} else {
// SSE/HTTP: if type isn't explicit: try http and fall back to sse
@ -481,21 +478,22 @@ Org-level secrets can only be used for MCP by Background Agents (https://docs.co
if (serverConfig.apiKey && !this.apiKeyCache.get(serverConfig.name)) {
this.apiKeyCache.set(serverConfig.name, serverConfig.apiKey);
}
const apiKey = this.apiKeyCache.get(serverConfig.name);
if (serverConfig.type === "sse") {
const transport = this.constructSseTransport(serverConfig);
const transport = constructSseTransport(serverConfig, apiKey);
await client.connect(transport, {});
} else if (serverConfig.type === "streamable-http") {
const transport = this.constructHttpTransport(serverConfig);
const transport = constructHttpTransport(serverConfig, apiKey);
await client.connect(transport, {});
} else {
try {
const transport = this.constructHttpTransport(serverConfig);
const transport = constructHttpTransport(serverConfig, apiKey);
await client.connect(transport, {});
} catch (e) {
if (isAuthError(e)) {
throw e;
}
const transport = this.constructSseTransport(serverConfig);
const transport = constructSseTransport(serverConfig, apiKey);
await client.connect(transport, {});
}
}
@ -525,7 +523,7 @@ Org-level secrets can only be used for MCP by Background Agents (https://docs.co
);
}
const transport = this.constructStdioTransport(
const transport = constructStdioTransport(
{
name: serverConfig.name,
command: "npx",
@ -542,81 +540,4 @@ Org-level secrets can only be used for MCP by Background Agents (https://docs.co
return client;
}
private constructSseTransport(
serverConfig: SseMcpServer,
): SSEClientTransport {
const apiKey = this.apiKeyCache.get(serverConfig.name);
// Merge apiKey into headers if provided
const headers = {
...serverConfig.requestOptions?.headers,
...(apiKey && {
Authorization: `Bearer ${apiKey}`,
}),
};
return new SSEClientTransport(new URL(serverConfig.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...headers,
},
}),
},
requestInit: { headers },
});
}
private constructHttpTransport(
serverConfig: HttpMcpServer,
): StreamableHTTPClientTransport {
// Merge apiKey into headers if provided
const apiKey = this.apiKeyCache.get(serverConfig.name);
const headers = {
...serverConfig.requestOptions?.headers,
...(apiKey && {
Authorization: `Bearer ${apiKey}`,
}),
};
return new StreamableHTTPClientTransport(new URL(serverConfig.url), {
requestInit: { headers },
});
}
private constructStdioTransport(
serverConfig: StdioMcpServer,
connection: ServerConnection,
): StdioClientTransport {
const env: Record<string, string> = serverConfig.env || {};
if (process.env) {
for (const [key, value] of Object.entries(process.env)) {
if (!(key in env) && !!value) {
env[key] = value;
}
}
}
const transport = new StdioClientTransport({
command: serverConfig.command,
args: serverConfig.args || [],
env,
cwd: serverConfig.cwd,
stderr: "pipe",
});
const stderrStream = transport.stderr;
if (stderrStream) {
stderrStream.on("data", (data: Buffer) => {
const stderrOutput = data.toString().trim();
if (stderrOutput) {
connection.warnings.push(stderrOutput);
}
});
}
return transport;
}
}

View file

@ -0,0 +1,105 @@
import { Agent as HttpsAgent } from "https";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import {
HttpMcpServer,
SseMcpServer,
StdioMcpServer,
} from "node_modules/@continuedev/config-yaml/dist/schemas/mcp/index.js";
import { MCPConnectionInfo } from "./types.js";
export function constructSseTransport(
serverConfig: SseMcpServer,
apiKey: string | undefined,
): SSEClientTransport {
const sseAgent =
serverConfig.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
const headers = {
...serverConfig.requestOptions?.headers,
...(apiKey && {
Authorization: `Bearer ${apiKey}`,
}),
};
return new SSEClientTransport(new URL(serverConfig.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...headers,
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: {
headers,
...(sseAgent && { agent: sseAgent }),
},
});
}
export function constructHttpTransport(
serverConfig: HttpMcpServer,
apiKey: string | undefined,
): StreamableHTTPClientTransport {
const streamableAgent =
serverConfig.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
const headers = {
...serverConfig.requestOptions?.headers,
...(apiKey && {
Authorization: `Bearer ${apiKey}`,
}),
};
return new StreamableHTTPClientTransport(new URL(serverConfig.url), {
requestInit: {
headers,
...(streamableAgent && { agent: streamableAgent }),
},
});
}
export function constructStdioTransport(
serverConfig: StdioMcpServer,
connection: MCPConnectionInfo,
): StdioClientTransport {
const env: Record<string, string> = serverConfig.env || {};
if (process.env) {
for (const [key, value] of Object.entries(process.env)) {
if (!(key in env) && !!value) {
env[key] = value;
}
}
}
const transport = new StdioClientTransport({
command: serverConfig.command,
args: serverConfig.args || [],
env,
cwd: serverConfig.cwd,
stderr: "pipe",
});
const stderrStream = transport.stderr;
if (stderrStream) {
stderrStream.on("data", (data: Buffer) => {
const stderrOutput = data.toString().trim();
if (stderrOutput) {
connection.warnings.push(stderrOutput);
}
});
}
return transport;
}

View file

@ -12,6 +12,7 @@ import { pruneLastMessage } from "../compaction.js";
import { services } from "../services/index.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { applyChatCompletionToolOverrides } from "../tools/applyToolOverrides.js";
import { ToolCall } from "../tools/index.js";
import {
chatCompletionStreamWithBackoff,
@ -460,7 +461,11 @@ export async function streamChatResponse(
);
// Recompute tools on each iteration to handle mode changes during streaming
const tools = await getRequestTools(isHeadless);
const rawTools = await getRequestTools(isHeadless);
const tools = applyChatCompletionToolOverrides(
rawTools,
model.chatOptions?.toolOverrides,
);
// Pre-API auto-compaction checkpoint (now includes tools)
const preCompactionResult = await handlePreApiCompaction(chatHistory, {

View file

@ -0,0 +1,64 @@
import type { ChatCompletionTool } from "openai/resources.mjs";
import { describe, expect, it } from "vitest";
import { applyChatCompletionToolOverrides } from "./applyToolOverrides.js";
describe("applyChatCompletionToolOverrides", () => {
const mockTools: ChatCompletionTool[] = [
{
type: "function",
function: { name: "read_file", description: "Read a file" },
},
{
type: "function",
function: { name: "write_file", description: "Write a file" },
},
];
it("returns tools unchanged when no overrides", () => {
expect(applyChatCompletionToolOverrides(mockTools, undefined)).toEqual(
mockTools,
);
expect(applyChatCompletionToolOverrides(mockTools, {})).toEqual(mockTools);
});
it("applies description override", () => {
const result = applyChatCompletionToolOverrides(mockTools, {
read_file: { description: "Custom read description" },
});
expect(result[0].function.description).toBe("Custom read description");
expect(result[1].function.description).toBe("Write a file");
});
it("filters out disabled tools", () => {
const result = applyChatCompletionToolOverrides(mockTools, {
read_file: { disabled: true },
});
expect(result).toHaveLength(1);
expect(result[0].function.name).toBe("write_file");
});
it("handles multiple overrides", () => {
const result = applyChatCompletionToolOverrides(mockTools, {
read_file: { description: "Custom read" },
write_file: { description: "Custom write" },
});
expect(result[0].function.description).toBe("Custom read");
expect(result[1].function.description).toBe("Custom write");
});
it("ignores overrides for non-existent tools", () => {
const result = applyChatCompletionToolOverrides(mockTools, {
non_existent_tool: { description: "Should be ignored" },
});
expect(result).toEqual(mockTools);
});
it("does not mutate original tools", () => {
const originalDescription = mockTools[0].function.description;
applyChatCompletionToolOverrides(mockTools, {
read_file: { description: "Modified description" },
});
expect(mockTools[0].function.description).toBe(originalDescription);
});
});

View file

@ -0,0 +1,31 @@
import type { ToolOverrideConfig } from "@continuedev/config-yaml";
import type { ChatCompletionTool } from "openai/resources.mjs";
/**
* Applies tool prompt overrides from YAML config to CLI tools.
* Supports description changes and disabling tools.
*/
export function applyChatCompletionToolOverrides(
tools: ChatCompletionTool[],
overrides: Record<string, ToolOverrideConfig> | undefined,
): ChatCompletionTool[] {
if (!overrides) {
return tools;
}
return tools
.filter((tool) => !overrides[tool.function.name]?.disabled)
.map((tool) => {
const override = overrides[tool.function.name];
if (!override?.description) {
return tool;
}
return {
...tool,
function: {
...tool.function,
description: override.description,
},
};
});
}

View file

@ -183,7 +183,6 @@ function useChatHandlers(
};
}
// eslint-disable-next-line complexity
const TUIChat: React.FC<TUIChatProps> = ({
remoteUrl,
configPath,

View file

@ -1,5 +1,6 @@
import { ModelConfig } from "@continuedev/config-yaml";
import type { ChatHistoryItem } from "core/index.js";
import { getAdjustedTokenCountFromModel } from "core/llm/getAdjustedTokenCount.js";
import { encode } from "gpt-tokenizer";
import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs";
@ -32,33 +33,6 @@ export function getModelMaxTokens(model: ModelConfig): number {
: maxTokens;
}
// Importing a bunch of tokenizers can be very resource intensive (MB-scale per tokenizer)
// Using token counting APIs (e.g. for anthropic) can be complicated and unreliable in many environments
// So for now we will just use super fast gpt-tokenizer and apply safety buffers
// I'm using rough estimates from this article to apply safety buffers to common tokenizers
// which will have HIGHER token counts than gpt. Roughly using token ratio from article + 10%
// https://medium.com/@disparate-ai/not-all-tokens-are-created-equal-7347d549af4d
const ANTHROPIC_TOKEN_MULTIPLIER = 1.23;
const GEMINI_TOKEN_MULTIPLIER = 1.18;
const MISTRAL_TOKEN_MULTIPLIER = 1.26;
function getAdjustedTokenCountFromModel(
baseTokens: number,
model: ModelConfig,
) {
let multiplier = 1;
const modelName = model.model?.toLowerCase() ?? "";
if (modelName.includes("claude")) {
multiplier = ANTHROPIC_TOKEN_MULTIPLIER;
} else if (modelName.includes("gemini")) {
multiplier = GEMINI_TOKEN_MULTIPLIER;
} else if (modelName.includes("stral")) {
// devstral, mixtral, mistral, etc
multiplier = MISTRAL_TOKEN_MULTIPLIER;
}
return Math.ceil(baseTokens * multiplier);
}
/**
* Count tokens in message content (string or multimodal array)
*/
@ -68,7 +42,7 @@ function countContentTokens(
): number {
if (typeof content === "string") {
const count = encode(content).length;
return getAdjustedTokenCountFromModel(count, model);
return getAdjustedTokenCountFromModel(count, model.model ?? "");
}
if (Array.isArray(content)) {
@ -81,7 +55,7 @@ function countContentTokens(
tokenCount += 1024; // Rough estimate for image tokens
}
}
return getAdjustedTokenCountFromModel(tokenCount, model);
return getAdjustedTokenCountFromModel(tokenCount, model.model ?? "");
}
return 0;

View file

@ -11,7 +11,7 @@
"dependencies": {
"@continuedev/config-types": "file:../../packages/config-types",
"@continuedev/fetch": "file:../../packages/fetch",
"@electron/rebuild": "^3.2.10",
"@electron/rebuild": "^3.7.2",
"@reduxjs/toolkit": "^1.9.3",
"@vscode/ripgrep": "^1.15.9",
"axios": "^1.13.1",
@ -796,9 +796,10 @@
}
},
"node_modules/@electron/rebuild": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-3.7.0.tgz",
"integrity": "sha512-VW++CNSlZwMYP7MyXEbrKjpzEwhB5kDNbzGtiPEjwYysqyTCF+YbNJ210Dj3AjWsGSV4iEEwNkmJN9yGZmVvmw==",
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-3.7.2.tgz",
"integrity": "sha512-19/KbIR/DAxbsCkiaGMXIdPnMCJLkcf8AvGnduJtWBs/CBwiAjY1apCqOLVxrXg+rtXFCngbXhBanWjxLUt1Mg==",
"license": "MIT",
"dependencies": {
"@electron/node-gyp": "git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2",
"@malept/cross-spawn-promise": "^2.0.0",

View file

@ -730,7 +730,7 @@
"dependencies": {
"@continuedev/config-types": "file:../../packages/config-types",
"@continuedev/fetch": "file:../../packages/fetch",
"@electron/rebuild": "^3.2.10",
"@electron/rebuild": "^3.7.2",
"@reduxjs/toolkit": "^1.9.3",
"@vscode/ripgrep": "^1.15.9",
"axios": "^1.13.1",

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View file

@ -1,8 +1,8 @@
import {
ArrowDownOnSquareIcon,
CloudIcon,
PencilSquareIcon,
TrashIcon,
CloudIcon,
} from "@heroicons/react/24/outline";
import { BaseSessionMetadata } from "core";
import type { RemoteSessionMetadata } from "core/control-plane/client";
@ -22,6 +22,7 @@ import {
} from "../../redux/thunks/session";
import { isShareSessionSupported } from "../../util";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { ToolTip } from "../gui/Tooltip";
const shareSessionSupported = isShareSessionSupported();
@ -144,6 +145,18 @@ export function HistoryTableRow({
Remote
</span>
)}
{sessionMetadata.messageCount !== undefined && (
<ToolTip
content={`${sessionMetadata.messageCount} message${
sessionMetadata.messageCount === 1 ? " is" : "s are"
} present in this session`}
>
<span className="bg-vsc-background text-secondary-foreground ml-auto inline-flex items-center rounded-full px-2 py-1 text-xs font-medium">
{sessionMetadata.messageCount}
</span>
</ToolTip>
)}
</div>
)}
@ -166,7 +179,7 @@ export function HistoryTableRow({
</td>
{hovered && !editing && (
<td className="bg-input absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
<td className="bg-input absolute right-2 top-12 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
{isRemote ? (
<HeaderButtonWithToolTip
text="Open in browser"

View file

@ -15,6 +15,7 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
import { setReasoningSetting } from "../../redux/slices/uiSlice";
import { exitEdit } from "../../redux/thunks/edit";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { ToolTip } from "../gui/Tooltip";
@ -136,9 +137,17 @@ function InputToolbar(props: InputToolbarProps) {
)}
{supportsReasoning && (
<HoverItem
onClick={() =>
dispatch(setHasReasoningEnabled(!hasReasoningEnabled))
}
onClick={() => {
dispatch(setHasReasoningEnabled(!hasReasoningEnabled));
if (defaultModel?.title) {
dispatch(
setReasoningSetting({
modelTitle: defaultModel.title,
enabled: !hasReasoningEnabled,
}),
);
}
}}
>
<ToolTip
place="top"

View file

@ -226,10 +226,12 @@ export function getSlashCommandDropdownOptions(
if (query.length === 0 && commandItems.length === 0) {
commandItems.push({
title: "Explore prompts",
title: "Create a prompt",
type: "action",
action: () =>
ideMessenger.post("openUrl", "https://continue.dev/explore/prompts"),
ideMessenger.request("config/addLocalWorkspaceBlock", {
blockType: "prompts",
}),
description: "",
name: "",
id: "",

View file

@ -2,8 +2,9 @@ import {
CheckIcon,
ChevronUpDownIcon,
CubeIcon,
MagnifyingGlassIcon,
} from "@heroicons/react/24/outline";
import { Fragment } from "react";
import { Fragment, useEffect, useMemo, useState } from "react";
import {
Listbox,
ListboxButton,
@ -19,6 +20,34 @@ interface ModelSelectionListboxProps {
setSelectedProvider: (val: DisplayInfo) => void;
topOptions?: DisplayInfo[];
otherOptions?: DisplayInfo[];
searchPlaceholder?: string;
}
/**
* Simple fuzzy search algorithm
* Returns a score based on how well the query matches the text
*/
function fuzzyScore(query: string, text: string): number {
const q = query.toLowerCase();
const t = text.toLowerCase();
if (!q) return 1; // Empty query matches everything
if (!t) return 0;
let score = 0;
let queryIdx = 0;
let lastMatchIdx = -1;
for (let i = 0; i < t.length && queryIdx < q.length; i++) {
if (t[i] === q[queryIdx]) {
score += 1 + (lastMatchIdx === i - 1 ? 5 : 0); // Bonus for consecutive matches
lastMatchIdx = i;
queryIdx++;
}
}
// Return 0 if not all query characters were found
return queryIdx === q.length ? score / t.length : 0;
}
function ModelSelectionListbox({
@ -26,9 +55,51 @@ function ModelSelectionListbox({
setSelectedProvider,
topOptions = [],
otherOptions = [],
searchPlaceholder = "Search models...",
}: ModelSelectionListboxProps) {
const [searchQuery, setSearchQuery] = useState("");
// Clear search query when provider changes
useEffect(() => {
setSearchQuery("");
}, [selectedProvider]);
// Combine and filter options based on fuzzy search
const filteredTopOptions = useMemo(() => {
if (!searchQuery) return topOptions;
return topOptions
.map((opt) => ({
option: opt,
score: fuzzyScore(searchQuery, opt.title),
}))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
.map(({ option }) => option);
}, [searchQuery, topOptions]);
const filteredOtherOptions = useMemo(() => {
if (!searchQuery) return otherOptions;
return otherOptions
.map((opt) => ({
option: opt,
score: fuzzyScore(searchQuery, opt.title),
}))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
.map(({ option }) => option);
}, [searchQuery, otherOptions]);
const hasResults =
filteredTopOptions.length > 0 || filteredOtherOptions.length > 0;
return (
<Listbox value={selectedProvider} onChange={setSelectedProvider}>
<Listbox
value={selectedProvider}
onChange={(value) => {
setSelectedProvider(value);
setSearchQuery("");
}}
>
<div className="relative mb-2 mt-1">
<ListboxButton className="bg-background border-border text-foreground hover:bg-input relative m-0 grid h-full w-full cursor-pointer grid-cols-[1fr_auto] items-center rounded-lg border border-solid py-2 pl-3 pr-10 text-left focus:outline-none">
<span className="flex items-center">
@ -54,87 +125,120 @@ function ModelSelectionListbox({
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<ListboxOptions className="bg-input rounded-default absolute left-0 top-full z-10 mt-1 h-fit w-3/5 overflow-y-auto p-0 focus:outline-none [&]:!max-h-[30vh]">
{topOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Popular
</div>
{topOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-default cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon className="h-3 w-3" aria-hidden="true" />
)}
</>
)}
</ListboxOption>
))}
<ListboxOptions className="bg-input rounded-default absolute left-0 top-full z-10 mt-1 flex h-fit w-3/5 flex-col overflow-y-auto p-0 focus:outline-none [&]:!max-h-[30vh]">
{/* Search Box */}
<div className="border-border sticky top-0 border-b p-2">
<div className="bg-background border-border flex items-center rounded border pl-2">
<MagnifyingGlassIcon className="text-description-muted h-4 w-4" />
<input
type="text"
placeholder={searchPlaceholder}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="bg-background text-foreground placeholder-description-muted w-full border-0 px-2 py-1.5 outline-none"
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
{topOptions.length > 0 && otherOptions.length > 0 && (
<div className="bg-border my-1 h-px min-h-px" />
)}
{otherOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Additional providers
</div>
{otherOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-default cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
</div>
{selected && (
<CheckIcon className="h-3 w-3" aria-hidden="true" />
)}
</>
{/* Results */}
<div className="flex-1 overflow-y-auto">
{!hasResults ? (
<div className="text-description-muted px-3 py-4 text-center text-xs">
No models found matching "{searchQuery}"
</div>
) : (
<>
{filteredTopOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Popular
</div>
{filteredTopOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon
className="h-3 w-3"
aria-hidden="true"
/>
)}
</>
)}
</ListboxOption>
))}
</div>
)}
{filteredTopOptions.length > 0 &&
filteredOtherOptions.length > 0 && (
<div className="bg-border my-1 h-px min-h-px" />
)}
</ListboxOption>
))}
</div>
)}
{filteredOtherOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Additional providers
</div>
{filteredOtherOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon
className="h-3 w-3"
aria-hidden="true"
/>
)}
</>
)}
</ListboxOption>
))}
</div>
)}
</>
)}
</div>
</ListboxOptions>
</Transition>
</div>

View file

@ -9,6 +9,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs";
import { DisplayInfo } from "../pages/AddNewModel/configs/models";
import {
initializeOpenRouterModels,
ProviderInfo,
providers,
} from "../pages/AddNewModel/configs/providers";
@ -40,6 +41,11 @@ export function AddModelForm({
const formMethods = useForm();
const ideMessenger = useContext(IdeMessengerContext);
// Initialize OpenRouter models from API on component mount
useEffect(() => {
void initializeOpenRouterModels();
}, []);
const popularProviderTitles = [
providers["openai"]?.title || "",
providers["anthropic"]?.title || "",
@ -47,6 +53,7 @@ export function AddModelForm({
providers["gemini"]?.title || "",
providers["azure"]?.title || "",
providers["ollama"]?.title || "",
providers["openrouter"]?.title || "",
];
const allProviders = Object.entries(providers)
@ -63,11 +70,10 @@ export function AddModelForm({
.filter((provider) => !popularProviderTitles.includes(provider.title))
.sort((a, b) => a.title.localeCompare(b.title));
const selectedProviderApiKeyUrl = selectedModel.params.model.startsWith(
"codestral",
)
? CODESTRAL_URL
: selectedProvider.apiKeyUrl;
const selectedProviderApiKeyUrl =
selectedModel && selectedModel.params.model.startsWith("codestral")
? CODESTRAL_URL
: selectedProvider.apiKeyUrl;
function isDisabled() {
if (selectedProvider.downloadUrl) {
@ -149,6 +155,7 @@ export function AddModelForm({
}}
topOptions={popularProviders}
otherOptions={otherProviders}
searchPlaceholder="Search providers..."
/>
<span className="text-description-muted mt-1 block text-xs">
Don't see your provider?{" "}

View file

@ -43,6 +43,9 @@ function ParallelListeners() {
const selectedProfileId = useAppSelector(
(store) => store.profiles.selectedProfileId,
);
const reasoningSettings = useAppSelector(
(store) => store.ui.reasoningSettings,
);
const hasDoneInitialConfigLoad = useRef(false);
// Load symbols for chat on any session change
@ -88,11 +91,18 @@ function ParallelListeners() {
const supportsReasoning = modelSupportsReasoning(chatModel);
const isReasoningDisabled =
chatModel?.completionOptions?.reasoning === false;
const wasReasoningPreviouslyEnabled = chatModel?.title
? reasoningSettings[chatModel.title] !== false
: true;
dispatch(
setHasReasoningEnabled(supportsReasoning && !isReasoningDisabled),
setHasReasoningEnabled(
supportsReasoning &&
!isReasoningDisabled &&
wasReasoningPreviouslyEnabled,
),
);
},
[dispatch, hasDoneInitialConfigLoad, selectedProfileId],
[dispatch, hasDoneInitialConfigLoad, selectedProfileId, reasoningSettings],
);
// Load config from the IDE

View file

@ -37,6 +37,76 @@ export interface ModelPackage {
}
export const models: { [key: string]: ModelPackage } = {
hermes3Llama31_405b: {
title: "Hermes 3 Llama 3.1 405B",
description:
"Nous Research's Hermes 3, a powerful instruction-tuned model built on Llama 3.1 405B with strong reasoning and tool use capabilities.",
refUrl: "https://nousresearch.com/hermes3",
params: {
title: "Hermes 3 Llama 3.1 405B",
model: "Hermes-3-Llama-3.1-405B",
contextLength: 32_000,
},
icon: "nous.png",
providerOptions: ["nous"],
isOpenSource: true,
},
hermes3Llama31_70b: {
title: "Hermes 3 Llama 3.1 70B",
description:
"Nous Research's Hermes 3, built on Llama 3.1 70B with strong instruction following and reasoning.",
refUrl: "https://nousresearch.com/hermes3",
params: {
title: "Hermes 3 Llama 3.1 70B",
model: "Hermes-3-Llama-3.1-70B",
contextLength: 32_000,
},
icon: "nous.png",
providerOptions: ["nous"],
isOpenSource: true,
},
hermes4_405b: {
title: "Hermes 4 405B",
description:
"Nous Research's Hermes 4, featuring enhanced reasoning with thinking tags for chain-of-thought.",
refUrl: "https://nousresearch.com",
params: {
title: "Hermes 4 405B",
model: "Hermes-4-405B",
contextLength: 128_000,
},
icon: "nous.png",
providerOptions: ["nous"],
isOpenSource: true,
},
hermes4_70b: {
title: "Hermes 4 70B",
description:
"Nous Research's Hermes 4 70B with reasoning capabilities and 128k context.",
refUrl: "https://nousresearch.com",
params: {
title: "Hermes 4 70B",
model: "Hermes-4-70B",
contextLength: 128_000,
},
icon: "nous.png",
providerOptions: ["nous"],
isOpenSource: true,
},
hermes43_36b: {
title: "Hermes 4.3 36B",
description:
"Nous Research's Hermes 4.3 36B, a compact reasoning model with 128k context.",
refUrl: "https://nousresearch.com",
params: {
title: "Hermes 4.3 36B",
model: "Hermes-4.3-36B",
contextLength: 128_000,
},
icon: "nous.png",
providerOptions: ["nous"],
isOpenSource: true,
},
deepseekV3Chat: {
title: "deepseek v3",
description: "A model from deekseek for chat",

View file

@ -0,0 +1,77 @@
import { ModelProviderTags } from "../../../components/modelSelection/utils";
import { ModelPackage } from "./models";
interface OpenRouterModel {
id: string;
name: string;
description: string;
context_length: number;
hugging_face_id: string;
}
function convertOpenRouterModelToPackage(model: OpenRouterModel): ModelPackage {
return {
title: model.name,
description: model.description,
refUrl: `https://openrouter.ai/models/${model.id}`,
params: {
title: model.name,
model: model.id,
contextLength: model.context_length,
},
isOpenSource: !!model.hugging_face_id,
tags: [ModelProviderTags.RequiresApiKey],
providerOptions: ["openrouter"],
icon: "openrouter.png",
};
}
async function fetchOpenRouterModelsFromAPI(): Promise<OpenRouterModel[]> {
const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/models";
try {
const response = await fetch(OPENROUTER_API_URL);
if (!response.ok) {
throw new Error(
`Failed to fetch OpenRouter models: ${response.status} ${response.statusText}`,
);
}
const data = await response.json();
if (!data.data || !Array.isArray(data.data)) {
console.warn("Invalid OpenRouter models data structure from API");
return [];
}
return data.data;
} catch (error) {
console.error("Error fetching OpenRouter models from API:", error);
return [];
}
}
export async function getOpenRouterModelsList(): Promise<ModelPackage[]> {
const models: { [key: string]: ModelPackage } = {};
const apiModels = await fetchOpenRouterModelsFromAPI();
apiModels.forEach((model: OpenRouterModel) => {
if (!model.id || !model.name) {
console.warn("Skipping model with missing id or name", model);
return;
}
// Create a unique key from the model id (replace slashes and dots with underscores)
const key = model.id.replace(/[\/.]/g, "_");
try {
models[key] = convertOpenRouterModelToPackage(model);
} catch (error) {
console.error(`Failed to convert model ${model.id}:`, error);
}
});
return Object.values(models);
}

View file

@ -3,6 +3,7 @@ import { ModelProviderTags } from "../../../components/modelSelection/utils";
import { completionParamsInputs } from "./completionParamsInputs";
import type { ModelPackage } from "./models";
import { models } from "./models";
import { getOpenRouterModelsList } from "./openRouterModel";
export interface InputDescriptor {
inputType: HTMLInputTypeAttribute;
@ -40,6 +41,39 @@ const openSourceModels = Object.values(models).filter(
({ isOpenSource }) => isOpenSource,
);
// Initialize OpenRouter models placeholder with a loading placeholder
const OPENROUTER_LOADING_PLACEHOLDER: ModelPackage = {
title: "Loading models...",
description: "Fetching available models from OpenRouter",
params: {
model: "placeholder",
contextLength: 0,
},
isOpenSource: false,
};
let openRouterModelsList: ModelPackage[] = [OPENROUTER_LOADING_PLACEHOLDER];
/**
* Initialize OpenRouter models by fetching from the API
* This should be called once when the component mounts
*/
export async function initializeOpenRouterModels() {
try {
const models = await getOpenRouterModelsList();
if (models.length > 0) {
openRouterModelsList = models;
// Update the providers object with the fetched models
if (providers.openrouter) {
providers.openrouter.packages = openRouterModelsList;
}
}
} catch (error) {
console.error("Failed to initialize OpenRouter models:", error);
// Keep placeholder on error so the UI doesn't break
}
}
export const apiBaseInput: InputDescriptor = {
inputType: "text",
key: "apiBase",
@ -178,6 +212,29 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
],
apiKeyUrl: "https://console.anthropic.com/account/keys",
},
openrouter: {
title: "OpenRouter",
provider: "openrouter",
description:
"OpenRouter provides access to a variety of LLMs including open-source and proprietary models.",
longDescription: `To get started with OpenRouter, sign up for an account at [openrouter.ai](https://openrouter.ai/) and obtain your API key from the dashboard.`,
icon: "openrouter.png",
tags: [ModelProviderTags.RequiresApiKey],
refPage: "openrouter",
apiKeyUrl: "https://openrouter.ai/settings/keys",
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your OpenRouter API key",
required: true,
},
...completionParamsInputsConfigs,
],
packages: openRouterModelsList,
},
moonshot: {
title: "Moonshot",
provider: "moonshot",
@ -1167,4 +1224,36 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
],
apiKeyUrl: "https://api.router.tetrate.ai/",
},
nous: {
title: "Nous Research",
provider: "nous",
refPage: "nous",
description:
"Nous Research provides Hermes models via an OpenAI-compatible API with advanced reasoning capabilities.",
longDescription:
"Nous Research offers Hermes models including Hermes 3 and Hermes 4 with strong instruction following and reasoning. Get an API key at [portal.nousresearch.com](https://portal.nousresearch.com).",
icon: "nous.png",
tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
params: {
apiBase: "https://inference-api.nousresearch.com/v1",
},
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your Nous Research API key",
required: true,
},
...completionParamsInputsConfigs,
],
packages: [
models.hermes43_36b,
models.hermes4_70b,
models.hermes4_405b,
models.hermes3Llama31_70b,
models.hermes3Llama31_405b,
],
apiKeyUrl: "https://portal.nousresearch.com",
},
};

View file

@ -179,15 +179,6 @@ export function HelpSection() {
<h3 className="mb-3 text-base font-medium">Resources</h3>
<Card className="!p-0">
<div className="flex flex-col">
<ConfigRow
title="Continue Hub"
description="Visit continue.dev to explore custom agents and blocks"
icon={LinkIcon}
onClick={() =>
ideMessenger.post("openUrl", "https://continue.dev/")
}
/>
<ConfigRow
title="Documentation"
description="Learn how to configure and use Continue"

View file

@ -658,6 +658,14 @@ export const sessionSlice = createSlice({
message.metadata?.responsesOutputItemId
) {
lastMessage.metadata = lastMessage.metadata || {};
// Accumulate fc_ IDs for parallel tool calls (OpenAI Responses API)
if (!lastMessage.metadata.responsesOutputItemIds) {
lastMessage.metadata.responsesOutputItemIds = [];
}
(lastMessage.metadata.responsesOutputItemIds as string[]).push(
message.metadata.responsesOutputItemId as string,
);
// Also keep singular for backwards compatibility
lastMessage.metadata.responsesOutputItemId = message.metadata
.responsesOutputItemId as string;
}

View file

@ -15,6 +15,7 @@ export type ToolGroupPolicy = "include" | "exclude";
export type ToolPolicies = { [toolName: string]: ToolPolicy };
export type RulePolicies = { [ruleName: string]: RulePolicy };
export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy };
export type ReasoningSettings = { [modelTitle: string]: boolean };
type UIState = {
showDialog: boolean;
@ -26,6 +27,7 @@ type UIState = {
toolSettings: ToolPolicies;
toolGroupSettings: ToolGroupPolicies;
ruleSettings: RulePolicies;
reasoningSettings: ReasoningSettings;
ttsActive: boolean;
};
@ -46,6 +48,7 @@ export const DEFAULT_UI_SLICE: UIState = {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
reasoningSettings: {},
};
export const uiSlice = createSlice({
@ -139,6 +142,13 @@ export const uiSlice = createSlice({
setTTSActive: (state, { payload }: PayloadAction<boolean>) => {
state.ttsActive = payload;
},
setReasoningSetting: (
state,
action: PayloadAction<{ modelTitle: string; enabled: boolean }>,
) => {
state.reasoningSettings[action.payload.modelTitle] =
action.payload.enabled;
},
},
});
@ -155,6 +165,7 @@ export const {
addRule,
toggleRuleSetting,
setTTSActive,
setReasoningSetting,
} = uiSlice.actions;
export default uiSlice.reducer;

View file

@ -52,7 +52,12 @@ const saveSubsetFilters = [
"codeToEdit",
]),
createFilter("config", []),
createFilter("ui", ["toolSettings", "toolGroupSettings", "ruleSettings"]),
createFilter("ui", [
"toolSettings",
"toolGroupSettings",
"ruleSettings",
"reasoningSettings",
]),
createFilter("indexing", []),
createFilter("tabs", ["tabs"]),
createFilter("profiles", [

View file

@ -740,6 +740,21 @@ export async function resolveBlock(
secrets: extractFQSNMap(rawYaml, [id]),
});
// Check for unresolved input template variables (missing required inputs)
const unresolvedInputs = getTemplateVariables(templatedYaml).filter((v) =>
v.startsWith("inputs."),
);
if (unresolvedInputs.length > 0) {
const missingInputNames = unresolvedInputs.map((v) =>
v.replace("inputs.", ""),
);
const blockName = packageIdentifierToShorthandSlug(id);
throw new Error(
`Missing required input(s) for block "${blockName}": ${missingInputNames.join(", ")}. ` +
`Please provide these values in the "with" block.`,
);
}
// Add source slug for mcp servers
const parsed = parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
if (

View file

@ -87,10 +87,38 @@ export const embedOptionsSchema = z.object({
});
export type EmbedOptions = z.infer<typeof embedOptionsSchema>;
/**
* Schema for overriding a tool's system message description.
* Used for models that don't support native tool calling.
*/
export const systemMessageDescriptionOverrideSchema = z.object({
prefix: z.string().optional(),
exampleArgs: z
.array(z.tuple([z.string(), z.union([z.string(), z.number()])]))
.optional(),
});
/**
* Schema for overriding built-in tool prompts.
* Allows customization of tool descriptions and behavior per model.
*/
export const toolOverrideSchema = z.object({
description: z.string().optional(),
displayTitle: z.string().optional(),
wouldLikeTo: z.string().optional(),
isCurrently: z.string().optional(),
hasAlready: z.string().optional(),
systemMessageDescription: systemMessageDescriptionOverrideSchema.optional(),
disabled: z.boolean().optional(),
});
export type ToolOverrideConfig = z.infer<typeof toolOverrideSchema>;
export const chatOptionsSchema = z.object({
baseSystemMessage: z.string().optional(),
baseAgentSystemMessage: z.string().optional(),
basePlanSystemMessage: z.string().optional(),
/** Tool overrides keyed by tool name (e.g., "run_terminal_command") */
toolOverrides: z.record(z.string(), toolOverrideSchema).optional(),
});
export type ChatOptions = z.infer<typeof chatOptionsSchema>;

View file

@ -10,7 +10,7 @@
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "^1.38.0",
"@openapitools/openapi-generator-cli": "^2.25.1",
"@openapitools/openapi-generator-cli": "^2.27.0",
"express": "^4.22.0",
"swagger-ui-express": "^5.0.0"
},
@ -19,9 +19,9 @@
}
},
"node_modules/@borewit/text-codec": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz",
"integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==",
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.1.tgz",
"integrity": "sha512-k7vvKPbf7J2fZ5klGRD9AeKfUvojuZIQ3BT5u7Jfv+puwXkUBUT5PVyMDfJZpy30CBDXGMgw7fguK/lpOMBvgw==",
"license": "MIT",
"funding": {
"type": "github",
@ -98,9 +98,9 @@
}
},
"node_modules/@isaacs/brace-expansion": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz",
"integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==",
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.1.tgz",
"integrity": "sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==",
"license": "MIT",
"dependencies": {
"@isaacs/balanced-match": "^4.0.1"
@ -109,102 +109,6 @@
"node": "20 || >=22"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
"string-width-cjs": "npm:string-width@^4.2.0",
"strip-ansi": "^7.0.1",
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
"wrap-ansi": "^8.1.0",
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@isaacs/cliui/node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"license": "MIT"
},
"node_modules/@isaacs/cliui/node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
"license": "MIT",
"dependencies": {
"eastasianwidth": "^0.2.0",
"emoji-regex": "^9.2.2",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@isaacs/cliui/node_modules/strip-ansi": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
"integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/wrap-ansi": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.1.0",
"string-width": "^5.0.1",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/@lukeed/csprng": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
@ -226,12 +130,12 @@
}
},
"node_modules/@nestjs/common": {
"version": "11.1.9",
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.9.tgz",
"integrity": "sha512-zDntUTReRbAThIfSp3dQZ9kKqI+LjgLp5YZN5c1bgNRDuoeLySAoZg46Bg1a+uV8TMgIRziHocglKGNzr6l+bQ==",
"version": "11.1.11",
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.11.tgz",
"integrity": "sha512-R/+A8XFqLgN8zNs2twhrOaE7dJbRQhdPX3g46am4RT/x8xGLqDphrXkUIno4cGUZHxbczChBAaAPTdPv73wDZA==",
"license": "MIT",
"dependencies": {
"file-type": "21.1.0",
"file-type": "21.2.0",
"iterare": "1.2.1",
"load-esm": "1.0.3",
"tslib": "2.8.1",
@ -257,9 +161,9 @@
}
},
"node_modules/@nestjs/core": {
"version": "11.1.9",
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.9.tgz",
"integrity": "sha512-a00B0BM4X+9z+t3UxJqIZlemIwCQdYoPKrMcM+ky4z3pkqqG1eTWexjs+YXpGObnLnjtMPVKWlcZHp3adDYvUw==",
"version": "11.1.11",
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.11.tgz",
"integrity": "sha512-H9i+zT3RvHi7tDc+lCmWHJ3ustXveABCr+Vcpl96dNOxgmrx4elQSTC4W93Mlav2opfLV+p0UTHY6L+bpUA4zA==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
@ -336,15 +240,15 @@
"integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw=="
},
"node_modules/@openapitools/openapi-generator-cli": {
"version": "2.25.1",
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.25.1.tgz",
"integrity": "sha512-IY0Vgnv//v2X7+gqAj+jE+CoygdeIx15ZaF2SK+/kQR/sHBJTgxOOc0V+ti2tfxv4pkOILcTcPhmuZIobxPQhg==",
"version": "2.27.0",
"resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.27.0.tgz",
"integrity": "sha512-JJWO9joe6TudGdHuwBi+NhEMIwXcz1B2FawBsJ5SjgTMQxSjArkChq+ro6Ovv6q1zfWavCs/q9uYeNPtRRcQBA==",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@nestjs/axios": "4.0.1",
"@nestjs/common": "11.1.9",
"@nestjs/core": "11.1.9",
"@nestjs/common": "11.1.11",
"@nestjs/core": "11.1.11",
"@nuxtjs/opencollective": "0.3.2",
"axios": "1.13.2",
"chalk": "4.1.2",
@ -352,8 +256,8 @@
"compare-versions": "6.1.1",
"concurrently": "9.2.1",
"console.table": "0.10.0",
"fs-extra": "11.3.2",
"glob": "12.0.0",
"fs-extra": "11.3.3",
"glob": "13.0.0",
"inquirer": "8.2.7",
"proxy-agent": "6.5.0",
"reflect-metadata": "0.2.2",
@ -378,14 +282,13 @@
"hasInstallScript": true
},
"node_modules/@tokenizer/inflate": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.3.1.tgz",
"integrity": "sha512-4oeoZEBQdLdt5WmP/hx1KZ6D3/Oid/0cUb2nk4F0pTDAWy+KCH3/EnAkZF/bvckWo8I33EqBm01lIPgmgc8rCA==",
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz",
"integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.1",
"fflate": "^0.8.2",
"token-types": "^6.0.0"
"debug": "^4.4.3",
"token-types": "^6.1.1"
},
"engines": {
"node": ">=18"
@ -857,20 +760,6 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/data-uri-to-buffer": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
@ -959,12 +848,6 @@
"node": ">= 0.4"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"license": "MIT"
},
"node_modules/easy-table": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz",
@ -1198,12 +1081,6 @@
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
"license": "MIT"
},
"node_modules/fflate": {
"version": "0.8.2",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
"license": "MIT"
},
"node_modules/figures": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz",
@ -1220,14 +1097,14 @@
}
},
"node_modules/file-type": {
"version": "21.1.0",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-21.1.0.tgz",
"integrity": "sha512-boU4EHmP3JXkwDo4uhyBhTt5pPstxB6eEXKJBu2yu2l7aAMMm7QQYQEzssJmKReZYrFdFOJS8koVo6bXIBGDqA==",
"version": "21.2.0",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-21.2.0.tgz",
"integrity": "sha512-vCYBgFOrJQLoTzDyAXAL/RFfKnXXpUYt4+tipVy26nJJhT7ftgGETf2tAQF59EEL61i3MrorV/PG6tf7LJK7eg==",
"license": "MIT",
"dependencies": {
"@tokenizer/inflate": "^0.3.1",
"strtok3": "^10.3.1",
"token-types": "^6.0.0",
"@tokenizer/inflate": "^0.4.1",
"strtok3": "^10.3.4",
"token-types": "^6.1.1",
"uint8array-extras": "^1.4.0"
},
"engines": {
@ -1287,22 +1164,6 @@
}
}
},
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
"signal-exit": "^4.0.1"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/form-data": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
@ -1336,9 +1197,9 @@
}
},
"node_modules/fs-extra": {
"version": "11.3.2",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz",
"integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==",
"version": "11.3.3",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.3.tgz",
"integrity": "sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==",
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
@ -1415,21 +1276,15 @@
}
},
"node_modules/glob": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-12.0.0.tgz",
"integrity": "sha512-5Qcll1z7IKgHr5g485ePDdHcNQY0k2dtv/bjYy0iuyGxQw2qSOiiXUXJ+AYQpg3HNoUMHqAruX478Jeev7UULw==",
"version": "13.0.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.0.tgz",
"integrity": "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA==",
"license": "BlueOak-1.0.0",
"dependencies": {
"foreground-child": "^3.3.1",
"jackspeak": "^4.1.1",
"minimatch": "^10.1.1",
"minipass": "^7.1.2",
"package-json-from-dist": "^1.0.0",
"path-scurry": "^2.0.0"
},
"bin": {
"glob": "dist/esm/bin.mjs"
},
"engines": {
"node": "20 || >=22"
},
@ -1650,12 +1505,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/iterare": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz",
@ -1665,21 +1514,6 @@
"node": ">=6"
}
},
"node_modules/jackspeak": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz",
"integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==",
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^8.0.2"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/jsbn": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
@ -1739,10 +1573,10 @@
}
},
"node_modules/lru-cache": {
"version": "11.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz",
"integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==",
"license": "ISC",
"version": "11.2.5",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.5.tgz",
"integrity": "sha512-vFrFJkWtJvJnD5hg+hJvVE8Lh/TcMzKnTgCWmtBipwI5yLX/iX+5UB2tfuyODF5E7k9xEzMdYgGqaSb1c0c5Yw==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
@ -1978,12 +1812,6 @@
"node": ">= 14"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0"
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@ -1992,15 +1820,6 @@
"node": ">= 0.8"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-scurry": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.1.tgz",
@ -2259,27 +2078,6 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
@ -2360,18 +2158,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
"license": "ISC",
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/smart-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
@ -2452,21 +2238,6 @@
"node": ">=8"
}
},
"node_modules/string-width-cjs": {
"name": "string-width",
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@ -2479,19 +2250,6 @@
"node": ">=8"
}
},
"node_modules/strip-ansi-cjs": {
"name": "strip-ansi",
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strtok3": {
"version": "10.3.4",
"resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz",
@ -2556,12 +2314,12 @@
}
},
"node_modules/token-types": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz",
"integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==",
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz",
"integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==",
"license": "MIT",
"dependencies": {
"@borewit/text-codec": "^0.1.0",
"@borewit/text-codec": "^0.2.1",
"@tokenizer/token": "^0.3.0",
"ieee754": "^1.2.1"
},
@ -2715,21 +2473,6 @@
"webidl-conversions": "^3.0.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
@ -2744,24 +2487,6 @@
"node": ">=8"
}
},
"node_modules/wrap-ansi-cjs": {
"name": "wrap-ansi",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",

View file

@ -15,7 +15,7 @@
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "^1.38.0",
"@openapitools/openapi-generator-cli": "^2.25.1",
"@openapitools/openapi-generator-cli": "^2.27.0",
"express": "^4.22.0",
"swagger-ui-express": "^5.0.0"
},

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,7 @@
"@ai-sdk/openai": "^1.0.10",
"@anthropic-ai/sdk": "^0.67.0",
"@aws-sdk/client-bedrock-runtime": "^3.931.0",
"@aws-sdk/credential-providers": "^3.931.0",
"@aws-sdk/credential-providers": "^3.974.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.38.0",
"@continuedev/fetch": "^1.6.0",

View file

@ -53,6 +53,7 @@ export class OpenAIApi implements BaseLlmApi {
apiKey: config.apiKey ?? "",
baseURL: this.apiBase,
fetch: customFetch(config.requestOptions),
timeout: config?.requestOptions?.timeout || undefined,
});
}