Merge branch 'main' into nate/cleanup
This commit is contained in:
commit
86567d6a34
158 changed files with 8255 additions and 1564 deletions
10
.github/workflows/jetbrains-release.yaml
vendored
10
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -116,7 +116,7 @@ jobs:
|
|||
|
||||
# Validate wrapper
|
||||
- name: Gradle Wrapper Validation
|
||||
uses: gradle/actions/wrapper-validation@v5
|
||||
uses: gradle/actions/wrapper-validation@v6
|
||||
|
||||
# # Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
|
|
@ -127,7 +127,7 @@ jobs:
|
|||
|
||||
# # Setup Gradle
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
with:
|
||||
gradle-home-cache-cleanup: true
|
||||
|
||||
|
|
@ -444,7 +444,7 @@ jobs:
|
|||
|
||||
# Setup Gradle
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
with:
|
||||
gradle-home-cache-cleanup: true
|
||||
|
||||
|
|
@ -491,7 +491,7 @@ jobs:
|
|||
|
||||
# Run Qodana inspections
|
||||
- name: Qodana - Code Inspection
|
||||
uses: JetBrains/qodana-action@v2025.3.1
|
||||
uses: JetBrains/qodana-action@v2025.3.2
|
||||
with:
|
||||
cache-default-branch-only: true
|
||||
|
||||
|
|
@ -522,7 +522,7 @@ jobs:
|
|||
|
||||
# Setup Gradle
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
with:
|
||||
gradle-home-cache-cleanup: true
|
||||
|
||||
|
|
|
|||
2
.github/workflows/metrics.yaml
vendored
2
.github/workflows/metrics.yaml
vendored
|
|
@ -52,7 +52,7 @@ jobs:
|
|||
echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Post a message in a channel
|
||||
uses: slackapi/slack-github-action@v2.1.1
|
||||
uses: slackapi/slack-github-action@v3.0.1
|
||||
with:
|
||||
webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
|
||||
webhook-type: incoming-webhook
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ jobs:
|
|||
distribution: "temurin"
|
||||
java-version: 17
|
||||
- name: Generate and submit dependency graph
|
||||
uses: gradle/actions/dependency-submission@v5
|
||||
uses: gradle/actions/dependency-submission@v6
|
||||
with:
|
||||
# The gradle project is not in the root of the repository.
|
||||
build-root-directory: extensions/intellij
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
20.19.0
|
||||
20.20.1
|
||||
|
|
|
|||
2
.nvmrc
2
.nvmrc
|
|
@ -1 +1 @@
|
|||
v20.19.0
|
||||
v20.20.1
|
||||
|
|
|
|||
|
|
@ -115,7 +115,7 @@ process as welcoming and straightforward as possible.
|
|||
|
||||
#### Pre-requisites
|
||||
|
||||
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it
|
||||
You should have Node.js version 20.20.1 (LTS) or higher installed. You can get it
|
||||
on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct
|
||||
version of Node.js for this project by running the following command in the root of the project:
|
||||
|
||||
|
|
|
|||
1074
binary/package-lock.json
generated
1074
binary/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -71,6 +71,77 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
// Qwen multi-file FIM template for repository-level autocompletion
|
||||
// https://github.com/continuedev/continue/issues/3589
|
||||
const qwenMultifileFimTemplate: AutocompleteTemplate = {
|
||||
compilePrefixSuffix: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceUris: string[],
|
||||
): [string, string] => {
|
||||
function getFileName(snippet: { uri: string; uniquePath: string }): string {
|
||||
return snippet.uri.startsWith("file://")
|
||||
? snippet.uniquePath
|
||||
: snippet.uri;
|
||||
}
|
||||
|
||||
if (snippets.length === 0) {
|
||||
return [prefix, suffix];
|
||||
}
|
||||
|
||||
const relativePaths = getShortestUniqueRelativeUriPaths(
|
||||
[
|
||||
...snippets.map((snippet) =>
|
||||
"filepath" in snippet ? snippet.filepath : "Untitled.txt",
|
||||
),
|
||||
filepath,
|
||||
],
|
||||
workspaceUris,
|
||||
);
|
||||
|
||||
const fileContents = snippets
|
||||
.map((snippet, i) => {
|
||||
if (snippet.type === AutocompleteSnippetType.Diff) {
|
||||
return `<|file_sep|>${getFileName(relativePaths[i])}\n${snippet.content}`;
|
||||
}
|
||||
return `<|file_sep|>${getFileName(relativePaths[i])}\n${snippet.content}`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const fullPrefix = `<|repo_name|>${reponame}\n${fileContents}\n<|file_sep|>${getFileName(
|
||||
relativePaths[relativePaths.length - 1],
|
||||
)}<|system_separator_istruction_repository_level|>${prefix}`;
|
||||
|
||||
return [fullPrefix, suffix];
|
||||
},
|
||||
template: (prefix: string, suffix: string): string => {
|
||||
if (prefix.includes("<|system_separator_istruction_repository_level|>")) {
|
||||
const [beforeSeparator, ...afterSeparator] = prefix.split(
|
||||
"<|system_separator_istruction_repository_level|>",
|
||||
);
|
||||
const combinedAfterSeparator = afterSeparator.join("");
|
||||
return `${beforeSeparator}\n<|fim_prefix|>${combinedAfterSeparator}<|fim_suffix|>${suffix}<|fim_middle|>`;
|
||||
}
|
||||
return `<|fim_prefix|>${prefix}<|fim_suffix|>${suffix}<|fim_middle|>`;
|
||||
},
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<|endoftext|>",
|
||||
"<|fim_prefix|>",
|
||||
"<|fim_middle|>",
|
||||
"<|fim_suffix|>",
|
||||
"<|fim_pad|>",
|
||||
"<|repo_name|>",
|
||||
"<|file_sep|>",
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
// https://www.ibm.com/granite/docs/models/granite#fim
|
||||
const granite4FimTemplate: AutocompleteTemplate = {
|
||||
template:
|
||||
|
|
@ -454,7 +525,7 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
}
|
||||
|
||||
if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) {
|
||||
return qwenCoderFimTemplate;
|
||||
return qwenMultifileFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("granite") && lowerCaseModel.includes("4")) {
|
||||
|
|
|
|||
|
|
@ -316,6 +316,7 @@ export class ConfigHandler {
|
|||
}
|
||||
|
||||
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
await this.isInitialized;
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
|
|
@ -323,7 +324,6 @@ export class ConfigHandler {
|
|||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
await this.isInitialized;
|
||||
const config = await this.currentProfile.loadConfig(
|
||||
this.additionalContextProviders,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest";
|
|||
export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed";
|
||||
|
||||
const ANTHROPIC_MODEL_CONFIG = {
|
||||
slugs: ["anthropic/claude-3-7-sonnet", "anthropic/claude-4-sonnet"],
|
||||
slugs: ["anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6"],
|
||||
apiKeyInputName: "ANTHROPIC_API_KEY",
|
||||
};
|
||||
const OPENAI_MODEL_CONFIG = {
|
||||
|
|
@ -19,7 +19,7 @@ const OPENAI_MODEL_CONFIG = {
|
|||
|
||||
// TODO: These need updating on the hub
|
||||
const GEMINI_MODEL_CONFIG = {
|
||||
slugs: ["google/gemini-2.5-pro", "google/gemini-2.0-flash"],
|
||||
slugs: ["google/gemini-3.1-pro-preview", "google/gemini-3-flash-preview"],
|
||||
apiKeyInputName: "GEMINI_API_KEY",
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
|
@ -12,6 +12,8 @@ import { IProfileLoader } from "./IProfileLoader.js";
|
|||
export default class LocalProfileLoader implements IProfileLoader {
|
||||
static ID = "local";
|
||||
|
||||
description: ProfileDescription;
|
||||
|
||||
constructor(
|
||||
private ide: IDE,
|
||||
private llmLogger: ILLMLogger,
|
||||
|
|
@ -19,7 +21,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
| { path: string; content: string }
|
||||
| undefined,
|
||||
) {
|
||||
const description: ProfileDescription = {
|
||||
this.description = {
|
||||
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
|
|
@ -36,19 +38,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
localPathToUri(getPrimaryConfigFilePath()),
|
||||
rawYaml: undefined,
|
||||
};
|
||||
this.description = description;
|
||||
if (overrideAssistantFile?.content) {
|
||||
try {
|
||||
const parsedAssistant = parseConfigYaml(
|
||||
overrideAssistantFile?.content ?? "",
|
||||
);
|
||||
this.description.title = parsedAssistant.name;
|
||||
} catch (e) {
|
||||
console.error("Failed to parse config file: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
description: ProfileDescription;
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const result = await doLoadConfig({
|
||||
|
|
@ -67,6 +57,12 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
|
||||
this.description.errors = result.errors;
|
||||
|
||||
// Use the config name from the loaded config (avoids duplicate file reads
|
||||
// and works in environments like WSL where paths may differ)
|
||||
if (result.configName) {
|
||||
this.description.title = result.configName;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -53,4 +53,43 @@ describe("LocalProfileLoader", () => {
|
|||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should update title from configName when available", async () => {
|
||||
mockDoLoadConfig.mockResolvedValueOnce({
|
||||
config: {},
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
configName: "My Custom Config",
|
||||
});
|
||||
|
||||
const loader = new LocalProfileLoader(
|
||||
testIde,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
);
|
||||
|
||||
expect(loader.description.title).toBe("Local Config");
|
||||
|
||||
await loader.doLoadConfig();
|
||||
|
||||
expect(loader.description.title).toBe("My Custom Config");
|
||||
});
|
||||
|
||||
it("should keep default title when configName is not set", async () => {
|
||||
mockDoLoadConfig.mockResolvedValueOnce({
|
||||
config: {},
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
});
|
||||
|
||||
const loader = new LocalProfileLoader(
|
||||
testIde,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
);
|
||||
|
||||
await loader.doLoadConfig();
|
||||
|
||||
expect(loader.description.title).toBe("Local Config");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -98,6 +98,7 @@ export default async function doLoadConfig(options: {
|
|||
let newConfig: ContinueConfig | undefined;
|
||||
let errors: ConfigValidationError[] | undefined;
|
||||
let configLoadInterrupted = false;
|
||||
let configName: string | undefined;
|
||||
|
||||
const hasPreReadContent =
|
||||
packageIdentifier.uriType === "file" &&
|
||||
|
|
@ -120,6 +121,7 @@ export default async function doLoadConfig(options: {
|
|||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
configLoadInterrupted = result.configLoadInterrupted;
|
||||
configName = result.configName;
|
||||
} else {
|
||||
const result = await loadContinueConfigFromJson(
|
||||
ide,
|
||||
|
|
@ -135,7 +137,12 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
|
||||
if (configLoadInterrupted || !newConfig) {
|
||||
return { errors, config: newConfig, configLoadInterrupted: true };
|
||||
return {
|
||||
errors,
|
||||
config: newConfig,
|
||||
configLoadInterrupted: true,
|
||||
configName,
|
||||
};
|
||||
}
|
||||
|
||||
// TODO using config result but result with non-fatal errors is an antipattern?
|
||||
|
|
@ -348,5 +355,10 @@ export default async function doLoadConfig(options: {
|
|||
// TODO: pass config to pre-load non-system TTS models
|
||||
await TTS.setup();
|
||||
|
||||
return { config: newConfig, errors, configLoadInterrupted: false };
|
||||
return {
|
||||
config: newConfig,
|
||||
errors,
|
||||
configLoadInterrupted: false,
|
||||
configName,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,9 +42,9 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
|||
configYaml.models = [
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-sonnet-4-5",
|
||||
model: "claude-sonnet-4-6",
|
||||
apiKey: "${{ secrets.ANTHROPIC_API_KEY }}",
|
||||
name: "Claude Sonnet 4.5",
|
||||
name: "Claude Sonnet 4.6",
|
||||
roles: ["chat", "edit"],
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -413,6 +413,7 @@ export async function loadContinueConfigFromYaml(options: {
|
|||
errors: configYamlResult.errors,
|
||||
config: undefined,
|
||||
configLoadInterrupted: true,
|
||||
configName: configYamlResult.configName,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -441,5 +442,6 @@ export async function loadContinueConfigFromYaml(options: {
|
|||
config: withShared,
|
||||
errors: [...(configYamlResult.errors ?? []), ...localErrors],
|
||||
configLoadInterrupted: false,
|
||||
configName: configYamlResult.configName,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,38 @@ import { LLMClasses } from "../../llm/llms";
|
|||
|
||||
const AUTODETECT = "AUTODETECT";
|
||||
|
||||
const ENV_STRING_KEYS = [
|
||||
"apiType",
|
||||
"apiVersion",
|
||||
"deployment",
|
||||
"deploymentId",
|
||||
"projectId",
|
||||
"region",
|
||||
"profile",
|
||||
"accessKeyId",
|
||||
"secretAccessKey",
|
||||
"modelArn",
|
||||
"aiGatewaySlug",
|
||||
"accountId",
|
||||
] as const;
|
||||
|
||||
function applyEnvOptions(
|
||||
options: LLMOptions,
|
||||
env: Record<string, string | boolean | number>,
|
||||
): void {
|
||||
if (
|
||||
"useLegacyCompletionsEndpoint" in env &&
|
||||
typeof env.useLegacyCompletionsEndpoint === "boolean"
|
||||
) {
|
||||
options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint;
|
||||
}
|
||||
for (const key of ENV_STRING_KEYS) {
|
||||
if (key in env && typeof env[key] === "string") {
|
||||
(options as any)[key] = env[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getModelClass(
|
||||
model: ModelConfig,
|
||||
): (typeof LLMClasses)[number] | undefined {
|
||||
|
|
@ -41,9 +73,12 @@ async function modelConfigToBaseLLM({
|
|||
config.requestOptions,
|
||||
);
|
||||
|
||||
const contextLength =
|
||||
model.contextLength ?? model.defaultCompletionOptions?.contextLength;
|
||||
|
||||
let options: LLMOptions = {
|
||||
...rest,
|
||||
contextLength: model.defaultCompletionOptions?.contextLength,
|
||||
contextLength,
|
||||
completionOptions: {
|
||||
...(model.defaultCompletionOptions ?? {}),
|
||||
model: model.model,
|
||||
|
|
@ -77,14 +112,14 @@ async function modelConfigToBaseLLM({
|
|||
|
||||
// Model capabilities - need to be undefined if not found
|
||||
// To fallback to our autodetection
|
||||
if (capabilities?.find((c) => c === "tool_use")) {
|
||||
if (capabilities?.includes("tool_use")) {
|
||||
options.capabilities = {
|
||||
...options.capabilities,
|
||||
tools: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (capabilities?.find((c) => c === "image_input")) {
|
||||
if (capabilities?.includes("image_input")) {
|
||||
options.capabilities = {
|
||||
...options.capabilities,
|
||||
uploadImage: true,
|
||||
|
|
@ -102,48 +137,8 @@ async function modelConfigToBaseLLM({
|
|||
// But we decided to move to nested `env` in YAML
|
||||
// Since types vary and we don't want to blindly spread env for now,
|
||||
// Each one is handled individually here
|
||||
const env = model.env ?? {};
|
||||
if (
|
||||
"useLegacyCompletionsEndpoint" in env &&
|
||||
typeof env.useLegacyCompletionsEndpoint === "boolean"
|
||||
) {
|
||||
options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint;
|
||||
}
|
||||
if ("apiType" in env && typeof env.apiType === "string") {
|
||||
options.apiType = env.apiType;
|
||||
}
|
||||
if ("apiVersion" in env && typeof env.apiVersion === "string") {
|
||||
options.apiVersion = env.apiVersion;
|
||||
}
|
||||
if ("deployment" in env && typeof env.deployment === "string") {
|
||||
options.deployment = env.deployment;
|
||||
}
|
||||
if ("deploymentId" in env && typeof env.deploymentId === "string") {
|
||||
options.deploymentId = env.deploymentId;
|
||||
}
|
||||
if ("projectId" in env && typeof env.projectId === "string") {
|
||||
options.projectId = env.projectId;
|
||||
}
|
||||
if ("region" in env && typeof env.region === "string") {
|
||||
options.region = env.region;
|
||||
}
|
||||
if ("profile" in env && typeof env.profile === "string") {
|
||||
options.profile = env.profile;
|
||||
}
|
||||
if ("accessKeyId" in env && typeof env.accessKeyId === "string") {
|
||||
options.accessKeyId = env.accessKeyId;
|
||||
}
|
||||
if ("secretAccessKey" in env && typeof env.secretAccessKey === "string") {
|
||||
options.secretAccessKey = env.secretAccessKey;
|
||||
}
|
||||
if ("modelArn" in env && typeof env.modelArn === "string") {
|
||||
options.modelArn = env.modelArn;
|
||||
}
|
||||
if ("aiGatewaySlug" in env && typeof env.aiGatewaySlug === "string") {
|
||||
options.aiGatewaySlug = env.aiGatewaySlug;
|
||||
}
|
||||
if ("accountId" in env && typeof env.accountId === "string") {
|
||||
options.accountId = env.accountId;
|
||||
if (model.env) {
|
||||
applyEnvOptions(options, model.env);
|
||||
}
|
||||
|
||||
const llm = new cls(options);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { homedir } from "os";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
import {
|
||||
|
|
@ -476,6 +477,13 @@ Org-level secrets can only be used for MCP by Background Agents (https://docs.co
|
|||
if (resolved.startsWith("file://")) {
|
||||
return fileURLToPath(resolved);
|
||||
}
|
||||
// Remote URIs (e.g. vscode-remote://ssh-remote+host/path) cannot be
|
||||
// used as a local cwd for child_process.spawn(). When the extension
|
||||
// runs in the Local Extension Host on Windows while connected to a
|
||||
// remote workspace, fall back to the user's home directory.
|
||||
if (resolved.includes("://")) {
|
||||
return homedir();
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
return resolved;
|
||||
|
|
|
|||
|
|
@ -175,6 +175,17 @@ describe("MCPConnection", () => {
|
|||
);
|
||||
expect(mockResolve).toHaveBeenCalledWith("src", ide);
|
||||
});
|
||||
|
||||
it("should fall back to homedir for remote URIs that cannot be used as local cwd", async () => {
|
||||
const ide = {} as any;
|
||||
vi.spyOn(ideUtils, "resolveRelativePathInDir").mockResolvedValue(
|
||||
"vscode-remote://ssh-remote+192.168.137.2/home/user/project",
|
||||
);
|
||||
const conn = new MCPConnection(baseOptions, { ide });
|
||||
|
||||
const { homedir } = require("os");
|
||||
await expect((conn as any).resolveCwd("src")).resolves.toBe(homedir());
|
||||
});
|
||||
});
|
||||
|
||||
describe("connectClient", () => {
|
||||
|
|
|
|||
|
|
@ -207,6 +207,84 @@ describe("executeFindAndReplace", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("indentation adjustment", () => {
|
||||
it("should adjust indentation when trimmedMatch finds unindented old_string in indented file", () => {
|
||||
const fileContent =
|
||||
"def foo():\n x = 1\n y = 2\n return x + y\n";
|
||||
// LLM sends unindented old_string that matches via trimmedMatch
|
||||
const oldString = "x = 1\ny = 2";
|
||||
const newString = "x = 10\ny = 20";
|
||||
const result = executeFindAndReplace(
|
||||
fileContent,
|
||||
oldString,
|
||||
newString,
|
||||
false,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"def foo():\n x = 10\n y = 20\n return x + y\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("should preserve relative inner indentation in multi-line replacement", () => {
|
||||
const fileContent =
|
||||
"class Foo:\n def bar(self):\n if True:\n x = 1\n";
|
||||
const oldString = "if True:\n x = 1";
|
||||
const newString = "if True:\n x = 1\n y = 2";
|
||||
const result = executeFindAndReplace(
|
||||
fileContent,
|
||||
oldString,
|
||||
newString,
|
||||
false,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"class Foo:\n def bar(self):\n if True:\n x = 1\n y = 2\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle tab vs space mismatch", () => {
|
||||
const fileContent = "function foo() {\n\tconst x = 1;\n}\n";
|
||||
// LLM sends with leading spaces (not tabs), triggering trimmedMatch
|
||||
const oldString = " const x = 1;";
|
||||
const newString = " const x = 2;\n const y = 3;";
|
||||
const result = executeFindAndReplace(
|
||||
fileContent,
|
||||
oldString,
|
||||
newString,
|
||||
false,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"function foo() {\n\tconst x = 2;\n\tconst y = 3;\n}\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("should not adjust indentation for exactMatch", () => {
|
||||
const fileContent = " x = 1\n";
|
||||
const oldString = " x = 1";
|
||||
const newString = " x = 2";
|
||||
const result = executeFindAndReplace(
|
||||
fileContent,
|
||||
oldString,
|
||||
newString,
|
||||
false,
|
||||
);
|
||||
expect(result).toBe(" x = 2\n");
|
||||
});
|
||||
|
||||
it("should handle whitespaceIgnoredMatch with different internal whitespace", () => {
|
||||
const fileContent = "def outer():\n if True:\n return 42\n";
|
||||
// Different internal whitespace triggers whitespaceIgnoredMatch
|
||||
const oldString = "if True:\n return 42";
|
||||
const newString = "if True:\n return 99";
|
||||
const result = executeFindAndReplace(
|
||||
fileContent,
|
||||
oldString,
|
||||
newString,
|
||||
false,
|
||||
);
|
||||
expect(result).toBe("def outer():\n if True:\n return 99\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
it("should handle single character replacement", () => {
|
||||
const content = "a b c";
|
||||
|
|
|
|||
|
|
@ -1,6 +1,86 @@
|
|||
import { EditOperation } from "../../tools/definitions/multiEdit";
|
||||
import { ContinueError, ContinueErrorReason } from "../../util/errors";
|
||||
import { findSearchMatches } from "./findSearchMatch";
|
||||
import { SearchMatchResult, findSearchMatches } from "./findSearchMatch";
|
||||
|
||||
/**
|
||||
* Get the leading whitespace of the first non-empty line in a string.
|
||||
*/
|
||||
function getLeadingIndent(text: string): string {
|
||||
const lines = text.split("\n");
|
||||
for (const line of lines) {
|
||||
if (line.trim().length > 0) {
|
||||
const match = line.match(/^(\s*)/);
|
||||
return match ? match[1] : "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the indentation of the file line containing a given character position.
|
||||
*/
|
||||
function getLineIndentAtPosition(
|
||||
fileContent: string,
|
||||
position: number,
|
||||
): string {
|
||||
const lineStart = fileContent.lastIndexOf("\n", position - 1) + 1;
|
||||
const lineEnd = fileContent.indexOf("\n", lineStart);
|
||||
const line = fileContent.substring(
|
||||
lineStart,
|
||||
lineEnd === -1 ? fileContent.length : lineEnd,
|
||||
);
|
||||
const match = line.match(/^(\s*)/);
|
||||
return match ? match[1] : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* When a fuzzy match strategy (trimmedMatch, whitespaceIgnoredMatch, etc.)
|
||||
* finds a match, the indentation of the matched region in the file may
|
||||
* differ from the indentation in the search string provided by the LLM.
|
||||
* This function adjusts newString so its indentation is relative to the
|
||||
* actual matched text in the file rather than the LLM-provided oldString.
|
||||
*/
|
||||
function adjustReplacementIndentation(
|
||||
fileContent: string,
|
||||
match: SearchMatchResult,
|
||||
oldString: string,
|
||||
newString: string,
|
||||
): string {
|
||||
if (
|
||||
match.strategyName === "exactMatch" ||
|
||||
match.strategyName === "emptySearch"
|
||||
) {
|
||||
return newString;
|
||||
}
|
||||
|
||||
const matchedIndent = getLineIndentAtPosition(fileContent, match.startIndex);
|
||||
const oldIndent = getLeadingIndent(oldString);
|
||||
|
||||
if (matchedIndent === oldIndent) {
|
||||
return newString;
|
||||
}
|
||||
|
||||
const lines = newString.split("\n");
|
||||
const adjusted = lines.map((line, index) => {
|
||||
if (line.trim().length === 0) {
|
||||
return line;
|
||||
}
|
||||
if (index === 0) {
|
||||
// First line: the file content before startIndex already provides
|
||||
// indentation, so strip the old indent rather than adding new
|
||||
if (oldIndent && line.startsWith(oldIndent)) {
|
||||
return line.slice(oldIndent.length);
|
||||
}
|
||||
return line;
|
||||
}
|
||||
// Subsequent lines: replace oldIndent prefix with matchedIndent
|
||||
if (line.startsWith(oldIndent)) {
|
||||
return matchedIndent + line.slice(oldIndent.length);
|
||||
}
|
||||
return line;
|
||||
});
|
||||
return adjusted.join("\n");
|
||||
}
|
||||
|
||||
export function executeFindAndReplace(
|
||||
fileContent: string,
|
||||
|
|
@ -23,9 +103,15 @@ export function executeFindAndReplace(
|
|||
let result = fileContent;
|
||||
for (let i = matches.length - 1; i >= 0; i--) {
|
||||
const match = matches[i];
|
||||
const adjustedNew = adjustReplacementIndentation(
|
||||
result,
|
||||
match,
|
||||
oldString,
|
||||
newString,
|
||||
);
|
||||
result =
|
||||
result.substring(0, match.startIndex) +
|
||||
newString +
|
||||
adjustedNew +
|
||||
result.substring(match.endIndex);
|
||||
}
|
||||
return result;
|
||||
|
|
@ -40,9 +126,15 @@ export function executeFindAndReplace(
|
|||
|
||||
// Apply single replacement
|
||||
const match = matches[0];
|
||||
const adjustedNew = adjustReplacementIndentation(
|
||||
fileContent,
|
||||
match,
|
||||
oldString,
|
||||
newString,
|
||||
);
|
||||
return (
|
||||
fileContent.substring(0, match.startIndex) +
|
||||
newString +
|
||||
adjustedNew +
|
||||
fileContent.substring(match.endIndex)
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,11 +66,13 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
|||
"openrouter",
|
||||
"deepseek",
|
||||
"xAI",
|
||||
"minimax",
|
||||
"groq",
|
||||
"gemini",
|
||||
"docker",
|
||||
"nous",
|
||||
"zAI",
|
||||
"tensorix",
|
||||
// TODO add these, change to inverted logic so only the ones that need templating are hardcoded
|
||||
// Asksage.ts
|
||||
// Azure.ts
|
||||
|
|
@ -128,6 +130,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
|
|||
"ovhcloud",
|
||||
"watsonx",
|
||||
"zAI",
|
||||
"tensorix",
|
||||
];
|
||||
|
||||
const MODEL_SUPPORTS_IMAGES: RegExp[] = [
|
||||
|
|
@ -246,6 +249,8 @@ const PARALLEL_PROVIDERS: string[] = [
|
|||
"vertexai",
|
||||
"function-network",
|
||||
"scaleway",
|
||||
"minimax",
|
||||
"tensorix",
|
||||
];
|
||||
|
||||
function llmCanGenerateInParallel(provider: string, model: string): boolean {
|
||||
|
|
|
|||
|
|
@ -298,15 +298,51 @@ describe("extractToolSequence", () => {
|
|||
);
|
||||
});
|
||||
|
||||
test("extractToolSequence should throw error when last message is not user or tool", () => {
|
||||
test("extractToolSequence should handle trailing assistant message", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("Hello"),
|
||||
createAssistantMessage("Hi there!"),
|
||||
];
|
||||
|
||||
expect(() => extractToolSequence(messages)).toThrow(
|
||||
"Error parsing chat history: no user/tool message found",
|
||||
);
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(1);
|
||||
expect(sequence[0].role).toBe("assistant");
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0].role).toBe("user");
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle trailing thinking message", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("Hello"),
|
||||
{
|
||||
role: "thinking",
|
||||
content: "Let me think about this...",
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(1);
|
||||
expect(sequence[0].role).toBe("thinking");
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0].role).toBe("user");
|
||||
});
|
||||
|
||||
test("extractToolSequence should collect full trailing thinking+assistant turn", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("Hello"),
|
||||
{ role: "thinking", content: "Let me think..." } as ChatMessage,
|
||||
createAssistantMessage("Hi there!"),
|
||||
];
|
||||
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(2);
|
||||
expect(sequence[0].role).toBe("thinking");
|
||||
expect(sequence[1].role).toBe("assistant");
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0].role).toBe("user");
|
||||
});
|
||||
|
||||
test("extractToolSequence should throw error when messages array is empty", () => {
|
||||
|
|
|
|||
|
|
@ -227,7 +227,7 @@ function countChatMessageTokens(
|
|||
*/
|
||||
function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
|
||||
const lastMsg = messages.pop();
|
||||
if (!lastMsg || !isUserOrToolMsg(lastMsg)) {
|
||||
if (!lastMsg) {
|
||||
throw new Error("Error parsing chat history: no user/tool message found");
|
||||
}
|
||||
|
||||
|
|
@ -262,6 +262,15 @@ function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
|
|||
}
|
||||
}
|
||||
}
|
||||
} else if (lastMsg.role === "assistant" || lastMsg.role === "thinking") {
|
||||
toolSequence.push(lastMsg);
|
||||
while (
|
||||
messages.length > 0 &&
|
||||
(messages[messages.length - 1].role === "thinking" ||
|
||||
messages[messages.length - 1].role === "assistant")
|
||||
) {
|
||||
toolSequence.unshift(messages.pop()!);
|
||||
}
|
||||
} else {
|
||||
// Single user message
|
||||
toolSequence.push(lastMsg);
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ import { parseDataUrl } from "../../util/url.js";
|
|||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
import { withLLMRetry } from "../utils/retry.js";
|
||||
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
|
|
@ -71,6 +70,29 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private async _getClient(): Promise<BedrockRuntimeClient> {
|
||||
if (this.apiKey) {
|
||||
// Bedrock API key authentication (bearer token)
|
||||
return new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
endpoint: this.apiBase,
|
||||
token: async () => ({ token: this.apiKey! }),
|
||||
});
|
||||
}
|
||||
|
||||
// IAM credential authentication
|
||||
const credentials = await this._getCredentials();
|
||||
return new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
endpoint: this.apiBase,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -82,22 +104,12 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
@withLLMRetry()
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
endpoint: this.apiBase,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
const client = await this._getClient();
|
||||
|
||||
let config_headers =
|
||||
this.requestOptions && this.requestOptions.headers
|
||||
|
|
@ -238,7 +250,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// Clean up state and let the original error bubble up to the retry decorator
|
||||
// Clean up state and let the original error bubble up for retry handling
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -602,15 +614,7 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
// EMBED //
|
||||
async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
const client = await this._getClient();
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
|
|
@ -685,15 +689,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
|
||||
try {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
const client = await this._getClient();
|
||||
|
||||
// Base payload for both models
|
||||
const payload: any = {
|
||||
|
|
|
|||
|
|
@ -207,11 +207,10 @@ class CometAPI extends OpenAI {
|
|||
"claude-3-5-haiku-latest",
|
||||
|
||||
// Gemini series
|
||||
"gemini-3-pro-preview",
|
||||
"gemini-3.1-pro-preview",
|
||||
"gemini-2.5-pro",
|
||||
"gemini-2.5-flash",
|
||||
"gemini-2.5-flash-lite",
|
||||
"gemini-2.0-flash",
|
||||
|
||||
// Grok series
|
||||
"grok-4-0709",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import {
|
|||
GeminiGenerationConfig,
|
||||
GeminiToolFunctionDeclaration,
|
||||
convertContinueToolToGeminiFunction,
|
||||
mergeConsecutiveGeminiMessages,
|
||||
} from "./gemini-types";
|
||||
|
||||
interface GeminiToolCallDelta extends ToolCallDelta {
|
||||
|
|
@ -36,7 +37,7 @@ class Gemini extends BaseLLM {
|
|||
static providerName = "gemini";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "gemini-pro",
|
||||
model: "gemini-2.5-flash",
|
||||
apiBase: "https://generativelanguage.googleapis.com/v1beta/",
|
||||
maxStopWords: 5,
|
||||
maxEmbeddingBatchSize: 100,
|
||||
|
|
@ -326,6 +327,8 @@ class Gemini extends BaseLLM {
|
|||
};
|
||||
}),
|
||||
};
|
||||
|
||||
body.contents = mergeConsecutiveGeminiMessages(body.contents);
|
||||
if (options) {
|
||||
body.generationConfig = this.convertArgs(options);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ class LlamaCpp extends BaseLLM {
|
|||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
prompt,
|
||||
stream: true,
|
||||
...this._convertArgs(options, prompt),
|
||||
|
|
|
|||
37
core/llm/llms/MiniMax.ts
Normal file
37
core/llm/llms/MiniMax.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class MiniMax extends OpenAI {
|
||||
static providerName = "minimax";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.minimax.io/v1/",
|
||||
model: "MiniMax-M2.7",
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
|
||||
const finalOptions = super._convertArgs(options, messages);
|
||||
|
||||
// MiniMax requires temperature in (0.0, 1.0] — zero is rejected
|
||||
if (
|
||||
finalOptions.temperature !== undefined &&
|
||||
finalOptions.temperature !== null
|
||||
) {
|
||||
if (finalOptions.temperature <= 0) {
|
||||
finalOptions.temperature = 0.01;
|
||||
} else if (finalOptions.temperature > 1) {
|
||||
finalOptions.temperature = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
// MiniMax does not support response_format
|
||||
if ((finalOptions as any).response_format) {
|
||||
delete (finalOptions as any).response_format;
|
||||
}
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
}
|
||||
|
||||
export default MiniMax;
|
||||
|
|
@ -6,6 +6,13 @@ import OpenAI from "./OpenAI.js";
|
|||
|
||||
class Moonshot extends OpenAI {
|
||||
static providerName = "moonshot";
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this.supportsReasoningContentField =
|
||||
this.model?.startsWith("kimi") ?? false;
|
||||
}
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.moonshot.cn/v1/",
|
||||
model: "moonshot-v1-8k",
|
||||
|
|
|
|||
226
core/llm/llms/Ollama.test.ts
Normal file
226
core/llm/llms/Ollama.test.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
jest.mock("@continuedev/fetch", () => ({
|
||||
streamResponse: jest.fn(),
|
||||
}));
|
||||
|
||||
import { ChatMessage } from "../../index.js";
|
||||
import Ollama from "./Ollama.js";
|
||||
|
||||
function createOllama(): Ollama {
|
||||
// Create instance without triggering constructor's fetch call
|
||||
const instance = Object.create(Ollama.prototype);
|
||||
instance.model = "test-model";
|
||||
instance.completionOptions = {};
|
||||
instance.fetch = jest.fn();
|
||||
return instance;
|
||||
}
|
||||
|
||||
describe("Ollama", () => {
|
||||
describe("_convertToOllamaMessage", () => {
|
||||
let ollama: Ollama;
|
||||
|
||||
beforeEach(() => {
|
||||
ollama = createOllama();
|
||||
});
|
||||
|
||||
it("should convert a basic user message", () => {
|
||||
const msg: ChatMessage = { role: "user", content: "hello" };
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
expect(result).toEqual({ role: "user", content: "hello" });
|
||||
});
|
||||
|
||||
it("should convert assistant message with toolCalls, stripping index and other unsupported fields", () => {
|
||||
const msg: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tc_123",
|
||||
type: "function",
|
||||
index: 0, // This field causes errors on Gemma3
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: '{"city":"London"}',
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
};
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
|
||||
expect(result.tool_calls).toBeDefined();
|
||||
expect(result.tool_calls).toHaveLength(1);
|
||||
expect(result.tool_calls[0]).toEqual({
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: { city: "London" },
|
||||
},
|
||||
});
|
||||
// Verify no index, id, or type fields leaked through
|
||||
expect(result.tool_calls[0]).not.toHaveProperty("index");
|
||||
expect(result.tool_calls[0]).not.toHaveProperty("id");
|
||||
expect(result.tool_calls[0]).not.toHaveProperty("type");
|
||||
});
|
||||
|
||||
it("should handle toolCalls with object arguments (not string)", () => {
|
||||
const msg: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tc_456",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: { query: "test" } as any,
|
||||
},
|
||||
} as any,
|
||||
],
|
||||
};
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
expect(result.tool_calls[0].function.arguments).toEqual({
|
||||
query: "test",
|
||||
});
|
||||
});
|
||||
|
||||
it("should not add tool_calls for assistant messages without them", () => {
|
||||
const msg: ChatMessage = { role: "assistant", content: "Sure!" };
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
expect(result.tool_calls).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should convert tool result messages", () => {
|
||||
const msg: ChatMessage = {
|
||||
role: "tool",
|
||||
content: '{"temp": 20}',
|
||||
toolCallId: "tc_123",
|
||||
};
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
expect(result.role).toBe("tool");
|
||||
expect(result.content).toBe('{"temp": 20}');
|
||||
});
|
||||
|
||||
it("should filter out toolCalls without a function name", () => {
|
||||
const msg: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tc_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "valid_tool",
|
||||
arguments: "{}",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "tc_2",
|
||||
type: "function",
|
||||
function: {
|
||||
name: undefined as any,
|
||||
arguments: "{}",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = (ollama as any)._convertToOllamaMessage(msg);
|
||||
expect(result.tool_calls).toHaveLength(1);
|
||||
expect(result.tool_calls[0].function.name).toBe("valid_tool");
|
||||
});
|
||||
});
|
||||
|
||||
describe("_reorderMessagesForToolCompat", () => {
|
||||
let ollama: Ollama;
|
||||
|
||||
beforeEach(() => {
|
||||
ollama = createOllama();
|
||||
});
|
||||
|
||||
it("should move system message from after tool to before assistant+tool block", () => {
|
||||
const messages = [
|
||||
{ role: "system" as const, content: "You are helpful" },
|
||||
{ role: "user" as const, content: "What's the weather?" },
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "",
|
||||
tool_calls: [{ function: { name: "get_weather", arguments: {} } }],
|
||||
},
|
||||
{ role: "tool" as const, content: '{"temp": 20}' },
|
||||
{ role: "system" as const, content: "Use metric units" },
|
||||
{ role: "user" as const, content: "Thanks" },
|
||||
];
|
||||
|
||||
const result = (ollama as any)._reorderMessagesForToolCompat(messages);
|
||||
|
||||
// No system message should follow a tool message
|
||||
for (let i = 1; i < result.length; i++) {
|
||||
if (result[i].role === "system") {
|
||||
expect(result[i - 1].role).not.toBe("tool");
|
||||
}
|
||||
}
|
||||
|
||||
// The moved system message should appear before the assistant
|
||||
const sysIdx = result.findIndex(
|
||||
(m: any) => m.role === "system" && m.content === "Use metric units",
|
||||
);
|
||||
const assistantIdx = result.findIndex((m: any) => m.role === "assistant");
|
||||
expect(sysIdx).toBeLessThan(assistantIdx);
|
||||
});
|
||||
|
||||
it("should not modify messages when no system follows tool", () => {
|
||||
const messages = [
|
||||
{ role: "system" as const, content: "You are helpful" },
|
||||
{ role: "user" as const, content: "Hello" },
|
||||
{ role: "assistant" as const, content: "Hi there" },
|
||||
];
|
||||
|
||||
const result = (ollama as any)._reorderMessagesForToolCompat(messages);
|
||||
expect(result).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should handle multiple tool results before a system message", () => {
|
||||
const messages = [
|
||||
{ role: "user" as const, content: "Do two things" },
|
||||
{
|
||||
role: "assistant" as const,
|
||||
content: "",
|
||||
tool_calls: [
|
||||
{ function: { name: "tool1", arguments: {} } },
|
||||
{ function: { name: "tool2", arguments: {} } },
|
||||
],
|
||||
},
|
||||
{ role: "tool" as const, content: "result1" },
|
||||
{ role: "tool" as const, content: "result2" },
|
||||
{ role: "system" as const, content: "extra instructions" },
|
||||
];
|
||||
|
||||
const result = (ollama as any)._reorderMessagesForToolCompat(messages);
|
||||
|
||||
// System should come before the assistant message
|
||||
const sysIdx = result.findIndex(
|
||||
(m: any) => m.content === "extra instructions",
|
||||
);
|
||||
const assistantIdx = result.findIndex((m: any) => m.role === "assistant");
|
||||
expect(sysIdx).toBeLessThan(assistantIdx);
|
||||
|
||||
// No system message should follow a tool message
|
||||
for (let i = 1; i < result.length; i++) {
|
||||
if (result[i].role === "system") {
|
||||
expect(result[i - 1].role).not.toBe("tool");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("should handle system message after tool when no preceding assistant", () => {
|
||||
// Edge case: tool messages without a preceding assistant
|
||||
const messages = [
|
||||
{ role: "tool" as const, content: "result" },
|
||||
{ role: "system" as const, content: "instructions" },
|
||||
];
|
||||
|
||||
const result = (ollama as any)._reorderMessagesForToolCompat(messages);
|
||||
|
||||
// System should be moved before tool
|
||||
expect(result[0].role).toBe("system");
|
||||
expect(result[1].role).toBe("tool");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -161,6 +161,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
private static modelsBeingInstalledMutex = new Mutex();
|
||||
|
||||
private fimSupported: boolean = false;
|
||||
private templateSupportsTools: boolean | undefined = undefined;
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
|
|
@ -227,6 +228,11 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
* it's a good indication the model supports FIM.
|
||||
*/
|
||||
this.fimSupported = !!body?.template?.includes(".Suffix");
|
||||
|
||||
// Check if model template supports tool calling (same pattern as .Suffix above)
|
||||
if (body?.template) {
|
||||
this.templateSupportsTools = body.template.includes(".Tools");
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
// console.warn("Error calling the Ollama /api/show endpoint: ", e);
|
||||
|
|
@ -313,6 +319,41 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
};
|
||||
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
|
||||
// Convert assistant tool calls to Ollama format, stripping unsupported
|
||||
// fields like `index` (which causes errors on Gemma3 models).
|
||||
if (
|
||||
message.role === "assistant" &&
|
||||
"toolCalls" in message &&
|
||||
message.toolCalls?.length
|
||||
) {
|
||||
ollamaMessage.tool_calls = message.toolCalls
|
||||
.filter((tc) => tc.function?.name)
|
||||
.map((tc) => {
|
||||
let args: JSONSchema7Object;
|
||||
if (typeof tc.function!.arguments === "string") {
|
||||
try {
|
||||
args = JSON.parse(tc.function!.arguments!);
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`Failed to parse tool call arguments for "${tc.function!.name}": ${e}`,
|
||||
);
|
||||
args = {};
|
||||
}
|
||||
} else {
|
||||
args = tc.function!.arguments
|
||||
? (tc.function!.arguments as unknown as JSONSchema7Object)
|
||||
: {};
|
||||
}
|
||||
return {
|
||||
function: {
|
||||
name: tc.function!.name!,
|
||||
arguments: args,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(message.content)) {
|
||||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
|
|
@ -409,12 +450,47 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorder messages so that system messages never appear directly after tool
|
||||
* messages. Some Ollama models (Mistral, Ministral) reject the sequence
|
||||
* `tool → system` with "Unexpected role 'system' after role 'tool'".
|
||||
* This moves such system messages to just before the preceding
|
||||
* assistant+tool block.
|
||||
*/
|
||||
private _reorderMessagesForToolCompat(
|
||||
messages: OllamaChatMessage[],
|
||||
): OllamaChatMessage[] {
|
||||
const result: OllamaChatMessage[] = [...messages];
|
||||
|
||||
for (let i = 1; i < result.length; i++) {
|
||||
if (result[i].role === "system" && result[i - 1].role === "tool") {
|
||||
// Find the start of the tool block (assistant tool_call + tool results)
|
||||
let insertIdx = i - 1;
|
||||
while (insertIdx > 0 && result[insertIdx - 1].role === "tool") {
|
||||
insertIdx--;
|
||||
}
|
||||
// Also skip past the assistant message that triggered the tool calls
|
||||
if (insertIdx > 0 && result[insertIdx - 1].role === "assistant") {
|
||||
insertIdx--;
|
||||
}
|
||||
|
||||
const [sysMsg] = result.splice(i, 1);
|
||||
result.splice(insertIdx, 0, sysMsg);
|
||||
// Don't increment i — re-check current position after splice
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const ollamaMessages = messages.map(this._convertToOllamaMessage);
|
||||
const ollamaMessages = this._reorderMessagesForToolCompat(
|
||||
messages.map(this._convertToOllamaMessage),
|
||||
);
|
||||
const chatOptions: OllamaChatOptions = {
|
||||
model: this._getModel(),
|
||||
messages: ollamaMessages,
|
||||
|
|
@ -424,8 +500,12 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
stream: options.stream,
|
||||
// format: options.format, // Not currently in base completion options
|
||||
};
|
||||
// This logic is because tools can ONLY be included with user message for ollama
|
||||
if (options.tools?.length && ollamaMessages.at(-1)?.role === "user") {
|
||||
// Only include tools with user messages, and only if the template supports them
|
||||
if (
|
||||
options.tools?.length &&
|
||||
ollamaMessages.at(-1)?.role === "user" &&
|
||||
this.templateSupportsTools !== false
|
||||
) {
|
||||
chatOptions.tools = options.tools.map((tool) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
|
|
@ -715,8 +795,12 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
const chunk = new TextDecoder().decode(value);
|
||||
const lines = chunk.split("\n").filter(Boolean);
|
||||
for (const line of lines) {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
try {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
} catch (e) {
|
||||
console.warn(`Error parsing Ollama pull response: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
|
|
|
|||
14
core/llm/llms/Tensorix.ts
Normal file
14
core/llm/llms/Tensorix.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
import type { LLMOptions } from "../../index.js";
|
||||
|
||||
class Tensorix extends OpenAI {
|
||||
static providerName = "tensorix";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.tensorix.ai/v1/",
|
||||
model: "deepseek/deepseek-chat-v3.1",
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
}
|
||||
|
||||
export default Tensorix;
|
||||
|
|
@ -424,3 +424,27 @@ interface LogprobsResult {
|
|||
interface TopCandidates {
|
||||
candidates: Candidate[];
|
||||
}
|
||||
|
||||
// Gemini requires strict user/model role alternation.
|
||||
export function mergeConsecutiveGeminiMessages(
|
||||
contents: GeminiChatContent[],
|
||||
): GeminiChatContent[] {
|
||||
if (contents.length === 0) {
|
||||
return contents;
|
||||
}
|
||||
|
||||
const merged: GeminiChatContent[] = [contents[0]];
|
||||
|
||||
for (let i = 1; i < contents.length; i++) {
|
||||
const current = contents[i];
|
||||
const previous = merged[merged.length - 1];
|
||||
|
||||
if (current.role === previous.role) {
|
||||
previous.parts = [...previous.parts, ...current.parts];
|
||||
} else {
|
||||
merged.push(current);
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import Lemonade from "./Lemonade";
|
|||
import LMStudio from "./LMStudio";
|
||||
import Mistral from "./Mistral";
|
||||
import Mimo from "./Mimo";
|
||||
import MiniMax from "./MiniMax";
|
||||
import MockLLM from "./Mock";
|
||||
import Moonshot from "./Moonshot";
|
||||
import Msty from "./Msty";
|
||||
|
|
@ -56,7 +57,7 @@ import SageMaker from "./SageMaker";
|
|||
import SambaNova from "./SambaNova";
|
||||
import Scaleway from "./Scaleway";
|
||||
import SiliconFlow from "./SiliconFlow";
|
||||
|
||||
import Tensorix from "./Tensorix";
|
||||
import TARS from "./TARS";
|
||||
import TestLLM from "./Test";
|
||||
import TextGenWebUI from "./TextGenWebUI";
|
||||
|
|
@ -92,6 +93,7 @@ export const LLMClasses = [
|
|||
LMStudio,
|
||||
Mistral,
|
||||
Mimo,
|
||||
MiniMax,
|
||||
Bedrock,
|
||||
BedrockImport,
|
||||
SageMaker,
|
||||
|
|
@ -120,6 +122,7 @@ export const LLMClasses = [
|
|||
VertexAI,
|
||||
xAI,
|
||||
SiliconFlow,
|
||||
Tensorix,
|
||||
Scaleway,
|
||||
Relace,
|
||||
Inception,
|
||||
|
|
|
|||
|
|
@ -1,50 +1,42 @@
|
|||
import { toResponsesInput } from "./openaiTypeConverters";
|
||||
import { toResponsesInput, isItemType } from "./openaiTypeConverters";
|
||||
import { ChatMessage } from "..";
|
||||
import type { ResponseInputItem } from "openai/resources/responses/responses.mjs";
|
||||
import type {
|
||||
EasyInputMessage,
|
||||
ResponseInputItem,
|
||||
ResponseFunctionToolCall,
|
||||
ResponseReasoningItem,
|
||||
ResponseOutputMessage,
|
||||
} from "openai/resources/responses/responses.mjs";
|
||||
|
||||
// Types for test assertions (simplified from OpenAI types)
|
||||
type FunctionCallItem = {
|
||||
type: "function_call";
|
||||
id: string;
|
||||
name: string;
|
||||
arguments: string;
|
||||
call_id: string;
|
||||
};
|
||||
|
||||
type FunctionCallOutputItem = {
|
||||
type: "function_call_output";
|
||||
call_id: string;
|
||||
output: string;
|
||||
};
|
||||
|
||||
type MessageItem = {
|
||||
role: string;
|
||||
content: unknown;
|
||||
};
|
||||
|
||||
// Helper functions for filtering results
|
||||
function getFunctionCalls(items: ResponseInputItem[]): FunctionCallItem[] {
|
||||
return items.filter(
|
||||
(item) => (item as { type?: string }).type === "function_call",
|
||||
) as unknown as FunctionCallItem[];
|
||||
function getFunctionCalls(
|
||||
items: ResponseInputItem[],
|
||||
): ResponseFunctionToolCall[] {
|
||||
return items.filter((i): i is ResponseFunctionToolCall =>
|
||||
isItemType<ResponseFunctionToolCall>(i, "function_call"),
|
||||
);
|
||||
}
|
||||
|
||||
function getFunctionCallOutputs(
|
||||
items: ResponseInputItem[],
|
||||
): FunctionCallOutputItem[] {
|
||||
return items.filter(
|
||||
(item) => (item as { type?: string }).type === "function_call_output",
|
||||
) as unknown as FunctionCallOutputItem[];
|
||||
): ResponseInputItem.FunctionCallOutput[] {
|
||||
return items.filter((i): i is ResponseInputItem.FunctionCallOutput =>
|
||||
isItemType<ResponseInputItem.FunctionCallOutput>(i, "function_call_output"),
|
||||
);
|
||||
}
|
||||
|
||||
function getMessagesByRole(
|
||||
function getReasoningItems(
|
||||
items: ResponseInputItem[],
|
||||
role: string,
|
||||
): MessageItem[] {
|
||||
): ResponseReasoningItem[] {
|
||||
return items.filter((i): i is ResponseReasoningItem =>
|
||||
isItemType<ResponseReasoningItem>(i, "reasoning"),
|
||||
);
|
||||
}
|
||||
|
||||
function getMessagesByRole(items: ResponseInputItem[], role: string) {
|
||||
return items.filter((item) => {
|
||||
const msg = item as { role?: string; type?: string };
|
||||
return msg.role === role && (!msg.type || msg.type === "message");
|
||||
}) as unknown as MessageItem[];
|
||||
if (!("role" in item) || item.role !== role) return false;
|
||||
return !("type" in item) || item.type === "message";
|
||||
});
|
||||
}
|
||||
|
||||
describe("openaiTypeConverters", () => {
|
||||
|
|
@ -82,7 +74,7 @@ describe("openaiTypeConverters", () => {
|
|||
expect(functionCalls[0].name).toBe("filesystem_list_directory");
|
||||
});
|
||||
|
||||
it("should NOT emit function_call when no fc_ ID in metadata", () => {
|
||||
it("should emit function_call WITHOUT id when no fc_ ID in metadata", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "assistant",
|
||||
|
|
@ -103,8 +95,11 @@ describe("openaiTypeConverters", () => {
|
|||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Should still emit function_call (without id) so tool results aren't orphaned
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(0);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(functionCalls[0].id).toBeUndefined();
|
||||
expect(functionCalls[0].call_id).toBe("call_xyz");
|
||||
|
||||
// Text should still be emitted
|
||||
const assistantMessages = getMessagesByRole(result, "assistant");
|
||||
|
|
@ -137,13 +132,61 @@ describe("openaiTypeConverters", () => {
|
|||
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(assistantMessages.length).toBe(1);
|
||||
expect(assistantMessages[0].content).toBe("Let me help you with that.");
|
||||
expect((assistantMessages[0] as EasyInputMessage).content).toBe(
|
||||
"Let me help you with that.",
|
||||
);
|
||||
});
|
||||
|
||||
it("should filter out msg_ IDs from responsesOutputItemIds", () => {
|
||||
// When streaming, both msg_ and fc_ IDs accumulate in responsesOutputItemIds.
|
||||
// Only fc_ IDs should be used for function_call items.
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Let me read those files.",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_001",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "read_file",
|
||||
arguments: '{"path":"test.py"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
metadata: {
|
||||
// msg_ ID came first (from message output_item.added),
|
||||
// fc_ ID came second (from function_call output_item.added)
|
||||
responsesOutputItemIds: ["msg_abc123", "fc_001"],
|
||||
responsesOutputItemId: "fc_001",
|
||||
},
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
// Must use fc_ ID, not msg_ ID
|
||||
expect(functionCalls[0].id).toBe("fc_001");
|
||||
expect(functionCalls[0].call_id).toBe("call_001");
|
||||
});
|
||||
});
|
||||
|
||||
describe("function_call_output handling", () => {
|
||||
it("should emit function_call_output for tool role messages", () => {
|
||||
it("should emit function_call_output when preceded by matching function_call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_abc123",
|
||||
type: "function",
|
||||
function: { name: "list_files", arguments: "{}" },
|
||||
},
|
||||
],
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "tool",
|
||||
content: '{"files": ["a.txt", "b.txt"]}',
|
||||
|
|
@ -157,9 +200,25 @@ describe("openaiTypeConverters", () => {
|
|||
expect(outputs.length).toBe(1);
|
||||
expect(outputs[0].call_id).toBe("call_abc123");
|
||||
});
|
||||
|
||||
it("should remove orphaned function_call_output with no matching function_call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "tool",
|
||||
content: '{"files": ["a.txt", "b.txt"]}',
|
||||
toolCallId: "call_abc123",
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Orphaned — no function_call with call_id "call_abc123" exists
|
||||
const outputs = getFunctionCallOutputs(result);
|
||||
expect(outputs.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Complete conversation flow tests (moved out of describe block to reduce nesting)
|
||||
// Complete conversation flow tests
|
||||
it("should handle full tool call cycle with fc_ IDs", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
|
|
@ -204,8 +263,6 @@ describe("openaiTypeConverters", () => {
|
|||
});
|
||||
|
||||
it("should handle parallel tool calls merged into ONE message with responsesOutputItemIds array", () => {
|
||||
// This is the REAL scenario: streaming parallel tool calls get merged into
|
||||
// ONE ChatMessage with multiple toolCalls and an array of fc_ IDs
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
|
|
@ -241,12 +298,10 @@ describe("openaiTypeConverters", () => {
|
|||
},
|
||||
],
|
||||
metadata: {
|
||||
// Array of fc_ IDs, one per tool call
|
||||
responsesOutputItemIds: ["fc_001", "fc_002", "fc_003"],
|
||||
responsesOutputItemId: "fc_003", // Also keep last one for backwards compat
|
||||
responsesOutputItemId: "fc_003",
|
||||
},
|
||||
} as ChatMessage,
|
||||
// Tool results
|
||||
{
|
||||
role: "tool",
|
||||
content: "# Python code",
|
||||
|
|
@ -269,7 +324,6 @@ describe("openaiTypeConverters", () => {
|
|||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(3);
|
||||
|
||||
// Verify each function_call has correct fc_ ID and call_id
|
||||
expect(functionCalls[0].id).toBe("fc_001");
|
||||
expect(functionCalls[0].call_id).toBe("call_001");
|
||||
expect(functionCalls[1].id).toBe("fc_002");
|
||||
|
|
@ -282,13 +336,11 @@ describe("openaiTypeConverters", () => {
|
|||
});
|
||||
|
||||
it("should handle 3 parallel tool calls when each has its own fc_ ID (separate messages)", () => {
|
||||
// Legacy scenario: Each function_call from OpenAI creates a separate ChatMessage
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Read these 3 files",
|
||||
},
|
||||
// First tool call
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
|
|
@ -304,7 +356,6 @@ describe("openaiTypeConverters", () => {
|
|||
],
|
||||
metadata: { responsesOutputItemId: "fc_001" },
|
||||
} as ChatMessage,
|
||||
// Second tool call
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
|
|
@ -320,7 +371,6 @@ describe("openaiTypeConverters", () => {
|
|||
],
|
||||
metadata: { responsesOutputItemId: "fc_002" },
|
||||
} as ChatMessage,
|
||||
// Third tool call
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
|
|
@ -336,7 +386,6 @@ describe("openaiTypeConverters", () => {
|
|||
],
|
||||
metadata: { responsesOutputItemId: "fc_003" },
|
||||
} as ChatMessage,
|
||||
// Tool results
|
||||
{
|
||||
role: "tool",
|
||||
content: "# Python code",
|
||||
|
|
@ -368,6 +417,293 @@ describe("openaiTypeConverters", () => {
|
|||
expect(functionOutputs.length).toBe(3);
|
||||
});
|
||||
|
||||
describe("reasoning item sanitization", () => {
|
||||
it("should remove reasoning items without encrypted_content", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
{ type: "summary_text", text: "Thinking about the problem" },
|
||||
// No encrypted_content
|
||||
],
|
||||
metadata: { reasoningId: "rs_001" },
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Here is the answer.",
|
||||
metadata: { responsesOutputItemId: "msg_001" },
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(0);
|
||||
|
||||
// Assistant message should still be present
|
||||
const assistantMsgs = getMessagesByRole(result, "assistant");
|
||||
expect(assistantMsgs.length).toBe(1);
|
||||
});
|
||||
|
||||
it("should keep reasoning items WITH encrypted_content followed by function_call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
{ type: "summary_text", text: "Let me use a tool" },
|
||||
{
|
||||
type: "encrypted_content",
|
||||
encrypted_content: "encrypted_data_here",
|
||||
},
|
||||
],
|
||||
metadata: { reasoningId: "rs_001" },
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_001",
|
||||
type: "function",
|
||||
function: { name: "read_file", arguments: '{"path":"a.txt"}' },
|
||||
},
|
||||
],
|
||||
metadata: {
|
||||
responsesOutputItemIds: ["fc_001"],
|
||||
},
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(1);
|
||||
expect(reasoning[0].id).toBe("rs_001");
|
||||
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(functionCalls[0].id).toBe("fc_001");
|
||||
});
|
||||
|
||||
it("should strip fc_ id from function_calls after removed reasoning", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
// No encrypted_content — will be removed
|
||||
],
|
||||
metadata: { reasoningId: "rs_001" },
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_001",
|
||||
type: "function",
|
||||
function: { name: "read_file", arguments: '{"path":"a.txt"}' },
|
||||
},
|
||||
],
|
||||
metadata: {
|
||||
responsesOutputItemIds: ["fc_001"],
|
||||
},
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "tool",
|
||||
content: "file contents",
|
||||
toolCallId: "call_001",
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Reasoning should be removed
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(0);
|
||||
|
||||
// function_call should still be emitted but without id
|
||||
// (so API doesn't look for the missing reasoning)
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(functionCalls[0].id).toBeUndefined();
|
||||
expect(functionCalls[0].call_id).toBe("call_001");
|
||||
|
||||
// function_call_output should still match
|
||||
const outputs = getFunctionCallOutputs(result);
|
||||
expect(outputs.length).toBe(1);
|
||||
expect(outputs[0].call_id).toBe("call_001");
|
||||
});
|
||||
|
||||
it("should strip msg_ id from message after removed reasoning", () => {
|
||||
// When reasoning is removed, a following message item's msg_ ID
|
||||
// also references that reasoning — must be stripped too.
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
// No encrypted_content — will be removed
|
||||
],
|
||||
metadata: { reasoningId: "rs_001" },
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Here is the answer.",
|
||||
metadata: { responsesOutputItemId: "msg_001" },
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(0);
|
||||
|
||||
// Message should still exist but without its msg_ ID
|
||||
const assistantMsgs = getMessagesByRole(result, "assistant");
|
||||
expect(assistantMsgs.length).toBe(1);
|
||||
expect((assistantMsgs[0] as ResponseOutputMessage).id).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should recover encrypted_content from metadata fallback", () => {
|
||||
// When reasoning_details doesn't contain encrypted_content but
|
||||
// metadata does (e.g. metadata was preserved but details were incomplete)
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
{ type: "summary_text", text: "Thinking..." },
|
||||
// No encrypted_content in reasoning_details
|
||||
],
|
||||
metadata: {
|
||||
reasoningId: "rs_001",
|
||||
encrypted_content: "recovered_encrypted_data",
|
||||
},
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_001",
|
||||
type: "function",
|
||||
function: { name: "read_file", arguments: '{"path":"a.txt"}' },
|
||||
},
|
||||
],
|
||||
metadata: { responsesOutputItemIds: ["fc_001"] },
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Reasoning should be KEPT because encrypted_content was recovered from metadata
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(1);
|
||||
expect(reasoning[0].encrypted_content).toBe("recovered_encrypted_data");
|
||||
|
||||
// function_call should keep its id since reasoning is present
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(functionCalls[0].id).toBe("fc_001");
|
||||
});
|
||||
|
||||
it("should remove trailing reasoning items (no valid successor)", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Hello",
|
||||
},
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
{ type: "reasoning_id", id: "rs_001" },
|
||||
{
|
||||
type: "encrypted_content",
|
||||
encrypted_content: "encrypted_data",
|
||||
},
|
||||
],
|
||||
metadata: { reasoningId: "rs_001" },
|
||||
} as ChatMessage,
|
||||
// No assistant/function_call follows — interrupted conversation
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const reasoning = getReasoningItems(result);
|
||||
expect(reasoning.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("orphaned function_call_output removal", () => {
|
||||
it("should remove function_call_output with no matching function_call", () => {
|
||||
// This can happen when conversation history is truncated/pruned
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Hello",
|
||||
},
|
||||
// function_call was pruned, but tool result remains
|
||||
{
|
||||
role: "tool",
|
||||
content: "result data",
|
||||
toolCallId: "call_orphan",
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Here are the results.",
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const outputs = getFunctionCallOutputs(result);
|
||||
expect(outputs.length).toBe(0);
|
||||
|
||||
// Other items should be preserved
|
||||
const userMsgs = getMessagesByRole(result, "user");
|
||||
expect(userMsgs.length).toBe(1);
|
||||
const assistantMsgs = getMessagesByRole(result, "assistant");
|
||||
expect(assistantMsgs.length).toBe(1);
|
||||
});
|
||||
|
||||
it("should keep function_call_output that has a matching function_call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_valid",
|
||||
type: "function",
|
||||
function: { name: "tool", arguments: "{}" },
|
||||
},
|
||||
],
|
||||
metadata: { responsesOutputItemIds: ["fc_valid"] },
|
||||
} as ChatMessage,
|
||||
{
|
||||
role: "tool",
|
||||
content: "result",
|
||||
toolCallId: "call_valid",
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
const outputs = getFunctionCallOutputs(result);
|
||||
expect(outputs.length).toBe(1);
|
||||
expect(outputs[0].call_id).toBe("call_valid");
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
it("should handle empty messages array", () => {
|
||||
const result = toResponsesInput([]);
|
||||
|
|
@ -380,7 +716,7 @@ describe("openaiTypeConverters", () => {
|
|||
role: "assistant",
|
||||
content: "No tools needed",
|
||||
toolCalls: [],
|
||||
metadata: { responsesOutputItemId: "fc_empty" },
|
||||
metadata: { responsesOutputItemId: "msg_empty" },
|
||||
} as ChatMessage,
|
||||
];
|
||||
|
||||
|
|
@ -389,7 +725,7 @@ describe("openaiTypeConverters", () => {
|
|||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(0);
|
||||
|
||||
// Should emit as regular message instead
|
||||
// Should emit as message with msg_ ID
|
||||
const assistantMessages = getMessagesByRole(result, "assistant");
|
||||
expect(assistantMessages.length).toBe(1);
|
||||
});
|
||||
|
|
@ -415,9 +751,11 @@ describe("openaiTypeConverters", () => {
|
|||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Should not emit function_call without fc_ ID
|
||||
// Should still emit function_call (without id)
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(0);
|
||||
expect(functionCalls.length).toBe(1);
|
||||
expect(functionCalls[0].id).toBeUndefined();
|
||||
expect(functionCalls[0].call_id).toBe("call_test");
|
||||
});
|
||||
|
||||
it("should handle more toolCalls than responsesOutputItemIds", () => {
|
||||
|
|
@ -451,11 +789,12 @@ describe("openaiTypeConverters", () => {
|
|||
|
||||
const result = toResponsesInput(messages);
|
||||
|
||||
// Should only emit 2 function_calls (matching the available IDs)
|
||||
// All 3 function_calls should be emitted; third one without id
|
||||
const functionCalls = getFunctionCalls(result);
|
||||
expect(functionCalls.length).toBe(2);
|
||||
expect(functionCalls.length).toBe(3);
|
||||
expect(functionCalls[0].id).toBe("fc_001");
|
||||
expect(functionCalls[1].id).toBe("fc_002");
|
||||
expect(functionCalls[2].id).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle toolCall with missing function name", () => {
|
||||
|
|
|
|||
|
|
@ -11,10 +11,14 @@ import {
|
|||
import type {
|
||||
EasyInputMessage,
|
||||
Response as OpenAIResponse,
|
||||
ResponseFunctionCallArgumentsDeltaEvent,
|
||||
ResponseFunctionToolCall,
|
||||
ResponseInput,
|
||||
ResponseInputItem,
|
||||
ResponseInputMessageContentList,
|
||||
ResponseOutputItem,
|
||||
ResponseOutputItemAddedEvent,
|
||||
ResponseOutputItemDoneEvent,
|
||||
ResponseOutputMessage,
|
||||
ResponseOutputText,
|
||||
ResponseReasoningItem,
|
||||
|
|
@ -36,6 +40,7 @@ import {
|
|||
ThinkingChatMessage,
|
||||
ToolCallDelta,
|
||||
} from "..";
|
||||
import { stripImages } from "../util/messageContent";
|
||||
|
||||
function appendReasoningFieldsIfSupported(
|
||||
msg: ChatCompletionAssistantMessageParam & {
|
||||
|
|
@ -51,14 +56,25 @@ function appendReasoningFieldsIfSupported(
|
|||
includeReasoningContentField?: boolean;
|
||||
},
|
||||
) {
|
||||
if (!prevMessage || prevMessage.role !== "thinking") return;
|
||||
|
||||
const includeReasoning = !!providerFlags?.includeReasoningField;
|
||||
const includeReasoningDetails = !!providerFlags?.includeReasoningDetailsField;
|
||||
const includeReasoningContent = !!providerFlags?.includeReasoningContentField;
|
||||
if (!includeReasoning && !includeReasoningDetails && !includeReasoningContent)
|
||||
return;
|
||||
|
||||
const hasThinkingContent = prevMessage && prevMessage.role === "thinking";
|
||||
|
||||
// DeepSeek Reasoner requires reasoning_content on every assistant message,
|
||||
// even when no thinking message precedes it (e.g. resumed sessions).
|
||||
// Default to empty string to avoid 400 "Missing reasoning_content field".
|
||||
if (includeReasoningContent) {
|
||||
msg.reasoning_content = hasThinkingContent
|
||||
? stripImages(prevMessage.content)
|
||||
: "";
|
||||
}
|
||||
|
||||
if (!hasThinkingContent) return;
|
||||
|
||||
const reasoningDetailsValue =
|
||||
prevMessage.reasoning_details ||
|
||||
(prevMessage.signature
|
||||
|
|
@ -86,10 +102,7 @@ function appendReasoningFieldsIfSupported(
|
|||
msg.reasoning_details = reasoningDetailsValue || [];
|
||||
}
|
||||
if (includeReasoning) {
|
||||
msg.reasoning = prevMessage.content as string;
|
||||
}
|
||||
if (includeReasoningContent) {
|
||||
msg.reasoning_content = prevMessage.content as string;
|
||||
msg.reasoning = stripImages(prevMessage.content);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -422,22 +435,13 @@ function handleFunctionCallArgsDelta(e: any): ChatMessage | undefined {
|
|||
}
|
||||
|
||||
function handleOutputItemAdded(
|
||||
e: ResponseStreamEvent,
|
||||
e: ResponseOutputItemAddedEvent,
|
||||
): ChatMessage | undefined {
|
||||
const item = (e as any).item as {
|
||||
type?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
arguments?: string;
|
||||
call_id?: string;
|
||||
summary?: Array<{ type: string; text: string }>;
|
||||
encrypted_content?: string;
|
||||
};
|
||||
if (!item || !item.type) return undefined;
|
||||
const { item } = e;
|
||||
if (item.type === "reasoning") {
|
||||
const details: Array<{ [k: string]: unknown }> = [];
|
||||
if (item.id) details.push({ type: "reasoning_id", id: item.id });
|
||||
if (typeof item.encrypted_content === "string" && item.encrypted_content) {
|
||||
if (item.encrypted_content) {
|
||||
details.push({
|
||||
type: "encrypted_content",
|
||||
encrypted_content: item.encrypted_content,
|
||||
|
|
@ -450,44 +454,64 @@ function handleOutputItemAdded(
|
|||
}
|
||||
}
|
||||
}
|
||||
const thinking: ThinkingChatMessage = {
|
||||
return {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: details,
|
||||
metadata: {
|
||||
reasoningId: item.id as string,
|
||||
encrypted_content: item.encrypted_content as string | undefined,
|
||||
reasoningId: item.id,
|
||||
encrypted_content: item.encrypted_content ?? undefined,
|
||||
},
|
||||
};
|
||||
return thinking;
|
||||
} satisfies ThinkingChatMessage;
|
||||
}
|
||||
if (item.type === "message" && typeof item.id === "string") {
|
||||
if (item.type === "message") {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
metadata: { responsesOutputItemId: item.id },
|
||||
};
|
||||
}
|
||||
if (item.type === "function_call" && typeof item.id === "string") {
|
||||
const name = item.name as string | undefined;
|
||||
const args = typeof item.arguments === "string" ? item.arguments : "";
|
||||
const call_id = item.call_id as string | undefined;
|
||||
const toolCalls: ToolCallDelta[] = name
|
||||
if (item.type === "function_call") {
|
||||
const toolCalls: ToolCallDelta[] = item.name
|
||||
? [
|
||||
{
|
||||
id: call_id || (item.id as string),
|
||||
id: item.call_id || item.id,
|
||||
type: "function",
|
||||
function: { name, arguments: args },
|
||||
function: { name: item.name, arguments: item.arguments || "" },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const assistant: AssistantChatMessage = {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls,
|
||||
metadata: { responsesOutputItemId: item.id as string },
|
||||
};
|
||||
return assistant;
|
||||
metadata: { responsesOutputItemId: item.id },
|
||||
} satisfies AssistantChatMessage;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// encrypted_content is only available at output_item.done, not at .added
|
||||
function handleOutputItemDone(
|
||||
e: ResponseOutputItemDoneEvent,
|
||||
): ChatMessage | undefined {
|
||||
const { item } = e;
|
||||
if (item.type === "reasoning" && item.encrypted_content) {
|
||||
return {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: [
|
||||
...(item.id ? [{ type: "reasoning_id", id: item.id }] : []),
|
||||
{
|
||||
type: "encrypted_content",
|
||||
encrypted_content: item.encrypted_content,
|
||||
},
|
||||
],
|
||||
metadata: {
|
||||
reasoningId: item.id,
|
||||
encrypted_content: item.encrypted_content,
|
||||
},
|
||||
} satisfies ThinkingChatMessage;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -571,7 +595,10 @@ function handleResponsesStreamEvent(
|
|||
return undefined;
|
||||
}
|
||||
if (t === "response.output_item.added") {
|
||||
return handleOutputItemAdded(e);
|
||||
return handleOutputItemAdded(e as ResponseOutputItemAddedEvent);
|
||||
}
|
||||
if (t === "response.output_item.done") {
|
||||
return handleOutputItemDone(e as ResponseOutputItemDoneEvent);
|
||||
}
|
||||
if (t === "response.reasoning_summary_text.delta") {
|
||||
return handleReasoningSummaryDelta(
|
||||
|
|
@ -784,20 +811,15 @@ function toResponseInputContentList(
|
|||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits function_call items for each tool call that has a corresponding fc_ ID.
|
||||
* Extracted to reduce cyclomatic complexity in toResponsesInput.
|
||||
*/
|
||||
/** Emits function_call items for each tool call. Omits `id` when no fc_ ID is available. */
|
||||
function emitFunctionCallsFromToolCalls(
|
||||
toolCalls: ToolCallDelta[],
|
||||
respIds: string[],
|
||||
fcIds: string[],
|
||||
input: ResponseInput,
|
||||
): void {
|
||||
for (let i = 0; i < toolCalls.length; i++) {
|
||||
const tc = toolCalls[i];
|
||||
const fcId = respIds[i];
|
||||
|
||||
if (!fcId) continue; // Skip if no fc_ ID for this tool call
|
||||
const fcId = fcIds[i];
|
||||
|
||||
const name = tc?.function?.name as string | undefined;
|
||||
const args = tc?.function?.arguments as string | undefined;
|
||||
|
|
@ -805,11 +827,11 @@ function emitFunctionCallsFromToolCalls(
|
|||
|
||||
if (name && call_id) {
|
||||
const functionCallItem: ResponseFunctionToolCall = {
|
||||
id: fcId,
|
||||
type: "function_call",
|
||||
name,
|
||||
arguments: typeof args === "string" ? args : "{}",
|
||||
call_id,
|
||||
id: fcId,
|
||||
};
|
||||
input.push(functionCallItem);
|
||||
}
|
||||
|
|
@ -847,6 +869,18 @@ function convertThinkingMessageToReasoningItem(
|
|||
reasoningText += d.text;
|
||||
}
|
||||
|
||||
// Fallback to metadata if reasoning_details was incomplete
|
||||
if (!id && typeof msg.metadata?.reasoningId === "string") {
|
||||
id = msg.metadata.reasoningId;
|
||||
}
|
||||
if (
|
||||
!encrypted &&
|
||||
typeof msg.metadata?.encrypted_content === "string" &&
|
||||
(msg.metadata.encrypted_content as string).length > 0
|
||||
) {
|
||||
encrypted = msg.metadata.encrypted_content as string;
|
||||
}
|
||||
|
||||
if (!id) return undefined;
|
||||
|
||||
const reasoningItem: ResponseReasoningItem = {
|
||||
|
|
@ -868,6 +902,87 @@ function convertThinkingMessageToReasoningItem(
|
|||
return reasoningItem;
|
||||
}
|
||||
|
||||
export function isItemType<T extends ResponseInputItem & { type: string }>(
|
||||
item: ResponseInputItem,
|
||||
type: T["type"],
|
||||
): item is T {
|
||||
return "type" in item && item.type === type;
|
||||
}
|
||||
|
||||
function isValidSuccessor(item: ResponseInputItem | undefined): boolean {
|
||||
if (!item) return false;
|
||||
if (isItemType<ResponseFunctionToolCall>(item, "function_call")) return true;
|
||||
if ("type" in item && item.type === "message") return true;
|
||||
if ("role" in item && item.role === "assistant") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes sequencing/ID issues that cause OpenAI Responses API 400 errors:
|
||||
* - Removes reasoning without encrypted_content; strips id from subsequent items
|
||||
* - Removes reasoning not followed by function_call or message
|
||||
* - Removes orphaned function_call_output with no matching function_call
|
||||
*/
|
||||
function sanitizeResponsesInput(input: ResponseInput): ResponseInput {
|
||||
const skipIndices = new Set<number>();
|
||||
const stripIdIndices = new Set<number>();
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
if (!isItemType<ResponseReasoningItem>(input[i], "reasoning")) continue;
|
||||
const reasoning = input[i] as ResponseReasoningItem;
|
||||
|
||||
if (!reasoning.encrypted_content) {
|
||||
// Can't pass reasoning without encrypted_content; strip id from
|
||||
// subsequent items so the API doesn't expect the missing reasoning
|
||||
skipIndices.add(i);
|
||||
for (let j = i + 1; j < input.length; j++) {
|
||||
if (
|
||||
isItemType<ResponseFunctionToolCall>(input[j], "function_call") ||
|
||||
("type" in input[j] && input[j].type === "message")
|
||||
) {
|
||||
stripIdIndices.add(j);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isValidSuccessor(input[i + 1])) {
|
||||
skipIndices.add(i);
|
||||
}
|
||||
}
|
||||
|
||||
const result: ResponseInput = [];
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
if (skipIndices.has(i)) continue;
|
||||
if (stripIdIndices.has(i)) {
|
||||
const { id: _id, ...rest } = input[i] as ResponseFunctionToolCall;
|
||||
result.push(rest as ResponseInputItem);
|
||||
} else {
|
||||
result.push(input[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove orphaned function_call_outputs
|
||||
const validCallIds = new Set<string>();
|
||||
for (const item of result) {
|
||||
if (isItemType<ResponseFunctionToolCall>(item, "function_call")) {
|
||||
validCallIds.add(item.call_id);
|
||||
}
|
||||
}
|
||||
return result.filter((item) => {
|
||||
if (
|
||||
!isItemType<ResponseInputItem.FunctionCallOutput>(
|
||||
item,
|
||||
"function_call_output",
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return validCallIds.has(item.call_id);
|
||||
});
|
||||
}
|
||||
|
||||
export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
|
||||
const input: ResponseInput = [];
|
||||
|
||||
|
|
@ -906,34 +1021,48 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
|
|||
}
|
||||
case "assistant": {
|
||||
const text = getTextFromMessageContent(msg.content);
|
||||
const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined;
|
||||
|
||||
// Separate fc_ IDs (for function_calls) from msg_ IDs (for messages)
|
||||
const allRespIds =
|
||||
(msg.metadata?.responsesOutputItemIds as string[] | undefined) || [];
|
||||
const respId = msg.metadata?.responsesOutputItemId as
|
||||
| string
|
||||
| undefined;
|
||||
const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined;
|
||||
// Get array of fc_ IDs for parallel tool calls, fallback to single respId
|
||||
// NOTE: responsesOutputItemIds is accumulated in sessionSlice.ts during streaming.
|
||||
// We rely on OpenAI streaming events arriving in order, so respIds[i] corresponds
|
||||
// to toolCalls[i] by position. See: https://platform.openai.com/docs/guides/function-calling
|
||||
const respIds =
|
||||
(msg.metadata?.responsesOutputItemIds as string[] | undefined) ||
|
||||
(respId ? [respId] : []);
|
||||
const fcIds = allRespIds.filter((id) => id.startsWith("fc_"));
|
||||
if (fcIds.length === 0 && respId?.startsWith("fc_")) {
|
||||
fcIds.push(respId);
|
||||
}
|
||||
const msgId =
|
||||
allRespIds.find((id) => id.startsWith("msg_")) ||
|
||||
(respId?.startsWith("msg_") ? respId : undefined);
|
||||
|
||||
if (Array.isArray(toolCalls) && toolCalls.length > 0) {
|
||||
emitFunctionCallsFromToolCalls(toolCalls, fcIds, input);
|
||||
|
||||
if (
|
||||
Array.isArray(toolCalls) &&
|
||||
toolCalls.length > 0 &&
|
||||
respIds.length > 0
|
||||
) {
|
||||
// Emit function_call for EACH tool call (supports parallel tool calls)
|
||||
emitFunctionCallsFromToolCalls(toolCalls, respIds, input);
|
||||
// Also emit text content if present alongside tool calls
|
||||
if (text && text.trim()) {
|
||||
pushMessage("assistant", text);
|
||||
if (msgId) {
|
||||
const outputMessageItem: ResponseOutputMessage = {
|
||||
id: msgId,
|
||||
role: "assistant",
|
||||
type: "message",
|
||||
status: "completed",
|
||||
content: [
|
||||
{
|
||||
type: "output_text",
|
||||
text,
|
||||
annotations: [],
|
||||
} satisfies ResponseOutputText,
|
||||
],
|
||||
};
|
||||
input.push(outputMessageItem);
|
||||
} else {
|
||||
pushMessage("assistant", text);
|
||||
}
|
||||
}
|
||||
} else if (respId) {
|
||||
// Emit full assistant output message item
|
||||
} else if (msgId) {
|
||||
const outputMessageItem: ResponseOutputMessage = {
|
||||
id: respId,
|
||||
id: msgId,
|
||||
role: "assistant",
|
||||
type: "message",
|
||||
status: "completed",
|
||||
|
|
@ -947,7 +1076,6 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
|
|||
};
|
||||
input.push(outputMessageItem);
|
||||
} else {
|
||||
// Fallback to EasyInput assistant message
|
||||
pushMessage("assistant", text || "");
|
||||
}
|
||||
break;
|
||||
|
|
@ -978,7 +1106,7 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
|
|||
}
|
||||
}
|
||||
|
||||
return input;
|
||||
return sanitizeResponsesInput(input);
|
||||
}
|
||||
|
||||
export type LlmApiRequestType =
|
||||
|
|
|
|||
|
|
@ -73,8 +73,31 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
|
|||
};
|
||||
|
||||
export const defaultApplyPrompt: PromptTemplateFunction = (
|
||||
history,
|
||||
_history,
|
||||
otherData,
|
||||
) => {
|
||||
return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code. Leave existing comments in place unless changes require modifying them.`;
|
||||
return [
|
||||
{
|
||||
role: "user",
|
||||
content: dedent`
|
||||
ORIGINAL CODE:
|
||||
\`\`\`
|
||||
${otherData.original_code}
|
||||
\`\`\`
|
||||
|
||||
SUGGESTED EDIT:
|
||||
\`\`\`
|
||||
${otherData.new_code}
|
||||
\`\`\`
|
||||
|
||||
Apply the SUGGESTED EDIT to the ORIGINAL CODE. Output the complete modified file.
|
||||
- Output ONLY code. Do NOT explain, summarize, or describe changes.
|
||||
- Leave existing comments in place unless changes require modifying them.
|
||||
- Preserve all unchanged code exactly as-is.`,
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: `\`\`\`\n`,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -387,9 +387,9 @@ describe("isRecommendedAgentModel", () => {
|
|||
expect(isRecommendedAgentModel("gemini-2.5-pro-preview")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for Gemini 3 Pro models", () => {
|
||||
expect(isRecommendedAgentModel("gemini-3-pro-preview")).toBe(true);
|
||||
expect(isRecommendedAgentModel("gemini-3-pro")).toBe(true);
|
||||
it("should return true for Gemini 3.1 Pro and 3 Flash Preview models", () => {
|
||||
expect(isRecommendedAgentModel("gemini-3.1-pro-preview")).toBe(true);
|
||||
expect(isRecommendedAgentModel("gemini-3-flash-preview")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for Gemini Flash models", () => {
|
||||
|
|
@ -454,14 +454,14 @@ describe("isRecommendedAgentModel", () => {
|
|||
|
||||
describe("case insensitivity", () => {
|
||||
it("should handle uppercase model names", () => {
|
||||
expect(isRecommendedAgentModel("GEMINI-3-PRO-PREVIEW")).toBe(true);
|
||||
expect(isRecommendedAgentModel("GEMINI-3.1-PRO-PREVIEW")).toBe(true);
|
||||
expect(isRecommendedAgentModel("CLAUDE-4-SONNET")).toBe(true);
|
||||
expect(isRecommendedAgentModel("DEEPSEEK-R1")).toBe(true);
|
||||
expect(isRecommendedAgentModel("O3-MINI")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle mixed case model names", () => {
|
||||
expect(isRecommendedAgentModel("Gemini-3-Pro")).toBe(true);
|
||||
expect(isRecommendedAgentModel("Gemini-3.1-Pro-Preview")).toBe(true);
|
||||
expect(isRecommendedAgentModel("Claude-Opus-4")).toBe(true);
|
||||
expect(isRecommendedAgentModel("DeepSeek-Reasoner")).toBe(true);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -12,9 +12,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return false;
|
||||
},
|
||||
azure: (model) => {
|
||||
const lower = model.toLowerCase();
|
||||
if (
|
||||
model.toLowerCase().startsWith("gpt-4") ||
|
||||
model.toLowerCase().startsWith("o3")
|
||||
lower.startsWith("gpt-4") ||
|
||||
lower.startsWith("gpt-5") ||
|
||||
lower.startsWith("gpt-4.1") ||
|
||||
lower.startsWith("o1") ||
|
||||
lower.startsWith("o3") ||
|
||||
lower.startsWith("o4")
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
|
|
@ -139,6 +144,27 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
modelName = model;
|
||||
}
|
||||
|
||||
// Some Ollama cloud models don't support tools despite matching the
|
||||
// family-name heuristic below (https://ollama.com/search?c=cloud)
|
||||
if (modelName.toLowerCase().includes(":cloud")) {
|
||||
if (
|
||||
[
|
||||
"cogito-2.1",
|
||||
"deepseek-v3.2",
|
||||
"gemini-3-flash-preview",
|
||||
"glm-4.6",
|
||||
"glm-4.7",
|
||||
"glm-5",
|
||||
"kimi-k2.5",
|
||||
"minimax-m2",
|
||||
"minimax-m2.5",
|
||||
"minimax-m2.7",
|
||||
].some((part) => modelName.toLowerCase().startsWith(part))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
|
||||
(part) => modelName.toLowerCase().includes(part),
|
||||
|
|
@ -173,6 +199,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"devstral",
|
||||
"exaone",
|
||||
"gpt-oss",
|
||||
"glm-4",
|
||||
"glm-5",
|
||||
"deepseek",
|
||||
"dolphin",
|
||||
].some((part) => modelName.toLowerCase().includes(part))
|
||||
) {
|
||||
return true;
|
||||
|
|
@ -233,7 +263,12 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
deepseek: (model) => {
|
||||
// https://api-docs.deepseek.com/quick_start/pricing
|
||||
// https://api-docs.deepseek.com/guides/function_calling
|
||||
if (model === "deepseek-reasoner" || model === "deepseek-chat") {
|
||||
const lower = model.toLowerCase();
|
||||
if (
|
||||
lower === "deepseek-reasoner" ||
|
||||
lower === "deepseek-chat" ||
|
||||
lower.startsWith("deepseek-coder")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -306,6 +341,8 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"amazon/nova",
|
||||
"deepseek/deepseek-r1",
|
||||
"deepseek/deepseek-chat",
|
||||
"deepseek/deepseek-v3",
|
||||
"deepseek/deepseek-coder",
|
||||
"meta-llama/llama-4",
|
||||
"all-hands/openhands-lm-32b",
|
||||
"lgai-exaone/exaone",
|
||||
|
|
@ -424,7 +461,7 @@ export function isRecommendedAgentModel(modelName: string): boolean {
|
|||
[/o[134]/],
|
||||
[/deepseek/, /r1|reasoner/],
|
||||
[/gemini/, /2\.5/, /pro/],
|
||||
[/gemini/, /3-pro/],
|
||||
[/gemini/, /3\.1-pro|3-flash-preview/],
|
||||
[/gpt/, /-5|5\.1|5\.2/],
|
||||
[/gpt-4\.1/],
|
||||
[/codex/],
|
||||
|
|
|
|||
|
|
@ -173,6 +173,38 @@ describe("Retry Functionality", () => {
|
|||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should retry on overloaded error", async () => {
|
||||
const error = new Error("The server is overloaded, please try again");
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10,
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should retry on malformed json error", async () => {
|
||||
const error = new Error("Malformed JSON received from Bedrock: ...");
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10,
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should not retry AbortError", async () => {
|
||||
const error = new Error("Aborted");
|
||||
error.name = "AbortError";
|
||||
|
|
|
|||
|
|
@ -104,6 +104,15 @@ function defaultShouldRetry(error: any, attempt: number): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Overloaded / malformed stream errors (e.g. Anthropic 529, interrupted SSE)
|
||||
const lowerMessage = (error.message ?? "").toLowerCase();
|
||||
if (
|
||||
lowerMessage.includes("overloaded") ||
|
||||
lowerMessage.includes("malformed json")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Abort signal errors should not be retried
|
||||
if (isAbortError(error)) {
|
||||
return false;
|
||||
|
|
|
|||
46
core/package-lock.json
generated
46
core/package-lock.json
generated
|
|
@ -120,7 +120,7 @@
|
|||
"vitest": "^3.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
"node": ">=20.20.1"
|
||||
}
|
||||
},
|
||||
"../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
|
||||
|
|
@ -11837,9 +11837,10 @@
|
|||
"peer": true
|
||||
},
|
||||
"node_modules/flatted": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz",
|
||||
"integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA=="
|
||||
"version": "3.4.2",
|
||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
|
||||
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/fn.name": {
|
||||
"version": "1.1.0",
|
||||
|
|
@ -12658,9 +12659,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.11.7",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.7.tgz",
|
||||
"integrity": "sha512-l7qMiNee7t82bH3SeyUCt9UF15EVmaBvsppY2zQtrbIhl/yzBTny+YUxsVjSjQ6gaqaeVtZmGocom8TzBlA4Yw==",
|
||||
"version": "4.12.7",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.7.tgz",
|
||||
"integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
|
|
@ -18358,33 +18359,18 @@
|
|||
}
|
||||
},
|
||||
"node_modules/socket.io-parser": {
|
||||
"version": "4.2.4",
|
||||
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
|
||||
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
|
||||
"version": "4.2.6",
|
||||
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
|
||||
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.3.1"
|
||||
"debug": "~4.4.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/socket.io-parser/node_modules/debug": {
|
||||
"version": "4.3.7",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
|
||||
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/socks": {
|
||||
"version": "2.8.3",
|
||||
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz",
|
||||
|
|
@ -19617,9 +19603,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.23.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.23.0.tgz",
|
||||
"integrity": "sha512-VfQPToRA5FZs/qJxLIinmU59u0r7LXqoJkCzinq3ckNJp3vKEh7jTWN589YQ5+aoAC/TGRLyJLCPKcLQbM8r9g==",
|
||||
"version": "6.24.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.24.0.tgz",
|
||||
"integrity": "sha512-lVLNosgqo5EkGqh5XUDhGfsMSoO8K0BAN0TyJLvwNRSl4xWGZlCVYsAIpa/OpA3TvmnM01GWcoKmc3ZWo5wKKA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
|
|
|
|||
|
|
@ -128,6 +128,6 @@
|
|||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
"node": ">=20.20.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
195
core/tools/implementations/runTerminalCommand.timeout.vitest.ts
Normal file
195
core/tools/implementations/runTerminalCommand.timeout.vitest.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IDE, ToolExtras } from "../..";
|
||||
import { runTerminalCommandImpl } from "./runTerminalCommand";
|
||||
|
||||
// Hoist mock function so it can be referenced in vi.mock factory
|
||||
const { mockSpawn } = vi.hoisted(() => ({
|
||||
mockSpawn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:child_process", () => ({
|
||||
default: {
|
||||
spawn: mockSpawn,
|
||||
},
|
||||
spawn: mockSpawn,
|
||||
}));
|
||||
|
||||
describe("runTerminalCommand timeout functionality", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockChildProc: any;
|
||||
let mockGetIdeInfo: ReturnType<typeof vi.fn>;
|
||||
let mockGetWorkspaceDirs: ReturnType<typeof vi.fn>;
|
||||
let mockOnPartialOutput: ReturnType<typeof vi.fn>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let setTimeoutSpy: any;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let clearTimeoutSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.clearAllTimers();
|
||||
vi.useFakeTimers();
|
||||
|
||||
// Spy on setTimeout and clearTimeout
|
||||
setTimeoutSpy = vi.spyOn(global, "setTimeout");
|
||||
clearTimeoutSpy = vi.spyOn(global, "clearTimeout");
|
||||
|
||||
// Create mock child process with EventEmitter behavior
|
||||
mockChildProc = new EventEmitter();
|
||||
mockChildProc.stdout = new EventEmitter();
|
||||
mockChildProc.stderr = new EventEmitter();
|
||||
// Use exitCode/signalCode to track process state (matches Node.js ChildProcess API)
|
||||
mockChildProc.exitCode = null;
|
||||
mockChildProc.signalCode = null;
|
||||
mockChildProc.killed = false;
|
||||
mockChildProc.kill = vi.fn((signal?: NodeJS.Signals) => {
|
||||
mockChildProc.killed = true;
|
||||
setTimeout(() => {
|
||||
mockChildProc.exitCode = signal === "SIGKILL" ? 137 : 143;
|
||||
mockChildProc.signalCode = signal ?? null;
|
||||
mockChildProc.emit("close", mockChildProc.exitCode);
|
||||
}, 100);
|
||||
return true;
|
||||
});
|
||||
|
||||
mockSpawn.mockReturnValue(mockChildProc);
|
||||
|
||||
mockGetIdeInfo = vi.fn().mockResolvedValue({ remoteName: "local" });
|
||||
mockGetWorkspaceDirs = vi
|
||||
.fn()
|
||||
.mockResolvedValue(["file:///tmp/test-workspace"]);
|
||||
mockOnPartialOutput = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const createMockExtras = (
|
||||
overrides: Partial<ToolExtras> = {},
|
||||
): ToolExtras => {
|
||||
const mockIde = {
|
||||
getIdeInfo: mockGetIdeInfo,
|
||||
getWorkspaceDirs: mockGetWorkspaceDirs,
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
readRangeInFile: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
getProblems: vi.fn(),
|
||||
subprocess: vi.fn(),
|
||||
getWorkspaceConfigs: vi.fn(),
|
||||
showToast: vi.fn(),
|
||||
listWorkspaceContents: vi.fn(),
|
||||
getTerminalContents: vi.fn(),
|
||||
listFolders: vi.fn(),
|
||||
getSessionId: vi.fn(),
|
||||
runCommand: vi.fn(),
|
||||
showLines: vi.fn(),
|
||||
saveFile: vi.fn(),
|
||||
getBranch: vi.fn(),
|
||||
showDiff: vi.fn(),
|
||||
getOpenFiles: vi.fn(),
|
||||
showVirtualFile: vi.fn(),
|
||||
openFile: vi.fn(),
|
||||
getRepo: vi.fn(),
|
||||
pathSep: vi.fn(),
|
||||
fileExists: vi.fn(),
|
||||
} as unknown as IDE;
|
||||
|
||||
return {
|
||||
ide: mockIde,
|
||||
llm: {} as any,
|
||||
fetch: vi.fn() as any,
|
||||
tool: {} as any,
|
||||
config: {} as any,
|
||||
onPartialOutput: mockOnPartialOutput,
|
||||
toolCallId: "test-tool-call-id",
|
||||
...overrides,
|
||||
};
|
||||
};
|
||||
|
||||
it("should set up timeout when waitForCompletion is true", async () => {
|
||||
const extras = createMockExtras();
|
||||
const args = { command: "echo test", waitForCompletion: true };
|
||||
const resultPromise = runTerminalCommandImpl(args, extras);
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 120_000);
|
||||
mockChildProc.exitCode = 0;
|
||||
mockChildProc.emit("close", 0);
|
||||
await resultPromise;
|
||||
expect(clearTimeoutSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should NOT set up timeout when waitForCompletion is false", async () => {
|
||||
const extras = createMockExtras();
|
||||
const args = { command: "sleep 10", waitForCompletion: false };
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
const timeoutCalls = setTimeoutSpy.mock.calls.filter(
|
||||
(call: any[]) => call[1] === 120_000,
|
||||
);
|
||||
expect(timeoutCalls.length).toBe(0);
|
||||
expect(result[0].status).toContain("background");
|
||||
});
|
||||
|
||||
it("should kill process when timeout fires (streaming)", async () => {
|
||||
const extras = createMockExtras();
|
||||
const args = { command: "sleep 300", waitForCompletion: true };
|
||||
const resultPromise = runTerminalCommandImpl(args, extras);
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(mockChildProc.kill).toHaveBeenCalledWith("SIGTERM");
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await vi.runAllTimersAsync();
|
||||
const result = await resultPromise;
|
||||
expect(result[0].content).toContain(
|
||||
"[Timeout: process killed after 2 minutes]",
|
||||
);
|
||||
});
|
||||
|
||||
it("should clear timeout on normal process exit", async () => {
|
||||
const extras = createMockExtras();
|
||||
const args = { command: "echo quick", waitForCompletion: true };
|
||||
const resultPromise = runTerminalCommandImpl(args, extras);
|
||||
// Flush async setup (getIdeInfo, getWorkspaceDirs) without advancing timer time
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
mockChildProc.stdout.emit("data", Buffer.from("quick\n"));
|
||||
mockChildProc.exitCode = 0;
|
||||
mockChildProc.emit("close", 0);
|
||||
await resultPromise;
|
||||
expect(clearTimeoutSpy).toHaveBeenCalled();
|
||||
expect(mockChildProc.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should clear SIGKILL timeout when process exits between SIGTERM and SIGKILL grace period", async () => {
|
||||
const extras = createMockExtras();
|
||||
const args = { command: "sleep 300", waitForCompletion: true };
|
||||
const resultPromise = runTerminalCommandImpl(args, extras);
|
||||
|
||||
// Let initial setup complete
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
|
||||
// Advance to trigger main timeout (120s) — SIGTERM sent, SIGKILL timer started
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(mockChildProc.kill).toHaveBeenCalledWith("SIGTERM");
|
||||
expect(mockChildProc.kill).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Process exits gracefully after 2 seconds (before 5s grace period)
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
mockChildProc.exitCode = 143;
|
||||
mockChildProc.signalCode = "SIGTERM";
|
||||
mockChildProc.emit("close", 143); // SIGTERM exit code
|
||||
|
||||
// Wait for promise to resolve
|
||||
await resultPromise;
|
||||
|
||||
// Advance past the SIGKILL grace period (3 more seconds)
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
// Verify SIGKILL was NOT called (timer was cleared)
|
||||
expect(mockChildProc.kill).toHaveBeenCalledTimes(1); // Only SIGTERM
|
||||
expect(mockChildProc.kill).not.toHaveBeenCalledWith("SIGKILL");
|
||||
});
|
||||
});
|
||||
|
|
@ -2,6 +2,10 @@ import iconv from "iconv-lite";
|
|||
import childProcess from "node:child_process";
|
||||
import os from "node:os";
|
||||
import { ContinueError, ContinueErrorReason } from "../../util/errors";
|
||||
|
||||
// Default timeout for terminal commands (2 minutes)
|
||||
const DEFAULT_TOOL_TIMEOUT_MS = 120_000;
|
||||
|
||||
// Automatically decode the buffer according to the platform to avoid garbled Chinese
|
||||
function getDecodedOutput(data: Buffer): string {
|
||||
if (process.platform === "win32") {
|
||||
|
|
@ -93,17 +97,14 @@ const getColorEnv = () => ({
|
|||
CLICOLOR_FORCE: "1",
|
||||
});
|
||||
|
||||
const ENABLED_FOR_REMOTES = [
|
||||
"",
|
||||
"local",
|
||||
"wsl",
|
||||
"dev-container",
|
||||
"devcontainer",
|
||||
"ssh-remote",
|
||||
"attached-container",
|
||||
"codespaces",
|
||||
"tunnel",
|
||||
];
|
||||
// Only spawn processes locally when there is no remote workspace.
|
||||
// With extensionKind: ["ui", "workspace"], the extension host almost always
|
||||
// runs on the local machine. childProcess.spawn() executes on the extension
|
||||
// host, so for any remote workspace it would run commands on the wrong machine
|
||||
// (or fail with ENOENT when the local shell doesn't match the remote OS).
|
||||
// All remote types delegate to ide.runCommand() which routes through VS Code's
|
||||
// integrated terminal and executes in the correct remote environment.
|
||||
const LOCAL_ONLY = ["", "local"];
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
const command = getStringArg(args, "command");
|
||||
|
|
@ -114,17 +115,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const toolCallId = extras.toolCallId || "";
|
||||
|
||||
// When the extension host runs on Windows but connects to a remote workspace
|
||||
// (WSL, Dev Container, SSH, etc.), we can't spawn shells directly — the
|
||||
// platform is "win32" but commands should run in the remote's Linux/macOS.
|
||||
// Use ide.runCommand() instead to let VS Code handle the remote execution.
|
||||
const isWindowsHostWithRemote =
|
||||
process.platform === "win32" && !["", "local"].includes(ideInfo.remoteName);
|
||||
|
||||
if (
|
||||
ENABLED_FOR_REMOTES.includes(ideInfo.remoteName) &&
|
||||
!isWindowsHostWithRemote
|
||||
) {
|
||||
if (LOCAL_ONLY.includes(ideInfo.remoteName)) {
|
||||
// For streaming output
|
||||
if (extras.onPartialOutput) {
|
||||
try {
|
||||
|
|
@ -133,6 +124,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
return new Promise((resolve, reject) => {
|
||||
let terminalOutput = "";
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
let sigkillTimeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (!waitForCompletion) {
|
||||
const status = "Command is running in the background...";
|
||||
|
|
@ -168,6 +161,47 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
);
|
||||
}
|
||||
|
||||
// Check if the child process is still running.
|
||||
// `childProc.killed` only indicates that kill() was called,
|
||||
// not that the process has actually exited.
|
||||
const isRunning = () =>
|
||||
childProc.exitCode === null && childProc.signalCode === null;
|
||||
|
||||
// Set up timeout for waitForCompletion mode
|
||||
if (waitForCompletion) {
|
||||
timeoutId = setTimeout(() => {
|
||||
if (isRunning()) {
|
||||
terminalOutput +=
|
||||
"\n[Timeout: process killed after 2 minutes]\n";
|
||||
|
||||
// Update UI with timeout message
|
||||
if (extras.onPartialOutput) {
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: "Command timed out",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
// Try graceful termination first
|
||||
childProc.kill("SIGTERM");
|
||||
|
||||
// Force kill after 5 seconds if still running
|
||||
sigkillTimeoutId = setTimeout(() => {
|
||||
if (isRunning()) {
|
||||
childProc.kill("SIGKILL");
|
||||
}
|
||||
}, 5_000);
|
||||
}
|
||||
}, DEFAULT_TOOL_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
childProc.stdout?.on("data", (data) => {
|
||||
// Skip if this process has been backgrounded
|
||||
if (isProcessBackgrounded(toolCallId)) return;
|
||||
|
|
@ -240,6 +274,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
}
|
||||
|
||||
childProc.on("close", (code) => {
|
||||
// Clear timeout on normal completion
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
// Clear inner SIGKILL timeout if process exits before grace period
|
||||
if (sigkillTimeoutId) {
|
||||
clearTimeout(sigkillTimeoutId);
|
||||
}
|
||||
|
||||
// Clean up process tracking
|
||||
if (toolCallId) {
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
|
|
@ -296,6 +340,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
});
|
||||
|
||||
childProc.on("error", (error) => {
|
||||
// Clear timeout on error
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
// Clear SIGKILL timeout to prevent delayed kill after rejection
|
||||
if (sigkillTimeoutId) {
|
||||
clearTimeout(sigkillTimeoutId);
|
||||
}
|
||||
|
||||
// Clean up process tracking
|
||||
if (toolCallId) {
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
|
|
@ -325,6 +379,9 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
getShellCommand(command);
|
||||
const output = await new Promise<{ stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
let sigkillTimeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const childProc = childProcess.spawn(
|
||||
nonStreamingShell,
|
||||
nonStreamingArgs,
|
||||
|
|
@ -342,6 +399,29 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
// Check if the child process is still running.
|
||||
// `childProc.killed` only indicates that kill() was called,
|
||||
// not that the process has actually exited.
|
||||
const isRunning = () =>
|
||||
childProc.exitCode === null && childProc.signalCode === null;
|
||||
|
||||
// Set up timeout
|
||||
timeoutId = setTimeout(() => {
|
||||
if (isRunning()) {
|
||||
stderr += "\n[Timeout: process killed after 2 minutes]\n";
|
||||
|
||||
// Try graceful termination first
|
||||
childProc.kill("SIGTERM");
|
||||
|
||||
// Force kill after 5 seconds if still running
|
||||
sigkillTimeoutId = setTimeout(() => {
|
||||
if (isRunning()) {
|
||||
childProc.kill("SIGKILL");
|
||||
}
|
||||
}, 5_000);
|
||||
}
|
||||
}, DEFAULT_TOOL_TIMEOUT_MS);
|
||||
|
||||
childProc.stdout?.on("data", (data) => {
|
||||
stdout += getDecodedOutput(data);
|
||||
});
|
||||
|
|
@ -351,6 +431,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
});
|
||||
|
||||
childProc.on("close", (code) => {
|
||||
// Clear outer timeout
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
// Clear inner SIGKILL timeout if process exits before grace period
|
||||
if (sigkillTimeoutId) {
|
||||
clearTimeout(sigkillTimeoutId);
|
||||
}
|
||||
|
||||
// Clean up process tracking
|
||||
if (toolCallId) {
|
||||
removeRunningProcess(toolCallId);
|
||||
|
|
@ -369,6 +459,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
});
|
||||
|
||||
childProc.on("error", (error) => {
|
||||
// Clear timeout on error
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
// Clear SIGKILL timeout to prevent delayed kill after rejection
|
||||
if (sigkillTimeoutId) {
|
||||
clearTimeout(sigkillTimeoutId);
|
||||
}
|
||||
|
||||
// Clean up process tracking
|
||||
if (toolCallId) {
|
||||
removeRunningProcess(toolCallId);
|
||||
|
|
@ -453,16 +553,17 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
}
|
||||
}
|
||||
|
||||
// For remote environments, just run the command
|
||||
// Note: waitForCompletion is not supported in remote environments yet
|
||||
// For remote environments (SSH, WSL, Dev Container, Codespaces, etc.),
|
||||
// delegate to VS Code's integrated terminal which handles remote execution.
|
||||
// Note: output capture and waitForCompletion are not yet supported for remotes.
|
||||
await extras.ide.runCommand(command);
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
"Terminal output not available. This is only available in local development environments and not in SSH environments for example.",
|
||||
status: "Command failed",
|
||||
"Command executed in remote terminal. Output capture is not yet available for remote environments.",
|
||||
status: "Command executed",
|
||||
},
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -271,11 +271,8 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
// In remote environments, it should use the IDE's runCommand
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
|
||||
// Match the actual output message
|
||||
expect(result[0].content).toContain("Terminal output not available");
|
||||
expect(result[0].content).toContain("SSH environments");
|
||||
// Verify status field indicates command failed in remote environments
|
||||
expect(result[0].status).toBe("Command failed");
|
||||
expect(result[0].content).toContain("Command executed in remote terminal");
|
||||
expect(result[0].status).toBe("Command executed");
|
||||
});
|
||||
|
||||
it("should handle errors when executing invalid commands", async () => {
|
||||
|
|
@ -608,7 +605,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
});
|
||||
|
||||
describe("remote environment handling", () => {
|
||||
it("should use ide.runCommand for non-enabled remote environments", async () => {
|
||||
it("should use ide.runCommand for remote environments", async () => {
|
||||
const extras = createMockExtras({
|
||||
remoteName: "some-unsupported-remote",
|
||||
});
|
||||
|
|
@ -619,7 +616,9 @@ describe("runTerminalCommandImpl", () => {
|
|||
);
|
||||
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo test");
|
||||
expect(result[0].content).toContain("Terminal output not available");
|
||||
expect(result[0].content).toContain(
|
||||
"Command executed in remote terminal",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle local environment with file URIs", async () => {
|
||||
|
|
@ -633,50 +632,33 @@ describe("runTerminalCommandImpl", () => {
|
|||
).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it("should handle WSL environment", async () => {
|
||||
mockGetWorkspaceDirs.mockResolvedValue(["file:///home/user/workspace"]);
|
||||
it("should use ide.runCommand for WSL environment", async () => {
|
||||
// WSL is a remote — commands should execute in WSL, not on the host
|
||||
const extras = createMockExtras({ remoteName: "wsl" });
|
||||
|
||||
await expect(
|
||||
runTerminalCommandImpl(
|
||||
{ command: "echo test", waitForCompletion: false },
|
||||
createMockExtras({ remoteName: "wsl" }),
|
||||
),
|
||||
).resolves.toBeDefined();
|
||||
const result = await runTerminalCommandImpl(
|
||||
{ command: "echo test" },
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo test");
|
||||
expect(result[0].content).toContain(
|
||||
"Command executed in remote terminal",
|
||||
);
|
||||
});
|
||||
|
||||
it("should use ide.runCommand when Windows host connects to WSL", async () => {
|
||||
// When extension runs on Windows but connects to WSL, we can't spawn
|
||||
// shells directly - must use ide.runCommand instead
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, "platform", { value: "win32" });
|
||||
it("should use ide.runCommand for dev-container environment", async () => {
|
||||
const extras = createMockExtras({ remoteName: "dev-container" });
|
||||
|
||||
try {
|
||||
const extras = createMockExtras({ remoteName: "wsl" });
|
||||
const result = await runTerminalCommandImpl(
|
||||
{ command: "echo test" },
|
||||
extras,
|
||||
);
|
||||
|
||||
const result = await runTerminalCommandImpl(
|
||||
{ command: "echo test" },
|
||||
extras,
|
||||
);
|
||||
|
||||
// Should fall back to ide.runCommand, not try to spawn powershell.exe
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo test");
|
||||
expect(result[0].content).toContain("Terminal output not available");
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", {
|
||||
value: originalPlatform,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("should handle dev-container environment", async () => {
|
||||
mockGetWorkspaceDirs.mockResolvedValue(["file:///workspace"]);
|
||||
|
||||
await expect(
|
||||
runTerminalCommandImpl(
|
||||
{ command: "echo test", waitForCompletion: false },
|
||||
createMockExtras({ remoteName: "dev-container" }),
|
||||
),
|
||||
).resolves.toBeDefined();
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo test");
|
||||
expect(result[0].content).toContain(
|
||||
"Command executed in remote terminal",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ export async function* interceptSystemToolCalls(
|
|||
return result.value;
|
||||
} else {
|
||||
for await (const message of result.value) {
|
||||
if (abortController.signal.aborted || parseState?.done) {
|
||||
if (abortController.signal.aborted) {
|
||||
break;
|
||||
}
|
||||
// Skip non-assistant messages or messages with native tool calls
|
||||
|
|
@ -96,12 +96,13 @@ export async function* interceptSystemToolCalls(
|
|||
},
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// Prevent content after tool calls for now
|
||||
if (parseState) {
|
||||
continue;
|
||||
// Completed tool calls should not terminate parsing for subsequent
|
||||
// chunks/messages; reset state so normal content (or another tool
|
||||
// call) can be handled.
|
||||
if (parseState.done) {
|
||||
parseState = undefined;
|
||||
}
|
||||
|
||||
} else {
|
||||
// Yield normal assistant message
|
||||
yield [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -242,7 +242,7 @@ describe("interceptSystemToolCalls", () => {
|
|||
).toBe("}");
|
||||
});
|
||||
|
||||
it("ignores content after a tool call", async () => {
|
||||
it("preserves content after a tool call", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "assistant", content: "```tool\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
|
|
@ -250,7 +250,7 @@ describe("interceptSystemToolCalls", () => {
|
|||
[{ role: "assistant", content: "value1\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
[{ role: "assistant", content: "```\n" }],
|
||||
[{ role: "assistant", content: "This content should be ignored" }],
|
||||
[{ role: "assistant", content: "This content should be preserved" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
|
|
@ -260,14 +260,102 @@ describe("interceptSystemToolCalls", () => {
|
|||
);
|
||||
|
||||
let result;
|
||||
// Process through all the tool call parts
|
||||
for (let i = 0; i < 6; i++) {
|
||||
// Process through all the tool call deltas (name, arg prefix, arg value, closing brace)
|
||||
for (let i = 0; i < 4; i++) {
|
||||
result = await generator.next();
|
||||
}
|
||||
|
||||
// The content after the tool call should be ignored
|
||||
// The trailing newline from "```\n" is yielded as text after the tool call ends
|
||||
result = await generator.next();
|
||||
expect(result.value).toBeUndefined();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "\n" }],
|
||||
},
|
||||
]);
|
||||
|
||||
// The content after the tool call should be preserved
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "This content should be preserved" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses a tool call that appears mid-message and preserves trailing content", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[
|
||||
{
|
||||
role: "assistant",
|
||||
content:
|
||||
"Before tool\n```tool\nTOOL_NAME: test_tool\nBEGIN_ARG: arg1\nvalue1\nEND_ARG\n```\nAfter tool",
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
framework,
|
||||
);
|
||||
|
||||
let result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "Before tool" }],
|
||||
},
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "\n" }],
|
||||
},
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name,
|
||||
).toBe("test_tool");
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toContain('{"arg1":');
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe('"value1"');
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe("}");
|
||||
|
||||
// The newline between the closing ``` and "After tool" is a separate chunk
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "\n" }],
|
||||
},
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "After tool" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("stops processing when aborted", async () => {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ export function convertToUnifiedMessage(
|
|||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
...(tc.extra_content && { extra_content: tc.extra_content }),
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -104,6 +105,7 @@ export function convertFromUnifiedMessage(
|
|||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
...(tc.extra_content && { extra_content: tc.extra_content }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
@ -270,6 +272,7 @@ export function convertToUnifiedHistory(
|
|||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
...(tc.extra_content && { extra_content: tc.extra_content }),
|
||||
};
|
||||
pendingToolCalls.set(toolCall.id, toolCall);
|
||||
|
||||
|
|
|
|||
|
|
@ -14,9 +14,12 @@ const withExponentialBackoff = async <T>(
|
|||
const result = await apiCall();
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
const lowerMessage = (error.message ?? "").toLowerCase();
|
||||
if (
|
||||
(error as APIError).response?.status === 429 ||
|
||||
/"code"\s*:\s*429/.test(error.message ?? "")
|
||||
/"code"\s*:\s*429/.test(error.message ?? "") ||
|
||||
lowerMessage.includes("overloaded") ||
|
||||
lowerMessage.includes("malformed json")
|
||||
) {
|
||||
const retryAfter = (error as APIError).response?.headers.get(
|
||||
RETRY_AFTER_HEADER,
|
||||
|
|
|
|||
2
core/vendor/package-lock.json
generated
vendored
2
core/vendor/package-lock.json
generated
vendored
|
|
@ -12,7 +12,7 @@
|
|||
"@xenova/transformers": "^2.14.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
"node": ">=20.20.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@huggingface/jinja": {
|
||||
|
|
|
|||
2
core/vendor/package.json
vendored
2
core/vendor/package.json
vendored
|
|
@ -13,6 +13,6 @@
|
|||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
"node": ">=20.20.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ Every tool has one of three permission levels:
|
|||
|
||||
## Defaults
|
||||
|
||||
Read-only tools (`Read`, `List`, `Search`, `Fetch`, `Diff`) default to `allow`. Write tools (`Edit`, `MultiEdit`, `Write`) and `Bash` default to `ask`. In [headless mode](/cli/headless-mode), `ask` tools are excluded since there's no one to approve them.
|
||||
Read-only tools (`Read`, `List`, `Search`, `Fetch`, `Diff`, `AskQuestion`, `Checklist`, `Status`, `CheckBackgroundJob`, `ReportFailure`, `UploadArtifact`) default to `allow`. `AskQuestion` is a built-in read-only tool that lets the agent pause and ask for clarification before continuing. Write tools (`Edit`, `MultiEdit`, `Write`) and `Bash` default to `ask`. In [headless mode](/cli/headless-mode), `ask` tools are excluded since there's no one to approve them.
|
||||
|
||||
## Overriding with flags
|
||||
|
||||
|
|
|
|||
|
|
@ -26,14 +26,26 @@ Type `/` to see available commands. Run `/help` for the full list.
|
|||
|
||||
| Command | What it does |
|
||||
|---------|-------------|
|
||||
| `/help` | Show the help message and keyboard shortcuts |
|
||||
| `/clear` | Clear the chat history |
|
||||
| `/login` | Authenticate with your account |
|
||||
| `/logout` | Sign out of your current session |
|
||||
| `/update` | Update the Continue CLI |
|
||||
| `/whoami` | Check who you're currently logged in as |
|
||||
| `/info` | Show session information, including token usage and cost |
|
||||
| `/model` | Switch between configured chat models |
|
||||
| `/config` | Switch configuration or organization |
|
||||
| `/compact` | Summarize chat history to free up context |
|
||||
| `/fork` | Branch the conversation from the current point |
|
||||
| `/resume` | Pick up a previous session |
|
||||
| `/info` | Show token usage and cost for this session |
|
||||
| `/init` | Create an `AGENTS.md` file for the current project |
|
||||
| `/mcp` | Manage MCP server connections |
|
||||
| `/init` | Create an `AGENTS.md` file for the current project |
|
||||
| `/compact` | Summarize chat history into a compact form |
|
||||
| `/resume` | Resume a previous chat session |
|
||||
| `/fork` | Start a forked chat session from the current history |
|
||||
| `/title` | Set the title for the current session |
|
||||
| `/rename` | Rename the current session (alias for `/title`) |
|
||||
| `/exit` | Exit the chat |
|
||||
| `/jobs` | List background jobs |
|
||||
|
||||
When you're connected to a remote environment, Continue also adds remote-only slash commands such as `/diff` and `/apply`.
|
||||
|
||||
## Resume previous sessions
|
||||
|
||||
|
|
@ -49,6 +61,17 @@ cn --resume
|
|||
|
||||
This restores the full conversation history, so the agent remembers prior context.
|
||||
|
||||
## Interactive questions in TUI mode
|
||||
|
||||
The agent can use the `AskQuestion` tool to gather clarifications before it continues. You will see a quiz-style prompt directly in the terminal.
|
||||
|
||||
- Use <kbd>↑</kbd>/<kbd>↓</kbd> to highlight an option
|
||||
- Press <kbd>Enter</kbd> to submit the highlighted option
|
||||
- Start typing to send a custom answer (even when options are shown)
|
||||
- If a default answer is provided, pressing <kbd>Enter</kbd> on an empty input submits that default
|
||||
|
||||
This is useful when the agent needs decisions like scope, preferences, or environment details before making edits.
|
||||
|
||||
## Tool Permissions
|
||||
|
||||
Tools that can modify your system (file writes, terminal commands) prompt for approval before executing. You get three options:
|
||||
|
|
@ -57,4 +80,4 @@ Tools that can modify your system (file writes, terminal commands) prompt for ap
|
|||
- **Continue + don't ask again** — approve and save a policy rule to `~/.continue/permissions.yaml`
|
||||
- **No** — reject the call and give the agent new instructions
|
||||
|
||||
Read-only tools (`Read`, `List`, `Search`, `Fetch`) run automatically. See [tool permissions](/cli/tool-permissions) for the full policy system.
|
||||
Read-only tools (`Read`, `List`, `Search`, `Fetch`, `Diff`, `AskQuestion`) run automatically. See [tool permissions](/cli/tool-permissions) for the full policy system.
|
||||
|
|
|
|||
|
|
@ -202,7 +202,7 @@ This matrix shows which models support tool use and image input capabilities. Co
|
|||
| Model | Tool Use | Image Input | Context Window |
|
||||
| :--------------- | -------- | ----------- | -------------- |
|
||||
| Gemini 2.5 Pro | Yes | Yes | 2M |
|
||||
| Gemini 2.0 Flash | Yes | Yes | 1M |
|
||||
| Gemini 2.5 Flash | Yes | Yes | 1M |
|
||||
|
||||
### Mistral
|
||||
|
||||
|
|
|
|||
|
|
@ -17,19 +17,19 @@ Cloudflare Workers AI can be used for both chat and tab autocompletion in Contin
|
|||
provider: cloudflare
|
||||
apiKey: <YOUR_CLOUDFARE_API_KEY>
|
||||
model: "@cf/meta/llama-3-8b-instruct"
|
||||
contextLength: 2400
|
||||
defaultCompletionOptions:
|
||||
contextLength: 2400
|
||||
maxTokens: 500
|
||||
roles:
|
||||
- chat
|
||||
env:
|
||||
accountId: YOUR CLOUDFLARE ACCOUNT ID
|
||||
accountId: YOUR CLOUDFLARE ACCOUNT ID
|
||||
- name: DeepSeek Coder 6.7b Instruct
|
||||
provider: cloudflare
|
||||
apiKey: <YOUR_CLOUDFARE_API_KEY>
|
||||
model: "@hf/thebloke/deepseek-coder-6.7b-instruct-awq"
|
||||
contextLength: 2400
|
||||
defaultCompletionOptions:
|
||||
contextLength: 2400
|
||||
maxTokens: 500
|
||||
roles:
|
||||
- chat
|
||||
|
|
|
|||
55
docs/customize/model-providers/more/minimax.mdx
Normal file
55
docs/customize/model-providers/more/minimax.mdx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
---
|
||||
title: "How to Configure MiniMax with Continue"
|
||||
sidebarTitle: "MiniMax"
|
||||
---
|
||||
|
||||
<Info>
|
||||
Get your API key from the [MiniMax Platform](https://platform.minimax.io)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
name: My Config
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- name: MiniMax M2.7
|
||||
provider: minimax
|
||||
model: MiniMax-M2.7
|
||||
apiKey: <YOUR_MINIMAX_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "MiniMax M2.7",
|
||||
"provider": "minimax",
|
||||
"model": "MiniMax-M2.7",
|
||||
"apiKey": "<YOUR_MINIMAX_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Available Models
|
||||
|
||||
| Model | Description |
|
||||
| :---- | :---------- |
|
||||
| `MiniMax-M2.7` | Latest flagship model with enhanced reasoning and coding. 204K context window. |
|
||||
| `MiniMax-M2.7-highspeed` | High-speed version of M2.7 for low-latency scenarios. 204K context window. |
|
||||
| `MiniMax-M2.5` | Peak performance with ultimate value. 204K context window. |
|
||||
| `MiniMax-M2.5-highspeed` | Same performance, faster and more agile. 204K context window. |
|
||||
|
||||
## Notes
|
||||
|
||||
- MiniMax uses an OpenAI-compatible API at `https://api.minimax.io/v1`
|
||||
- Set the `MINIMAX_API_KEY` environment variable or configure `apiKey` in your config
|
||||
- For users in China, set `apiBase` to `https://api.minimaxi.com/v1/`
|
||||
93
docs/customize/model-providers/more/tensorix.mdx
Normal file
93
docs/customize/model-providers/more/tensorix.mdx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
---
|
||||
title: "Tensorix"
|
||||
description: "Configure Tensorix with Continue to access DeepSeek, Llama, Qwen, GLM, and other models through a single OpenAI-compatible API gateway"
|
||||
---
|
||||
|
||||
[Tensorix](https://tensorix.ai) is an OpenAI-compatible API gateway that provides access to DeepSeek, Llama, Qwen, GLM, MiniMax, and other models. Pay-as-you-go with no subscription required.
|
||||
|
||||
<Info>
|
||||
You can get an API key from
|
||||
[app.tensorix.ai](https://app.tensorix.ai).
|
||||
</Info>
|
||||
|
||||
## Chat Model
|
||||
|
||||
We recommend configuring **deepseek/deepseek-chat-v3.1** as your chat model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
name: My Config
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- name: DeepSeek Chat
|
||||
provider: tensorix
|
||||
model: deepseek/deepseek-chat-v3.1
|
||||
apiKey: <YOUR_TENSORIX_API_KEY>
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "DeepSeek Chat",
|
||||
"provider": "tensorix",
|
||||
"model": "deepseek/deepseek-chat-v3.1",
|
||||
"apiKey": "<YOUR_TENSORIX_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Autocomplete Model
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
name: My Config
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- name: DeepSeek Chat
|
||||
provider: tensorix
|
||||
model: deepseek/deepseek-chat-v3.1
|
||||
apiKey: <YOUR_TENSORIX_API_KEY>
|
||||
roles:
|
||||
- autocomplete
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "DeepSeek Chat",
|
||||
"provider": "tensorix",
|
||||
"model": "deepseek/deepseek-chat-v3.1",
|
||||
"apiKey": "<YOUR_TENSORIX_API_KEY>"
|
||||
}
|
||||
],
|
||||
"tabAutocompleteModel": {
|
||||
"title": "DeepSeek Chat",
|
||||
"provider": "tensorix",
|
||||
"model": "deepseek/deepseek-chat-v3.1",
|
||||
"apiKey": "<YOUR_TENSORIX_API_KEY>"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Embeddings Model
|
||||
|
||||
Tensorix provides access to various embedding models. [Click here](https://tensorix.ai/models) to see a list of available models.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Tensorix.ts)
|
||||
|
|
@ -38,6 +38,7 @@ Beyond the top-level providers, Continue supports many other options:
|
|||
| [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation |
|
||||
| [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting |
|
||||
| [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services |
|
||||
| [MiniMax](/customize/model-providers/more/minimax) | High-performance models with 200K+ context window |
|
||||
|
||||
### Local Model Options
|
||||
|
||||
|
|
|
|||
|
|
@ -77,6 +77,24 @@ Prompt caching is not supported in JSON configuration files, so use the YAML syn
|
|||
|
||||
## How to Set Up Authentication for Amazon Bedrock
|
||||
|
||||
### Bedrock API Keys
|
||||
|
||||
[Bedrock API keys](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html) let you authenticate without IAM credentials. Set your API key via the `apiKey` field:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude Sonnet
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-sonnet-4-20250514-v1:0
|
||||
apiKey: ${{ secrets.BEDROCK_API_KEY }}
|
||||
env:
|
||||
region: us-east-1
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
|
||||
### AWS Credentials
|
||||
|
||||
Authentication will be through temporary or long-term credentials in
|
||||
`~/.aws/credentials` under a configured profile (e.g. "bedrock").
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ Example:
|
|||
models:
|
||||
- name: My Custom Apply Template
|
||||
provider: anthropic
|
||||
model: claude-3-5-sonnet-latest
|
||||
model: claude-sonnet-4-6
|
||||
promptTemplates:
|
||||
apply: |
|
||||
Original: {{{original_code}}}
|
||||
|
|
|
|||
|
|
@ -115,9 +115,9 @@ If you prefer to use a model from [xAI](../model-providers/more/xAI), then we re
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Gemini 3 Pro from Google
|
||||
### Gemini 3.1 Pro from Google
|
||||
|
||||
If you prefer to use a model from [Google](../model-providers/top-level/gemini), then we recommend Gemini 3 Pro.
|
||||
If you prefer to use a model from [Google](../model-providers/top-level/gemini), then we recommend Gemini 3.1 Pro.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
@ -127,9 +127,9 @@ If you prefer to use a model from [Google](../model-providers/top-level/gemini),
|
|||
schema: v1
|
||||
|
||||
models:
|
||||
- name: Gemini 3 Pro
|
||||
- name: Gemini 3.1 Pro
|
||||
provider: gemini
|
||||
model: gemini-3-pro-preview
|
||||
model: gemini-3.1-pro-preview
|
||||
apiKey: <YOUR_GEMINI_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ version: 0.0.1
|
|||
schema: v1
|
||||
|
||||
models:
|
||||
- name: Claude 4 Sonnet
|
||||
- name: Claude Sonnet 4.6
|
||||
provider: anthropic
|
||||
model: claude-3-5-sonnet-latest
|
||||
model: claude-sonnet-4-6
|
||||
apiKey: <YOUR_ANTHROPIC_API_KEY>
|
||||
roles:
|
||||
- edit
|
||||
|
|
|
|||
|
|
@ -58,10 +58,10 @@ Read more about [model roles](/customize/model-roles), [model capabilities](/cus
|
|||
3. Add `OPENROUTER_API_KEY` to your environment or config
|
||||
4. Click `Reload config` in the config selector in the Continue IDE extension
|
||||
|
||||
[Gemini 2.5 Pro](https://continue.dev/google/gemini-2.5-pro) from Google
|
||||
[Gemini 3.1 Pro](https://continue.dev/google/gemini-3.1-pro-preview) from Google
|
||||
|
||||
1. Get your API key from [Google AI Studio](https://aistudio.google.com)
|
||||
2. Add [Gemini 2.5 Pro](https://continue.dev/google/gemini-2.5-pro) your Continue config
|
||||
2. Add [Gemini 3.1 Pro](https://continue.dev/google/gemini-3.1-pro-preview) your Continue config
|
||||
3. Add `GEMINI_API_KEY` to your environment or config
|
||||
4. Click `Reload config` in the config selector in the Continue IDE extension
|
||||
|
||||
|
|
|
|||
|
|
@ -116,6 +116,7 @@
|
|||
"customize/model-providers/more/moonshot",
|
||||
"customize/model-providers/more/nous",
|
||||
"customize/model-providers/more/nvidia",
|
||||
"customize/model-providers/more/tensorix",
|
||||
"customize/model-providers/more/together",
|
||||
"customize/model-providers/more/xAI",
|
||||
"customize/model-providers/more/zai"
|
||||
|
|
|
|||
|
|
@ -38,7 +38,15 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
|
|||
|
||||
You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
|
||||
|
||||
**_Windows VS Code Users_**: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
|
||||
**_Windows VS Code Users_**: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension may help Continue use the Windows certificate store, but `requestOptions.caBundlePath` is the most reliable fix.
|
||||
|
||||
### Common SSL certificate errors
|
||||
|
||||
If your logs include errors such as `unable to verify the first certificate`, `self signed certificate in certificate chain`, `certificate verify failed`, or `CERT_UNTRUSTED`, Continue was able to reach the endpoint but could not verify the TLS certificate chain it returned.
|
||||
|
||||
In most cases, the fix is to export the root or intermediate CA certificate for that endpoint and set `requestOptions.caBundlePath` in your model configuration. If the server also requires mutual TLS, add `requestOptions.clientCertificate` as well.
|
||||
|
||||
For step-by-step diagnosis with `curl` and `openssl`, see [Troubleshooting SSL certificate errors](/troubleshooting#ssl-certificate-errors).
|
||||
|
||||
### VS Code Proxy Settings
|
||||
|
||||
|
|
@ -315,4 +323,4 @@ If you'd like to perform a clean reset of the extension, including removing all
|
|||
|
||||
## Still having trouble?
|
||||
|
||||
You can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly.
|
||||
You can also join [GitHub Discussions](https://github.com/continuedev/continue/discussions) for additional support. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly.
|
||||
|
|
|
|||
|
|
@ -120,3 +120,5 @@ config.json
|
|||
]
|
||||
}
|
||||
```
|
||||
|
||||
If your endpoint uses a private or corporate CA but does not require mutual TLS, configure `requestOptions.caBundlePath` instead. For common errors like `unable to verify the first certificate` or `CERT_UNTRUSTED`, see [Configure Certificates](/faqs#configure-certificates) and [SSL certificate errors](/troubleshooting#ssl-certificate-errors).
|
||||
|
|
|
|||
|
|
@ -208,8 +208,8 @@ models:
|
|||
- name: Optimized DeepSeek
|
||||
provider: ollama
|
||||
model: deepseek-r1:32b
|
||||
contextLength: 8192 # Adjust context window (default varies by model)
|
||||
completionOptions:
|
||||
defaultCompletionOptions:
|
||||
contextLength: 8192 # Adjust context window (default varies by model)
|
||||
temperature: 0.7 # Controls randomness (0.0-1.0)
|
||||
top_p: 0.9 # Nucleus sampling threshold
|
||||
top_k: 40 # Top-k sampling
|
||||
|
|
|
|||
699
docs/package-lock.json
generated
699
docs/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -16,7 +16,7 @@
|
|||
"mintlify": "^4.2.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@c15t/react": "^1.8.2",
|
||||
"@c15t/react": "^1.8.5",
|
||||
"axios": "^1.13.5",
|
||||
"sharp": "^0.34.5",
|
||||
"tar-fs": "^3.1.1"
|
||||
|
|
|
|||
|
|
@ -110,6 +110,7 @@ The `models` section defines the language models used in your configuration. Mod
|
|||
- `stop`: An array of stop tokens that will terminate the completion.
|
||||
- `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models.
|
||||
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
|
||||
- `keepAlive`: For Ollama, the number of seconds to keep the model loaded after the last request (default: `1800`).
|
||||
|
||||
- `requestOptions`: HTTP request options specific to the model.
|
||||
|
||||
|
|
@ -382,7 +383,7 @@ name: My Config
|
|||
version: 1.0.0
|
||||
schema: v1
|
||||
models:
|
||||
- uses: anthropic/claude-3.5-sonnet
|
||||
- uses: anthropic/claude-sonnet-4-6
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
override:
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export const ModelRecommendations = ({ role = "all" }) => {
|
|||
"[Claude Opus 4.1](https://continue.dev/anthropic/claude-4-1-opus)",
|
||||
"[Claude Sonnet 4](https://continue.dev/anthropic/claude-4-sonnet)",
|
||||
"[GPT-5](https://continue.dev/openai/gpt-5)",
|
||||
"[Gemini 2.5 Pro](https://continue.dev/google/gemini-2.5-pro)",
|
||||
"[Gemini 3.1 Pro](https://continue.dev/google/gemini-3.1-pro-preview)",
|
||||
],
|
||||
notes: "Closed models are slightly better than open models",
|
||||
},
|
||||
|
|
@ -72,7 +72,7 @@ export const ModelRecommendations = ({ role = "all" }) => {
|
|||
"[Claude Opus 4.1](https://continue.dev/anthropic/claude-4-1-opus)",
|
||||
"[Claude Sonnet 4](https://continue.dev/anthropic/claude-4-sonnet)",
|
||||
"[GPT-5](https://continue.dev/openai/gpt-5)",
|
||||
"[Gemini 2.5 Pro](https://continue.dev/google/gemini-2.5-pro)",
|
||||
"[Gemini 3.1 Pro](https://continue.dev/google/gemini-3.1-pro-preview)",
|
||||
],
|
||||
notes: "Closed and open models have pretty similar performance",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ description: "Comprehensive guide to resolving common issues with Continue, incl
|
|||
3. [Download an older version](#download-an-older-version)
|
||||
4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving)
|
||||
5. [MCP Server connection issues](#mcp-server-connection-issues)
|
||||
6. [Check FAQs for common issues](/faqs)
|
||||
6. [SSL certificate errors](#ssl-certificate-errors)
|
||||
7. [Check FAQs for common issues](/faqs)
|
||||
|
||||
## Check the logs
|
||||
|
||||
|
|
@ -104,6 +105,65 @@ To find the full path to a command on your system:
|
|||
|
||||
This issue typically affects macOS users with large development environments and is being tracked in [#7870](https://github.com/continuedev/continue/issues/7870) and [#6699](https://github.com/continuedev/continue/issues/6699).
|
||||
|
||||
## SSL certificate errors
|
||||
|
||||
If Continue can reach your model endpoint but cannot verify its TLS certificate chain, you may see `fetch failed` alongside errors such as:
|
||||
|
||||
- `unable to verify the first certificate`
|
||||
- `self signed certificate in certificate chain`
|
||||
- `certificate verify failed`
|
||||
- `CERT_UNTRUSTED`
|
||||
|
||||
This usually happens when you are connecting to a self-hosted model, enterprise proxy, or internal endpoint that uses a private CA or an incomplete certificate chain.
|
||||
|
||||
### Quick fix: trust the CA bundle
|
||||
|
||||
Add the root or intermediate certificate for that endpoint to your model's `requestOptions.caBundlePath`:
|
||||
|
||||
```yaml
|
||||
models:
|
||||
- name: Secure endpoint
|
||||
provider: openai
|
||||
model: gpt-4.1
|
||||
apiBase: https://llm.example.com/v1
|
||||
requestOptions:
|
||||
caBundlePath: /path/to/ca-chain.pem
|
||||
```
|
||||
|
||||
If your setup requires mutual TLS, configure `requestOptions.clientCertificate` too. The self-hosting guide includes an example in [How to Set Up Authentication](/guides/how-to-self-host-a-model#how-to-set-up-authentication).
|
||||
|
||||
### Diagnose the certificate problem
|
||||
|
||||
1. Reproduce the error in the Continue logs so you can confirm the exact hostname that failed.
|
||||
2. Test the endpoint directly with `curl`:
|
||||
|
||||
```bash
|
||||
curl -v https://llm.example.com/v1/models
|
||||
```
|
||||
|
||||
3. Inspect the certificate chain with OpenSSL:
|
||||
|
||||
```bash
|
||||
openssl s_client -showcerts -connect llm.example.com:443 -servername llm.example.com </dev/null
|
||||
```
|
||||
|
||||
4. Save the required root or intermediate certificate as a PEM file and point `requestOptions.caBundlePath` at it.
|
||||
5. Verify the fix with curl before retrying in Continue:
|
||||
|
||||
```bash
|
||||
curl --cacert /path/to/ca-chain.pem https://llm.example.com/v1/models
|
||||
```
|
||||
|
||||
### Common setups
|
||||
|
||||
For self-hosted or enterprise deployments, these options usually help:
|
||||
|
||||
- Private CA or corporate proxy: set `requestOptions.caBundlePath`
|
||||
- Mutual TLS: set `requestOptions.clientCertificate`
|
||||
- Windows VS Code: if your certificates are managed through the Windows certificate store, the [win-ca extension](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) may help, but `requestOptions.caBundlePath` remains the most reliable option
|
||||
|
||||
As a temporary debugging step, you can set `requestOptions.verifySsl: false` to confirm the failure is certificate-related. Do not leave this disabled in normal use.
|
||||
|
||||
|
||||
## Still having trouble?
|
||||
|
||||
|
|
|
|||
1770
extensions/cli/package-lock.json
generated
1770
extensions/cli/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -20,7 +20,7 @@ param(
|
|||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue' # Faster downloads
|
||||
|
||||
$script:RequiredNodeVersion = [version]"20.19.0"
|
||||
$script:RequiredNodeVersion = [version]"20.20.1"
|
||||
$script:PackageName = "@continuedev/cli"
|
||||
$script:CliCommand = "cn"
|
||||
$script:FnmInstalled = $false
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ set -euo pipefail
|
|||
# Continue CLI Installer - Unix (macOS, Linux, WSL, Git Bash)
|
||||
# curl -fsSL https://continue.dev/install.sh | bash
|
||||
|
||||
REQUIRED_NODE_VERSION="20.19.0"
|
||||
REQUIRED_NODE_VERSION="20.20.1"
|
||||
PACKAGE_NAME="@continuedev/cli"
|
||||
CLI_COMMAND="cn"
|
||||
NETWORK_TIMEOUT=60
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
export const getAllSlashCommands = vi.fn(() => [
|
||||
export const getAllSlashCommands = vi.fn(async () => [
|
||||
{ name: "help", description: "Show help", category: "system" },
|
||||
{ name: "login", description: "Login to Continue", category: "system" },
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -5,3 +5,5 @@ export const constructSystemMessage = vi
|
|||
.mockResolvedValue(
|
||||
"You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question.",
|
||||
);
|
||||
|
||||
export const loadMarkdownRulesWithMetadata = vi.fn().mockReturnValue([]);
|
||||
|
|
|
|||
|
|
@ -17,8 +17,8 @@ describe("Slash Commands Integration", () => {
|
|||
};
|
||||
|
||||
describe("System Commands Registration", () => {
|
||||
it("should include all system commands in the commands list", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
it("should include all system commands in the commands list", async () => {
|
||||
const commands = await getAllSlashCommands(mockAssistant);
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
// Check that system commands are present (mode commands have been removed)
|
||||
|
|
@ -29,15 +29,15 @@ describe("Slash Commands Integration", () => {
|
|||
expect(commandNames).toContain("config");
|
||||
});
|
||||
|
||||
it("should include assistant prompt commands", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
it("should include assistant prompt commands", async () => {
|
||||
const commands = await getAllSlashCommands(mockAssistant);
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
expect(commandNames).toContain("test-prompt");
|
||||
});
|
||||
|
||||
it("should categorize system commands correctly", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
it("should categorize system commands correctly", async () => {
|
||||
const commands = await getAllSlashCommands(mockAssistant);
|
||||
const systemCommands = commands.filter((cmd) =>
|
||||
["help", "clear", "exit", "model", "config"].includes(cmd.name),
|
||||
);
|
||||
|
|
@ -47,8 +47,8 @@ describe("Slash Commands Integration", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("should categorize assistant commands correctly", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
it("should categorize assistant commands correctly", async () => {
|
||||
const commands = await getAllSlashCommands(mockAssistant);
|
||||
const assistantCommands = commands.filter(
|
||||
(cmd) => cmd.name === "test-prompt",
|
||||
);
|
||||
|
|
@ -57,5 +57,18 @@ describe("Slash Commands Integration", () => {
|
|||
expect(cmd.category).toBe("assistant");
|
||||
});
|
||||
});
|
||||
|
||||
it("should only show remote mode commands in remote mode", async () => {
|
||||
const commands = await getAllSlashCommands(mockAssistant, {
|
||||
isRemoteMode: true,
|
||||
});
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
// In remote mode, only remote commands should be available
|
||||
expect(commandNames).toContain("exit");
|
||||
expect(commandNames).toContain("diff");
|
||||
expect(commandNames).toContain("apply");
|
||||
expect(commandNames).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
|
||||
import {
|
||||
getSkillSlashCommandName,
|
||||
loadMarkdownSkills,
|
||||
} from "../util/loadMarkdownSkills.js";
|
||||
|
||||
// Export command functions
|
||||
export { chat } from "./chat.js";
|
||||
export { listSessionsCommand } from "./ls.js";
|
||||
|
|
@ -93,14 +98,65 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
description: "List background jobs",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "sessions",
|
||||
description: "Show all chat sessions",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "skills",
|
||||
description: "List all available skills",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "import-skill",
|
||||
description: "Import a skill from a URL or name into ~/.continue/skills",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "export",
|
||||
description: "Export a session to JSON file",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "import",
|
||||
description: "Import a session from JSON file",
|
||||
category: "system",
|
||||
},
|
||||
];
|
||||
|
||||
export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
|
||||
{
|
||||
name: "exit",
|
||||
description: "Exit the remote environment",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "diff",
|
||||
description: "Show the current diff from the remote environment",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "apply",
|
||||
description: "Apply the current diff to the local working tree",
|
||||
category: "system",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get all available slash commands including system commands and assistant prompts
|
||||
*/
|
||||
export function getAllSlashCommands(
|
||||
export async function getAllSlashCommands(
|
||||
assistant: AssistantConfig,
|
||||
): SlashCommand[] {
|
||||
options: { isRemoteMode?: boolean } = {},
|
||||
): Promise<SlashCommand[]> {
|
||||
const { isRemoteMode = false } = options;
|
||||
|
||||
// In remote mode, only show the exit command
|
||||
if (isRemoteMode) {
|
||||
return REMOTE_MODE_SLASH_COMMANDS;
|
||||
}
|
||||
|
||||
// All system commands are available
|
||||
const systemCommands = SYSTEM_SLASH_COMMANDS;
|
||||
|
||||
|
|
@ -115,7 +171,15 @@ export function getAllSlashCommands(
|
|||
// Get invokable rule commands
|
||||
const invokableRuleCommands = getInvokableRuleSlashCommands(assistant);
|
||||
|
||||
return [...systemCommands, ...assistantCommands, ...invokableRuleCommands];
|
||||
// Get skill commands
|
||||
const skillCommands = await getSkillSlashCommands();
|
||||
|
||||
return [
|
||||
...systemCommands,
|
||||
...assistantCommands,
|
||||
...invokableRuleCommands,
|
||||
...skillCommands,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -162,3 +226,16 @@ export function getInvokableRuleSlashCommands(
|
|||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get skill-based slash commands from Markdown skills
|
||||
*/
|
||||
export async function getSkillSlashCommands(): Promise<SlashCommand[]> {
|
||||
const { skills } = await loadMarkdownSkills();
|
||||
|
||||
return skills.map((skill) => ({
|
||||
name: getSkillSlashCommandName(skill),
|
||||
description: skill.description,
|
||||
category: "assistant" as const,
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
121
extensions/cli/src/commands/review/resolveReviews.test.ts
Normal file
121
extensions/cli/src/commands/review/resolveReviews.test.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveReviews } from "./resolveReviews.js";
|
||||
|
||||
vi.mock("../../auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn(() => null),
|
||||
getAccessToken: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("../../env.js", () => ({
|
||||
env: { apiBase: "https://api.continue.dev" },
|
||||
}));
|
||||
|
||||
vi.mock("../../util/logger.js", () => ({
|
||||
logger: { debug: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("fs", async () => {
|
||||
const actual = await vi.importActual("fs");
|
||||
return {
|
||||
...actual,
|
||||
existsSync: vi.fn(),
|
||||
readdirSync: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("resolveReviews local discovery", () => {
|
||||
const originalCwd = process.cwd;
|
||||
|
||||
beforeEach(() => {
|
||||
process.cwd = () => "/test/repo";
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
vi.mocked(fs.readdirSync).mockReturnValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.cwd = originalCwd;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("discovers files from .continue/agents/", async () => {
|
||||
vi.mocked(fs.existsSync).mockImplementation((p) => {
|
||||
return p === path.join("/test/repo", ".continue", "agents");
|
||||
});
|
||||
vi.mocked(fs.readdirSync).mockImplementation(((p: fs.PathLike) => {
|
||||
if (p === path.join("/test/repo", ".continue", "agents")) {
|
||||
return ["security-review.md", "style-check.md"];
|
||||
}
|
||||
return [];
|
||||
}) as typeof fs.readdirSync);
|
||||
|
||||
const reviews = await resolveReviews();
|
||||
expect(reviews).toHaveLength(2);
|
||||
expect(reviews[0].name).toBe("security review");
|
||||
expect(reviews[0].sourceType).toBe("local");
|
||||
expect(reviews[0].source).toContain("agents");
|
||||
});
|
||||
|
||||
it("discovers files from .continue/checks/", async () => {
|
||||
vi.mocked(fs.existsSync).mockImplementation((p) => {
|
||||
return p === path.join("/test/repo", ".continue", "checks");
|
||||
});
|
||||
vi.mocked(fs.readdirSync).mockImplementation(((p: fs.PathLike) => {
|
||||
if (p === path.join("/test/repo", ".continue", "checks")) {
|
||||
return ["anti-slop.md"];
|
||||
}
|
||||
return [];
|
||||
}) as typeof fs.readdirSync);
|
||||
|
||||
const reviews = await resolveReviews();
|
||||
expect(reviews).toHaveLength(1);
|
||||
expect(reviews[0].name).toBe("anti slop");
|
||||
expect(reviews[0].source).toContain("checks");
|
||||
});
|
||||
|
||||
it("discovers files from both directories without duplicates", async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.readdirSync).mockImplementation(((p: fs.PathLike) => {
|
||||
const dir = String(p);
|
||||
if (dir.endsWith("agents")) {
|
||||
return ["security-review.md", "shared.md"];
|
||||
}
|
||||
if (dir.endsWith("checks")) {
|
||||
return ["anti-slop.md", "shared.md"];
|
||||
}
|
||||
return [];
|
||||
}) as typeof fs.readdirSync);
|
||||
|
||||
const reviews = await resolveReviews();
|
||||
// agents/security-review.md, agents/shared.md, checks/anti-slop.md
|
||||
// checks/shared.md is skipped (duplicate filename, agents/ takes precedence)
|
||||
expect(reviews).toHaveLength(3);
|
||||
const names = reviews.map((r) => r.name);
|
||||
expect(names).toContain("security review");
|
||||
expect(names).toContain("shared");
|
||||
expect(names).toContain("anti slop");
|
||||
|
||||
// The "shared" entry should come from agents/, not checks/
|
||||
const shared = reviews.find((r) => r.name === "shared");
|
||||
expect(shared?.source).toContain("agents");
|
||||
});
|
||||
|
||||
it("returns empty array when neither directory exists", async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
const reviews = await resolveReviews();
|
||||
expect(reviews).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("handles directory read errors gracefully", async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.readdirSync).mockImplementation(() => {
|
||||
throw new Error("Permission denied");
|
||||
});
|
||||
|
||||
const reviews = await resolveReviews();
|
||||
expect(reviews).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -14,7 +14,7 @@ export interface ResolvedReview {
|
|||
* Determine which reviews to run, using three sources in order:
|
||||
* 1. CLI --agent flags (highest priority)
|
||||
* 2. Hub API (if logged in and no --agent flags)
|
||||
* 3. Local .continue/agents/*.md (fallback)
|
||||
* 3. Local .continue/agents/*.md and .continue/checks/*.md (fallback)
|
||||
*/
|
||||
export async function resolveReviews(
|
||||
agentFlags?: string[],
|
||||
|
|
@ -34,7 +34,7 @@ export async function resolveReviews(
|
|||
return hubReviews;
|
||||
}
|
||||
|
||||
// Source 3: Local .continue/agents/*.md
|
||||
// Source 3: Local .continue/agents/*.md and .continue/checks/*.md
|
||||
const localReviews = resolveFromLocal();
|
||||
if (localReviews.length > 0) {
|
||||
return localReviews;
|
||||
|
|
@ -51,24 +51,41 @@ async function resolveFromHub(): Promise<ResolvedReview[]> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Resolve reviews from local .continue/agents/*.md files.
|
||||
* Resolve reviews from local .continue/agents/*.md and .continue/checks/*.md files.
|
||||
* Agents take precedence over checks if the same filename exists in both directories.
|
||||
*/
|
||||
function resolveFromLocal(): ResolvedReview[] {
|
||||
const agentsDir = path.join(process.cwd(), ".continue", "agents");
|
||||
if (!fs.existsSync(agentsDir)) {
|
||||
return [];
|
||||
const cwd = process.cwd();
|
||||
const dirs = [
|
||||
path.join(cwd, ".continue", "agents"),
|
||||
path.join(cwd, ".continue", "checks"),
|
||||
];
|
||||
|
||||
const seen = new Set<string>();
|
||||
const results: ResolvedReview[] = [];
|
||||
|
||||
for (const dir of dirs) {
|
||||
if (!fs.existsSync(dir)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const files = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
|
||||
for (const file of files) {
|
||||
if (!seen.has(file)) {
|
||||
seen.add(file);
|
||||
results.push({
|
||||
name: path.basename(file, ".md").replace(/[-_]/g, " "),
|
||||
source: path.join(dir, file),
|
||||
sourceType: "local" as const,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Directory read failed, skip
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const files = fs.readdirSync(agentsDir).filter((f) => f.endsWith(".md"));
|
||||
return files.map((file) => ({
|
||||
name: path.basename(file, ".md").replace(/[-_]/g, " "),
|
||||
source: path.join(agentsDir, file),
|
||||
sourceType: "local" as const,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function isLocalPath(agent: string): boolean {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ export function getDefaultToolPolicies(
|
|||
{ tool: "AskQuestion", permission: "allow" },
|
||||
{ tool: "Checklist", permission: "allow" },
|
||||
{ tool: "Diff", permission: "allow" },
|
||||
{ tool: "Skills", permission: "allow" },
|
||||
{ tool: "Exit", permission: "allow" }, // Exit tool is generally safe (headless mode only)
|
||||
{ tool: "Fetch", permission: "allow" }, // Technically not read only but edge casey to post w query params
|
||||
{ tool: "List", permission: "allow" },
|
||||
|
|
@ -56,6 +57,7 @@ export const PLAN_MODE_POLICIES: ToolPermissionPolicy[] = [
|
|||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "ReportFailure", permission: "allow" },
|
||||
{ tool: "Search", permission: "allow" },
|
||||
{ tool: "Skills", permission: "allow" },
|
||||
{ tool: "Status", permission: "allow" },
|
||||
{ tool: "UploadArtifact", permission: "allow" },
|
||||
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ describe("ChatHistoryService", () => {
|
|||
|
||||
expect(state.history).toEqual([]);
|
||||
expect(state.compactionIndex).toBeNull();
|
||||
expect(state.sessionId).toBe("test-session-id");
|
||||
expect(state.sessionId).toBe("");
|
||||
expect(state.isRemoteMode).toBe(false);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
import type { ChatHistoryItem, ToolStatus } from "core/index.js";
|
||||
import { createHistoryItem } from "core/util/messageConversion.js";
|
||||
|
||||
import {
|
||||
updateSessionHistory,
|
||||
loadSessionById,
|
||||
createSession,
|
||||
} from "../session.js";
|
||||
import { loadSessionById, updateSessionHistory } from "../session.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService } from "./BaseService.js";
|
||||
|
|
@ -76,23 +72,31 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
|
|||
|
||||
/**
|
||||
* Initialize the service with optional session
|
||||
* If no session is provided, we delay session creation until content is added
|
||||
*/
|
||||
async doInitialize(
|
||||
session?: any,
|
||||
isRemoteMode = false,
|
||||
): Promise<ChatHistoryState> {
|
||||
const activeSession = session || createSession([]);
|
||||
|
||||
logger.debug("Initializing ChatHistoryService", {
|
||||
sessionId: activeSession.sessionId,
|
||||
historyLength: activeSession.history.length,
|
||||
sessionId: session?.sessionId,
|
||||
historyLength: session?.history?.length,
|
||||
isRemoteMode,
|
||||
});
|
||||
|
||||
if (session) {
|
||||
return {
|
||||
history: session.history || [],
|
||||
compactionIndex: this.findCompactionIndex(session.history || []),
|
||||
sessionId: session.sessionId,
|
||||
isRemoteMode,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
history: activeSession.history || [],
|
||||
compactionIndex: this.findCompactionIndex(activeSession.history || []),
|
||||
sessionId: activeSession.sessionId,
|
||||
history: [],
|
||||
compactionIndex: null,
|
||||
sessionId: "",
|
||||
isRemoteMode,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,9 @@ vi.mock("../configLoader.js", () => ({
|
|||
vi.mock("../util/logger.js");
|
||||
vi.mock("./ServiceContainer.js");
|
||||
vi.mock("@continuedev/config-yaml");
|
||||
vi.mock("src/systemMessage.js", () => ({
|
||||
loadMarkdownRulesWithMetadata: vi.fn().mockReturnValue([]),
|
||||
}));
|
||||
|
||||
const defaultModel = {
|
||||
provider: "anthropic",
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
|
||||
import { isStringRule } from "src/hubLoader.js";
|
||||
import { loadMarkdownRulesWithMetadata } from "src/systemMessage.js";
|
||||
import { getErrorString } from "src/util/error.js";
|
||||
|
||||
import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
|
||||
|
|
@ -275,6 +276,17 @@ export class ConfigService
|
|||
const loadedConfig = result.config;
|
||||
const merged = mergeUnrolledAssistants(loadedConfig, additional);
|
||||
|
||||
const markdownRules = loadMarkdownRulesWithMetadata();
|
||||
if (markdownRules.length > 0) {
|
||||
const existingRuleContents = new Set(
|
||||
(merged.rules ?? []).map((r) => (typeof r === "string" ? r : r?.rule)),
|
||||
);
|
||||
const newRules = markdownRules.filter(
|
||||
(r) => !existingRuleContents.has(r.rule),
|
||||
);
|
||||
merged.rules = [...(merged.rules ?? []), ...newRules];
|
||||
}
|
||||
|
||||
const withModel = await this.addDefaultChatModelIfNone(
|
||||
merged,
|
||||
apiClient,
|
||||
|
|
|
|||
|
|
@ -195,7 +195,7 @@ describe("SessionManager", () => {
|
|||
});
|
||||
|
||||
describe("saveSession", () => {
|
||||
it("should save the current session to file", () => {
|
||||
it("should save the current session to file when it has content", () => {
|
||||
const session = getCurrentSession();
|
||||
session.title = "Test Session";
|
||||
session.history = [
|
||||
|
|
@ -216,6 +216,32 @@ describe("SessionManager", () => {
|
|||
);
|
||||
});
|
||||
|
||||
it("should not save empty sessions", () => {
|
||||
const session = getCurrentSession();
|
||||
session.history = [];
|
||||
|
||||
saveSession();
|
||||
|
||||
expect(mockFs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not save sessions with only system messages", () => {
|
||||
const session = getCurrentSession();
|
||||
session.history = [
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "System message",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
saveSession();
|
||||
|
||||
expect(mockFs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should filter out system messages except the first one", () => {
|
||||
const session = getCurrentSession();
|
||||
session.history = [
|
||||
|
|
|
|||
|
|
@ -258,12 +258,36 @@ export function getCompleteStateSnapshot(
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a session has meaningful content for saving
|
||||
*/
|
||||
function hasSessionContent(session: Session): boolean {
|
||||
if (!session.history || session.history.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const nonSystemMessages = session.history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
|
||||
return nonSystemMessages.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the current session to file
|
||||
*/
|
||||
export function saveSession(): void {
|
||||
try {
|
||||
const session = SessionManager.getInstance().getCurrentSession();
|
||||
const manager = SessionManager.getInstance();
|
||||
if (!manager.hasSession()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = manager.getCurrentSession();
|
||||
if (!hasSessionContent(session)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionToSave = getSessionPersistenceSnapshot(session);
|
||||
historyManager.save(sessionToSave);
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -60,8 +60,21 @@ vi.mock("os", () => ({
|
|||
vi.mock("path", () => ({
|
||||
default: {
|
||||
join: vi.fn((...parts) => parts.join("/")),
|
||||
isAbsolute: vi.fn((p: string) => p.startsWith("/")),
|
||||
resolve: vi.fn((...parts) => parts.join("/")),
|
||||
},
|
||||
join: vi.fn((...parts) => parts.join("/")),
|
||||
isAbsolute: vi.fn((p: string) => p.startsWith("/")),
|
||||
resolve: vi.fn((...parts) => parts.join("/")),
|
||||
}));
|
||||
|
||||
// Mock history manager to avoid file system operations
|
||||
vi.mock("core/util/history.js", () => ({
|
||||
default: {
|
||||
list: vi.fn(() => []),
|
||||
load: vi.fn(() => ({ history: [] })),
|
||||
save: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock session functions
|
||||
|
|
|
|||
|
|
@ -1,12 +1,22 @@
|
|||
import fs from "fs";
|
||||
|
||||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import chalk from "chalk";
|
||||
import type { Session } from "core/index.js";
|
||||
import historyManager from "core/util/history.js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { getAllSlashCommands } from "./commands/commands.js";
|
||||
import { handleInit } from "./commands/init.js";
|
||||
import { handleInfoSlashCommand } from "./infoScreen.js";
|
||||
import { getCurrentSession, updateSessionTitle } from "./session.js";
|
||||
import { telemetryService } from "./telemetry/telemetryService.js";
|
||||
import { buildImportSkillPrompt } from "./tools/skills.js";
|
||||
import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
|
||||
import {
|
||||
getSkillSlashCommandName,
|
||||
loadMarkdownSkills,
|
||||
} from "./util/loadMarkdownSkills.js";
|
||||
|
||||
type CommandHandler = (
|
||||
args: string[],
|
||||
|
|
@ -99,10 +109,151 @@ function handleJobs() {
|
|||
return { openJobsSelector: true };
|
||||
}
|
||||
|
||||
async function handleSkills(): Promise<SlashCommandResult> {
|
||||
const { skills } = await loadMarkdownSkills();
|
||||
|
||||
if (!skills.length) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.yellow(
|
||||
"No skills found. Add skills under .continue/skills or .claude/skills.",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const header = chalk.bold("Available skills:");
|
||||
const lines = skills.map(
|
||||
(skill) =>
|
||||
`${chalk.cyan(skill.name)} - ${skill.description} ${chalk.gray(
|
||||
`(${skill.path})`,
|
||||
)}`,
|
||||
);
|
||||
|
||||
return {
|
||||
exit: false,
|
||||
output: [header, "", ...lines].join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
async function handleImportSkill(args: string[]): Promise<SlashCommandResult> {
|
||||
const query = args.join(" ").trim();
|
||||
|
||||
if (!query) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.yellow(
|
||||
"Please provide a skill URL or name. Usage: /import-skill <url-or-name>",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
newInput: buildImportSkillPrompt(query),
|
||||
};
|
||||
}
|
||||
|
||||
function handleSessions() {
|
||||
return { openSessionSelector: true };
|
||||
}
|
||||
|
||||
const EXPORTED_SESSION_VERSION = 1;
|
||||
|
||||
interface ExportedSession {
|
||||
version: number;
|
||||
exportedAt: string;
|
||||
session: Session;
|
||||
}
|
||||
|
||||
function isValidExportedSession(data: unknown): data is ExportedSession {
|
||||
if (typeof data !== "object" || data === null) {
|
||||
return false;
|
||||
}
|
||||
const obj = data as Record<string, unknown>;
|
||||
return (
|
||||
obj.version === EXPORTED_SESSION_VERSION &&
|
||||
typeof obj.exportedAt === "string" &&
|
||||
typeof obj.session === "object" &&
|
||||
obj.session !== null &&
|
||||
typeof (obj.session as Record<string, unknown>).sessionId === "string" &&
|
||||
typeof (obj.session as Record<string, unknown>).title === "string" &&
|
||||
Array.isArray((obj.session as Record<string, unknown>).history)
|
||||
);
|
||||
}
|
||||
|
||||
function handleExport(_args: string[]): SlashCommandResult {
|
||||
return {
|
||||
exit: false,
|
||||
openExportSelector: true,
|
||||
};
|
||||
}
|
||||
|
||||
function handleImport(args: string[]): SlashCommandResult {
|
||||
const filePath = args.join(" ").trim();
|
||||
if (!filePath) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.yellow(
|
||||
"Please provide a file path. Usage: /import <file-path>",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.red(`File not found: ${filePath}`),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const fileContent = fs.readFileSync(filePath, "utf-8");
|
||||
const exportedData: unknown = JSON.parse(fileContent);
|
||||
|
||||
if (!isValidExportedSession(exportedData)) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.red(
|
||||
"Invalid session file: expected a valid Continue exported session (version 1).",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
let session = exportedData.session;
|
||||
|
||||
const existing = historyManager.load(session.sessionId);
|
||||
const sessionExists = existing.history.length > 0;
|
||||
|
||||
if (sessionExists) {
|
||||
const originalId = session.sessionId;
|
||||
session = {
|
||||
...session,
|
||||
sessionId: uuidv4(),
|
||||
};
|
||||
historyManager.save(session);
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.green(
|
||||
`Session imported with new ID: ${session.sessionId}\n` +
|
||||
chalk.gray(`(original ID: ${originalId} already existed)`),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
historyManager.save(session);
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.green(
|
||||
`Session imported: ${session.sessionId} (${session.title})`,
|
||||
),
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
exit: false,
|
||||
output: chalk.red(`Failed to import session: ${error.message}`),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const commandHandlers: Record<string, CommandHandler> = {
|
||||
help: handleHelp,
|
||||
clear: () => {
|
||||
|
|
@ -135,7 +286,11 @@ const commandHandlers: Record<string, CommandHandler> = {
|
|||
return { openUpdateSelector: true };
|
||||
},
|
||||
jobs: handleJobs,
|
||||
skills: () => handleSkills(),
|
||||
"import-skill": (args) => handleImportSkill(args),
|
||||
sessions: handleSessions,
|
||||
export: handleExport,
|
||||
import: handleImport,
|
||||
};
|
||||
|
||||
export async function handleSlashCommands(
|
||||
|
|
@ -180,8 +335,22 @@ export async function handleSlashCommands(
|
|||
return { newInput };
|
||||
}
|
||||
|
||||
const { skills } = await loadMarkdownSkills();
|
||||
if (skills.length) {
|
||||
const normalizedCommand = command.trim().toLowerCase();
|
||||
const matchingSkill = skills.find(
|
||||
(skill) => getSkillSlashCommandName(skill) === normalizedCommand,
|
||||
);
|
||||
|
||||
if (matchingSkill) {
|
||||
return {
|
||||
newInput: `Load the skill using the **Skills** tool and then set the **skill_name** parameter to "${matchingSkill.name}".`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this command would match any available commands (same logic as UI)
|
||||
const allCommands = getAllSlashCommands(assistant);
|
||||
const allCommands = await getAllSlashCommands(assistant);
|
||||
const hasMatches = allCommands.some((cmd) =>
|
||||
cmd.name.toLowerCase().includes(command.toLowerCase()),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -87,6 +87,7 @@ export async function handleToolCalls(
|
|||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
...(tc.extra_content && { extra_content: tc.extra_content }),
|
||||
})),
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -240,6 +240,11 @@ export function processToolCallDelta(
|
|||
// JSON not complete yet, continue
|
||||
}
|
||||
}
|
||||
|
||||
// Capture extra_content
|
||||
if (toolCallDelta.extra_content) {
|
||||
toolCall.extra_content = toolCallDelta.extra_content;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to detect provider from model name
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import { execSync } from "child_process";
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { parseMarkdownRule, RuleObject } from "@continuedev/config-yaml";
|
||||
|
||||
import { env } from "./env.js";
|
||||
import { processRule } from "./hubLoader.js";
|
||||
import { PermissionMode } from "./permissions/types.js";
|
||||
import { serviceContainer } from "./services/ServiceContainer.js";
|
||||
|
|
@ -74,6 +77,79 @@ async function getConfigYamlRules(): Promise<string[]> {
|
|||
return [];
|
||||
}
|
||||
|
||||
function getRuleNameFromPath(filePath: string): string {
|
||||
const segments = filePath.split(/[/\\]/);
|
||||
const lastTwoParts = segments.slice(-2);
|
||||
return lastTwoParts.filter(Boolean).join("/").replace(/\.md$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan .continue/rules/ directories for markdown rule files and return the rules with metadata that should be always-applied
|
||||
*/
|
||||
export function loadMarkdownRulesWithMetadata(): RuleObject[] {
|
||||
const cwd = process.cwd();
|
||||
const rulesDirs = [
|
||||
path.join(cwd, ".continue", "rules"),
|
||||
path.join(env.continueHome, "rules"),
|
||||
];
|
||||
|
||||
const rules: RuleObject[] = [];
|
||||
|
||||
for (const dir of rulesDirs) {
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
|
||||
let files: string[];
|
||||
try {
|
||||
files = fs.readdirSync(dir, { recursive: true }) as string[];
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (!String(file).endsWith(".md")) continue;
|
||||
|
||||
const filePath = path.join(dir, String(file));
|
||||
try {
|
||||
const stat = fs.statSync(filePath);
|
||||
if (!stat.isFile()) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, "utf-8");
|
||||
const { frontmatter, markdown } = parseMarkdownRule(content);
|
||||
|
||||
if (frontmatter.invokable) continue;
|
||||
|
||||
const isAlwaysApply =
|
||||
frontmatter.alwaysApply === true ||
|
||||
(frontmatter.alwaysApply === undefined &&
|
||||
!frontmatter.globs &&
|
||||
!frontmatter.regex);
|
||||
|
||||
if (isAlwaysApply && markdown.trim()) {
|
||||
const ruleName =
|
||||
frontmatter.name || getRuleNameFromPath(String(file));
|
||||
rules.push({
|
||||
name: ruleName,
|
||||
rule: markdown,
|
||||
description: frontmatter.description,
|
||||
globs: frontmatter.globs,
|
||||
regex: frontmatter.regex,
|
||||
alwaysApply: true,
|
||||
sourceFile: filePath,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Skip files that can't be read or parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and construct a comprehensive system message with base message and rules section
|
||||
* @param additionalRules - Additional rules from --rule flags
|
||||
|
|
@ -124,6 +200,17 @@ export async function constructSystemMessage(
|
|||
const configYamlRules = await getConfigYamlRules();
|
||||
processedRules.push(...configYamlRules);
|
||||
|
||||
// Load markdown rules from .continue/rules/ directories
|
||||
const markdownRules = loadMarkdownRulesWithMetadata();
|
||||
// Deduplicate against already-loaded rules
|
||||
const existingRulesSet = new Set(processedRules);
|
||||
for (const rule of markdownRules) {
|
||||
if (!existingRulesSet.has(rule.rule)) {
|
||||
processedRules.push(rule.rule);
|
||||
existingRulesSet.add(rule.rule);
|
||||
}
|
||||
}
|
||||
|
||||
// Construct the comprehensive system message
|
||||
let systemMessage = baseSystemMessage;
|
||||
|
||||
|
|
|
|||
|
|
@ -80,3 +80,36 @@ ${skills.map((skill) => `\nname: ${skill.name}\ndescription: ${skill.description
|
|||
},
|
||||
};
|
||||
};
|
||||
|
||||
export function buildImportSkillPrompt(identifier: string): string {
|
||||
return `
|
||||
# Overview
|
||||
|
||||
The user wants to import skills.
|
||||
|
||||
User-provided skill identifier:
|
||||
${identifier}
|
||||
|
||||
# Guidelines
|
||||
- There can be multiple skills in a single repository.
|
||||
- Use the available tools to fetch content and write files. When you are done, briefly summarize which skill you imported and where you saved it.
|
||||
- Use the "AskQuestion" tool where required to clarify with the user.
|
||||
|
||||
# Process:
|
||||
|
||||
**Identifier can either be a URL or a skill name**
|
||||
|
||||
- If it looks like a URL (for example, it starts with http:// or https://), open that URL and inspect its contents to find the code or files that define the skill.
|
||||
- If the URL is a GitHub repository, look for the skills folder. There can be multiple skills within subdirectories.
|
||||
- If it looks like a skill name, you should search for the most relevant open-source skill or repository that matches the skill identifier.
|
||||
- Ask questions to the user to clarify which skill they are referring to if there are multiple options in your findings.
|
||||
|
||||
**Create the skill files**
|
||||
|
||||
- The skills should be created under the directory: ~/.continue/skills/<skill-name>
|
||||
- The subdirectory name should match the name of the skill directory in the fetched repository.
|
||||
- The relevant files and folders along with SKILL.md should be present inside the created skill subdirectory.
|
||||
- If the skill already exists, ask question to the user to clarify whether they want to update it.
|
||||
- Important: Before writing any files, ask the user if they want to proceed with the import.
|
||||
`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ export interface ToolCall {
|
|||
arguments: any;
|
||||
argumentsStr: string;
|
||||
startNotified: boolean;
|
||||
extra_content?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PreprocessedToolCall extends ToolCall {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useMemo } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { getAllSlashCommands } from "../commands/commands.js";
|
||||
import {
|
||||
getAllSlashCommands,
|
||||
type SlashCommand,
|
||||
} from "../commands/commands.js";
|
||||
|
||||
const MAX_DESCRIPTION_LENGTH = 80;
|
||||
|
||||
|
|
@ -27,18 +30,36 @@ const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
|
|||
filter,
|
||||
selectedIndex,
|
||||
}) => {
|
||||
// Memoize the slash commands to prevent excessive re-renders
|
||||
const allCommands = useMemo(() => {
|
||||
if (assistant) {
|
||||
return getAllSlashCommands(assistant);
|
||||
}
|
||||
|
||||
const [allCommands, setAllCommands] = useState<SlashCommand[]>(
|
||||
// Fallback - basic commands without assistant
|
||||
return [
|
||||
{ name: "help", description: "Show help message" },
|
||||
{ name: "clear", description: "Clear the chat history" },
|
||||
{ name: "exit", description: "Exit the chat" },
|
||||
];
|
||||
[
|
||||
{ name: "help", description: "Show help message", category: "system" },
|
||||
{
|
||||
name: "clear",
|
||||
description: "Clear the chat history",
|
||||
category: "system",
|
||||
},
|
||||
{ name: "exit", description: "Exit the chat", category: "system" },
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let stale = false;
|
||||
|
||||
const loadCommands = async () => {
|
||||
if (assistant) {
|
||||
const commands = await getAllSlashCommands(assistant);
|
||||
if (!stale) {
|
||||
setAllCommands(commands);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadCommands();
|
||||
|
||||
return () => {
|
||||
stale = true;
|
||||
};
|
||||
}, [assistant?.prompts, assistant?.rules]);
|
||||
|
||||
// Filter commands based on the current filter
|
||||
|
|
|
|||
|
|
@ -255,6 +255,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
onShowUpdateSelector: () => navigateTo("update"),
|
||||
onShowSessionSelector: () => navigateTo("session"),
|
||||
onShowJobsSelector: () => navigateTo("jobs"),
|
||||
onShowExportSelector: () => navigateTo("export"),
|
||||
onReload: handleReload,
|
||||
onClear: handleClear,
|
||||
onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1),
|
||||
|
|
@ -300,6 +301,71 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
[closeCurrentScreen, setChatHistory, setShowIntroMessage],
|
||||
);
|
||||
|
||||
// Export session handler
|
||||
const handleExportSession = useCallback(
|
||||
async (sessionId: string) => {
|
||||
try {
|
||||
const { loadSessionById } = await import("../session.js");
|
||||
const fs = await import("fs");
|
||||
const path = await import("path");
|
||||
|
||||
const session = loadSessionById(sessionId);
|
||||
if (!session) {
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Failed to export: Session ${sessionId} not found`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
closeCurrentScreen();
|
||||
return;
|
||||
}
|
||||
|
||||
const exportPayload = {
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
session,
|
||||
};
|
||||
|
||||
const defaultPath = path.join(
|
||||
process.cwd(),
|
||||
`continue-session-${session.sessionId}.json`,
|
||||
);
|
||||
const jsonOutput = JSON.stringify(exportPayload, null, 2);
|
||||
fs.writeFileSync(defaultPath, jsonOutput, "utf-8");
|
||||
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Session exported to ${defaultPath}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
closeCurrentScreen();
|
||||
} catch (error: any) {
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Failed to export session: ${error.message}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
closeCurrentScreen();
|
||||
}
|
||||
},
|
||||
[closeCurrentScreen, setChatHistory],
|
||||
);
|
||||
|
||||
// Determine if input should be disabled
|
||||
// Allow input even when services are loading, but disable for UI overlays
|
||||
const isInputDisabled =
|
||||
|
|
@ -400,6 +466,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
handleConfigSelect={handleConfigSelect}
|
||||
handleModelSelect={handleModelSelect}
|
||||
handleSessionSelect={handleSessionSelect}
|
||||
handleExportSession={handleExportSession}
|
||||
handleReload={handleReload}
|
||||
closeCurrentScreen={closeCurrentScreen}
|
||||
activePermissionRequest={activePermissionRequest}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@
|
|||
|
||||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Box, Text, useApp, useInput } from "ink";
|
||||
import React, { useCallback, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { getAllSlashCommands } from "../commands/commands.js";
|
||||
import {
|
||||
getAllSlashCommands,
|
||||
type SlashCommand,
|
||||
} from "../commands/commands.js";
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import type { PermissionMode } from "../permissions/types.js";
|
||||
import type { FileIndexServiceState } from "../services/FileIndexService.js";
|
||||
|
|
@ -178,18 +181,26 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
fileIndex: FileIndexServiceState;
|
||||
}>(["fileIndex"]);
|
||||
|
||||
const getSlashCommands = () => {
|
||||
if (assistant) {
|
||||
return getAllSlashCommands(assistant);
|
||||
}
|
||||
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([
|
||||
{ name: "help", description: "Show help message", category: "system" },
|
||||
{
|
||||
name: "clear",
|
||||
description: "Clear the chat history",
|
||||
category: "system",
|
||||
},
|
||||
{ name: "exit", description: "Exit the chat", category: "system" },
|
||||
]);
|
||||
|
||||
// Fallback - basic commands without assistant
|
||||
return [
|
||||
{ name: "help", description: "Show help message" },
|
||||
{ name: "clear", description: "Clear the chat history" },
|
||||
{ name: "exit", description: "Exit the chat" },
|
||||
];
|
||||
};
|
||||
useEffect(() => {
|
||||
const loadCommands = async () => {
|
||||
if (assistant) {
|
||||
const commands = await getAllSlashCommands(assistant);
|
||||
setSlashCommands(commands);
|
||||
}
|
||||
};
|
||||
|
||||
void loadCommands();
|
||||
}, [assistant?.prompts, assistant?.rules]);
|
||||
|
||||
// Cycle through permission modes
|
||||
const cycleModes = async () => {
|
||||
|
|
@ -251,8 +262,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0];
|
||||
|
||||
// We're in a slash command context - check if it's a complete command
|
||||
const allCommands = getSlashCommands();
|
||||
const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash);
|
||||
const exactMatch = slashCommands.find((cmd) => cmd.name === afterSlash);
|
||||
|
||||
// Hide selector if we have an exact match and there's any additional content
|
||||
if (exactMatch) {
|
||||
|
|
@ -271,7 +281,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
}
|
||||
|
||||
// Check if there are any matching commands
|
||||
const filteredCommands = allCommands.filter((cmd) =>
|
||||
const filteredCommands = slashCommands.filter((cmd) =>
|
||||
cmd.name.toLowerCase().includes(afterSlash.toLowerCase()),
|
||||
);
|
||||
|
||||
|
|
@ -342,8 +352,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
|
||||
// Get filtered commands for navigation - using the same sorting logic as SlashCommandUI
|
||||
const getFilteredCommands = () => {
|
||||
const allCommands = getSlashCommands();
|
||||
return allCommands
|
||||
return slashCommands
|
||||
.filter((cmd) =>
|
||||
cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase()),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ interface ScreenContentProps {
|
|||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
handleSessionSelect: (sessionId: string) => Promise<void>;
|
||||
handleExportSession: (sessionId: string) => Promise<void>;
|
||||
handleReload: () => Promise<void>;
|
||||
closeCurrentScreen: () => void;
|
||||
activePermissionRequest: ActivePermissionRequest | null;
|
||||
|
|
@ -73,6 +74,7 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
handleSessionSelect,
|
||||
handleExportSession,
|
||||
handleReload: _handleReload,
|
||||
closeCurrentScreen,
|
||||
activePermissionRequest,
|
||||
|
|
@ -163,6 +165,16 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
);
|
||||
}
|
||||
|
||||
// Export selector
|
||||
if (isScreenActive("export")) {
|
||||
return (
|
||||
<SessionSelectorWithLoading
|
||||
onSelect={handleExportSession}
|
||||
onExit={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Jobs selector
|
||||
if (isScreenActive("jobs")) {
|
||||
return <JobsSelector onCancel={closeCurrentScreen} />;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue