Merge branch 'main' into 2025-08-05-03-21-49

This commit is contained in:
Juan Calderon-Perez 2025-08-05 20:57:03 -04:00 • committed by GitHub
commit 4b126e4b9e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
84 changed files with 5056 additions and 383 deletions

20
.claude/lint-check.sh Executable file
View file

@ -0,0 +1,20 @@
#!/bin/bash
# Get file path from hook input
FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1)
# Function to run lint and typecheck
run_checks() {
local dir=$1
cd "$dir"
npm run lint >&2 && npm run tsc:check >&2
}
# Run checks based on file location
if [[ "$FILE_PATH" == *"/core/"* ]]; then
run_checks core
elif [[ "$FILE_PATH" == *"/gui/"* ]]; then
run_checks gui
elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then
run_checks extensions/vscode
fi

15
.claude/settings.json Normal file
View file

@ -0,0 +1,15 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh"
}
]
}
]
}
}

View file

@ -1,5 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: Something else? Message us on Discord :)
- name: Have a feature request?
url: https://github.com/continuedev/continue/discussions
about: Upvote existing suggestions or make a new one
- name: Have a question?
url: https://github.com/continuedev/continue/discussions
about: Search for existing questions or ask a new one
- name: Something else? Join the Continue Community
url: https://discord.gg/vapESyrFmJ
about: Join our Discord to ask questions, share thoughts, and more!
about: Join our Discord to chat with our community

View file

@ -1,35 +0,0 @@
---
name: 💪 Improvement suggestion
description: Share how you think Continue could be better
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to share your perspective! We are keen to hear how you think Continue could work better for you.
- type: checkboxes
id: checkboxes
attributes:
label: Validations
description: Before submitting your suggested improvement
options:
- label: I believe this is a way to improve. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
required: false
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement) that requests the same enhancement
required: false
- type: textarea
attributes:
label: Problem
description: Please describe the problem you are aiming to solve with this suggested improvement. If applicable, add a screenshot, gif, or video to better convey your idea.
placeholder: |
Short description
validations:
required: false
- type: textarea
attributes:
label: Solution
description: Please describe what you might want to happen to address this issue. If applicable, add a screenshot, gif, or video to better convey your idea.
placeholder: |
Short description
validations:
required: false

View file

@ -40,7 +40,7 @@ jobs:
fi
- name: Add PR title guidance comment
if: steps.pr-title-check.outputs.valid == 'false'
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v7
with:
script: |
@ -88,6 +88,9 @@ jobs:
].join('\n')
});
}
- name: Ensure job always succeeds
if: always()
run: echo "✅ Conventional commits check completed (warning only)"
security-audit:
name: Security Audit

View file

@ -10,6 +10,11 @@ extensions/vscode/.vscode-test
extensions/vscode/bin
extensions/vscode/build
extensions/vscode/out
extensions/vscode/gui
extensions/vscode/e2e/.test-extensions
extensions/vscode/e2e/test-continue
extensions/vscode/models
extensions/intellij/src/main/resources
gui/dist
**/.continueignore
CHANGELOG.md
@ -19,7 +24,4 @@ CHANGELOG.md
core/vendor
coverage
e2e
extensions/vscode/gui
extensions/vscode/models
extensions/intellij/src/main/resources
packages/continue-sdk

View file

