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

This commit is contained in:
Juan Calderon-Perez 2025-08-07 22:37:56 -04:00 • committed by GitHub
commit b0484fc375
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
72 changed files with 1112 additions and 654 deletions

View file

@ -1,9 +0,0 @@
---
name: Add Continue pun easter eggs
description: Adds an easter egg whenever the "continue" keyword
pattern: "continue"
---
Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
Do not add a comment if the use of "continue" is not in a code continue statement

View file

@ -9,10 +9,18 @@ on:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the JetBrains marketplace"
build_only:
description: "If true, only build the extension for the given channels, don't publish"
required: true
default: false
default: "true"
eap_channel:
description: "If true, build/publish the extension to the EAP channel"
required: true
default: "true"
stable_channel:
description: "If true, build/publish the extension to the Stable channel"
required: true
default: "true"
defaults:
run:
@ -37,50 +45,50 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
bump-version:
runs-on: ubuntu-latest
needs:
- check_release_name
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
# bump-version:
# runs-on: ubuntu-latest
# needs:
# - check_release_name
# if: github.event_name != 'workflow_dispatch' || github.event.inputs.eap_channel == 'true' || github.event.inputs.stable_channel == 'true'
# permissions:
# contents: write
# pull-requests: write
# steps:
# # 0. Setup git
# - name: Checkout
# uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
# - name: Set up Git
# run: |
# git config --local user.email "action@github.com"
# git config --local user.name "GitHub Action"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
# - name: Create PR branch
# run: |
# BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
# git checkout -b $BRANCH_NAME
# echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in gradle.properties
run: |
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
# - name: Bump version in gradle.properties
# run: |
# awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
# rm -rf tmp
# NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
# echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the JetBrains extension version after successful pre-release publication.
# - name: Create Pull Request
# uses: peter-evans/create-pull-request@v7
# with:
# token: ${{ secrets.CI_GITHUB_TOKEN }}
# commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
# title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
# body: |
# Automated PR to bump the JetBrains extension version after successful pre-release publication.
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
# branch: ${{ env.BRANCH_NAME }}
# base: main
# delete-branch: true
# Prepare and publish the plugin to JetBrains Marketplace repository
build:
@ -223,9 +231,30 @@ jobs:
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build the plugin if not publishing
- name: Build EAP Plugin (no publish)
if: github.event_name != 'release' && github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew buildPlugin --info --stacktrace
- name: Build Stable Plugin (no publish)
if: github.event_name != 'release' && github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew buildPlugin --info --stacktrace
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true')
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -235,7 +264,7 @@ jobs:
run: ./gradlew publishPlugin --info --stacktrace
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true')
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}

View file

@ -68,6 +68,7 @@ async function modelConfigToBaseLLM({
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
nextEdit: model.capabilities?.includes("next_edit"),
},
autocompleteOptions: model.autocompleteOptions,
};

6
core/index.d.ts vendored
View file

@ -1093,7 +1093,10 @@ export interface Tool {
faviconUrl?: string;
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
systemMessageDescription?: {
prefix: string;
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
}
@ -1138,6 +1141,7 @@ export interface BaseCompletionOptions {
export interface ModelCapability {
uploadImage?: boolean;
tools?: boolean;
nextEdit?: boolean;
}
export interface ModelDescription {

View file

@ -1,4 +1,5 @@
import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
import { NEXT_EDIT_MODELS } from "./constants.js";
import {
anthropicTemplateMessages,
@ -173,6 +174,34 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
);
}
// NOTE: When updating this list,
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.MODEL_1,
];
function modelSupportsNextEdit(
capabilities: ModelCapability | undefined,
model: string,
title: string | undefined,
): boolean {
if (capabilities?.nextEdit !== undefined) {
return capabilities.nextEdit;
}
const lower = model.toLowerCase();
if (
MODEL_SUPPORTS_NEXT_EDIT.some(
(modelName) => lower.includes(modelName) || title?.includes(modelName),
)
) {
return true;
}
return false;
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
@ -391,4 +420,5 @@ export {
autodetectTemplateType,
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsNextEdit,
};

View file

@ -1,5 +1,5 @@
import { expect, test } from "vitest";
import { autodetectTemplateType } from "./autodetect";
import { describe, expect, it, test } from "vitest";
import { autodetectTemplateType, modelSupportsNextEdit } from "./autodetect";
test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => {
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
@ -201,3 +201,137 @@ test("autodetectTemplateType handles models with mixed keywords", () => {
expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined
expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2
});
describe("modelSupportsNextEdit", () => {
describe("when capabilities.nextEdit is defined", () => {
it("should return true when capabilities.nextEdit is true", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
},
"any-model",
"Any Title",
),
).toBe(true);
});
it("should return false when capabilities.nextEdit is false", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"Mercury Coder",
),
).toBe(false);
});
it("should prioritize capabilities over model name matching", () => {
// Even though model name matches, capabilities should take precedence.
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"Mercury Coder",
),
).toBe(false);
});
});
describe("when capabilities.nextEdit is undefined", () => {
it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
expect(
modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
).toBe(true);
});
it("should return true for model-1", () => {
expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
});
it("should return true when model contains supported model name as substring", () => {
expect(
modelSupportsNextEdit(
undefined,
"provider/mercury-coder-nextedit-v2",
undefined,
),
).toBe(true);
});
it("should return true when title contains supported model name", () => {
expect(
modelSupportsNextEdit(
undefined,
"some-model",
"This is mercury-coder-nextedit model",
),
).toBe(true);
});
it("should return true when title contains model-1", () => {
expect(
modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
).toBe(true);
});
it("should return true for unsupported models that have capabilities explicitly set to true", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
},
"gpt-4",
"GPT-4 Model",
),
).toBe(true);
});
it("should return false for unsupported models", () => {
expect(modelSupportsNextEdit(undefined, "gpt-4", "GPT-4 Model")).toBe(
false,
);
});
it("should return false when model and title are both undefined/null", () => {
expect(modelSupportsNextEdit(undefined, "", undefined)).toBe(false);
});
it("should return false when model and title do not contain supported names", () => {
expect(
modelSupportsNextEdit(undefined, "claude-3", "Claude 3 Sonnet"),
).toBe(false);
});
});
describe("edge cases", () => {
it("should handle empty strings", () => {
expect(modelSupportsNextEdit(undefined, "", "")).toBe(false);
});
it("should handle undefined title gracefully", () => {
expect(
modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
).toBe(true);
});
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
).toBe(true);
});
it("should handle capabilities with other properties", () => {
expect(
modelSupportsNextEdit(
{
nextEdit: true,
uploadImage: false,
},
"unsupported-model",
undefined,
),
).toBe(true);
});
});
});

View file

@ -19,6 +19,11 @@ export enum LLMConfigurationStatuses {
MISSING_ENV_SECRET = "missing-env-secret",
}
export enum NEXT_EDIT_MODELS {
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
MODEL_1 = "model-1",
}
export {
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,

View file

@ -61,7 +61,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
If you need to use multiple tools, you can call call multiple read only tools simultaneously.
If you need to use multiple tools, you can call multiple read only tools simultaneously.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;

View file

@ -5,30 +5,30 @@ describe("OpenAI", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o1")).toBeTruthy();
expect(openai.isOSeriesModel("o3")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o4-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o3-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o1-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o1")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o3")).toBeTruthy();
// artificially correct samples for future models
expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
expect(openai.isOSeriesModel("o6")).toBeTruthy();
expect(openai.isOSeriesModel("o77")).toBeTruthy();
expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o5-mini")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o6")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o77")).toBeTruthy();
expect(openai.isOSeriesOrGpt5Model("o54-mini")).toBeTruthy();
});
test("should identify incorrect o-series models", () => {
const openai = new OpenAI({
model: "o3-mini",
});
expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-o4-mini")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-4.5")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("gpt-4.1")).toBeFalsy();
// artificially wrong samples
expect(openai.isOSeriesModel("os1")).toBeFalsy();
expect(openai.isOSeriesModel("so1")).toBeFalsy();
expect(openai.isOSeriesModel("ao31")).toBeFalsy();
expect(openai.isOSeriesModel("1os")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("os1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("so1")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("ao31")).toBeFalsy();
expect(openai.isOSeriesOrGpt5Model("1os")).toBeFalsy();
});
});

View file