@ -1,4 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../control-plane/client.js";
import {
@ -46,7 +46,7 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
totalConfigLoads: number = 0;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
private initter: EventEmitter;
@ -121,7 +121,7 @@ export class ConfigHandler {
this.workspaceDirs = null; // forces workspace dirs reload
try {
const orgs = await this.getOrgs();
const { orgs, errors } = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
@ -136,21 +136,20 @@ export class ConfigHandler {
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
} else {
selectedOrg = fallback;
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
}
this.initter.emit("init");
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
@ -161,28 +160,52 @@ export class ConfigHandler {
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig(reason);
await this.reloadConfig(reason, errors);
} catch (e) {
if (e instanceof Error && e.message.includes("AbortError")) {
if (signal.aborted) {
return;
} else {
this.initter.emit("init"); // Error case counts for initialization
this.initter.emit("init"); // Error case counts as init
throw e;
}
}
}
private async getOrgs(): Promise<OrgWithProfiles[]> {
private async getOrgs(): Promise<{
orgs: OrgWithProfiles[];
errors?: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
return orgs;
} else {
return [await this.getLocalOrg()];
try {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
// TODO make try/catch more granular here, to catch specific org errors
return { orgs };
} catch (e) {
errors.push({
fatal: false,
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
}
// Load local org if not signed in or hub orgs fail
try {
const orgs = [await this.getLocalOrg()];
return { orgs };
} catch (e) {
errors.push({
fatal: true,
message: `Error loading local assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
return {
orgs: [],
errors,
};
}
}
@ -276,9 +299,7 @@ export class ConfigHandler {
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
let currentProfile: ProfileLifecycleManager | null;
if (!currentSelection) {
currentProfile = fallback;
} else {
if (currentSelection) {
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
@ -287,6 +308,8 @@ export class ConfigHandler {
} else {
currentProfile = fallback;
}
} else {
currentProfile = fallback;
}
if (currentProfile) {
@ -460,14 +483,17 @@ export class ConfigHandler {
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig(reason: string) {
async reloadConfig(reason: string, injectErrors?: ConfigValidationError[]) {
const startTime = performance.now();
this.totalConfigLoads += 1;
this.totalConfigReloads += 1;
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: [
{ message: "Current profile not found", fatal: true },
...(injectErrors ?? []),
],
configLoadInterrupted: true,
};
}
@ -483,22 +509,35 @@ export class ConfigHandler {
}
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(this.additionalContextProviders);
const {
config,
errors = [],
configLoadInterrupted,
} = await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (injectErrors) {
errors.unshift(...injectErrors);
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
this.initter.emit("init");
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
duration,
reason,
totalConfigLoads: this.totalConfigLoads,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
});
return { config, errors, configLoadInterrupted };
return {
config,
errors: errors.length ? errors : undefined,
configLoadInterrupted,
};
}
// Listeners setup - can listen to current profile updates

View file

@ -18,6 +18,7 @@ import {
SlashCommandDescWithSource,
Tool,
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
@ -216,15 +217,39 @@ export default async function doLoadConfig(options: {
}));
newConfig.tools.push(...serverTools);
// Fetch MCP prompt content during config load
const serverSlashCommands: SlashCommandDescWithSource[] =
server.prompts.map((prompt) => ({
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
}));
await Promise.all(
server.prompts.map(async (prompt) => {
let promptContent: string | undefined;
try {
// Fetch the actual prompt content from the MCP server
const mcpPromptResponse = await mcpManager.getPrompt(
server.name,
prompt.name,
{}, // Empty args for now - TODO: handle prompt arguments
);
promptContent = stringifyMcpPrompt(mcpPromptResponse);
} catch (error) {
console.warn(
`Failed to fetch MCP prompt content for ${prompt.name} from server ${server.name}:`,
error,
);
// Keep promptContent as undefined so the UI can show a fallback
}
return {
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
prompt: promptContent, // Store the actual prompt content
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
};
}),
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources
@ -333,6 +358,9 @@ export default async function doLoadConfig(options: {
};
if (newConfig.analytics) {
// FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
// controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
// where undefined is :workspaceId
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,

View file

@ -20,8 +20,12 @@ export default class ContinueProxyAnalyticsProvider
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (!this.controlPlaneProxyInfo?.workspaceId) {
return;
}
const url = new URL(
`proxy/analytics/${this.controlPlaneProxyInfo?.workspaceId}/capture`,
`proxy/analytics/${this.controlPlaneProxyInfo.workspaceId}/capture`,
this.controlPlaneProxyInfo?.controlPlaneProxyUrl,
).toString();
void fetch(url, {

View file

@ -0,0 +1,713 @@
import { findSearchMatch, SearchMatchResult } from "./findSearchMatch";
/**
* Helper function to perform a replacement using the match result
* This simulates what the actual replacement tool would do
*/
function performReplacement(
fileContent: string,
match: SearchMatchResult,
replacement: string,
): string {
return (
fileContent.substring(0, match.startIndex) +
replacement +
fileContent.substring(match.endIndex)
);
}
/**
* Helper function to test a specific strategy by crafting inputs that
* will fail all previous strategies
*/
function testSpecificStrategy(
fileContent: string,
searchContent: string,
expectedStrategy: string,
): SearchMatchResult | null {
const result = findSearchMatch(fileContent, searchContent);
if (result && result.strategyName !== expectedStrategy) {
throw new Error(
`Expected strategy ${expectedStrategy} but got ${result.strategyName}`,
);
}
return result;
}
/**
* Helper function to verify that a match result correctly identifies
* the intended content and replacement works properly
*/
function verifyMatchAndReplacement(
fileContent: string,
searchContent: string,
expectedMatchedText: string,
replacementText: string,
expectedResult: string,
): void {
const match = findSearchMatch(fileContent, searchContent);
if (!match) {
throw new Error("No match found");
}
// Verify the match captures the expected text
const actualMatchedText = fileContent.substring(
match.startIndex,
match.endIndex,
);
expect(actualMatchedText).toBe(expectedMatchedText);
// Verify replacement works correctly
const result = performReplacement(fileContent, match, replacementText);
expect(result).toBe(expectedResult);
}
describe("Strategy-specific tests", () => {
describe("exactMatch strategy", () => {
it("should handle exact match at various positions", () => {
const testCases = [
{
name: "at start",
fileContent: "abc def ghi",
searchContent: "abc",
expectedStart: 0,
expectedEnd: 3,
},
{
name: "in middle",
fileContent: "abc def ghi",
searchContent: "def",
expectedStart: 4,
expectedEnd: 7,
},
{
name: "at end",
fileContent: "abc def ghi",
searchContent: "ghi",
expectedStart: 8,
expectedEnd: 11,
},
{
name: "entire content",
fileContent: "abc def ghi",
searchContent: "abc def ghi",
expectedStart: 0,
expectedEnd: 11,
},
];
testCases.forEach(
({ name, fileContent, searchContent, expectedStart, expectedEnd }) => {
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(expectedStart);
expect(result!.endIndex).toBe(expectedEnd);
// Verify the matched content
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
},
);
});
it("should handle multiline exact matches", () => {
const fileContent = `line1
line2
line3
line4`;
const searchContent = `line2
line3`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(6); // After "line1\n"
expect(result!.endIndex).toBe(17); // End of "line3"
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should handle content with special characters", () => {
const fileContent = `const regex = /[a-z]+/gi;
const str = "Hello, World!";
const result = str.match(regex);`;
const searchContent = `const str = "Hello, World!";`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should verify replacement works correctly for exact matches", () => {
verifyMatchAndReplacement(
"const a = 1;\nconst b = 2;\nconst c = 3;",
"const b = 2;",
"const b = 2;",
"const b = 42;",
"const a = 1;\nconst b = 42;\nconst c = 3;",
);
});
it("should handle Windows-style line endings", () => {
const fileContent = "line1\r\nline2\r\nline3";
const searchContent = "line2";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(7); // After "line1\r\n"
expect(result!.endIndex).toBe(12); // End of "line2"
});
it("should handle mixed line endings", () => {
const fileContent = "line1\nline2\r\nline3\rline4";
const searchContent = "line2\r\nline3";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
});
describe("trimmedMatch strategy", () => {
it("should match when only whitespace differs at edges", () => {
const testCases = [
{
name: "leading spaces",
fileContent: "abc\n def\nghi",
searchContent: " def",
trimmedSearch: "def",
},
{
name: "trailing spaces",
fileContent: "abc\ndef \nghi",
searchContent: "def ",
trimmedSearch: "def",
},
{
name: "both leading and trailing",
fileContent: "abc\n def \nghi",
searchContent: " def ",
trimmedSearch: "def",
},
{
name: "tabs and spaces",
fileContent: "abc\n\t def \t\nghi",
searchContent: "\t def \t",
trimmedSearch: "def",
},
];
testCases.forEach(
({ name, fileContent, searchContent, trimmedSearch }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// For cases where exact match exists, it should be preferred
if (fileContent.indexOf(searchContent) !== -1) {
expect(result!.strategyName).toBe("exactMatch");
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
} else {
expect(result!.strategyName).toBe("trimmedMatch");
// The match should find the trimmed content with surrounding whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(trimmedSearch);
}
},
);
});
it("should handle multiline content with edge whitespace", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2; `;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used
expect(result!.strategyName).toBe("trimmedMatch");
});
it("should verify replacement with trimmed matches", () => {
const fileContent = "start\n targetContent \nend";
const searchContent = " targetContent ";
const replacement = "newContent";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("trimmedMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe("start\nnewContent\nend");
});
it("should handle edge case with only whitespace", () => {
const fileContent = " \n \n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find exact match since the content matches exactly
expect(result!.strategyName).toBe("exactMatch");
});
});
describe("whitespaceIgnoredMatch strategy", () => {
it("should match content with different indentation", () => {
const fileContent = `function test() {
const x = 1;
if (x > 0) {
return true;
}
}`;
const searchContent = `const x=1;
if(x>0){
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the match covers the intended code block
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("const x = 1");
expect(matchedContent).toContain("return true");
});
it("should handle complex whitespace variations", () => {
const testCases = [
{
name: "spaces vs tabs",
fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}",
searchContent: "if (condition) { return true; }",
},
{
name: "multiple spaces collapsed",
fileContent: "const result = calculate( x , y );",
searchContent: "const result=calculate(x,y);",
},
{
name: "newlines removed",
fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}",
searchContent: "function test(){return 1;}",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the entire content is matched
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent.replace(/\s/g, "")).toBe(
searchContent.replace(/\s/g, ""),
);
});
});
it("should handle partial matches with whitespace differences", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
}`;
const searchContent = `constructor(name){this.name=name;this.items=[];}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// The match should cover the constructor method
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("constructor");
expect(matchedContent).toContain("this.items = []");
});
it("should verify replacement with whitespace-ignored matches", () => {
const fileContent = `function calculate ( a , b ) {
return a + b ;
}`;
const searchContent = `function calculate(a,b){return a+b;}`;
const replacement = `function calculate(x, y) {
return x + y;
}`;
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("whitespaceIgnoredMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge cases with empty content after whitespace removal", () => {
const fileContent = " \n\t\r\n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
// Since search content doesn't exist in file but trims to empty, should return emptySearch
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("emptySearch");
});
it("should match correctly when multiple potential matches exist", () => {
const fileContent = `const a=1;
const a = 1 ;
const a = 1;`;
const searchContent = "const a = 1;";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find the exact match first (third occurrence)
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(33); // After first two lines
});
});
describe("jaroWinklerFuzzyMatch strategy", () => {
it("should match similar code with variable name differences", () => {
const fileContent = `function calculateTotal(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
}
return sum;
}`;
const searchContent = `function calculateTotal(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should match code with minor typos", () => {
const testCases = [
{
name: "typo in function name",
fileContent: "function getUserName() { return this.name; }",
searchContent: "function getUserNaem() { return this.name; }",
},
{
name: "typo in variable",
fileContent: "const message = 'Hello World';",
searchContent: "const mesage = 'Hello World';",
},
{
name: "missing character",
fileContent: "console.log('Debug info');",
searchContent: "console.log('Debug nfo');",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
});
it("should not match when similarity is too low", () => {
const fileContent = "function add(a, b) { return a + b; }";
const searchContent =
"class Calculator { multiply(x, y) { return x * y; } }";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiline fuzzy matches", () => {
const fileContent = `if (userIsLoggedIn) {
showDashboard();
loadUserData();
}`;
const searchContent = `if (isUserLoggedIn) {
displayDashboard();
fetchUserData();
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should verify replacement with fuzzy matches", () => {
const fileContent = "const userName = 'John';";
const searchContent = "const usrName = 'John';"; // Typo in variable name
const replacement = "const userName = 'Jane';";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("jaroWinklerFuzzyMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge case with very short strings", () => {
const fileContent = "ab";
const searchContent = "ac";
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity on short strings
expect(result).toBeNull();
});
});
describe("Empty search content", () => {
it("should always return position 0 for empty search", () => {
const testCases = [
{ fileContent: "some content" },
{ fileContent: "" },
{ fileContent: "line1\nline2\nline3" },
{ fileContent: " spaces " },
];
testCases.forEach(({ fileContent }) => {
const result = findSearchMatch(fileContent, "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
it("should treat whitespace-only search as empty", () => {
const searchVariants = [" ", "\n\n", "\t\t", " \n\t "];
searchVariants.forEach((searchContent) => {
const result = findSearchMatch("test content", searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
});
describe("Strategy precedence", () => {
it("should always prefer exact match over other strategies", () => {
const fileContent = `exact match
exact match with spaces
exactmatch`;
// This should find exact match even though fuzzy would also work
const result = findSearchMatch(fileContent, "exact match");
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(0);
});
it("should prefer trimmed match over whitespace-ignored", () => {
const fileContent = " content ";
const searchContent = " content ";
// Should find exact match
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("exactMatch");
});
it("should prefer whitespace-ignored over fuzzy", () => {
const fileContent = "const x = 1;";
const searchContent = "const x=1;";
// Should use whitespace-ignored, not fuzzy
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("Replacement verification tests", () => {
it("should correctly replace content found by each strategy", () => {
const testCases = [
{
name: "exact match replacement",
fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;",
searchContent: "const b = 2;",
replacement: "const b = 42;",
expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;",
expectedStrategy: "exactMatch",
},
{
name: "trimmed match replacement",
fileContent: "start\n target \nend",
searchContent: " target ",
replacement: "replaced",
expectedResult: "start\nreplaced\nend",
expectedStrategy: "trimmedMatch",
},
{
name: "whitespace-ignored replacement",
fileContent: "if ( x > 0 ) { return true; }",
searchContent: "if(x>0){return true;}",
replacement: "if (x > 0) { return false; }",
expectedResult: "if (x > 0) { return false; }",
expectedStrategy: "whitespaceIgnoredMatch",
},
];
testCases.forEach(
({
name,
fileContent,
searchContent,
replacement,
expectedResult,
expectedStrategy,
}) => {
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe(expectedStrategy);
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(expectedResult);
},
);
});
it("should handle edge cases in replacement", () => {
// Empty replacement
verifyMatchAndReplacement(
"before target after",
"target",
"target",
"",
"before after",
);
// Replacement longer than original
verifyMatchAndReplacement(
"short",
"short",
"short",
"much longer replacement",
"much longer replacement",
);
// Multiline replacement
verifyMatchAndReplacement(
"single line",
"single",
"single",
"multi\nline\nreplacement",
"multi\nline\nreplacement line",
);
});
});
describe("Performance and edge cases", () => {
it("should handle very long content efficiently", () => {
const longContent = "x".repeat(10000) + "target" + "y".repeat(10000);
const result = findSearchMatch(longContent, "target");
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(10000);
expect(result!.endIndex).toBe(10006);
});
it("should handle unicode and special characters", () => {
const testCases = [
{
fileContent: "const emoji = '🚀🌟🎉';",
searchContent: "🚀🌟🎉",
},
{
fileContent: "const chinese = '你好世界';",
searchContent: "你好世界",
},
{
fileContent: "const regex = /\\d+/g;",
searchContent: "/\\d+/g",
},
];
testCases.forEach(({ fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(searchContent);
});
});
it("should handle null bytes and control characters", () => {
const fileContent = "before\x00null\x01byte\x02after";
const searchContent = "\x00null\x01byte\x02";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("exactMatch");
});
});
});

View file

@ -43,20 +43,48 @@ function exactMatch(
/**
* Trimmed content matching strategy
* Finds content where the search content (when trimmed) matches content in the file,
* and returns the span that includes the file content's whitespace
*/
function trimmedMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const trimmedSearchContent = searchContent.trim();
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedIndex !== -1) {
return {
startIndex: trimmedIndex,
endIndex: trimmedIndex + trimmedSearchContent.length,
};
// Don't apply if search content has no leading/trailing whitespace to trim
if (trimmedSearchContent === searchContent) {
return null;
}
return null;
// Don't match if trimmed content is empty
if (trimmedSearchContent === "") {
return null;
}
// Look for the trimmed content in the file
const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedContentIndex === -1) {
return null;
}
// Find the boundaries that include surrounding whitespace (but not newlines)
// Look backwards for horizontal whitespace (spaces and tabs)
let startIndex = trimmedContentIndex;
while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
startIndex--;
}
// Look forwards for horizontal whitespace (spaces and tabs)
let endIndex = trimmedContentIndex + trimmedSearchContent.length;
while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
endIndex++;
}
return {
startIndex,
endIndex,
};
}
/**
@ -298,10 +326,24 @@ export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
const trimmedSearchContent = searchContent.trim();
// Handle truly empty search content
if (searchContent === "") {
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Handle whitespace-only search content that trims to empty
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Empty search content matches the beginning of the file
// Check if the whitespace-only search content has an exact match first
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
strategyName: "exactMatch",
};
}
// If no exact match for whitespace-only content, treat as empty search
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}

6
core/index.d.ts vendored
View file

@ -1069,6 +1069,11 @@ export interface ToolExtras {
codeBaseIndexer?: CodebaseIndexer;
}
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export interface Tool {
type: "function";
function: {
@ -1089,6 +1094,7 @@ export interface Tool {
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
defaultToolPolicy?: ToolPolicy;
}
interface ToolChoice {

View file

@ -155,6 +155,24 @@ function llmCanGenerateInParallel(provider: string, model: string): boolean {
return PARALLEL_PROVIDERS.includes(provider);
}
function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
modelName: string,
): boolean {
return (
modelName.includes("gpt") ||
modelName.includes("command") ||
modelName.includes("aya") ||
modelName.includes("chat-bison") ||
modelName.includes("pplx") ||
modelName.includes("gemini") ||
modelName.includes("grok") ||
modelName.includes("moonshot") ||
modelName.includes("kimi") ||
modelName.includes("mercury") ||
/^o\d/.test(modelName)
);
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
@ -162,20 +180,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "codellama-70b";
}
if (
lower.includes("gpt") ||
lower.includes("command") ||
lower.includes("aya") ||
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini") ||
lower.includes("grok") ||
lower.includes("moonshot") ||
lower.includes("mercury") ||
/^o\d/.test(lower)
) {
if (isProviderHandlesTemplatingOrNoTemplateTypeRequired(lower)) {
return undefined;
}
if (lower.includes("llama3") || lower.includes("llama-3")) {
return "llama3";
}

View file

@ -9,6 +9,22 @@ import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
const errorMessages = {
invalid_request_error:
"There was an issue with the format or content of your request.",
authentication_error: "There's an issue with your API key.",
permission_error:
"Your API key does not have permission to use the specified resource.",
not_found_error: "The requested resource was not found.",
request_too_large:
"Request exceeds the maximum allowed number of bytes (32 MB limit).",
rate_limit_error: "Your account has hit a rate limit.",
api_error:
"An unexpected error has occurred internal to Anthropic's systems.",
overloaded_error:
"Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
};
class Anthropic extends BaseLLM {
static providerName = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
@ -183,9 +199,9 @@ class Anthropic extends BaseLLM {
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {
if (json.error?.type === "overloaded_error") {
if (json.error?.type in errorMessages) {
throw new Error(
"The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
errorMessages[json.error.type as keyof typeof errorMessages],
);
}
throw new Error(json.message);

View file

@ -132,7 +132,7 @@ const isFileInDirectory = (
* Checks if a rule is a root-level rule (.continue directory or no file path)
*/
const isRootLevelRule = (rule: RuleWithSource): boolean => {
return !rule.ruleFile || rule.ruleFile.startsWith(".continue/");
return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
};
/**

View file

@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
ruleFile: "/path/to/repo/.continue/rules.md",
// No restriction, should apply to all files
};
@ -212,7 +212,7 @@ describe("Rule policies", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
ruleFile: "/my/project/.continue/rules.md",
};
// Off policy should override even global rules

View file

@ -30,6 +30,11 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
).toBe(true);
});
it("should return true for Gemma models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/gemma")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/gemma3")).toBe(true);
});
it("should return true for O3 models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
});
@ -56,6 +61,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma3")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
});
});
@ -98,6 +104,11 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("o3-preview")).toBe(true);
});
it("should return true for Gemma models", () => {
expect(supportsFn("gemma")).toBe(true);
expect(supportsFn("gemma3")).toBe(true);
});
it("should return undefined for unsupported models", () => {
expect(supportsFn("gpt-3.5-turbo")).toBe(false);
expect(supportsFn("davinci")).toBe(false);
@ -106,6 +117,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should handle case insensitivity", () => {
expect(supportsFn("GPT-4-turbo")).toBe(true);
expect(supportsFn("O3-preview")).toBe(true);
expect(supportsFn("Gemma3")).toBe(true);
});
});

View file

@ -25,6 +25,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"o3",
"gemini",
"claude-opus-4",
"gemma",
].some((part) => model.toLowerCase().startsWith(part));
},
anthropic: (model) => {
@ -65,6 +66,12 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
if (model.toLowerCase().includes("exaone")) {
return true;
}
// https://ai.google.dev/gemma/docs/capabilities/function-calling
if (model.toLowerCase().startsWith("gemma")) {
return true;
}
// firworks-ai https://docs.fireworks.ai/guides/function-calling
if (model.startsWith("accounts/fireworks/models/")) {
switch (model.substring(26)) {
@ -291,6 +298,22 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
}
}
return false;
},
moonshot: (model) => {
// support moonshot models
// https://platform.moonshot.ai/docs/pricing/chat#concepts
if (
model.toLowerCase().startsWith("kimi") &&
model.toLowerCase() !== "kimi-thinking-preview"
) {
return true;
}
if (model.toLowerCase().startsWith("moonshot")) {
return true;
}
return false;
},
};

View file

@ -52,7 +52,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
newSessionWithPrompt: [{ prompt: string }, void];
userInput: [{ input: string }, void];
focusContinueInput: [undefined, void];

View file

@ -27,6 +27,7 @@ export const codebaseTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CodebaseTool,
`To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,

View file

@ -31,6 +31,7 @@ export const createNewFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateNewFile,
`To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,

View file

@ -60,6 +60,7 @@ export const createRuleBlock: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateRuleBlock,
`Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.

View file

@ -40,6 +40,7 @@ export const editFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.EditExistingFile,
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with

View file

@ -26,6 +26,7 @@ export const fetchUrlContentTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FetchUrlContent,
`To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,

View file

@ -26,6 +26,7 @@ export const globSearchTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FileGlobSearch,
`To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,

View file

@ -27,6 +27,7 @@ export const grepSearchTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.GrepSearch,
`To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,

View file

@ -0,0 +1,17 @@
export { codebaseTool } from "./codebaseTool";
export { createNewFileTool } from "./createNewFile";
export { createRuleBlock } from "./createRuleBlock";
export { editFileTool } from "./editFile";
export { fetchUrlContentTool } from "./fetchUrlContent";
export { globSearchTool } from "./globSearch";
export { grepSearchTool } from "./grepSearch";
export { lsTool } from "./ls";
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
export { readFileTool } from "./readFile";
export { requestRuleTool } from "./requestRule";
export { runTerminalCommandTool } from "./runTerminalCommand";
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
export { searchWebTool } from "./searchWeb";
export { viewDiffTool } from "./viewDiff";
export { viewRepoMapTool } from "./viewRepoMap";
export { viewSubdirectoryTool } from "./viewSubdirectory";

View file

@ -31,6 +31,7 @@ export const lsTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.LSTool,
`To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,

View file

@ -20,6 +20,7 @@ export const readCurrentlyOpenFileTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadCurrentlyOpenFile,
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.

View file

@ -27,6 +27,7 @@ export const readFileTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadFile,
`To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,

View file

@ -60,6 +60,7 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
defaultToolPolicy: "disabled",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),

View file

@ -56,6 +56,7 @@ export const runTerminalCommandTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RunTerminalCommand,
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool

View file

@ -11,9 +11,6 @@ export interface SearchAndReplaceInFileArgs {
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
const SEARCH_AND_REPLACE_TOOL_DESCRIPTION = `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`;
const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION =
"The path of the file to modify, relative to the root of the workspace.";
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
[exact content to find]
=======
@ -40,7 +37,8 @@ const SEARCH_AND_REPLACE_RULES = `Critical rules:
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
6. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section`;
* To delete code: Use empty REPLACE section
7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`;
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
@ -73,14 +71,14 @@ export const searchAndReplaceInFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION,
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION,
description: `The path of the file to modify, relative to the root of the workspace.`,
},
diffs: {
type: "array",
@ -94,7 +92,7 @@ export const searchAndReplaceInFileTool: Tool = {
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchAndReplaceInFile,
`To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
`To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
Each block should follow this format:
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
@ -106,18 +104,11 @@ ${SEARCH_AND_REPLACE_RULES}
[
"diffs",
`[
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE",
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE"
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}",
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}"
]`,
],
],
),
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -26,6 +26,7 @@ export const searchWebTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchWeb,
`To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,

View file

@ -0,0 +1,54 @@
import { describe, expect, it } from "@jest/globals";
import { ConfigDependentToolParams, GetTool, Tool } from "../..";
import * as toolDefinitions from "./index";
describe("Tool Definitions", () => {
// Mock params for tools that need them
const mockParams: ConfigDependentToolParams = {
rules: [],
enableExperimentalTools: false,
};
// Helper function to get the actual tool object
const getToolObject = (toolDefinition: Tool | GetTool): Tool => {
if (typeof toolDefinition === "function") {
return toolDefinition(mockParams);
}
return toolDefinition;
};
it("should have all required parameters defined in properties for each tool", () => {
const exportedTools = Object.values(toolDefinitions);
exportedTools.forEach((toolDefinition) => {
const tool = getToolObject(toolDefinition);
// Each tool should have the required structure
expect(tool).toHaveProperty("type", "function");
expect(tool).toHaveProperty("function");
expect(tool.function).toHaveProperty("parameters");
const parameters = tool.function.parameters;
// If there are required parameters, they should be defined in properties
if (
parameters &&
parameters.required &&
Array.isArray(parameters.required)
) {
expect(parameters).toHaveProperty("properties");
expect(typeof parameters.properties).toBe("object");
// Check each required parameter is defined in properties
parameters.required.forEach((requiredParam: string) => {
expect(parameters.properties).toHaveProperty(requiredParam);
// Each property should have at least a type
const property = parameters.properties[requiredParam];
expect(property).toHaveProperty("type");
expect(typeof property.type).toBe("string");
});
}
});
});
});

View file

@ -20,6 +20,7 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithoutPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewDiff,
`To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,

View file

@ -20,6 +20,7 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewRepoMap,
`To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,

View file

@ -26,6 +26,7 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewSubdirectory,
`To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,

View file

@ -1,50 +1,38 @@
import { ConfigDependentToolParams, IDE, Tool } from "..";
import { codebaseTool } from "./definitions/codebaseTool";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/ls";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { requestRuleTool } from "./definitions/requestRule";
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
import { searchAndReplaceInFileTool } from "./definitions/searchAndReplaceInFile";
import { searchWebTool } from "./definitions/searchWeb";
import { viewDiffTool } from "./definitions/viewDiff";
import { viewRepoMapTool } from "./definitions/viewRepoMap";
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
const getLocalOnlyToolDefinitions = () => [grepSearchTool];
const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool];
const getBaseToolDefinitions = () => [
readFileTool,
createNewFileTool,
runTerminalCommandTool,
globSearchTool,
searchWebTool,
viewDiffTool,
readCurrentlyOpenFileTool,
lsTool,
createRuleBlock,
fetchUrlContentTool,
toolDefinitions.readFileTool,
toolDefinitions.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
toolDefinitions.searchWebTool,
toolDefinitions.viewDiffTool,
toolDefinitions.readCurrentlyOpenFileTool,
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
];
export const getConfigDependentToolDefinitions = (
params: ConfigDependentToolParams,
): Tool[] => [
requestRuleTool(params),
toolDefinitions.requestRuleTool(params),
// Search and replace is now generally available
searchAndReplaceInFileTool,
toolDefinitions.searchAndReplaceInFileTool,
// Keep edit file tool available for models that need it
editFileTool,
toolDefinitions.editFileTool,
...(params.enableExperimentalTools
? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
? [
toolDefinitions.viewRepoMapTool,
toolDefinitions.viewSubdirectoryTool,
toolDefinitions.codebaseTool,
]
: []),
];

505
docs/c15t-cookie-banner.js Normal file
View file

@ -0,0 +1,505 @@
// Cookie Banner Implementation for Continue Documentation
// This script implements a cookie consent banner in offline mode
(function () {
"use strict";
// Configuration
const COOKIE_NAME = "continue_cookie_consent";
const COOKIE_EXPIRY_DAYS = 365;
// Default consent state
const defaultConsent = {
necessary: true,
analytics: false,
marketing: false,
};
// Wait for the page to fully load
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initializeCookieBanner);
} else {
initializeCookieBanner();
}
function initializeCookieBanner() {
// Check if banner is already initialized
if (window.cookieBannerInitialized) {
return;
}
window.cookieBannerInitialized = true;
// Get stored consent
const storedConsent = getStoredConsent();
// Apply stored consent or show banner
if (storedConsent) {
applyConsent(storedConsent);
} else {
// Set default consent (deny all except necessary)
applyConsent(defaultConsent);
showCookieBanner();
}
}
function getStoredConsent() {
const cookie = document.cookie
.split(";")
.find((c) => c.trim().startsWith(COOKIE_NAME + "="));
if (cookie) {
try {
return JSON.parse(decodeURIComponent(cookie.split("=")[1]));
} catch (e) {
console.error("Failed to parse consent cookie:", e);
}
}
return null;
}
function setConsentCookie(consent) {
const date = new Date();
date.setTime(date.getTime() + COOKIE_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
const expires = "expires=" + date.toUTCString();
document.cookie =
COOKIE_NAME +
"=" +
encodeURIComponent(JSON.stringify(consent)) +
";" +
expires +
";path=/;SameSite=Lax";
}
function applyConsent(consent) {
// Apply Google Analytics consent
if (window.gtag) {
window.gtag("consent", "update", {
analytics_storage: consent.analytics ? "granted" : "denied",
ad_user_data: consent.marketing ? "granted" : "denied",
ad_personalization: consent.marketing ? "granted" : "denied",
});
}
// Apply PostHog consent
if (window.posthog) {
if (consent.analytics) {
window.posthog.opt_in_capturing();
} else {
window.posthog.opt_out_capturing();
}
}
// Store consent
setConsentCookie(consent);
}
function showCookieBanner() {
// Create banner (no overlay - users can continue browsing)
const banner = document.createElement("div");
banner.className = "cookie-banner";
banner.innerHTML = `
<div class="cookie-banner-content">
<div class="cookie-banner-text">
<p>We use cookies to enhance your experience on our documentation site. By continuing to browse, you agree to our use of cookies.</p>
</div>
<div class="cookie-banner-actions">
<button class="cookie-btn cookie-btn-secondary" onclick="window.showPreferencesDialog()">Manage Preferences</button>
<button class="cookie-btn cookie-btn-primary" onclick="window.acceptAllCookies()">Accept All</button>
</div>
</div>
`;
document.body.appendChild(banner);
// Make functions globally available
window.acceptAllCookies = function () {
const consent = {
necessary: true,
analytics: true,
marketing: true,
};
applyConsent(consent);
hideCookieBanner();
};
window.showPreferencesDialog = showPreferencesDialog;
}
function hideCookieBanner() {
const banner = document.querySelector(".cookie-banner");
if (banner) banner.remove();
}
function showPreferencesDialog() {
hideCookieBanner();
const currentConsent = getStoredConsent() || defaultConsent;
// Create dialog overlay
const dialogOverlay = document.createElement("div");
dialogOverlay.className = "cookie-dialog-overlay";
dialogOverlay.onclick = function (e) {
if (e.target === dialogOverlay) {
hidePreferencesDialog();
}
};
// Create dialog
const dialog = document.createElement("div");
dialog.className = "cookie-dialog";
dialog.innerHTML = `
<div class="cookie-dialog-header">
<h2>Cookie Preferences</h2>
<button class="cookie-dialog-close" onclick="window.hidePreferencesDialog()">×</button>
</div>
<div class="cookie-dialog-body">
<p>We use cookies and similar technologies to help personalize content and offer a better experience. You can customize your preferences below:</p>
<div class="cookie-category">
<div class="cookie-category-header">
<label class="cookie-switch">
<input type="checkbox" id="cookie-necessary" checked disabled>
<span class="cookie-slider"></span>
</label>
<div class="cookie-category-info">
<h3>Necessary Cookies</h3>
<p>These cookies are essential for the website to function properly and cannot be disabled.</p>
</div>
</div>
</div>
<div class="cookie-category">
<div class="cookie-category-header">
<label class="cookie-switch">
<input type="checkbox" id="cookie-analytics" ${currentConsent.analytics ? "checked" : ""}>
<span class="cookie-slider"></span>
</label>
<div class="cookie-category-info">
<h3>Analytics Cookies</h3>
<p>These cookies help us understand how visitors interact with our website by collecting and reporting information anonymously.</p>
</div>
</div>
</div>
<div class="cookie-category">
<div class="cookie-category-header">
<label class="cookie-switch">
<input type="checkbox" id="cookie-marketing" ${currentConsent.marketing ? "checked" : ""}>
<span class="cookie-slider"></span>
</label>
<div class="cookie-category-info">
<h3>Identification Cookies</h3>
<p>These cookies help us understand how you use our documentation and allow us to recognize you across visits. We use this data to improve your experience and help you get the most value from our products.</p>
</div>
</div>
</div>
</div>
<div class="cookie-dialog-footer">
<button class="cookie-btn cookie-btn-secondary" onclick="window.rejectAllCookies()">Reject All</button>
<button class="cookie-btn cookie-btn-primary" onclick="window.savePreferences()">Save Preferences</button>
</div>
`;
dialogOverlay.appendChild(dialog);
document.body.appendChild(dialogOverlay);
// Make functions globally available
window.hidePreferencesDialog = hidePreferencesDialog;
window.rejectAllCookies = function () {
const consent = {
necessary: true,
analytics: false,
marketing: false,
};
applyConsent(consent);
hidePreferencesDialog();
};
window.savePreferences = function () {
const consent = {
necessary: true,
analytics: document.getElementById("cookie-analytics").checked,
marketing: document.getElementById("cookie-marketing").checked,
};
applyConsent(consent);
hidePreferencesDialog();
};
}
function hidePreferencesDialog() {
const dialogOverlay = document.querySelector(".cookie-dialog-overlay");
if (dialogOverlay) dialogOverlay.remove();
}
// Add styles
const style = document.createElement("style");
style.textContent = `
.cookie-banner {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: #1a1a1a;
color: #ffffff;
padding: 1.5rem;
z-index: 9999;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
.cookie-banner-content {
max-width: 1200px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 2rem;
flex-wrap: wrap;
}
.cookie-banner-text {
flex: 1;
min-width: 300px;
}
.cookie-banner-text p {
margin: 0;
font-size: 14px;
line-height: 1.5;
}
.cookie-banner-actions {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.cookie-btn {
padding: 0.5rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.cookie-btn-primary {
background: #6b7280;
color: #ffffff;
}
.cookie-btn-primary:hover {
background: #4b5563;
}
.cookie-btn-secondary {
background: transparent;
color: #ffffff;
border: 1px solid #6b7280;
}
.cookie-btn-secondary:hover {
background: #6b7280;
}
/* Dialog-specific button styles */
.cookie-dialog-footer .cookie-btn-secondary {
color: #6b7280;
border-color: #6b7280;
}
.cookie-dialog-footer .cookie-btn-secondary:hover {
color: #ffffff;
background: #6b7280;
}
.cookie-dialog-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 10000;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.cookie-dialog {
background: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
max-width: 600px;
width: 100%;
max-height: 90vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.cookie-dialog-header {
padding: 1.5rem;
border-bottom: 1px solid #e5e7eb;
display: flex;
align-items: center;
justify-content: space-between;
}
.cookie-dialog-header h2 {
margin: 0;
font-size: 1.5rem;
color: #1a1a1a;
}
.cookie-dialog-close {
background: none;
border: none;
font-size: 1.5rem;
color: #6b7280;
cursor: pointer;
padding: 0;
width: 2rem;
height: 2rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
transition: all 0.2s;
}
.cookie-dialog-close:hover {
background: #f3f4f6;
}
.cookie-dialog-body {
padding: 1.5rem;
overflow-y: auto;
flex: 1;
}
.cookie-dialog-body > p {
margin: 0 0 1.5rem 0;
color: #6b7280;
line-height: 1.5;
}
.cookie-category {
margin-bottom: 1.5rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid #e5e7eb;
}
.cookie-category:last-child {
margin-bottom: 0;
padding-bottom: 0;
border-bottom: none;
}
.cookie-category-header {
display: flex;
align-items: flex-start;
gap: 1rem;
}
.cookie-category-info {
flex: 1;
}
.cookie-category-info h3 {
margin: 0 0 0.5rem 0;
font-size: 1.1rem;
color: #1a1a1a;
}
.cookie-category-info p {
margin: 0;
color: #6b7280;
font-size: 14px;
line-height: 1.5;
}
.cookie-switch {
position: relative;
display: inline-block;
width: 48px;
height: 24px;
flex-shrink: 0;
}
.cookie-switch input {
opacity: 0;
width: 0;
height: 0;
}
.cookie-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #e5e7eb;
transition: .4s;
border-radius: 24px;
}
.cookie-slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
.cookie-switch input:checked + .cookie-slider {
background-color: #6b7280;
}
.cookie-switch input:checked + .cookie-slider:before {
transform: translateX(24px);
}
.cookie-switch input:disabled + .cookie-slider {
background-color: #9ca3af;
cursor: not-allowed;
}
.cookie-dialog-footer {
padding: 1.5rem;
border-top: 1px solid #e5e7eb;
display: flex;
justify-content: flex-end;
gap: 1rem;
}
@media (max-width: 640px) {
.cookie-banner-content {
flex-direction: column;
align-items: stretch;
}
.cookie-banner-actions {
justify-content: stretch;
}
.cookie-btn {
flex: 1;
}
.cookie-dialog {
margin: 1rem;
}
}
`;
document.head.appendChild(style);
})();

View file

@ -13,4 +13,4 @@ description: "Model Context Protocol servers provide specialized functionality:"
## Learn More
Learn more in the [MCP deep dive](/customization/mcp-tools), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.

View file

@ -0,0 +1,246 @@
---
title: Model Capabilities
description: Understanding and configuring model capabilities for tools and image support
keywords: [capabilities, tools, function calling, image input, config]
---
Continue needs to know what features your models support to provide the best experience. This guide explains how model capabilities work and how to configure them.
## What are Model Capabilities?
Model capabilities tell Continue what features a model supports:
- **`tool_use`** - Whether the model can use tools and functions
- **`image_input`** - Whether the model can process images
Without proper capability configuration, you may encounter issues like:
- Agent mode being unavailable (requires tools)
- Tools not working at all
- Image uploads being disabled
## How Continue Detects Capabilities
Continue uses a two-tier system for determining model capabilities:
### 1. Automatic Detection (Default)
Continue automatically detects capabilities based on your provider and model name. For example:
- **OpenAI**: GPT-4 and GPT-3.5 Turbo models support tools
- **Anthropic**: Claude 3.5+ models support both tools and images
- **Ollama**: Most models support tools, vision models support images
- **Google**: All Gemini models support function calling
This works well for popular models, but may not cover custom deployments or newer models.
For implementation details, see:
- [toolSupport.ts](https://github.com/continuedev/continue/blob/main/core/llm/toolSupport.ts) - Tool capability detection logic
- [@continuedev/llm-info](https://www.npmjs.com/package/@continuedev/llm-info) - Image support detection
### 2. Manual Configuration
You can add capabilities to models that Continue doesn't automatically detect in your `config.yaml`.
<Note>
You cannot override autodetection - you can only add capabilities. Continue will always use its built-in knowledge about your model in addition to any capabilities you specify.
</Note>
```yaml
models:
- name: my-custom-gpt4
provider: openai
apiBase: https://my-deployment.com/v1
model: gpt-4-custom
capabilities:
- tool_use
- image_input
```
## When to Add Capabilities
Add capabilities when:
1. **Using custom deployments** - Your API endpoint serves a model with different capabilities than the standard version
2. **Using newer models** - Continue doesn't yet recognize a newly released model
3. **Experiencing issues** - Autodetection isn't working correctly for your setup
4. **Using proxy services** - Some proxy services modify model capabilities
## Configuration Examples
### Basic Configuration
Add tool support for a model that Continue doesn't recognize:
```yaml
models:
- name: custom-model
provider: openai
model: my-fine-tuned-gpt4
capabilities:
- tool_use
```
<Info>
The `tool_use` capability is for native tool/function calling support. The
model must actually support tools for this to work.
</Info>
<Warning>
**Experimental**: System message tools are available as an experimental feature
for models without native tool support. These are not automatically used as a
fallback and must be explicitly configured. Most models are trained for native
tools, so system message tools may not work as well.
</Warning>
### Disable Capabilities
Explicitly set no capabilities (autodetection will still apply):
```yaml
models:
- name: limited-claude
provider: anthropic
model: claude-4.0-sonnet
capabilities: [] # Empty array doesn't disable autodetection
```
<Warning>
An empty capabilities array does not disable autodetection. Continue will
still detect and use the model's actual capabilities. To truly limit a model's
capabilities, you would need to use a model that doesn't support those
features.
</Warning>
### Multiple Capabilities
Enable both tools and image support:
```yaml
models:
- name: multimodal-gpt
provider: openai
model: gpt-4-vision-preview
capabilities:
- tool_use
- image_input
```
## Common Scenarios
Some providers and custom deployments may require explicit capability configuration:
- **OpenRouter**: May not preserve the original model's capabilities
- **Custom API endpoints**: May have different capabilities than standard models
- **Local models**: May need explicit capabilities if using non-standard model names
Example configuration:
```yaml
models:
- name: custom-deployment
provider: openai
apiBase: https://custom-api.company.com/v1
model: custom-gpt
capabilities:
- tool_use # If supports function calling
- image_input # If supports vision
```
## Troubleshooting
For troubleshooting capability-related issues like Agent mode being unavailable or tools not working, see the [Troubleshooting guide](/troubleshooting#agent-mode-is-unavailable-or-tools-arent-working).
## Best Practices
1. **Start with autodetection** - Only override if you experience issues
2. **Test after changes** - Verify tools and images work as expected
3. **Keep Continue updated** - Newer versions improve autodetection
Remember: Setting capabilities only adds to autodetection. Continue will still use its built-in knowledge about your model in addition to your specified capabilities.
## Model Capability Support
This matrix shows which models support tool use and image input capabilities. Continue auto-detects these capabilities, but you can override them if needed.
### OpenAI
| Model | Tool Use | Image Input | Context Window |
| :------------ | -------- | ----------- | -------------- |
| o3 | Yes | No | 128k |
| o3-mini | Yes | No | 128k |
| GPT-4o | Yes | Yes | 128k |
| GPT-4 Turbo | Yes | Yes | 128k |
| GPT-4 | Yes | No | 8k |
| GPT-3.5 Turbo | Yes | No | 16k |
### Anthropic
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| Claude 4 Sonnet | Yes | Yes | 200k |
| Claude 3.5 Sonnet | Yes | Yes | 200k |
| Claude 3.5 Haiku | Yes | Yes | 200k |
### Google
| Model | Tool Use | Image Input | Context Window |
| :--------------- | -------- | ----------- | -------------- |
| Gemini 2.5 Pro | Yes | Yes | 2M |
| Gemini 2.0 Flash | Yes | Yes | 1M |
### Mistral
| Model | Tool Use | Image Input | Context Window |
| :-------------- | -------- | ----------- | -------------- |
| Devstral Medium | Yes | No | 32k |
| Mistral | Yes | No | 32k |
### DeepSeek
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| DeepSeek V3 | Yes | No | 128k |
| DeepSeek Coder V2 | Yes | No | 128k |
| DeepSeek Chat | Yes | No | 64k |
### xAI
| Model | Tool Use | Image Input | Context Window |
| :----- | -------- | ----------- | -------------- |
| Grok 4 | Yes | Yes | 128k |
### Moonshot AI
| Model | Tool Use | Image Input | Context Window |
| :------ | -------- | ----------- | -------------- |
| Kimi K2 | Yes | Yes | 128k |
### Qwen
| Model | Tool Use | Image Input | Context Window |
| :---------------- | -------- | ----------- | -------------- |
| Qwen Coder 3 480B | Yes | No | 128k |
### Ollama (Local Models)
| Model | Tool Use | Image Input | Context Window |
| :------------- | -------- | ----------- | -------------- |
| Qwen 3 Coder | Yes | No | 32k |
| Devstral Small | Yes | No | 32k |
| Llama 3.1 | Yes | No | 128k |
| Llama 3 | Yes | No | 8k |
| Mistral | Yes | No | 32k |
| Codestral | Yes | No | 32k |
| Gemma 3 4B | Yes | No | 8k |
### Notes
- **Tool Use**: Function calling support (tools are required for Agent mode)
- **Image Input**: Processing images
- **Context Window**: Maximum number of tokens the model can process in a single request
---
**Is your model missing or incorrect?** Help improve this documentation! You can edit this page on GitHub using the link below.

View file

@ -4,13 +4,17 @@ title: "LM Studio"
[LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class:
## Chat model
We recommend configuring **Llama3.1 8B** as your chat model.
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: LM Studio
- name: Llama3.1 8B Instruct
provider: lmstudio
model: llama2-7b
model: meta-llama-3.1-8b-instruct
```
</Tab>
<Tab title="JSON">
@ -18,9 +22,9 @@ title: "LM Studio"
{
"models": [
{
"title": "LM Studio",
"title": "Llama3.1 8B Instruct",
"provider": "lmstudio",
"model": "llama2-7b"
"model": "meta-llama-3.1-8b-instruct"
}
]
}
@ -28,7 +32,7 @@ title: "LM Studio"
</Tab>
</Tabs>
### Embeddings model
## Embeddings model
LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models)
@ -63,21 +67,24 @@ To configure a remote instance of LM Studio, add the `"apiBase"` property to you
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Nomic Embed Text
- name: Llama3.1 8B Instruct
provider: lmstudio
model: nomic-ai/nomic-embed-text-v1.5-GGUF
roles:
- embed
model: meta-llama-3.1-8b-instruct
apiBase: http://<MY ENDPOINT>/v1
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"embeddingsProvider": {
"provider": "lmstudio",
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
{
"models": [
{
"title": "Llama3.1 8B Instruct",
"provider": "lmstudio",
"model": "meta-llama-3.1-8b-instruct",
"apiBase": "http://<MY ENDPOINT>/v1"
}
]
}
}
```
</Tab>
</Tabs>

View file

@ -71,3 +71,50 @@ For example, to prevent extra long prompts from being compressed, you can explic
</Tabs>
Learn more about available settings [here](https://openrouter.ai/docs).
## Model Capabilities
OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support.
<Info>
Continue automatically uses system message tools for models that don't support native function calling, so Agent mode should work even without explicit capability configuration. However, you can still override capabilities if needed.
</Info>
If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Claude via OpenRouter
provider: openrouter
model: anthropic/claude-3.5-sonnet
apiBase: https://openrouter.ai/api/v1
apiKey: <YOUR_OPEN_ROUTER_API_KEY>
capabilities:
- tool_use # Enable function calling for Agent mode
- image_input # Enable image upload support
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Claude via OpenRouter",
"provider": "openrouter",
"model": "anthropic/claude-3.5-sonnet",
"apiBase": "https://openrouter.ai/api/v1",
"apiKey": "<YOUR_OPEN_ROUTER_API_KEY>",
"capabilities": {
"tools": true,
"uploadImage": true
}
}
]
}
```
</Tab>
</Tabs>
Note: Not all models support function calling. Check the [OpenRouter models page](https://openrouter.ai/models) for specific model capabilities.

View file

@ -123,3 +123,42 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m
```
</Tab>
</Tabs>
## Model Capabilities
Ollama models usually have their capabilities auto-detected correctly. However, if you're using custom model names or experiencing issues with tools/images not working, you can explicitly set capabilities:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Custom Vision Model
provider: ollama
model: my-custom-llava
capabilities:
- tool_use # Enable if your model supports function calling
- image_input # Enable for vision models like llava
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Custom Vision Model",
"provider": "ollama",
"model": "my-custom-llava",
"capabilities": {
"tools": true,
"uploadImage": true
}
}
]
}
```
</Tab>
</Tabs>
<Note>
Most standard Ollama models (like llama3.1, mistral, etc.) support tool use by default. Vision models (like llava) also support image input.
</Note>

View file

@ -125,6 +125,7 @@
"customize/model-providers/more/together",
"customize/model-providers/more/lmstudio",
"customize/model-providers/more/llamacpp",
"customize/model-providers/more/llamastack",
"customize/model-providers/more/openrouter",
"customize/model-providers/more/huggingfaceinferenceapi",
"customize/model-providers/more/cohere",
@ -168,7 +169,8 @@
"customize/deep-dives/autocomplete",
"customize/deep-dives/development-data",
"customize/deep-dives/vscode-actions",
"customize/deep-dives/mcp"
"customize/deep-dives/mcp",
"customize/deep-dives/model-capabilities"
]
},
{
@ -704,10 +706,6 @@
"source": "/advanced/model-providers/more/flowise",
"destination": "/customize/model-providers/more/flowise"
},
{
"source": "/advanced/model-providers/more/llamastack",
"destination": "/customize/model-providers/llamastack"
},
{
"source": "/reference/Model Providers/huggingfaceinferenceapi",
"destination": "/customize/model-providers/more/huggingfaceinferenceapi"
@ -740,6 +738,14 @@
"source": "/advanced/model-providers/more/llamacpp",
"destination": "/customize/model-providers/more/llamacpp"
},
{
"source": "/reference/Model Providers/llamastack",
"destination": "/customize/model-providers/more/llamastack"
},
{
"source": "/advanced/model-providers/more/llamastack",
"destination": "/customize/model-providers/more/llamastack"
},
{
"source": "/reference/Model Providers/llamafile",
"destination": "/customize/model-providers/more/llamafile"

View file

@ -1,3 +1,37 @@
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling.
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup).
The recommended models and how to set them up can be found [here](/features/chat/model-setup).
## System Message Tools
<Info>
System message tools are experimental and may change in future releases.
</Info>
Continue implements an innovative approach called **system message tools** that ensures consistent tool functionality across all models, regardless of their native capabilities. This allows Agent mode to work seamlessly with a wider range of models and providers.
### How It Works
Instead of relying solely on native tool calling APIs (which vary between providers), Continue converts tools into XML format and includes them in the system message. The model generates tool calls as structured XML within its response, which Continue then parses and executes. This approach provides:
- **Universal compatibility** - Any model capable of following instructions can use tools, not just those with native tool support
- **Consistent behavior** - Tool calls work identically across OpenAI, Anthropic, local models, and others
- **Better reliability** - Models that struggle with native tools often perform better with system message tools
- **Seamless switching** - Change between providers without modifying your workflow
### Recommended Models
For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
**Premium Models:**
- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
- **GPT-4** models (OpenAI) - Excellent native tool support
- **DeepSeek** models - Strong performance with competitive pricing
**Local Models:**
While more limited in capabilities, these models can work with system message tools:
- Qwen2.5-Coder 32B - Best local option for Agent mode
- Devstral 27B - Good for code-specific tasks
- Smaller models (7B-13B) - May struggle with complex tool interactions
### Configuration
Agent mode automatically determines whether to use native or system message tools based on the model's capabilities. No additional configuration is required - simply select your model and Continue handles the rest.

View file

@ -43,3 +43,7 @@ This model provides good suggestions while keeping your code completely private.
## Need Help?
If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete).
## Model Compatibility
To see a complete list of models and their capabilities, visit our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -97,4 +97,8 @@ Their limited tool calling and reasoning capabilities will make it challenging t
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
3. Click `Reload config` in the assistant selector in the Continue IDE extension
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
## Model Compatibility
To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -10,3 +10,7 @@ We also recommend setting up an Apply model for the best Edit experience.
- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
## Model Compatibility
For a complete overview of which models support various features, see our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).

View file

@ -84,3 +84,9 @@ cn --ask Bash(curl*)
# Never use the Fetch tool
cn --exclude Fetch
```
## Troubleshooting
Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`.
If you have feedback on the alpha, please [share in our Discord](https://discord.com/invite/EfJEfdFnDQ).

View file

@ -24,13 +24,13 @@ Learn more in the [@Docs context provider documentation](/customize/context/docu
Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub.
Learn more in the [MCP deep dive](/customization/mcp-tools), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
## Rules
Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub.
Learn more in the [rules deep dive](/customization/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
## Prompts

2583
docs/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -14,5 +14,8 @@
"type": "commonjs",
"devDependencies": {
"mintlify": "^4.2.3"
},
"dependencies": {
"@c15t/react": "^1.4.4"
}
}

View file

@ -175,7 +175,11 @@ The `models` section defines the language models used in your configuration. Mod
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include:
- `tool_use`: Enables function/tool calling support (required for Agent mode)
- `image_input`: Enables image upload and processing support
Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.

View file

@ -135,6 +135,64 @@ If you are having persistent errors with indexing, our recommendation is to rebu
This can be accomplished using the following command: `Continue: Rebuild codebase index`.
### Agent mode is unavailable or tools aren't working
If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues.
<Info>
Continue uses system message tools as a fallback for models without native tool support, so most models should work with Agent mode automatically.
</Info>
#### Check if your model has tool support
1. Not all models support native tool/function calling, but Continue will automatically use system message tools as a fallback
2. Try adding `capabilities: ["tool_use"]` to your model config to force tool support
3. Verify your provider supports function calling or that system message tools are working correctly
#### Tools Not Working
If tools aren't being called:
1. Ensure `tool_use` is in your capabilities
2. Check that your API endpoint actually supports function calling
3. Some providers may use different function calling formats
#### Images Not Uploading
If you can't upload images:
1. Add `image_input` to capabilities
2. Ensure your model actually supports vision (e.g., gpt-4-vision, claude-3)
3. Check that your provider passes through image data
#### Add capabilities
If Continue's autodetection isn't working correctly, you can manually add capabilities in your `config.yaml`:
```yaml
models:
- name: my-model
provider: openai
model: gpt-4
capabilities:
- tool_use
- image_input
```
#### Verify with provider
Some proxy services (like OpenRouter) or custom deployments may not preserve tool calling capabilities. Check your provider's documentation.
#### Verifying Current Capabilities
To see what capabilities Continue detected for your model:
1. Check the mode selector tooltips - they indicate if tools are available
2. Try uploading an image - if disabled, the model lacks `image_input`
3. Check if Agent mode is available - requires `tool_use`
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for complete configuration details.
### Android Studio - "Nothing to show" in Chat
This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details.

View file

@ -287,6 +287,7 @@ describe("GUI Test", () => {
}).timeout(DEFAULT_TIMEOUT.MD);
it("should render tool call", async () => {
await GUIActions.toggleToolPolicy(view, "view_diff", 0);
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
await messageInput.sendKeys(Key.ENTER);

View file

@ -1,5 +1,3 @@
import * as path from "path";
import { getContinueRcPath, getTsConfigPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
@ -58,10 +56,10 @@ export async function activateExtension(context: vscode.ExtensionContext) {
const yamlMatcher = ".continue/**/*.yaml";
const yamlConfig = vscode.workspace.getConfiguration("yaml");
const newPath = path.join(
context.extension.extensionUri.fsPath,
const newPath = vscode.Uri.joinPath(
context.extension.extensionUri,
"config-yaml-schema.json",
);
).toString();
try {
await yamlConfig.update(

View file

@ -0,0 +1,24 @@
import styled, { keyframes } from "styled-components";
const ellipsisAnimation = keyframes`
0% { width: 0; }
33% { width: 0.33em; }
66% { width: 0.66em; }
100% { width: 1em; }
`;
export const AnimatedEllipsis = styled.span`
display: inline-block;
width: 1em; /* Fixed width to match the maximum animation width */
&::after {
content: "...";
display: inline-block;
overflow: hidden;
vertical-align: bottom;
animation: ${ellipsisAnimation} 2s infinite;
width: 0;
}
`;
export default AnimatedEllipsis;

View file

@ -2,7 +2,7 @@ import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useDeleteCompaction } from "../../util/compactConversation";

View file

@ -110,21 +110,18 @@ export default function StepContainer(props: StepContainerProps) {
{props.isLast && <ThinkingIndicator historyItem={props.item} />}
</div>
{shouldRenderResponseAction() && (
// We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete
{shouldRenderResponseAction() && !isStreaming && (
<div
className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`}
>
{!isStreaming && (
<ResponseActions
isTruncated={isTruncated}
onDelete={onDelete}
onContinueGeneration={onContinueGeneration}
index={props.index}
item={props.item}
isLast={props.isLast}
/>
)}
<ResponseActions
isTruncated={isTruncated}
onDelete={onDelete}
onContinueGeneration={onContinueGeneration}
index={props.index}
item={props.item}
isLast={props.isLast}
/>
</div>
)}

View file

@ -237,6 +237,13 @@ export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
key={tab.id}
isActive={tab.isActive}
onClick={() => handleTabClick(tab.id)}
onAuxClick={(e) => {
// Middle mouse button
if (e.button === 1) {
e.preventDefault();
handleTabClose(tab.id);
}
}}
>
<TabTitle>{tab.title}</TabTitle>
<CloseButton

View file

@ -1,4 +1,4 @@
import styled, { keyframes } from "styled-components";
import styled from "styled-components";
import { varWithFallback } from "../styles/theme";
export const defaultBorderRadius = "0.5rem";
@ -199,21 +199,3 @@ export const CloseButton = styled.button`
justify-content: center;
cursor: pointer;
`;
const ellipsisAnimation = keyframes`
0% { width: 0; }
33% { width: 0.33em; }
66% { width: 0.66em; }
100% { width: 1em; }
`;
export const AnimatedEllipsis = styled.span`
&::after {
content: "...";
display: inline-block;
overflow: hidden;
vertical-align: bottom;
animation: ${ellipsisAnimation} 2s infinite;
width: 0;
}
`;

View file

@ -35,4 +35,5 @@ export const GradientBorder = styled.div<{
display: flex;
flex-direction: row;
align-items: center;
margin-top: ${(props) => (props.loading ? "8px" : "")};
`;

View file

@ -1,4 +1,4 @@
import { AnimatedEllipsis } from "../../..";
import { AnimatedEllipsis } from "../../../AnimatedEllipsis";
export function GeneratingIndicator({
text = "Generating",

View file

@ -189,7 +189,7 @@ describe("processEditorContent", () => {
expect(result.parts).toEqual([
{
type: "text",
text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n",
text: "Check this code:\n\n```js example.js (1-1)\nfunction test() {\n return 'hello';\n}\n```\n",
},
]);
expect(result.selectedCode).toHaveLength(1);
@ -347,7 +347,7 @@ describe("processEditorContent", () => {
expect(result.parts).toEqual([
{
type: "text",
text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?",
text: "Please explain this code and also check @related\n\n```ts script.ts (1-1)\nconst x = 42;\n```\n\nWhat does this constant do?",
},
{
type: "imageUrl",

View file

@ -96,7 +96,7 @@ export function processEditorContent(editorState: JSONContent) {
rif.filepath,
window.workspacePaths ?? [],
);
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename} (${rif.range.start.line + 1}-${rif.range.end.line + 1})\n${contextItem.content}\n\`\`\`\n`;
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText;

View file

@ -3,13 +3,13 @@ import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { getUriPathBasename } from "core/util/uri";
import { ComponentType, useContext, useMemo } from "react";
import { AnimatedEllipsis } from "../..";
import {
IdeMessengerContext,
IIdeMessenger,
} from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { selectIsGatheringContext } from "../../../redux/slices/sessionSlice";
import { AnimatedEllipsis } from "../../AnimatedEllipsis";
import FileIcon from "../../FileIcon";
import SafeImg from "../../SafeImg";
import ToggleDiv from "../../ToggleDiv";

View file

@ -4,8 +4,10 @@ import { ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useEffect, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscBackground } from "../..";
import { getFontSize } from "../../../util";
import { AnimatedEllipsis } from "../../AnimatedEllipsis";
import StyledMarkdownPreview from "../../StyledMarkdownPreview";
const SpoilerButton = styled.div`
@ -36,34 +38,11 @@ const ButtonContent = styled.div`
gap: 6px;
`;
export const ThinkingText = styled.span`
position: relative;
padding-right: 12px;
const ThinkingTextContainer = styled.span`
display: inline-block;
min-width: fit-content;
&:after {
content: "...";
position: absolute;
animation: ellipsis 1s steps(4, end) infinite;
width: 0px;
display: inline-block;
overflow: hidden;
}
@keyframes ellipsis {
0%,
100% {
width: 0px;
}
33% {
width: 8px;
}
66% {
width: 16px;
}
90% {
width: 24px;
}
}
padding-right: 1em; /* Reserve space for the ellipsis animation */
`;
const MarkdownWrapper = styled.div`
@ -120,12 +99,13 @@ function ThinkingBlockPeek({
className="flex items-center justify-start pl-2 text-xs text-gray-300"
data-testid="thinking-block-peek"
>
<SpoilerButton onClick={() => setOpen((prev) => !prev)}>
<SpoilerButton onClick={() => setOpen(!open)}>
<ButtonContent>
{inProgress ? (
<ThinkingText>
<span>
{redactedThinking ? "Redacted Thinking" : "Thinking"}
</ThinkingText>
<AnimatedEllipsis />
</span>
) : redactedThinking ? (
"Redacted Thinking"
) : (
@ -141,7 +121,6 @@ function ThinkingBlockPeek({
</ButtonContent>
</SpoilerButton>
</div>
<div
className={`ml-2 mt-2 overflow-y-auto transition-none duration-300 ease-in-out ${
open ? "mb-2 mt-5 opacity-100" : "max-h-0 border-0 opacity-0"

View file

@ -30,7 +30,6 @@ import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfter
import { store } from "../redux/store";
import { cancelStream } from "../redux/thunks/cancelStream";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
import { findToolCallById, logToolUsage } from "../redux/util";
import {
@ -220,16 +219,6 @@ function ParallelListeners() {
dispatch(setTTSActive(status));
});
// TODO - remove?
useWebviewListener("submitMessage", async (data) => {
void dispatch(
streamResponseThunk({
editorState: data.message,
modifiers: { useCodebase: false, noContext: true },
}),
);
});
useWebviewListener("addContextItem", async (data) => {
dispatch(
addContextItemsAtIndex({

View file

@ -1,5 +1,5 @@
import { IndexingProgressUpdate } from "core";
import { AnimatedEllipsis } from "../../../components";
import { AnimatedEllipsis } from "../../../components/AnimatedEllipsis";
export interface IndexingProgressTitleTextProps {
update: IndexingProgressUpdate;

View file

@ -10,7 +10,10 @@ import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump
import { waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { ChatMessage } from "core";
import { toggleToolSetting } from "../../../redux/slices/uiSlice";
import {
setToolPolicy,
toggleToolSetting,
} from "../../../redux/slices/uiSlice";
import {
getElementByTestId,
getElementByText,
@ -173,7 +176,12 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
addAndSelectMockLlm(store, ideMessenger);
// Enable automatic edit and yolo mode
store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile));
store.dispatch(
setToolPolicy({
toolName: BuiltInToolNames.EditExistingFile,
policy: "allowedWithoutPermission",
}),
);
triggerConfigUpdate({
store,
ideMessenger,

View file

@ -10,11 +10,18 @@ export const selectSlashCommandComboBoxInputs = createSelector(
(slashCommands) => {
return (
slashCommands?.map((cmd) => {
let content = cmd.prompt;
// For MCP prompts without content, show that it failed to load
if (cmd.source === "mcp-prompt" && !content) {
content = "[MCP Prompt - failed to load content during startup]";
}
return {
title: cmd.name,
description: cmd.description,
type: "slashCommand" as ComboBoxItemType,
content: cmd.prompt,
content: content,
} as ComboBoxItem;
}) || []
);

View file

@ -1,6 +1,7 @@
import { createSelector } from "@reduxjs/toolkit";
import { Tool } from "core";
import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { RootState } from "../store";
export const selectActiveTools = createSelector(
@ -14,11 +15,15 @@ export const selectActiveTools = createSelector(
if (mode === "chat") {
return [];
} else {
const enabledTools = tools.filter(
(tool) =>
policies[tool.function.name] !== "disabled" &&
groupPolicies[tool.group] !== "exclude",
);
const enabledTools = tools.filter((tool) => {
const toolPolicy =
policies[tool.function.name] ??
tool.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return (
toolPolicy !== "disabled" && groupPolicies[tool.group] !== "exclude"
);
});
if (mode === "plan") {
return enabledTools.filter(
(t) => t.group !== BUILT_IN_GROUP_NAME || t.readonly,

View file

@ -1,5 +1,5 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RuleWithSource, Tool } from "core";
import { RuleWithSource, Tool, ToolPolicy } from "core";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
@ -7,11 +7,6 @@ import {
} from "../../components/OnboardingCard";
import { getLocalStorage, LocalStorageKey } from "../../util/localStorage";
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export type RulePolicy = "on" | "off";
export type ToolGroupPolicy = "include" | "exclude";
@ -50,21 +45,7 @@ export const uiSlice = createSlice({
),
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {
[BuiltInToolNames.ReadFile]: "allowedWithoutPermission",
[BuiltInToolNames.EditExistingFile]: "allowedWithPermission",
[BuiltInToolNames.CreateNewFile]: "allowedWithPermission",
[BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission",
[BuiltInToolNames.GrepSearch]: "allowedWithoutPermission",
[BuiltInToolNames.FileGlobSearch]: "allowedWithoutPermission",
[BuiltInToolNames.SearchWeb]: "allowedWithoutPermission",
[BuiltInToolNames.FetchUrlContent]: "allowedWithPermission",
[BuiltInToolNames.ViewDiff]: "allowedWithoutPermission",
[BuiltInToolNames.LSTool]: "allowedWithoutPermission",
[BuiltInToolNames.CreateRuleBlock]: "allowedWithPermission",
[BuiltInToolNames.RequestRule]: "disabled",
[BuiltInToolNames.SearchAndReplaceInFile]: "allowedWithPermission",
},
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
@ -95,7 +76,7 @@ export const uiSlice = createSlice({
// Tools
addTool: (state, action: PayloadAction<Tool>) => {
state.toolSettings[action.payload.function.name] =
"allowedWithPermission";
action.payload.defaultToolPolicy ?? DEFAULT_TOOL_SETTING;
},
setToolPolicy: (
state,

View file

@ -1,9 +1,6 @@
import { ToolPolicy } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
clearToolPolicy,
setToolPolicy,
ToolPolicy,
} from "../redux/slices/uiSlice";
import { clearToolPolicy, setToolPolicy } from "../redux/slices/uiSlice";
import { AppDispatch } from "../redux/store";
const validPolicyValues: ToolPolicy[] = [

View file

@ -5,8 +5,8 @@
"tsc:watch:vscode": "tsc --project extensions/vscode/tsconfig.json --watch --noEmit --pretty",
"tsc:watch:core": "tsc --project core/tsconfig.json --watch --noEmit --pretty",
"tsc:watch:binary": "tsc --project binary/tsconfig.json --watch --noEmit --pretty",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore"
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore"
},
"devDependencies": {
"@typescript-eslint/parser": "^7.8.0",

View file

@ -80,10 +80,7 @@ export class ContinueHubClient implements IContinueHubClient {
const alwaysUseProxy = options.alwaysUseProxy ?? false;
try {
const urlObj = new URL(
organizationId ? "ide/list-assistants" : "ide/list-assistants",
this.apiBase,
);
const urlObj = new URL("ide/list-assistants", this.apiBase);
if (organizationId) {
urlObj.searchParams.set("organizationId", organizationId);
}

View file

@ -4645,6 +4645,19 @@
"node": ">=8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@ -5291,6 +5304,20 @@
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/duplexer2": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",
@ -5533,6 +5560,24 @@
"is-arrayish": "^0.2.1"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-module-lexer": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
@ -5540,6 +5585,33 @@
"dev": true,
"license": "MIT"
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.25.8",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.8.tgz",
@ -5898,12 +5970,15 @@
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@ -5995,8 +6070,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@ -6060,6 +6133,30 @@
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-package-type": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz",
@ -6070,6 +6167,19 @@
"node": ">=8.0.0"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/get-stream": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
@ -6211,6 +6321,18 @@
"node": ">=14"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
@ -6260,12 +6382,37 @@
"node": ">=8"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dev": true,
"peer": true,
"dependencies": {
"function-bind": "^1.1.2"
},
@ -7727,6 +7874,15 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/meow": {
"version": "13.2.0",
"resolved": "https://registry.npmjs.org/meow/-/meow-13.2.0.tgz",

View file

@ -55,6 +55,14 @@ export class AnthropicApi implements BaseLlmApi {
return cachingStrategy(cleanBody);
}
private maxTokensForModel(model: string): number {
if (model.includes("haiku")) {
return 8192;
}
return 32_000;
}
public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
let stop = undefined;
if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
@ -81,7 +89,7 @@ export class AnthropicApi implements BaseLlmApi {
: systemMessage,
top_p: oaiBody.top_p,
temperature: oaiBody.temperature,
max_tokens: oaiBody.max_tokens ?? 4096, // max_tokens is required
max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required
model: oaiBody.model,
stop_sequences: stop,
stream: oaiBody.stream,

View file

@ -59,6 +59,30 @@ describe("AnthropicCachingStrategies", () => {
const result = CACHING_STRATEGIES.systemOnly(body);
expect(result).toEqual(body);
});
it("should not add more than 5 cached messages", () => {
const body = {
system: [
{ text: "system message 1" },
{ text: "system message 2" },
{ text: "system message 3" },
{ text: "system message 4" },
{ text: "system message 5" },
],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemOnly(body);
expect(result.system).toEqual([
{ text: "system message 1", cache_control: { type: "ephemeral" } },
{ text: "system message 2", cache_control: { type: "ephemeral" } },
{ text: "system message 3", cache_control: { type: "ephemeral" } },
{ text: "system message 4", cache_control: { type: "ephemeral" } },
{ text: "system message 5" },
]);
expect(result.messages).toEqual(body.messages);
});
});
describe("systemAndToolsStrategy", () => {
@ -119,6 +143,30 @@ describe("AnthropicCachingStrategies", () => {
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result).toEqual(body);
});
it("should add only 4 cache controls in total to both system and tools", () => {
const body = {
system: [
{ text: "system message 1" },
{ text: "system message 2" },
{ text: "system message 3" },
{ text: "system message 4" },
],
tools: [{ name: "tool1" }, { name: "tool2" }],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result.system).toEqual([
{ text: "system message 1", cache_control: { type: "ephemeral" } },
{ text: "system message 2", cache_control: { type: "ephemeral" } },
{ text: "system message 3", cache_control: { type: "ephemeral" } },
{ text: "system message 4", cache_control: { type: "ephemeral" } },
]);
expect(result.tools).toEqual(body.tools);
expect(result.messages).toEqual(body.messages);
});
});
describe("optimizedStrategy", () => {
@ -203,6 +251,46 @@ describe("AnthropicCachingStrategies", () => {
]);
});
it("should add maximum 4 cache control blocks", () => {
const body = {
system: [{ text: "system message 1" }, { text: "system message 2" }],
tools: [{ name: "tool" }],
messages: [
{ content: "small content" },
{ content: "a".repeat(2100) },
{ content: "b".repeat(2100) },
{
content: [
{ type: "text", text: "c".repeat(2100) },
{ type: "image", data: "image" },
],
},
],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.system).toEqual([
{ text: "system message 1", cache_control: { type: "ephemeral" } },
{ text: "system message 2", cache_control: { type: "ephemeral" } },
]);
expect(result.tools).toEqual([
{ name: "tool", cache_control: { type: "ephemeral" } },
]);
expect(result.messages[0]).toEqual({ content: "small content" });
expect(result.messages[1]).toEqual({
content: [
{
type: "text",
text: "a".repeat(2100),
cache_control: { type: "ephemeral" },
},
],
});
expect(result.messages[2].content).toEqual(body.messages[2].content);
expect(result.messages[3].content).toEqual(body.messages[3].content);
});
it("should handle complex message structure", () => {
const body = {
system: [{ text: "system" }],

View file

@ -1,3 +1,5 @@
const MAX_CACHING_MESSAGES = 4;
// Caching strategy type - transforms a clean Anthropic body by adding cache_control
export type CachingStrategy = (anthropicBody: any) => any;
@ -9,13 +11,20 @@ const noCachingStrategy: CachingStrategy = (body) => body;
// Strategy 2: System Messages Only (Current Implementation)
const systemOnlyStrategy: CachingStrategy = (body) => {
let availableCacheMessages = MAX_CACHING_MESSAGES;
if (body.system && Array.isArray(body.system)) {
return {
...body,
system: body.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
})),
system: body.system.map((item: any) => {
if (availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...item,
cache_control: { type: "ephemeral" },
};
}
return item;
}),
};
}
return body;
@ -24,19 +33,27 @@ const systemOnlyStrategy: CachingStrategy = (body) => {
// Strategy 3: System and Tools (High Impact)
const systemAndToolsStrategy: CachingStrategy = (body) => {
const result = { ...body };
let availableCacheMessages = MAX_CACHING_MESSAGES;
// Cache system messages
if (result.system && Array.isArray(result.system)) {
result.system = result.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
}));
result.system = result.system.map((item: any) => {
if (availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...item,
cache_control: { type: "ephemeral" },
};
}
return item;
});
}
// Cache tool definitions
if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
result.tools = result.tools.map((tool: any, index: number) => {
if (index === result.tools.length - 1) {
if (index === result.tools.length - 1 && availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...tool,
cache_control: { type: "ephemeral" },
@ -52,19 +69,27 @@ const systemAndToolsStrategy: CachingStrategy = (body) => {
// Strategy 4: Optimized (Intelligent Caching)
const optimizedStrategy: CachingStrategy = (body) => {
const result = { ...body };
let availableCacheMessages = MAX_CACHING_MESSAGES;
// Always cache system messages
if (result.system && Array.isArray(result.system)) {
result.system = result.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
}));
result.system = result.system.map((item: any) => {
if (availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...item,
cache_control: { type: "ephemeral" },
};
}
return item;
});
}
// Cache tool definitions
if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
result.tools = result.tools.map((tool: any, index: number) => {
if (index === result.tools.length - 1) {
if (index === result.tools.length - 1 && availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...tool,
cache_control: { type: "ephemeral" },
@ -79,7 +104,8 @@ const optimizedStrategy: CachingStrategy = (body) => {
result.messages = result.messages.map((message: any) => {
if (message.content && typeof message.content === "string") {
const tokens = estimateTokenCount(message.content);
if (tokens > 500) {
if (tokens > 500 && availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...message,
content: [
@ -95,7 +121,8 @@ const optimizedStrategy: CachingStrategy = (body) => {
const updatedContent = message.content.map((item: any) => {
if (item.type === "text" && item.text) {
const tokens = estimateTokenCount(item.text);
if (tokens > 500) {
if (tokens > 500 && availableCacheMessages > 0) {
availableCacheMessages -= 1;
return {
...item,
cache_control: { type: "ephemeral" },

View file

@ -1,4 +1,4 @@
import { describe, test, vi, expect, afterEach } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import { runAdapterTest } from "./adapter-test-utils.js";
// Mock the fetch package
@ -53,7 +53,7 @@ describe("Anthropic Adapter Tests", () => {
messages: [{ role: "user", content: "hello" }],
system: undefined,
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
max_tokens: 32000,
stream: undefined,
},
},
@ -107,7 +107,7 @@ describe("Anthropic Adapter Tests", () => {
messages: [{ role: "user", content: "hello" }],
system: undefined,
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
max_tokens: 32000,
stream: true,
},
},
@ -168,7 +168,7 @@ describe("Anthropic Adapter Tests", () => {
},
],
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
max_tokens: 32000,
stream: true,
},
},