@ -36,12 +36,12 @@ function isChatOnlyModel(model: string): boolean {
return model.startsWith("gpt") || model.startsWith("o");
}
const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => {
return messages?.map((message: any) => {
if (message?.role === "system") {
return {
...message,
role: "user",
role: "developer",
};
}
@ -77,8 +77,8 @@ class OpenAI extends BaseLLM {
return model;
}
public isOSeriesModel(model?: string): boolean {
return !!model && !!model.match(/^o[0-9]+/);
public isOSeriesOrGpt5Model(model?: string): boolean {
return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5"));
}
private isFireworksAiModel(model?: string): boolean {
@ -139,13 +139,13 @@ class OpenAI extends BaseLLM {
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isOSeriesModel(options.model)) {
if (this.isOSeriesOrGpt5Model(options.model)) {
// a) use max_completion_tokens instead of max_tokens
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
// b) don't support system message
finalOptions.messages = formatMessageForO1(finalOptions.messages);
finalOptions.messages = formatMessageForO1OrGpt5(finalOptions.messages);
}
if (options.model === "o1") {
@ -241,13 +241,13 @@ class OpenAI extends BaseLLM {
body.stop = body.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
if (this.isOSeriesModel(body.model)) {
if (this.isOSeriesOrGpt5Model(body.model)) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;
// b) don't support system message
body.messages = formatMessageForO1(body.messages);
body.messages = formatMessageForO1OrGpt5(body.messages);
}
if (body.model === "o1") {

View file

@ -54,26 +54,28 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
openai: (model) => {
const lower = model.toLowerCase();
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (
model.toLowerCase().startsWith("gpt-4") ||
model.toLowerCase().startsWith("o3")
lower.startsWith("gpt-4") ||
lower.startsWith("gpt-5") ||
lower.startsWith("o3")
) {
return true;
}
// LGAI EXAONE models expose an OpenAI-compatible API with tool
// calling support when served via frameworks like vLLM
if (model.toLowerCase().includes("exaone")) {
if (lower.includes("exaone")) {
return true;
}
if (model.toLowerCase().includes("gpt-oss")) {
if (lower.includes("gpt-oss")) {
return true;
}
// https://ai.google.dev/gemma/docs/capabilities/function-calling
if (model.toLowerCase().startsWith("gemma")) {
if (lower.startsWith("gemma")) {
return true;
}

View file

@ -30,6 +30,7 @@ import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { myersDiff } from "../diff/myers.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { replaceEscapedCharacters } from "../util/text.js";
@ -341,6 +342,14 @@ export class NextEditProvider {
return { token, startTime, helper: undefined };
}
// In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
// For other editors, this check should be done in their respective config reloaders.
// This is left for a final check.
if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
console.error(`${llm.model} is not capable of next edit.`);
return { token, startTime, helper: undefined };
}
if (llm.promptTemplates?.autocomplete) {
options.template = llm.promptTemplates.autocomplete as string;
}

View file

@ -30,15 +30,11 @@ import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
} from "./utils";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
type TemplateRenderer = (vars: TemplateVars) => string;
export type NextEditModelName =
| "mercury-coder-nextedit"
| "model-1"
| "this field is not used";
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
},
@ -46,13 +42,10 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
template:
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
},
"this field is not used": {
template: "NEXT_EDIT",
},
};
function templateRendererOfModel(
modelName: NextEditModelName,
modelName: NEXT_EDIT_MODELS,
): TemplateRenderer {
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
if (!template) {
@ -70,18 +63,7 @@ export async function renderPrompt(
helper: HelperVars,
ctx: any,
): Promise<PromptMetadata> {
let modelName = helper.modelName as NextEditModelName;
if (modelName === "this field is not used") {
return {
prompt: {
role: "user",
content: "NEXT_EDIT",
},
userEdits: "",
userExcerpts: helper.fileContents,
};
}
let modelName = helper.modelName as NEXT_EDIT_MODELS;
// Validate that the modelName is actually a supported model.
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
@ -91,7 +73,7 @@ export async function renderPrompt(
);
if (matchingModel) {
modelName = matchingModel as NextEditModelName;
modelName = matchingModel as NEXT_EDIT_MODELS;
} else {
throw new Error(
`${helper.modelName} is not yet supported for next edit.`,

View file

@ -14,11 +14,11 @@ import {
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import {
NextEditModelName,
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./NextEditPromptEngine";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
@ -30,25 +30,19 @@ describe("NextEditPromptEngine", () => {
beforeEach(() => {
mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
model1Helper = {
modelName: "continuedev/model-1" as NextEditModelName,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
testHelper = {
modelName: "this field is not used" as NextEditModelName,
modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
unsupportedHelper = {
modelName: "mistral/codestral" as NextEditModelName,
modelName: "mistral/codestral" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -99,16 +93,6 @@ describe("NextEditPromptEngine", () => {
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
});
it("should handle 'this field is not used' model name", async () => {
const result = await renderPrompt(testHelper, ctx);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toBe("NEXT_EDIT");
expect(result.userEdits).toBe("");
expect(result.userExcerpts).toBe(testHelper.fileContents);
});
it("should throw error for unsupported model name", async () => {
await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
"mistral/codestral is not yet supported for next edit.",
@ -209,7 +193,7 @@ describe("NextEditPromptEngine", () => {
describe("insertTokens", () => {
it("should correctly insert cursor and editable region tokens", () => {
const mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },

View file

@ -1,15 +1,13 @@
type NextEditModelName = "mercury-coder-nextedit";
export function isNextEditTest(): boolean {
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
export function isModelCapableOfNextEdit(modelName: string): boolean {
// In test mode, we can control whether next edit is enabled via environment variable.
if (process.env.NEXT_EDIT_TEST_ENABLED === "false") {
if (enabled === "false") {
return false;
}
if (process.env.NEXT_EDIT_TEST_ENABLED === "true") {
if (enabled === "true") {
return true;
}
const supportedModels: NextEditModelName[] = ["mercury-coder-nextedit"];
return supportedModels.some((supported) => modelName.includes(supported));
return false;
}

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const codebaseTool: Tool = {
type: "function",
@ -28,9 +27,10 @@ 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:`,
[["query", "How is user authentication handled in this codebase?"]],
),
systemMessageDescription: {
prefix: `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,
exampleArgs: [
["query", "How is user authentication handled in this codebase?"],
],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const createNewFileTool: Tool = {
type: "function",
@ -32,12 +31,11 @@ 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:`,
[
systemMessageDescription: {
prefix: `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:`,
exampleArgs: [
["filepath", "path/to/the_file.txt"],
["contents", "Contents of the file"],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
const NAME_ARG_DESC =
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')";
@ -61,9 +60,8 @@ 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.
systemMessageDescription: {
prefix: `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.
This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules.
To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments:
- name: ${NAME_ARG_DESC}
@ -72,7 +70,7 @@ To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call a
- globs: ${GLOB_ARG_DESC}
- alwaysApply: ${ALWAYS_APPLY_DESC}
For example:`,
[
exampleArgs: [
["name", "Use PropTypes"],
[
"rule",
@ -85,5 +83,5 @@ For example:`,
["globs", "**/*.js"],
["alwaysApply", "false"],
],
),
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
@ -41,19 +40,18 @@ export const editFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.EditExistingFile,
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
systemMessageDescription: {
prefix: `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
- filepath: the relative filepath to the file.
- changes: ${CHANGES_DESCRIPTION}
Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first.
For example:`,
[
exampleArgs: [
["filepath", "path/to/the_file.ts"],
[
"changes",
"// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...",
],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const fetchUrlContentTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ 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:`,
[["url", "https://example.com"]],
),
systemMessageDescription: {
prefix: `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:`,
exampleArgs: [["url", "https://example.com"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const globSearchTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ 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`,
[["pattern", "*.py"]],
),
systemMessageDescription: {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const grepSearchTool: Tool = {
type: "function",
@ -28,9 +27,8 @@ 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:`,
[["query", ".*main_services.*"]],
),
systemMessageDescription: {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const lsTool: Tool = {
type: "function",
@ -32,12 +31,11 @@ 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:`,
[
systemMessageDescription: {
prefix: `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,
exampleArgs: [
["dirPath", "path/to/dir"],
["recursive", "false"],
],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readCurrentlyOpenFileTool: Tool = {
type: "function",
@ -21,10 +20,8 @@ export const readCurrentlyOpenFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadCurrentlyOpenFile,
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
systemMessageDescription: {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
[],
),
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readFileTool: Tool = {
type: "function",
@ -27,10 +26,9 @@ export const readFileTool: Tool = {
},
},
},
systemMessageDescription: {
prefix: `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:`,
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
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:`,
[["filepath", "path/to/the_file.txt"]],
),
};

View file

@ -1,6 +1,5 @@
import { ConfigDependentToolParams, GetTool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface RequestRuleArgs {
name: string;
@ -60,10 +59,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
systemMessageDescription: {
prefix: getRequestRuleSystemMessageDescription(rules),
exampleArgs: [["name", "rule_name"]],
},
defaultToolPolicy: "disabled",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),
[["name", "rule_name"]],
),
});

View file

@ -1,7 +1,6 @@
import os from "os";
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
/**
* Get the preferred shell for the current platform
@ -57,12 +56,11 @@ export const runTerminalCommandTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RunTerminalCommand,
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
systemMessageDescription: {
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
${RUN_COMMAND_NOTES}
You can also optionally include the waitForCompletion argument set to false to run the command in the background.
For example, to see the git log, you could respond with:`,
[["command", "git log"]],
),
exampleArgs: [["command", "git log"]],
},
};

View file

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface SearchAndReplaceInFileArgs {
filepath: string;
@ -90,16 +89,15 @@ 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 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.
systemMessageDescription: {
prefix: `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}
${SEARCH_AND_REPLACE_RULES}
For example, you could respond with:`,
[
exampleArgs: [
["filepath", "path/to/file.ts"],
[
"diffs",
@ -109,6 +107,6 @@ ${SEARCH_AND_REPLACE_RULES}
]`,
],
],
),
},
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const searchWebTool: Tool = {
type: "function",
@ -27,9 +26,8 @@ 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:`,
[["query", "What is the current weather in San Francisco?"]],
),
systemMessageDescription: {
prefix: `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:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
};

View file

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewDiffTool: Tool = {
type: "function",
@ -20,10 +19,8 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
systemMessageDescription: {
prefix: `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.`,
},
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

@ -1,7 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewRepoMapTool: Tool = {
type: "function",
@ -20,10 +19,8 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
systemMessageDescription: {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
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

@ -1,6 +1,5 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewSubdirectoryTool: Tool = {
type: "function",
@ -26,10 +25,9 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
systemMessageDescription: {
prefix: `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.`,
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
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.`,
[["directory_path", "path/to/subdirectory"]],
),
};

View file

@ -1,91 +1,13 @@
import { Tool } from "../..";
import { closeTag } from "./systemToolUtils";
import { SystemMessageToolsFramework } from "./types";
export const TOOL_INSTRUCTIONS_TAG = "<tool_use_instructions>";
export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION";
export const TOOL_DESCRIPTION_TAG = "DESCRIPTION";
const EXAMPLE_DYNAMIC_TOOL = `
\`\`\`tool_definition
TOOL_NAME: example_tool
TOOL_ARG: arg_1 (string, required)
Description of the first argument
END_ARG
TOOL_ARG: arg_2 (number, optional)
END_ARG
\`\`\``.trim();
const EXAMPLE_DYNAMIC_TOOL_CALL = `
\`\`\`tool
TOOL_NAME: example_tool
BEGIN_ARG: arg_1
The value
of arg 1
END_ARG
BEGIN_ARG: arg_2
3
END_ARG
\`\`\``.trim();
export function createSystemMessageExampleCall(
name: string,
instructions: string,
args: Array<[string, string]> = [],
) {
let callExample = `\`\`\`tool
TOOL_NAME: ${name}`;
// Add each argument dynamically
for (const [argName, argValue] of args) {
callExample += `
BEGIN_ARG: ${argName}
${argValue}
END_ARG`;
}
callExample += `
\`\`\``;
return `${instructions.trim()}
${callExample}`;
}
function toolToSystemToolDefinition(tool: Tool): string {
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
if (tool.function.description) {
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
}
if (tool.function.parameters && "properties" in tool.function.parameters) {
for (const [key, value] of Object.entries(
tool.function.parameters.properties as object,
)) {
const isRequired = tool.function.parameters.required?.includes(key);
const requiredText = isRequired ? "required" : "optional";
let argType = "string";
if ("type" in value) {
argType = value.type;
}
let argDescription = "";
if ("description" in value) {
argDescription = value.description;
}
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
if (argDescription) {
toolDefinition += argDescription + "\n";
}
toolDefinition += `END_ARG\n`;
}
}
toolDefinition += `\`\`\``;
return toolDefinition.trim();
}
export const generateToolsSystemMessage = (tools: Tool[]): string => {
export const generateToolsSystemMessage = (
tools: Tool[],
framework: SystemMessageToolsFramework,
): string => {
if (tools.length === 0) {
return "";
}
@ -99,17 +21,17 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
const instructions: string[] = [];
instructions.push(TOOL_INSTRUCTIONS_TAG);
instructions.push(
`You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`,
);
instructions.push(
`To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`,
);
instructions.push(framework.systemMessagePrefix);
if (withPredefinedMessage.length > 0) {
instructions.push(`\nThe following tools are available to you:`);
for (const tool of withPredefinedMessage) {
instructions.push(`\n${tool.systemMessageDescription}`);
const definition = framework.createSystemMessageExampleCall(
tool.function.name,
tool.systemMessageDescription!.prefix,
tool.systemMessageDescription!.exampleArgs,
);
instructions.push(`\n${definition}`);
}
}
@ -120,7 +42,7 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
for (const tool of tools) {
try {
const definition = toolToSystemToolDefinition(tool);
const definition = framework.toolToSystemToolDefinition(tool);
instructions.push(`\n${definition}`);
} catch (e) {
console.error(
@ -131,35 +53,28 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => {
}
instructions.push(`\nFor example, this tool definition:\n`);
instructions.push(EXAMPLE_DYNAMIC_TOOL);
instructions.push(framework.exampleDynamicToolDefinition);
instructions.push("\nCan be called like this:\n");
instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL);
instructions.push(framework.exampleDynamicToolCall);
}
instructions.push(
`\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`,
);
instructions.push(
`Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`,
);
instructions.push(
`Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`,
);
instructions.push(
`You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`,
);
instructions.push("\n" + framework.systemMessageSuffix);
instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`);
return instructions.join("\n");
};
export function addSystemMessageToolsToSystemMessage(
framework: SystemMessageToolsFramework,
baseSystemMessage: string,
systemMessageTools: Tool[],
): string {
let systemMessage = baseSystemMessage;
if (systemMessageTools.length > 0) {
const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools);
const toolsSystemMessage = generateToolsSystemMessage(
systemMessageTools,
framework,
);
systemMessage += `\n\n${toolsSystemMessage}`;
}

View file

@ -12,22 +12,7 @@ import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
import { SystemMessageToolsFramework } from "./types";
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
@ -46,6 +31,7 @@ function toolCallStateToSystemToolOutput(state: ToolCallState): string {
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
framework: SystemMessageToolsFramework,
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
@ -55,7 +41,7 @@ export function convertToolCallStatesToSystemCallsAndOutput(
parts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
text: framework.toolCallStateToSystemToolCall(state),
})),
);
}

View file

@ -1,19 +1,16 @@
let boundaryTypeIndex = 0;
import { SystemMessageToolsFramework } from "./types";
// Poor models are really bad at following instructions
// Give some leeway in how the initiate
const acceptedToolStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\nTOOL_NAME:"],
];
export function detectToolCallStart(buffer: string) {
export function detectToolCallStart(
buffer: string,
toolCallFramework: SystemMessageToolsFramework,
) {
const starts = toolCallFramework.acceptedToolCallStarts;
let modifiedBuffer = buffer;
let isInToolCall = false;
let isInPartialStart = false;
const lowerCaseBuffer = buffer.toLowerCase();
for (let i = 0; i < acceptedToolStarts.length; i++) {
const [start, replacement] = acceptedToolStarts[i];
for (let i = 0; i < starts.length; i++) {
const [start, replacement] = starts[i];
if (lowerCaseBuffer.startsWith(start)) {
// for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive
if (i !== 0) {

View file

@ -1,12 +1,12 @@
import { ChatMessage, PromptLog, TextMessagePart } from "../..";
import { normalizeToMessageParts } from "../../util/messageContent";
import { detectToolCallStart } from "./detectToolCallStart";
import {
getInitialTooLCallParseState,
handleToolCallBuffer,
ToolCallParseState,
} from "./parseSystemToolCall";
import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
import {
getInitialToolCallParseState,
SystemMessageToolsFramework,
ToolCallParseState,
} from "./types";
/*
Function to intercept tool calls in markdown code blocks format from a chat message stream
@ -24,6 +24,7 @@ import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
export async function* interceptSystemToolCalls(
messageGenerator: AsyncGenerator<ChatMessage[], PromptLog | undefined>,
abortController: AbortController,
systemToolFramework: SystemMessageToolsFramework,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
let buffer = "";
let parseState: ToolCallParseState | undefined;
@ -70,19 +71,22 @@ export async function* interceptSystemToolCalls(
buffer += chunk;
if (!parseState) {
const { isInPartialStart, isInToolCall, modifiedBuffer } =
detectToolCallStart(buffer);
detectToolCallStart(buffer, systemToolFramework);
if (isInPartialStart) {
continue;
}
if (isInToolCall) {
parseState = getInitialTooLCallParseState();
parseState = getInitialToolCallParseState();
buffer = modifiedBuffer;
}
}
if (parseState && !parseState.done) {
const delta = handleToolCallBuffer(buffer, parseState);
const delta = systemToolFramework.handleToolCallBuffer(
buffer,
parseState,
);
if (delta) {
yield [
{

View file

@ -1,102 +0,0 @@
import {
AssistantChatMessage,
MessagePart,
ToolCallState,
UserChatMessage,
} from "../..";
import {
normalizeToMessageParts,
renderContextItems,
} from "../../util/messageContent";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
// TODO - include tool call id for parallel. Confuses dumb models
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
if (state.status === "canceled") {
output += CANCELLED_TOOL_CALL_MESSAGE;
} else if (state.output?.length) {
output += renderContextItems(state.output);
} else {
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
}
return output;
}
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
} {
const assistantParts = normalizeToMessageParts(originalAssistantMessage);
if (originalAssistantMessage.toolCalls) {
assistantParts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
})),
);
}
const userParts: MessagePart[] = [];
if (toolCallStates) {
for (const state of toolCallStates) {
userParts.push({
type: "text",
text: toolCallStateToSystemToolOutput(state),
});
}
}
if (userParts.length === 0) {
userParts.push({
type: "text",
text: "No tool output for tool calls",
});
}
const nonEmptyAssistantParts = assistantParts.filter(
(p) => p.type !== "text" || !!p.text,
);
const nonEmptyUserParts = userParts.filter(
(p) => p.type !== "text" || !!p.text,
);
// new message with tool calls moved to content
const assistantMessage: AssistantChatMessage = {
...originalAssistantMessage,
content: nonEmptyAssistantParts,
toolCalls: undefined, // remove tool calls from the assistant message
};
const userMessage: UserChatMessage = {
role: "user",
content: nonEmptyUserParts,
};
return {
assistantMessage,
userMessage,
};
}

View file

@ -1,12 +1,13 @@
import { describe, expect, it } from "vitest";
import { Tool } from "../..";
import { Tool } from "../../..";
import {
TOOL_INSTRUCTIONS_TAG,
addSystemMessageToolsToSystemMessage,
createSystemMessageExampleCall,
generateToolsSystemMessage,
} from "./buildToolsSystemMessage";
import { closeTag } from "./systemToolUtils";
} from "../buildToolsSystemMessage";
import { SystemMessageToolCodeblocksFramework } from ".";
import { closeTag } from "../systemToolUtils";
const SHARED_TOOL_FIELDS = {
displayTitle: "DUD",
@ -15,9 +16,11 @@ const SHARED_TOOL_FIELDS = {
type: "function" as const,
};
const framework = new SystemMessageToolCodeblocksFramework();
describe("createSystemMessageExampleCall", () => {
it("creates a system message example call with no args", () => {
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
);
@ -28,7 +31,7 @@ describe("createSystemMessageExampleCall", () => {
});
it("creates a system message example call with args", () => {
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[
@ -49,7 +52,7 @@ describe("createSystemMessageExampleCall", () => {
it("handles multiline arg values correctly", () => {
const multilineValue = "value\nwith\nmultiple\nlines";
const result = createSystemMessageExampleCall(
const result = framework.createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[["arg1", multilineValue]],
@ -63,7 +66,7 @@ describe("createSystemMessageExampleCall", () => {
describe("generateToolsSystemMessage", () => {
it("returns empty string for empty tools array", () => {
const result = generateToolsSystemMessage([]);
const result = generateToolsSystemMessage([], framework);
expect(result).toBe("");
});
@ -81,12 +84,14 @@ describe("generateToolsSystemMessage", () => {
required: [],
},
},
systemMessageDescription: customDescription,
systemMessageDescription: {
prefix: customDescription,
},
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check structure rather than exact text
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
@ -123,7 +128,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for key elements without requiring exact wording
expect(result).includes(`TOOL_NAME: ${toolName}`);
@ -150,7 +155,9 @@ describe("generateToolsSystemMessage", () => {
required: [],
},
},
systemMessageDescription: customMsg,
systemMessageDescription: {
prefix: customMsg,
},
...SHARED_TOOL_FIELDS,
},
{
@ -172,7 +179,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for both types of tools
expect(result).includes(customMsg);
@ -202,7 +209,7 @@ describe("generateToolsSystemMessage", () => {
},
];
const result = generateToolsSystemMessage(tools);
const result = generateToolsSystemMessage(tools, framework);
// Check for example sections without exact text
expect(result).includes("```tool_definition");
@ -221,7 +228,11 @@ describe("generateToolsSystemMessage", () => {
describe("addSystemMessageToolsToSystemMessage", () => {
it("returns original system message when no tools are provided", () => {
const baseMessage = "This is the base system message";
const result = addSystemMessageToolsToSystemMessage(baseMessage, []);
const result = addSystemMessageToolsToSystemMessage(
framework,
baseMessage,
[],
);
expect(result).toBe(baseMessage);
});
@ -243,7 +254,11 @@ describe("addSystemMessageToolsToSystemMessage", () => {
},
];
const result = addSystemMessageToolsToSystemMessage(baseMessage, tools);
const result = addSystemMessageToolsToSystemMessage(
framework,
baseMessage,
tools,
);
expect(result.startsWith(baseMessage)).toBe(true);
expect(result).includes(TOOL_INSTRUCTIONS_TAG);

View file

@ -1,10 +1,12 @@
import { describe, expect, it } from "vitest";
import { detectToolCallStart } from "./detectToolCallStart";
import { SystemMessageToolCodeblocksFramework } from ".";
import { detectToolCallStart } from "../detectToolCallStart";
describe("detectToolCallStart", () => {
let framework = new SystemMessageToolCodeblocksFramework();
it("detects standard tool call start", () => {
const buffer = "```tool\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -13,7 +15,7 @@ describe("detectToolCallStart", () => {
it("detects tool_name start without codeblock", () => {
const buffer = "tool_name: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -22,7 +24,7 @@ describe("detectToolCallStart", () => {
it("detects case-insensitive tool call start", () => {
const buffer = "```ToOl\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -31,7 +33,7 @@ describe("detectToolCallStart", () => {
it("detects case-insensitive tool_name start", () => {
const buffer = "ToOl_NaMe: example_tool";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
@ -40,7 +42,7 @@ describe("detectToolCallStart", () => {
it("identifies partial tool call start", () => {
const buffer = "```to";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
@ -49,7 +51,7 @@ describe("detectToolCallStart", () => {
it("identifies partial tool_name start", () => {
const buffer = "tool_na";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
@ -58,7 +60,7 @@ describe("detectToolCallStart", () => {
it("does not detect tool call in unrelated text", () => {
const buffer = "This is some regular text.";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);
@ -67,7 +69,7 @@ describe("detectToolCallStart", () => {
it("does not detect tool call in similar but different markdown block", () => {
const buffer = "```javascript\nconst x = 10;";
const result = detectToolCallStart(buffer);
const result = detectToolCallStart(buffer, framework);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);

View file

@ -0,0 +1,120 @@
import { Tool, ToolCallState } from "../../..";
import { SystemMessageToolsFramework } from "../types";
import { handleToolCallBuffer } from "./parseSystemToolCall";
export class SystemMessageToolCodeblocksFramework
implements SystemMessageToolsFramework
{
// Poor models are really bad at following instructions, alternate starts allowed:
acceptedToolCallStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\nTOOL_NAME:"],
];
toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
handleToolCallBuffer = handleToolCallBuffer;
toolToSystemToolDefinition(tool: Tool): string {
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
if (tool.function.description) {
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
}
if (tool.function.parameters && "properties" in tool.function.parameters) {
for (const [key, value] of Object.entries(
tool.function.parameters.properties as object,
)) {
const isRequired = tool.function.parameters.required?.includes(key);
const requiredText = isRequired ? "required" : "optional";
let argType = "string";
if ("type" in value) {
argType = value.type;
}
let argDescription = "";
if ("description" in value) {
argDescription = value.description;
}
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
if (argDescription) {
toolDefinition += argDescription + "\n";
}
toolDefinition += `END_ARG\n`;
}
}
toolDefinition += `\`\`\``;
return toolDefinition.trim();
}
systemMessagePrefix = `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.
To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`;
systemMessageSuffix = `If it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions
Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.
Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.
You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`;
exampleDynamicToolDefinition = `
\`\`\`tool_definition
TOOL_NAME: example_tool
TOOL_ARG: arg_1 (string, required)
Description of the first argument
END_ARG
TOOL_ARG: arg_2 (number, optional)
END_ARG
\`\`\``.trim();
exampleDynamicToolCall = `
\`\`\`tool
TOOL_NAME: example_tool
BEGIN_ARG: arg_1
The value
of arg 1
END_ARG
BEGIN_ARG: arg_2
3
END_ARG
\`\`\``.trim();
createSystemMessageExampleCall(
toolName: string,
prefix: string,
exampleArgs: Array<[string, string | number]> = [],
) {
let callExample = `\`\`\`tool
TOOL_NAME: ${toolName}`;
// Add each argument dynamically
for (const [argName, argValue] of exampleArgs) {
callExample += `
BEGIN_ARG: ${argName}
${argValue}
END_ARG`;
}
callExample += `
\`\`\``;
return `${prefix.trim()}
${callExample}`;
}
}

View file

@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it } from "vitest";
import { AssistantChatMessage, ChatMessage, PromptLog } from "../..";
import { interceptSystemToolCalls } from "./interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from ".";
import { AssistantChatMessage, ChatMessage, PromptLog } from "../../..";
import { interceptSystemToolCalls } from "../interceptSystemToolCalls";
describe("interceptSystemToolCalls", () => {
let abortController: AbortController;
let framework = new SystemMessageToolCodeblocksFramework();
beforeEach(() => {
abortController = new AbortController();
@ -27,6 +29,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
let result = await generator.next();
@ -64,6 +67,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
const result = await generator.next();
@ -91,6 +95,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
const result = await generator.next();
@ -116,6 +121,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// First chunk should be normal text
@ -185,6 +191,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// First chunk should be normal text
@ -249,6 +256,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
let result;
@ -271,6 +279,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// Process the first part
@ -300,6 +309,7 @@ describe("interceptSystemToolCalls", () => {
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
framework,
);
// Skip to number arg end

View file

@ -1,34 +1,12 @@
import { ToolCallDelta } from "../..";
import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils";
export type ToolCallParseState = {
toolCallId: string;
isOnArgBeginLine: boolean;
currentArgName: string | undefined;
currentArgLines: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialTooLCallParseState = (): ToolCallParseState => ({
toolCallId: generateOpenAIToolCallId(),
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});
import { ToolCallDelta } from "../../..";
import { createDelta } from "../systemToolUtils";
import { ToolCallParseState } from "../types";
/*
Efficiently applies chunks to a tool call state as they come in
Expects chunks to be broken so that new lines and codeblocks are alone
For now, this parser collects entire arg before
This is because support for JSON booleans is tricky otherwise
*/
export function handleToolCallBuffer(
chunk: string,
@ -72,14 +50,14 @@ export function handleToolCallBuffer(
}
return;
default:
if (state.isOnArgBeginLine) {
if (state.isWithinArgStart) {
if (isNewLine) {
const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim();
if (!argName) {
throw new Error("Invalid begin arg line");
}
state.currentArgName = argName;
state.isOnArgBeginLine = false;
state.isWithinArgStart = false;
const argPrefix = state.processedArgNames.size === 0 ? "{" : ",";
return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId);
}
@ -87,8 +65,8 @@ export function handleToolCallBuffer(
if (isNewLine) {
const isEndArgTag = line.match(/end_?arg/i);
if (isEndArgTag) {
let trimmedValue = state.currentArgLines.join("").trim();
state.currentArgLines.length = 0;
let trimmedValue = state.currentArgChunks.join("").trim();
state.currentArgChunks.length = 0;
state.processedArgNames.add(state.currentArgName);
state.currentArgName = undefined;
@ -120,14 +98,14 @@ export function handleToolCallBuffer(
return createDelta("", stringifiedArg, state.toolCallId);
}
} else {
state.currentArgLines.push(line);
state.currentArgChunks.push(line);
}
}
} else {
// Check for entry into arg
const isBeginArgLine = line.match(/begin_?arg:/i);
if (isBeginArgLine) {
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
}
// Check for exit

View file

@ -1,32 +1,12 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
ToolCallParseState,
getInitialTooLCallParseState,
handleToolCallBuffer,
} from "./parseSystemToolCall";
describe("getInitialTooLCallParseState", () => {
it("returns a properly initialized parse state", () => {
const state = getInitialTooLCallParseState();
expect(state).toEqual({
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
toolCallId: expect.any(String),
});
});
});
import { getInitialToolCallParseState, ToolCallParseState } from "../types";
import { handleToolCallBuffer } from "./parseSystemToolCall";
describe("handleToolCallBuffer", () => {
let state: ToolCallParseState;
beforeEach(() => {
state = getInitialTooLCallParseState();
state = getInitialToolCallParseState();
});
it("handles the ```tool\ntool_name the name", () => {
@ -88,7 +68,7 @@ describe("handleToolCallBuffer", () => {
const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
expect(state.isWithinArgStart).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
@ -101,7 +81,7 @@ describe("handleToolCallBuffer", () => {
id: expect.any(String),
});
expect(state.currentArgName).toBe("test_arg");
expect(state.isOnArgBeginLine).toBe(false);
expect(state.isWithinArgStart).toBe(false);
});
it("handles case-insensitive begin arg", () => {
@ -109,7 +89,7 @@ describe("handleToolCallBuffer", () => {
const result = handleToolCallBuffer("begin_arg: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
expect(state.isWithinArgStart).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
@ -135,13 +115,13 @@ describe("handleToolCallBuffer", () => {
const newLineResult2 = handleToolCallBuffer("\n", state);
expect(newLineResult2).toBeUndefined();
expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]);
expect(state.currentArgChunks).toEqual(["line 1\n", "line 2\n"]);
});
it("ends an argument correctly with string value", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
state.currentArgChunks = ["string value"];
const result = handleToolCallBuffer("END_ARG", state);
expect(result).toBeUndefined();
@ -163,7 +143,7 @@ describe("handleToolCallBuffer", () => {
it("handles case-insensitive end arg", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
state.currentArgChunks = ["string value"];
const result = handleToolCallBuffer("end_arg", state);
expect(result).toBeUndefined();
@ -183,7 +163,7 @@ describe("handleToolCallBuffer", () => {
it("attempts to parse JSON values", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["123"];
state.currentArgChunks = ["123"];
handleToolCallBuffer("END_ARG", state);
const newLineResult = handleToolCallBuffer("\n", state);
@ -201,7 +181,7 @@ describe("handleToolCallBuffer", () => {
it("handles multiple arguments", () => {
// Setup first arg
state.currentLineIndex = 2;
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
state.lineChunks[2] = ["BEGIN_ARG: first_arg"];
handleToolCallBuffer("\n", state);
@ -213,7 +193,7 @@ describe("handleToolCallBuffer", () => {
expect(state.processedArgNames.has("first_arg")).toBe(true);
// Setup second arg
state.isOnArgBeginLine = true;
state.isWithinArgStart = true;
handleToolCallBuffer("BEGIN_ARG: second_arg", state);
handleToolCallBuffer("\n", state);
handleToolCallBuffer("value2", state);
@ -270,7 +250,7 @@ describe("handleToolCallBuffer", () => {
it("handles JSON array args", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = [
state.currentArgChunks = [
"[\n",
'"------- SEARCH\n',
" subtract(number) {\n",

View file

@ -0,0 +1,51 @@
import { Tool, ToolCallDelta, ToolCallState } from "../..";
import { generateOpenAIToolCallId } from "./systemToolUtils";
export interface SystemMessageToolsFramework {
acceptedToolCallStarts: [string, string][];
toolCallStateToSystemToolCall(state: ToolCallState): string;
handleToolCallBuffer(
chunk: string,
state: ToolCallParseState,
): ToolCallDelta | undefined;
toolToSystemToolDefinition: (tool: Tool) => string;
systemMessagePrefix: string;
systemMessageSuffix: string;
exampleDynamicToolDefinition: string;
exampleDynamicToolCall: string;
createSystemMessageExampleCall(
toolName: string,
prefix: string,
exampleArgs?: Array<[string, string | number]>,
): string;
}
export type ToolCallParseState = {
toolCallId: string;
isWithinArgStart: boolean;
currentArgName: string | undefined;
currentArgChunks: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialToolCallParseState = (): ToolCallParseState => ({
toolCallId: generateOpenAIToolCallId(),
isWithinArgStart: false,
currentArgName: undefined,
currentArgChunks: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});

View file

@ -60,6 +60,11 @@ Example
`config.ts` must export a `modifyConfig` function, like:
<Warning>
The `slashCommands` array shown below is deprecated. For creating custom slash
commands, use [prompt files](./slash-commands) instead.
</Warning>
```ts title="config.ts"
export function modifyConfig(config: Config): Config {
config.slashCommands?.push({
@ -82,4 +87,4 @@ export function modifyConfig(config: Config): Config {
});
return config;
}
```
```

View file

@ -9,7 +9,14 @@ keywords: [slash command, custom commands, step]
Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown.
![slash-commands](/images/slash-commands.png)
Slash commands can be combined with additional instructions, including [context providers](../custom-providers.mdx) or highlighted code.
Slash commands can be combined with additional instructions, including [context providers](../custom-providers) or highlighted code.
<Note>
**Recommended approach**: Use prompt files to create slash commands instead of
the deprecated `config.json` approach. The methods described below provide
better flexibility and are the actively maintained ways to add custom
commands.
</Note>
## Prompts
@ -21,7 +28,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/
It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
Learn more about prompt files [here](./prompts.md)
Learn more about prompt files [here](./prompts).
### MCP Server prompts

View file

@ -1,12 +1,18 @@
---
title: "config.json Reference"
title: "config.json Reference (Deprecated)"
description: "Legacy configuration reference for config.json - use config.yaml instead"
noindex: true
---
<Info>
We recently introduced a new configuration format, `config.yaml`, to replace
`config.json`. See the `config.yaml` reference and migration guide
[here](/reference).
</Info>
<Warning>
**This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use:
- [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands
- [config.yaml](/reference) for configuration
See the `config.yaml` reference and migration guide
[here](/reference).
</Warning>
Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json).
@ -468,16 +474,19 @@ Several experimental config parameters are available, as described below:
- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.=
- `modelRoles`:
- `inlineEdit`: Model title for inline edits.
- `applyCodeBlock`: Model title for applying code blocks.
- `repoMapFileSelection`: Model title for repo map selections.
- `quickActions`: Array of custom quick actions
- `title` (**required**): Display title for the quick action.
- `prompt` (**required**): Prompt for quick action.
- `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`.
- `contextMenuPrompts`:
- `comment`: Prompt for commenting code.
- `docstring`: Prompt for adding docstrings.
- `fix`: Prompt for fixing code.
@ -529,15 +538,18 @@ Some deprecated `config.json` settings are no longer stored in config and have b
- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false
- `tabAutocompleteOptions`
- `useCache`: This value will override during migration.
- `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated)
- `multilineCompletions`: This value will override during migration.
- `experimental`
- `useChromiumForDocsCrawling`: This value will override during migration.
- `readResponseTTS`: This value will override during migration.
- `ui` - all will override during migration
- `codeBlockToolbarPosition`
- `fontSize`
- `codeWrap`

View file

@ -287,7 +287,6 @@ 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

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.73",
"version": "1.1.75",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -43,9 +43,10 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider
import { VsCodeMessenger } from "./VsCodeMessenger";
import { getAst } from "core/autocomplete/util/ast";
import { modelSupportsNextEdit } from "core/llm/autodetect";
import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker";
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
import { isModelCapableOfNextEdit } from "core/nextEdit/utils";
import { isNextEditTest } from "core/nextEdit/utils";
import { localPathOrUriToPath } from "core/util/pathToUri";
import { JumpManager } from "../activation/JumpManager";
import setupNextEditWindowManager, {
@ -202,8 +203,13 @@ export class VsCodeExtension {
async ({ config: newConfig, configLoadInterrupted }) => {
const autocompleteModel = newConfig?.selectedModelByRole.autocomplete;
if (
autocompleteModel &&
isModelCapableOfNextEdit(autocompleteModel.model)
(autocompleteModel &&
modelSupportsNextEdit(
autocompleteModel.capabilities,
autocompleteModel.model,
autocompleteModel.title,
)) ||
isNextEditTest()
) {
// Set up next edit window manager only for Continue team members
await setupNextEditWindowManager(context);

View file

@ -1,12 +1,12 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { TrashIcon } from "@heroicons/react/24/outline";
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useDeleteCompaction } from "../../util/compactConversation";
import { AnimatedEllipsis } from "../AnimatedEllipsis";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
interface ConversationSummaryProps {
item: ChatHistoryItem;
@ -14,7 +14,7 @@ interface ConversationSummaryProps {
}
export default function ConversationSummary(props: ConversationSummaryProps) {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState(true);
const isLoading = useAppSelector(
(state) => state.session.compactionLoading[props.index] || false,
);

View file

@ -263,7 +263,7 @@ export function StepContainerPreToolbar({
}
return (
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mb-2 mt-2 flex min-w-0 flex-col outline outline-1">
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1">
<div
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
style={{ fontSize: `${getFontSize() - 2}px` }}

View file

@ -245,12 +245,14 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
// Trigger warning message
ideMessenger.ide.showToast(
"warning",
fileSize > 0 ? "File exceeds context length" : "Can't load the file",
fileSize > 0
? "File exceeds model's context length"
: "Error loading file",
{
modal: true,
detail:
fileSize > 0
? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model`
? `'${item.title}' cannot be added because it exceeds the model's allowed context length. File size: ${formatFileSize(fileSize)}`
: `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
},
);

View file

@ -60,6 +60,9 @@ function PromptRow({
}
};
const canEdit =
prompt.promptFile && !prompt.promptFile.startsWith("builtin:");
return (
<div
className="hover:bg-list-active hover:text-list-active-foreground flex items-center justify-between gap-3 rounded-md px-2 py-1 hover:cursor-pointer"
@ -78,8 +81,9 @@ function PromptRow({
</div>
<div className="flex items-center gap-2">
<PencilIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={handleEditClick}
className={`h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125 ${!canEdit ? "pointer-events-none cursor-not-allowed opacity-50" : ""}`}
onClick={canEdit ? handleEditClick : undefined}
aria-disabled={!canEdit}
/>
<div
onClick={handleBookmarkClick}

View file

@ -1121,6 +1121,18 @@ export const models: { [key: string]: ModelPackage } = {
icon: "cohere.png",
isOpenSource: false,
},
gpt5: {
title: "GPT-5",
description: "OpenAI's next-generation, high-intelligence flagship model",
params: {
model: "gpt-5",
contextLength: 400_000,
title: "GPT-5",
},
providerOptions: ["openai"],
icon: "openai.png",
isOpenSource: false,
},
gpt4turbo: {
title: "GPT-4 Turbo",
description:

View file

@ -52,12 +52,13 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
openai: {
title: "OpenAI",
provider: "openai",
description: "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model",
description: "Use gpt-5, gpt-4, or any other OpenAI model",
longDescription:
"Use gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
"Use gpt-5, gpt-4, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
icon: "openai.png",
tags: [ModelProviderTags.RequiresApiKey],
packages: [
models.gpt5,
models.gpt4o,
models.gpt4omini,
models.gpt4turbo,

View file

@ -80,7 +80,7 @@ export function ToolCallDiv({
if (shouldShowGroupedUI) {
return (
<div className="border-border rounded-lg border p-3">
<div className="border-border rounded-lg border p-3 pb-0">
<GroupedToolCallHeader
toolCallStates={toolCallStates}
activeCalls={activeCalls}
@ -103,7 +103,7 @@ export function ToolCallDiv({
}
return toolCallStates.map((toolCallState) => (
<div className="p-4 pb-1" key={toolCallState.toolCallId}>
<div className="px-4 py-1" key={toolCallState.toolCallId}>
{renderToolCall(toolCallState)}
</div>
));

View file

@ -14,6 +14,7 @@ import {
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
export const callToolById = createAsyncThunk<
void,
@ -36,9 +37,11 @@ export const callToolById = createAsyncThunk<
// Check if this is an auto-approved tool
const toolSettings = state.ui.toolSettings;
const isAutoApproved =
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission";
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
toolCallState.tool?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
const isAutoApproved = toolPolicy === "allowedWithoutPermission";
posthog.capture("gui_tool_call_decision", {
decision: isAutoApproved ? "auto_accept" : "accept",

View file

@ -25,9 +25,11 @@ import { constructMessages } from "../util/constructMessages";
import { modelSupportsNativeTools } from "core/llm/toolSupport";
import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage";
import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
import { callToolById } from "./callToolById";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
/**
* Handles the execution of tool calls that may be automatically accepted.
* Sets all tools as generated first, then executes auto-approved tool calls.
@ -35,6 +37,7 @@ import { callToolById } from "./callToolById";
async function handleToolCallExecution(
dispatch: AppThunkDispatch,
getState: () => RootState,
activeTools: Tool[],
): Promise<void> {
const newState = getState();
const toolSettings = newState.ui.toolSettings;
@ -51,11 +54,15 @@ async function handleToolCallExecution(
}
// Check if ALL tool calls are auto-approved - if not, wait for user approval
const allAutoApproved = toolCallStates.every(
(toolCallState) =>
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission",
);
const allAutoApproved = toolCallStates.every((toolCallState) => {
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) => tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return toolPolicy == "allowedWithoutPermission";
});
// Set all tools as generated first
toolCallStates.forEach((toolCallState) => {
@ -147,6 +154,9 @@ export const streamNormalInput = createAsyncThunk<
// Use the centralized selector to determine if system message tools should be used
const useSystemTools = selectUseSystemMessageTools(state);
const useNativeTools = !useSystemTools && supportsNativeTools;
const systemToolsFramework = useSystemTools
? new SystemMessageToolCodeblocksFramework()
: undefined;
// Construct completion options
let completionOptions: LLMFullCompletionOptions = {};
@ -169,10 +179,15 @@ export const streamNormalInput = createAsyncThunk<
const baseSystemMessage = getBaseSystemMessage(
state.session.mode,
selectedChatModel,
activeTools,
);
const systemMessage = useSystemTools
? addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools)
const systemMessage = systemToolsFramework
? addSystemMessageToolsToSystemMessage(
systemToolsFramework,
baseSystemMessage,
activeTools,
)
: baseSystemMessage;
const withoutMessageIds = state.session.history.map((item) => {
@ -185,7 +200,7 @@ export const streamNormalInput = createAsyncThunk<
systemMessage,
state.config.config.rules,
state.ui.ruleSettings,
!useNativeTools,
systemToolsFramework,
);
// TODO parallel tool calls will cause issues with this
@ -233,8 +248,8 @@ export const streamNormalInput = createAsyncThunk<
},
streamAborter.signal,
);
if (!useNativeTools && activeTools.length > 0) {
gen = interceptSystemToolCalls(gen, streamAborter);
if (systemToolsFramework && activeTools.length > 0) {
gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework);
}
let next = await gen.next();
@ -289,11 +304,16 @@ export const streamNormalInput = createAsyncThunk<
// Check if ALL generating tool calls are auto-approved
const allAutoApproved =
generatingToolCalls.length > 0 &&
generatingToolCalls.every(
(toolCallState) =>
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission",
);
generatingToolCalls.every((toolCallState) => {
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) =>
tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
return toolPolicy == "allowedWithoutPermission";
});
// Only set inactive if:
// 1. There are no tool calls, OR
@ -303,6 +323,6 @@ export const streamNormalInput = createAsyncThunk<
dispatch(setInactive());
}
await handleToolCallExecution(dispatch, getState);
await handleToolCallExecution(dispatch, getState, activeTools);
},
);

View file

@ -15,6 +15,7 @@ import {
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "core/tools/constants";
import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools";
import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types";
import { findLast, findLastIndex } from "core/util/findLast";
import {
normalizeToMessageParts,
@ -30,7 +31,7 @@ export function constructMessages(
baseSystemMessage: string | undefined,
availableRules: RuleWithSource[],
rulePolicies: RulePolicies,
useSystemMessageTools?: boolean,
useSystemToolsFramework?: SystemMessageToolsFramework,
): {
messages: ChatMessage[];
appliedRules: RuleWithSource[];
@ -95,11 +96,12 @@ export function constructMessages(
});
} else if (item.message.role === "assistant") {
// When using system message tools, convert tool calls/states to text content
if (item.toolCallStates?.length && useSystemMessageTools) {
if (item.toolCallStates?.length && useSystemToolsFramework) {
const { userMessage, assistantMessage } =
convertToolCallStatesToSystemCallsAndOutput(
item.message,
item.toolCallStates ?? [],
useSystemToolsFramework,
);
msgs.push({
message: assistantMessage,

View file

@ -1,10 +1,10 @@
import { ModelDescription } from "core";
import { ModelDescription, Tool } from "core";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
DEFAULT_PLAN_SYSTEM_MESSAGE,
} from "core/llm/defaultSystemMessages";
import { getBaseSystemMessage } from "./getBaseSystemMessage";
import { getBaseSystemMessage, NO_TOOL_WARNING } from "./getBaseSystemMessage";
test("getBaseSystemMessage should return the correct system message based on mode", () => {
const mockModel = {
@ -13,33 +13,74 @@ test("getBaseSystemMessage should return the correct system message based on mod
baseAgentSystemMessage: "Custom Agent System Message",
} as ModelDescription;
// Test agent mode with custom message
expect(getBaseSystemMessage("agent", mockModel)).toBe(
const mockTool = {
function: {
name: "testTool",
description: "Test tool",
parameters: {},
},
} as Tool;
// Test agent mode with custom message and tools
expect(getBaseSystemMessage("agent", mockModel, [mockTool])).toBe(
"Custom Agent System Message",
);
// Test plan mode with custom message
expect(getBaseSystemMessage("plan", mockModel)).toBe(
// Test plan mode with custom message and tools
expect(getBaseSystemMessage("plan", mockModel, [mockTool])).toBe(
"Custom Plan System Message",
);
// Test chat mode with custom message
expect(getBaseSystemMessage("chat", mockModel)).toBe(
// Test chat mode with custom message and tools
expect(getBaseSystemMessage("chat", mockModel, [mockTool])).toBe(
"Custom Chat System Message",
);
// Test agent mode with default message
expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe(
DEFAULT_AGENT_SYSTEM_MESSAGE,
);
// Test agent mode with default message and tools
expect(
getBaseSystemMessage("agent", {} as ModelDescription, [mockTool]),
).toBe(DEFAULT_AGENT_SYSTEM_MESSAGE);
// Test plan mode with default message
expect(getBaseSystemMessage("plan", {} as ModelDescription)).toBe(
// Test plan mode with default message and tools
expect(getBaseSystemMessage("plan", {} as ModelDescription, [mockTool])).toBe(
DEFAULT_PLAN_SYSTEM_MESSAGE,
);
// Test chat mode with default message
expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe(
// Test chat mode with default message and tools
expect(getBaseSystemMessage("chat", {} as ModelDescription, [mockTool])).toBe(
DEFAULT_CHAT_SYSTEM_MESSAGE,
);
});
test("getBaseSystemMessage should append no-tools warning for agent/plan modes without tools", () => {
const mockModel = {
baseChatSystemMessage: "Custom Chat System Message",
basePlanSystemMessage: "Custom Plan System Message",
baseAgentSystemMessage: "Custom Agent System Message",
} as ModelDescription;
// Test agent mode without tools
expect(getBaseSystemMessage("agent", mockModel, [])).toBe(
"Custom Agent System Message" + NO_TOOL_WARNING,
);
// Test plan mode without tools
expect(getBaseSystemMessage("plan", mockModel, [])).toBe(
"Custom Plan System Message" + NO_TOOL_WARNING,
);
// Test chat mode without tools (should not append warning)
expect(getBaseSystemMessage("chat", mockModel, [])).toBe(
"Custom Chat System Message",
);
// Test agent mode with undefined tools
expect(getBaseSystemMessage("agent", mockModel)).toBe(
"Custom Agent System Message" + NO_TOOL_WARNING,
);
// Test plan mode with undefined tools
expect(getBaseSystemMessage("plan", mockModel)).toBe(
"Custom Plan System Message" + NO_TOOL_WARNING,
);
});

View file

@ -1,19 +1,32 @@
import { ModelDescription } from "core";
import { ModelDescription, Tool } from "core";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
DEFAULT_PLAN_SYSTEM_MESSAGE,
} from "core/llm/defaultSystemMessages";
export const NO_TOOL_WARNING =
"\n\nTHE USER HAS NOT PROVIDED ANY TOOLS, DO NOT ATTEMPT TO USE ANY TOOLS. STOP AND LET THE USER KNOW THAT THERE ARE NO TOOLS AVAILABLE. The user can provide tools by enabling them in the Tool Policies section of the notch (wrench icon)";
export function getBaseSystemMessage(
messageMode: string,
model: ModelDescription,
activeTools?: Tool[],
): string {
let baseMessage: string;
if (messageMode === "agent") {
return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
baseMessage = model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
} else if (messageMode === "plan") {
return model.basePlanSystemMessage ?? DEFAULT_PLAN_SYSTEM_MESSAGE;
baseMessage = model.basePlanSystemMessage ?? DEFAULT_PLAN_SYSTEM_MESSAGE;
} else {
return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
baseMessage = model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
}
// Add no-tools warning for agent/plan modes when no tools are available
if (messageMode !== "chat" && (!activeTools || activeTools.length === 0)) {
baseMessage += NO_TOOL_WARNING;
}
return baseMessage;
}

View file

@ -93,9 +93,11 @@ describe("E2E Scenarios", () => {
const registry: Registry = {
getContent: async function (id: PackageIdentifier): Promise<string> {
const slug = packageIdentifierToShorthandSlug(id);
return fs
.readFileSync(`./src/__tests__/packages/${slug}.yaml`)
.toString();
const filePath =
id.uriType === "slug"
? `./src/__tests__/packages/${slug}.yaml`
: id.filePath;
return fs.readFileSync(filePath).toString();
},
};
@ -230,7 +232,7 @@ describe("E2E Scenarios", () => {
orgScopeId: "test-org",
currentUserSlug: "test-user",
onPremProxyUrl: null,
// Add an injected block
// Add injected blocks
injectBlocks: [
{
uriType: "slug",
@ -240,11 +242,16 @@ describe("E2E Scenarios", () => {
versionSlug: "latest",
},
},
{
uriType: "file",
filePath: "./src/__tests__/local-files/rules.yaml",
},
],
},
);
const config = unrolledConfig.config;
const errors = unrolledConfig.errors;
// The original rules array should have two items
expect(config?.rules?.length).toBe(3); // Now 3 with the injected block
@ -255,7 +262,72 @@ describe("E2E Scenarios", () => {
);
// Check the injected doc block was added
expect(config?.rules?.[2]).toBe("Be kind");
expect(
typeof config?.rules?.[2] !== "string" &&
config?.rules?.[2]?.rule === "Be humble",
);
// Check if we receive one error that is caused by duplicate rules
expect(errors?.length).toBe(1);
expect(errors?.[0].message.includes("Duplicate rules detected"));
});
it("duplicate detection should happen in the assistant config first and then the intected blocks", async () => {
const unrolledConfig = await unrollAssistant(
{
uriType: "file",
filePath: "./src/__tests__/local-files/duplicate-test-assistant.yaml",
},
registry,
{
renderSecrets: true,
platformClient,
orgScopeId: "test-org",
currentUserSlug: "test-user",
onPremProxyUrl: null,
// Add injected blocks
injectBlocks: [
{
uriType: "file",
filePath: "./src/__tests__/local-files/rules.yaml",
},
{
uriType: "file",
filePath: "./src/__tests__/local-files/mcpServer.yaml",
},
{
uriType: "file",
filePath: "./src/__tests__/local-files/prompt.yaml",
},
],
},
);
const config = unrolledConfig.config;
const errors = unrolledConfig.errors;
// Check if all the duplicate blocks get removed
expect(config?.models?.length).toBe(1);
expect(config?.context?.length).toBe(1);
expect(config?.mcpServers?.length).toBe(1);
expect(config?.rules?.length).toBe(1);
expect(config?.prompts?.length).toBe(1);
expect(config?.docs?.length).toBe(1);
// Check if there are 8 duplication detected
expect(errors?.length).toBe(8);
// Beginning of the assistant config duplication check
expect(
errors?.[0].message.includes("Duplicate models named gpt-5 detected"),
).toBe(true);
// Beginning of the injected blocks duplication check
expect(errors?.[4].message.includes("Duplicate rules detected")).toBe(true);
expect(
errors?.[6].message.includes(
"Duplicate mcpServers named Browser search detected",
),
).toBe(true);
});
it.skip("should prioritize org over user / package secrets", () => {});

View file

@ -0,0 +1,39 @@
name: Duplicate Test Assistant
version: 0.0.1
schema: v1
docs:
- name: React
startUrl: https://react.dev
- name: React
startUrl: https://react.dev
rules:
- Be humble
- uses: ./src/__tests__/local-files/rules.yaml
models:
- name: gpt-5
provider: openai
model: gpt-5
apiKey: ${{ secrets.OPENAI_API_KEY }}
roles:
- chat
- name: gpt-5
provider: openai
model: gpt-5
apiKey: ${{ secrets.OPENAI_API_KEY }}
roles:
- chat
mcpServers:
- uses: ./src/__tests__/local-files/mcpServer.yaml
prompts:
- uses: ./src/__tests__/local-files/prompt.yaml
- uses: ./src/__tests__/local-files/prompt.yaml
context:
- provider: doc
- provider: doc

View file

@ -0,0 +1,8 @@
name: Local MCP Server
version: 0.0.1
schema: v1
mcpServers:
- name: Browser search
command: npx
args:
- "@playwright/mcp@latest"

View file

@ -0,0 +1,7 @@
name: Local prompt
version: 0.0.1
schema: v1
prompts:
- name: duplication test
description: test purpose
prompt: Please check that this prompt should only appear once

View file

@ -0,0 +1,6 @@
name: Rules
version: 0.0.1
schema: v1
rules:
- Be humble

View file

@ -0,0 +1,76 @@
import { BLOCK_TYPES, BlockType } from "./getBlockType.js";
export class BlockDuplicationDetector {
private records: Map<string, Set<string>>;
constructor() {
this.records = new Map();
for (const blockType of BLOCK_TYPES) {
this.records.set(blockType, new Set());
}
}
private isRuleDuplicated(rule: any): boolean {
if (typeof rule === "string") {
return this.check(rule, "rules");
} else {
return this.check(rule.name, "rules");
}
}
private isContextDuplicated(context: any): boolean {
return this.check(context.provider, "context");
}
private isCommonBlockDuplicated(block: any, blockType: BlockType): boolean {
return this.check(block.name, blockType);
}
private check(identifier: string, blockType: BlockType): boolean {
if (this.records.get(blockType)!.has(identifier)) {
return true;
} else {
this.records.get(blockType)!.add(identifier);
return false;
}
}
// Check if the name is duplicated within the same blockType
isDuplicated(
block: any,
blockType: BlockType,
injectError?: (errorMsg: string) => void,
): boolean {
// Not checking any null or undefined object
if (block === null || block === undefined) {
return false;
}
switch (blockType) {
case "rules":
if (this.isRuleDuplicated(block)) {
injectError?.(
`Duplicate rules${typeof block === "string" ? "" : ` named ${block.name}`} detected. The duplicate one has been deleted for preventing unexpected behavior.`,
);
return true;
}
return false;
case "context":
if (this.isContextDuplicated(block)) {
injectError?.(
`Duplicate ${block.provider} context providers detected. The duplicate one has been deleted for preventing unexpected behavior.`,
);
return true;
}
return false;
default:
if (this.isCommonBlockDuplicated(block, blockType)) {
injectError?.(
`Duplicate ${blockType} named ${block.name} detected. The duplicate one has been deleted for preventing unexpected behavior.`,
);
return true;
}
return false;
}
}
}

View file

@ -20,6 +20,7 @@ import {
Rule,
} from "../schemas/index.js";
import { ConfigResult, ConfigValidationError } from "../validation.js";
import { BlockDuplicationDetector } from "./blockDuplicationDetector.js";
import {
packageIdentifierToShorthandSlug,
useProxyForUnrenderedSecrets,
@ -306,6 +307,13 @@ export async function unrollBlocks(
): Promise<ConfigResult<AssistantUnrolled>> {
const errors: ConfigValidationError[] = [];
function injectDuplicationError(errorMsg: string) {
errors.push({
fatal: false,
message: errorMsg,
});
}
const unrolledAssistant: AssistantUnrolled = {
name: assistant.name,
version: assistant.version,
@ -484,7 +492,7 @@ export async function unrollBlocks(
const injectedResults = await Promise.all(injectedBlockPromises);
const injectedErrors: ConfigValidationError[] = [];
const injectedBlocks: {
blockType: string;
blockType: BlockType;
resolvedBlock: any;
source?: string;
}[] = [];
@ -521,16 +529,27 @@ export async function unrollBlocks(
errors.push(...rulesResult.errors);
errors.push(...injectedResult.errors);
const detector = new BlockDuplicationDetector();
// Assign section results
for (const sectionResult of sectionResults) {
if (sectionResult.blocks) {
unrolledAssistant[sectionResult.section] = sectionResult.blocks;
unrolledAssistant[sectionResult.section] = sectionResult.blocks.filter(
(block) =>
!detector.isDuplicated(
block,
sectionResult.section,
injectDuplicationError,
),
);
}
}
// Assign rules result
if (rulesResult.rules) {
unrolledAssistant.rules = rulesResult.rules;
unrolledAssistant.rules = rulesResult.rules.filter(
(rule) => !detector.isDuplicated(rule, "rules", injectDuplicationError),
);
}
// Add injected blocks
@ -539,16 +558,20 @@ export async function unrollBlocks(
resolvedBlock,
source,
} of injectedResult.injectedBlocks) {
const key = blockType as BlockType;
const key = blockType;
if (!unrolledAssistant[key]) {
unrolledAssistant[key] = [];
}
const blocksWithSourceFiles = injectLocalSourceFile(
const filteredBlocks = injectLocalSourceFile(
key,
resolvedBlock,
source,
).filter(
(block: any) =>
!detector.isDuplicated(block, blockType, injectDuplicationError),
);
unrolledAssistant[key]?.push(...blocksWithSourceFiles);
unrolledAssistant[key]?.push(...filteredBlocks);
}
const configResult: ConfigResult<AssistantUnrolled> = {

View file

@ -36,6 +36,7 @@ export type ModelRole = z.infer<typeof modelRolesSchema>;
export const modelCapabilitySchema = z.union([
z.literal("tool_use"),
z.literal("image_input"),
z.literal("next_edit"),
]);
export type ModelCapability = z.infer<typeof modelCapabilitySchema>;

View file

@ -75,6 +75,15 @@ export const OpenAi: ModelProvider = {
contextLength: 128000,
maxCompletionTokens: 4096,
},
// gpt-5
{
model: "gpt-5",
displayName: "GPT-5",
contextLength: 400000,
maxCompletionTokens: 128000,
regex: /gpt-5/,
recommendedFor: ["chat"],
},
// gpt-4o
{
model: "gpt-4o",

View file

@ -38,7 +38,7 @@ export class OpenAIApi implements BaseLlmApi {
// o-series models - only apply for official OpenAI API
const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
if (isOfficialOpenAIAPI) {
if (body.model.startsWith("o")) {
if (body.model.startsWith("o") || body.model.includes("gpt-5")) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;