Merge branch 'main' into nate/cli-headless-flag

This commit is contained in:
Nate 2025-09-08 11:50:12 -07:00
commit 025e2c55ae
40 changed files with 1004 additions and 416 deletions

View file

@ -59,6 +59,7 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:

View file

@ -41,7 +41,7 @@ jobs:
- name: Add PR title guidance comment
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: comments } = await github.rest.issues.listComments({

View file

@ -44,7 +44,7 @@ jobs:
- name: Determine and apply tier label
if: steps.check-author.outputs.should_label == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const pr = context.payload.pull_request;

View file

@ -29,7 +29,7 @@ jobs:
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForIssueComment({
@ -49,7 +49,7 @@ jobs:
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: pr } = await github.rest.pulls.get({
@ -107,7 +107,7 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
@ -144,7 +144,7 @@ jobs:
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForPullRequestReviewComment({
@ -172,21 +172,59 @@ jobs:
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Get review context
if: steps.check-mention.outputs.contains_mention == 'true'
id: review-context
uses: actions/github-script@v7
with:
script: |
let reviewContext = '';
// Check if this comment is a reply to another review comment
if (context.payload.comment.in_reply_to_id) {
try {
const { data: originalComment } = await github.rest.pulls.getReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.in_reply_to_id
});
reviewContext = `**Original review comment by @${originalComment.user.login}:**
${originalComment.body}
**Reply by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
} catch (error) {
console.log('Could not fetch original comment, using current comment only');
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
} else {
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
core.setOutput('context', reviewContext);
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Debug: Echo the branch we're starting the session on
echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
${{ steps.review-context.outputs.context }}
Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
@ -211,7 +249,7 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:

View file

@ -190,7 +190,7 @@ jobs:
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
let comment = '';
@ -307,7 +307,7 @@ jobs:
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const labels = [];

View file

@ -370,8 +370,17 @@ export abstract class BaseLLM implements ILLM {
},
});
if (error !== undefined) {
if (error === "cancel" || error.name === "AbortError") {
if (typeof error === "undefined") {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
} else {
if (error === "cancel" || error?.name?.includes("AbortError")) {
interaction?.logItem({
kind: "cancel",
promptTokens,
@ -393,15 +402,6 @@ export abstract class BaseLLM implements ILLM {
});
return "error";
}
} else {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
}
@ -615,6 +615,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk: formattedContent,
});
completion += formattedContent;
yield content;
}
@ -630,6 +631,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk,
});
completion += chunk;
yield chunk;
}

View file

@ -8,7 +8,7 @@ export interface EditToolArgs {
}
export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
"Note this tool CANNOT be called in parallel with other tools.";
"This tool CANNOT be called in parallel with other tools.";
const CHANGES_DESCRIPTION =
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
import { singleFindAndReplaceTool } from "./singleFindAndReplace";
export interface EditOperation {
old_string: string;
@ -24,60 +25,41 @@ export const multiEditTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.MultiEdit,
description: `This is a tool for making multiple edits to a single file in one operation. It
is built on top of the single find and replace tool and allows you to perform multiple
find-and-replace operations efficiently. Prefer this tool over the single find and replace tool
when you need to make multiple edits to the same file.
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file.
Before using this tool:
1. Use the read_file tool to understand the file's contents and context
2. Verify the directory path is correct
To make multiple file edits, provide the following:
1. filepath: The path to the file to modify (relative to the root of the workspace)
To make multiple edits to a file, provide the following:
1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct)
2. edits: An array of edit operations to perform, where each edit contains:
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
- old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
- All edits are applied in sequence, in the order they are provided
- Each edit operates on the result of the previous edit
- All edits must be valid for the operation to succeed - if any edit fails,
none will be applied
- This tool is ideal when you need to make several changes to different parts
of the same file
- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
- This tool is ideal when you need to make several changes to different parts of the same file
CRITICAL REQUIREMENTS:
1. All edits follow the same requirements as the single find and replace tool
2. The edits are atomic - either all succeed or none are applied
3. Plan your edits carefully to avoid conflicts between sequential operations
4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
WARNING:
- The tool will fail if edits.old_string doesn't match the file contents
exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same
- Since edits are applied in sequence, ensure that earlier edits don't affect
the text that later edits are trying to find
When making edits:
1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
2. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
3. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- Use replace_all for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
If you want to create a new file, use:
- A new file path
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits are not allowed - there is no need since you are creating`,
- Subsequent edits are not allowed - there is no need since you are creating
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`,
parameters: {
type: "object",
required: ["filepath", "edits"],
@ -97,16 +79,18 @@ If you want to create a new file, use:
properties: {
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace (exact match including whitespace/indentation)",
},
new_string: {
type: "string",
description: "The text to replace it with",
description:
"The text to replace it with. MUST be different than old_string.",
},
replace_all: {
type: "boolean",
description:
"Replace all occurrences of old_string (default false)",
"Replace all occurrences of old_string (default false) in the file",
},
},
},

View file

@ -20,33 +20,18 @@ export const singleFindAndReplaceTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SingleFindAndReplace,
description: `Performs exact string replacements in files.
Usage:
- You must use your \`read_file\` tool at least once in the conversation before
editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read_file tool output, ensure you preserve the exact
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
number prefix format is: spaces + line number + tab. Everything after that tab
is the actual file content to match. Never include any part of the line number
prefix in the old_string or new_string.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
description: `Performs exact string replacements in a file.
IMPORTANT:
- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
a larger string with more surrounding context to make it unique or use
\`replace_all\` to change every instance of \`old_string\`.
- Use \`replace_all\` for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.`,
WARNINGS:
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`,
parameters: {
type: "object",
required: ["filepath", "old_string", "new_string"],
@ -58,12 +43,13 @@ parameter is useful if you want to rename a variable for instance.`,
},
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace - must be exact including whitespace/indentation",
},
new_string: {
type: "string",
description:
"The text to replace it with (must be different from old_string)",
"The text to replace it with (MUST be different from old_string)",
},
replace_all: {
type: "boolean",

View file

@ -3,6 +3,6 @@ title: “Customize Autocomplete Settings in Continue”
description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.”
---
Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings.
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).

View file

@ -408,4 +408,4 @@ The following configuration example includes:
</Tab>
</Tabs>
This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings).
This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon).

View file

@ -0,0 +1,138 @@
shell Mode (CLI TUI)
Overview
- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
- It is intended for quick terminal command execution without leaving the TUI.
Activation
- shell mode is activated when the current input (trimmed) starts with !
- Example: "!git status" or " !ls -la" both activate shell mode.
- Visual indicator:
- Input border color changes to yellow.
- The input prompt indicator changes to a yellow "$".
- The input placeholder includes "! for shell mode".
Deactivation / Exiting shell Mode
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
Interaction with other input helpers
- When in shell mode (input starts with !):
- "@" file search suggestions are disabled.
- "/" slash command UI is disabled.
- When in slash command mode (input starts with /):
- "@" file search suggestions are disabled.
Submission behavior
- On submit (Enter) with a shell-mode input:
- The leading ! is removed and the remainder is treated as the shell command to run.
- The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress.
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
Execution semantics
- The command is executed in the same way as terminal tool commands, minus permissions
Output handling
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
- Output is truncated to the first 5000 lines if exceeded.
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
"[Command timed out after 30 seconds of no output]".
Keyboard behaviors (summary)
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately.
- Shift+Enter: new line.
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
Scope / Modes
- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
Error handling
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
Examples
- "!git status" → shows a shell tool call immediately, then populates with the git status output.
- "!echo hello" → shows a shell tool call immediately, then output "hello".
- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message.
Shell Mode (CLI TUI)
Overview
- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
- It is intended for quick terminal command execution without leaving the TUI.
Activation
- Shell mode is activated when the current input (trimmed) starts with !
- Example: "!git status" or " !ls -la" both activate Shell mode.
- Visual indicator:
- Input border color changes to yellow.
- The input prompt indicator changes to a yellow "$".
- The input placeholder includes "! for shell mode".
Deactivation / Exiting Shell Mode
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
Interaction with other input helpers
- When in shell mode (input starts with !):
- "@" file search suggestions are disabled.
- "/" slash command UI is disabled.
- When in slash command mode (input starts with /):
- "@" file search suggestions are disabled.
Submission behavior
- On submit (Enter) with a shell-mode input:
- The leading ! is removed and the remainder is treated as the shell command to run.
- The TUI immediately appends an assistant message representing a Shell tool call, with status set to calling, so users can see that the command is in progress.
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
Execution semantics
- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same.
Output handling
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
- Output is truncated to the first 5000 lines if exceeded.
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
"[Command timed out after 30 seconds of no output]".
Keyboard behaviors (summary)
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately.
- Shift+Enter: new line.
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
Scope / Modes
- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
Error handling
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
Examples
- "!git status" → shows a Shell tool call immediately, then populates with the git status output.
- "!echo hello" → shows a Shell tool call immediately, then output "hello".
- "!some-unknown-cmd" → shows a Shell tool call immediately, then sets status to error with an error message.

View file

@ -28,6 +28,7 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
` ${chalk.cyan("Enter")} Submit message`,
` ${chalk.cyan("Shift+Enter")} New line`,
` ${chalk.cyan("\\")} Line continuation (at end of line)`,
` ${chalk.cyan("!")} Shell mode - run shell commands`,
"",
chalk.white("Controls:"),
` ${chalk.cyan("Ctrl+C")} Clear input`,
@ -39,9 +40,11 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
chalk.white("Special Characters:"),
` ${chalk.cyan("@")} Search and attach files for context`,
` ${chalk.cyan("/")} Access slash commands`,
` ${chalk.cyan("!")} Execute bash commands directly`,
"",
chalk.white("Available Commands:"),
` Type ${chalk.cyan("/")} to see available slash commands`,
` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
].join("\n");
posthogService.capture("useSlashCommand", { name: "help" });
return { output: helpMessage };

View file

@ -1,8 +1,9 @@
import * as fs from "fs";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { editTool, markFileAsRead, readFilesSet } from "./edit.js";
import { editTool } from "./edit.js";
import { markFileAsRead, readFilesSet } from "./readFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
@ -21,6 +22,7 @@ vi.mock("fs", async () => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
unlinkSync: vi.fn(),
realpathSync: vi.fn(),
};
});
@ -34,6 +36,7 @@ describe("editTool", () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
});
afterEach(() => {
@ -126,7 +129,7 @@ describe("editTool", () => {
const result = await editTool.preprocess!(args);
expect(result.args).toEqual({
file_path: testFilePath,
resolvedPath: testFilePath,
newContent: "Hi there\nThis is a test file\nGoodbye world",
oldContent: originalContent,
});
@ -163,7 +166,7 @@ describe("editTool", () => {
it("should successfully write file and return success message", async () => {
const newContent = "Hi there\nThis is a test file\nGoodbye world";
const args = {
file_path: testFilePath,
resolvedPath: testFilePath,
newContent,
oldContent: originalContent,
};
@ -186,7 +189,7 @@ describe("editTool", () => {
});
const args = {
file_path: testFilePath,
resolvedPath: testFilePath,
newContent: "new content",
oldContent: originalContent,
};

View file

@ -8,6 +8,7 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@ -18,40 +19,23 @@ export interface EditArgs {
replace_all?: boolean;
}
// Track files that have been read in the current session
export const readFilesSet = new Set<string>();
export const editTool: Tool = {
name: "Edit",
displayName: "Edit",
readonly: false,
isBuiltIn: true,
description: `Performs exact string replacements in files.
description: `Performs exact string replacements in a file.
USAGE:
- ALWAYS use the \`${readFileTool.name}\` tool just before making edits, to understand the file's up-to-date contents and context.
- When editing text from ${readFileTool.name} tool output, ensure you preserve exact whitespace/indentation.
- Always prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
Usage:
- You must use your \`Read\` tool at least once in the conversation before
editing. This tool will error if you attempt an edit without reading the file.
- When editing text from Read tool output, ensure you preserve the exact
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
number prefix format is: spaces + line number + tab. Everything after that tab
is the actual file content to match. Never include any part of the line number
prefix in the old_string or new_string.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
a larger string with more surrounding context to make it unique or use
\`replace_all\` to change every instance of \`old_string\`.
- Use \`replace_all\` for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.`,
WARNINGS:
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
- The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`,
parameters: {
file_path: {
type: "string",
@ -60,13 +44,14 @@ parameter is useful if you want to rename a variable for instance.`,
},
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace - must be exact including whitespace/indentation",
required: true,
},
new_string: {
type: "string",
description:
"The text to replace it with (must be different from old_string)",
"The text to replace it with (MUST be different from old_string)",
required: true,
},
replace_all: {
@ -82,18 +67,12 @@ parameter is useful if you want to rename a variable for instance.`,
new_string,
replace_all = false,
} = args as EditArgs;
throwIfFileIsSecurityConcern(file_path);
// Check if file has been read
if (!readFilesSet.has(file_path)) {
throw new Error(
`You must use the Read tool to read ${file_path} before editing it.`,
);
}
// Validate arguments
if (!file_path) {
throw new Error("file_path is required");
}
if (!old_string) {
throw new Error("old_string is required");
}
@ -104,13 +83,24 @@ parameter is useful if you want to rename a variable for instance.`,
throw new Error("old_string and new_string must be different");
}
const resolvedPath = fs.realpathSync(file_path);
// Check if file has been read
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
);
}
throwIfFileIsSecurityConcern(resolvedPath);
// Check if file exists
if (!fs.existsSync(file_path)) {
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${file_path} does not exist`);
}
// Read current file content
const oldContent = fs.readFileSync(file_path, "utf-8");
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
// Check if old_string exists in the file
if (!oldContent.includes(old_string)) {
@ -134,11 +124,11 @@ parameter is useful if you want to rename a variable for instance.`,
}
// Generate diff for preview
const diff = generateDiff(oldContent, newContent, file_path);
const diff = generateDiff(oldContent, newContent, resolvedPath);
return {
args: {
file_path,
resolvedPath,
newContent,
oldContent,
},
@ -155,19 +145,19 @@ parameter is useful if you want to rename a variable for instance.`,
};
},
run: async (args: {
file_path: string;
resolvedPath: string;
newContent: string;
oldContent: string;
}) => {
try {
fs.writeFileSync(args.file_path, args.newContent, "utf-8");
fs.writeFileSync(args.resolvedPath, args.newContent, "utf-8");
// Get lines for telemetry
const { added, removed } = calculateLinesOfCodeDiff(
args.oldContent,
args.newContent,
);
const language = getLanguageFromFilePath(args.file_path);
const language = getLanguageFromFilePath(args.resolvedPath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
@ -184,21 +174,16 @@ parameter is useful if you want to rename a variable for instance.`,
const diff = generateDiff(
args.oldContent,
args.newContent,
args.file_path,
args.resolvedPath,
);
return `Successfully edited ${args.file_path}\nDiff:\n${diff}`;
return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`;
} catch (error) {
throw new Error(
`Error: failed to edit ${args.file_path}: ${
`Error: failed to edit ${args.resolvedPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
},
};
// Function to mark a file as read (to be called from the read tool)
export function markFileAsRead(filePath: string) {
readFilesSet.add(filePath);
}

View file

@ -1,9 +1,10 @@
import * as fs from "fs";
import * as path from "path";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { multiEditTool, markFileAsRead } from "./multiEdit.js";
import { multiEditTool } from "./multiEdit.js";
import { markFileAsRead } from "./readFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
@ -22,6 +23,7 @@ vi.mock("fs", async () => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
unlinkSync: vi.fn(),
realpathSync: vi.fn(),
};
});
@ -35,6 +37,7 @@ describe("multiEditTool", () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
});
afterEach(() => {

View file

@ -9,12 +9,11 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { markFileAsRead, readFilesSet } from "./edit.js";
import { editTool } from "./edit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
export { markFileAsRead };
export interface EditOperation {
old_string: string;
new_string: string;
@ -26,15 +25,10 @@ export interface MultiEditArgs {
edits: EditOperation[];
}
// Function to check if file has been read (shared with edit tool)
function hasFileBeenRead(filePath: string): boolean {
return readFilesSet.has(filePath);
}
// Helper functions for multiEdit validation
function validateMultiEditArgs(args: any): {
original_path: string;
file_path: string;
resolved_path: string;
edits: EditOperation[];
} {
const { file_path, edits } = args as MultiEditArgs;
@ -53,7 +47,9 @@ function validateMultiEditArgs(args: any): {
? file_path
: path.resolve(process.cwd(), file_path);
return { original_path: file_path, file_path: absolutePath, edits };
const resolvedPath = fs.realpathSync(absolutePath);
return { original_path: file_path, resolved_path: resolvedPath, edits };
}
function validateEdits(edits: EditOperation[]): void {
@ -74,26 +70,25 @@ function validateEdits(edits: EditOperation[]): void {
}
function validateFileAccess(
original_path: string,
file_path: string,
resolvedPath: string,
isCreatingNewFile: boolean,
): void {
if (isCreatingNewFile) {
// For new file creation, check if parent directory exists
const parentDir = path.dirname(file_path);
const parentDir = path.dirname(resolvedPath);
if (parentDir && !fs.existsSync(parentDir)) {
throw new Error(`Parent directory does not exist: ${parentDir}`);
}
} else {
// For existing files, check if file has been read
// Check with the original path first, then with absolute path
if (!hasFileBeenRead(original_path) && !hasFileBeenRead(file_path)) {
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the Read tool to read ${original_path} before editing it.`,
`You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`,
);
}
if (!fs.existsSync(file_path)) {
throw new Error(`File ${file_path} does not exist`);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${resolvedPath} does not exist`);
}
}
}
@ -138,87 +133,42 @@ export const multiEditTool: Tool = {
displayName: "MultiEdit",
readonly: false,
isBuiltIn: true,
description: `This is a tool for making multiple edits to a single file in one operation. It
is built on top of the Edit tool and allows you to perform multiple
find-and-replace operations efficiently. Prefer this tool over the Edit tool
when you need to make multiple edits to the same file.
Before using this tool:
1. Use the Read tool to understand the file's contents and context
2. Verify the directory path is correct
To make multiple file edits, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not
relative)
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
To make multiple edits to a file, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not relative)
2. edits: An array of edit operations to perform, where each edit contains:
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
- old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
- All edits are applied in sequence, in the order they are provided
- Each edit operates on the result of the previous edit
- All edits must be valid for the operation to succeed - if any edit fails,
none will be applied
- This tool is ideal when you need to make several changes to different parts
of the same file
- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead
- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
- This tool is ideal when you need to make several changes to different parts of the same file
CRITICAL REQUIREMENTS:
1. All edits follow the same requirements as the single Edit tool
2. The edits are atomic - either all succeed or none are applied
3. Plan your edits carefully to avoid conflicts between sequential operations
WARNING:
- The tool will fail if edits.old_string doesn't match the file contents
exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same
- Since edits are applied in sequence, ensure that earlier edits don't affect
the text that later edits are trying to find
When making edits:
1. ALWAYS use the ${readFileTool.name} tool just before making edits, to understand the file's up-to-date contents and context
2. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state
- Always use absolute file paths (starting with /)
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- Use replace_all for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
If you want to create a new file, use:
- A new file path, including dir name if needed
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits: normal edit operations on the created content
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
- Subsequent edits: normal edit operations on the created content`,
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`,
parameters: {
file_path: {
type: "string",
@ -237,9 +187,9 @@ If you want to create a new file, use:
},
preprocess: async (args) => {
// Validate and extract arguments
const { original_path, file_path, edits } = validateMultiEditArgs(args);
const { resolved_path, edits } = validateMultiEditArgs(args);
throwIfFileIsSecurityConcern(file_path);
throwIfFileIsSecurityConcern(resolved_path);
// Validate each edit operation
validateEdits(edits);
@ -248,12 +198,12 @@ If you want to create a new file, use:
const isCreatingNewFile = edits[0].old_string === "";
// Validate file access
validateFileAccess(original_path, file_path, isCreatingNewFile);
validateFileAccess(resolved_path, isCreatingNewFile);
// Read current file content (or start with empty for new files)
let currentContent = "";
if (!isCreatingNewFile) {
currentContent = fs.readFileSync(file_path, "utf-8");
currentContent = fs.readFileSync(resolved_path, "utf-8");
}
const originalContent = currentContent;
@ -266,11 +216,11 @@ If you want to create a new file, use:
}
// Generate diff for preview
const diff = generateDiff(originalContent, newContent, file_path);
const diff = generateDiff(originalContent, newContent, resolved_path);
return {
args: {
file_path,
file_path: resolved_path,
newContent,
originalContent,
isCreatingNewFile,
@ -279,7 +229,7 @@ If you want to create a new file, use:
preview: [
{
type: "text",
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`,
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`,
},
{
type: "diff",

View file

@ -2,10 +2,15 @@ import * as fs from "fs";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { markFileAsRead } from "./edit.js";
import { formatToolArgument } from "./formatters.js";
import { Tool } from "./types.js";
// Track files that have been read in the current session
export const readFilesSet = new Set<string>();
export function markFileAsRead(filePath: string) {
readFilesSet.add(filePath);
}
export const readFileTool: Tool = {
name: "Read",
displayName: "Read",
@ -41,9 +46,10 @@ export const readFileTool: Tool = {
if (!fs.existsSync(filepath)) {
return `Error: File does not exist: ${filepath}`;
}
const content = fs.readFileSync(filepath, "utf-8");
const realPath = fs.realpathSync(filepath);
const content = fs.readFileSync(realPath, "utf-8");
// Mark this file as read for the edit tool
markFileAsRead(filepath);
markFileAsRead(realPath);
const lines = content.split("\n");
if (lines.length > 5000) {

View file

@ -33,7 +33,7 @@ export const runTerminalCommandTool: Tool = {
displayName: "Bash",
description: `Executes a terminal command and returns the output
The command will be executed from the current working directory: ${process.cwd()}
Commands are automatically executed from the current working directory (${process.cwd()}), so there's no need to change directories with 'cd' commands.
`,
parameters: {
command: {

View file

@ -20,6 +20,77 @@ import {
import { SlashCommandUI } from "./SlashCommandUI.js";
import { TextBuffer } from "./TextBuffer.js";
// Small presentational helpers to reduce cyclomatic complexity in UserInput
const InterruptedBanner: React.FC<{ wasInterrupted: boolean }> = ({
wasInterrupted,
}) => {
if (!wasInterrupted) return null;
return (
<Box paddingX={1} marginBottom={0}>
<Text color="yellow">⚠ Interrupted by user - Press enter to resume</Text>
</Box>
);
};
const SlashCommandsMaybe: React.FC<{
show: boolean;
inputMode: boolean;
hideNormalUI: boolean;
isRemoteMode: boolean;
assistant?: AssistantConfig;
filter: string;
selectedIndex: number;
}> = ({
show,
inputMode,
hideNormalUI,
isRemoteMode,
assistant,
filter,
selectedIndex,
}) => {
if (!show || !inputMode || hideNormalUI || !(isRemoteMode || assistant))
return null;
return (
<SlashCommandUI
assistant={assistant}
filter={filter}
selectedIndex={selectedIndex}
isRemoteMode={isRemoteMode}
/>
);
};
const FileSearchMaybe: React.FC<{
show: boolean;
inputMode: boolean;
hideNormalUI: boolean;
isRemoteMode: boolean;
filter: string;
selectedIndex: number;
onSelect: (path: string) => void | Promise<void>;
onFilesUpdated: (files: Array<{ path: string; displayName: string }>) => void;
}> = ({
show,
inputMode,
hideNormalUI,
isRemoteMode,
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
if (!show || !inputMode || hideNormalUI || isRemoteMode) return null;
return (
<FileSearchUI
filter={filter}
selectedIndex={selectedIndex}
onSelect={onSelect}
onFilesUpdated={onFilesUpdated}
/>
);
};
interface UserInputProps {
onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void;
isWaitingForResponse: boolean;
@ -78,10 +149,13 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition(0);
setShowSlashCommands(false);
setShowFileSearch(false);
setShowBashMode(false);
inputHistory.resetNavigation();
}, [textBuffer]);
const [slashCommandFilter, setSlashCommandFilter] = useState("");
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const [showBashMode, setShowBashMode] = useState(false);
const [showFileSearch, setShowFileSearch] = useState(false);
const [fileSearchFilter, setFileSearchFilter] = useState("");
const [selectedFileIndex, setSelectedFileIndex] = useState(0);
@ -131,6 +205,18 @@ const UserInput: React.FC<UserInputProps> = ({
return nextMode;
};
// Update shell mode state based on input
const updateBashModeState = (text: string) => {
const trimmed = text.trimStart();
const isBash = trimmed.startsWith("!");
setShowBashMode(isBash);
if (isBash) {
// Disable other helpers while in shell mode
setShowSlashCommands(false);
setShowFileSearch(false);
}
};
// Update slash command UI state based on input
const updateSlashCommandState = (text: string, cursor: number) => {
// Only show slash commands if slash is the very first character
@ -139,6 +225,9 @@ const UserInput: React.FC<UserInputProps> = ({
return;
}
// When using slash commands, disable file search
setShowFileSearch(false);
const trimmedText = text.trimStart();
const beforeCursor = trimmedText.slice(
0,
@ -196,6 +285,13 @@ const UserInput: React.FC<UserInputProps> = ({
return;
}
// Disable file search if we're in shell mode or slash command mode
const trimmed = text.trimStart();
if (trimmed.startsWith("!") || trimmed.startsWith("/")) {
setShowFileSearch(false);
return;
}
// Check if we're in a file search context
const beforeCursor = text.slice(0, cursor);
const lastAtIndex = beforeCursor.lastIndexOf("@");
@ -234,6 +330,7 @@ const UserInput: React.FC<UserInputProps> = ({
setFileSearchFilter(afterAt);
setSelectedFileIndex(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
}
};
@ -278,6 +375,7 @@ const UserInput: React.FC<UserInputProps> = ({
setInputText(newText);
setCursorPosition(newCursorPos);
setShowSlashCommands(false);
setShowBashMode(false);
}
};
@ -437,6 +535,7 @@ const UserInput: React.FC<UserInputProps> = ({
setInputText("");
setCursorPosition(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
return true;
}
@ -462,6 +561,15 @@ const UserInput: React.FC<UserInputProps> = ({
const handleEscapeKey = (key: any): boolean => {
if (!key.escape) return false;
// If only "!" is present, clear shell mode
if (inputMode && showBashMode && inputText.trim() === "!") {
textBuffer.clear();
setInputText("");
setCursorPosition(0);
setShowBashMode(false);
return true;
}
// Handle escape key to interrupt streaming
if (isWaitingForResponse && onInterrupt) {
onInterrupt();
@ -491,6 +599,7 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition(newCursor);
updateSlashCommandState(newText, newCursor);
updateFileSearchState(newText, newCursor);
updateBashModeState(newText);
inputHistory.resetNavigation();
};
@ -587,14 +696,16 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition,
updateSlashCommandState,
updateFileSearchState,
updateBashModeState,
inputHistory,
});
});
const renderInputText = () => {
const placeholderText = isRemoteMode
? "Ask anything, / for slash commands"
: placeholder || "Ask anything, @ for context, / for slash commands";
? "Ask anything, / for slash commands, ! for shell mode"
: placeholder ||
"Ask anything, @ for context, / for slash commands, ! for shell mode";
if (inputText.length === 0) {
return (
<>
@ -677,50 +788,44 @@ const UserInput: React.FC<UserInputProps> = ({
return (
<Box flexDirection="column">
{/* Interruption message - shown just above the input box */}
{wasInterrupted && (
<Box paddingX={1} marginBottom={0}>
<Text color="yellow">
⚠ Interrupted by user - Press enter to resume
</Text>
</Box>
)}
<InterruptedBanner wasInterrupted={!!wasInterrupted} />
{/* Input box */}
<Box
borderStyle="round"
borderTop={true}
paddingX={1}
borderColor={isRemoteMode ? "cyan" : "gray"}
borderColor={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "gray"}
>
<Text color={isRemoteMode ? "cyan" : "blue"} bold>
{isRemoteMode ? "◉" : "●"}{" "}
<Text
color={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "blue"}
bold
>
{showBashMode ? "$" : isRemoteMode ? "◉" : "●"}
</Text>
{renderInputText()}
</Box>
{/* Slash command UI - show in remote mode OR when assistant is available */}
{showSlashCommands &&
inputMode &&
!hideNormalUI &&
(isRemoteMode || assistant) && (
<SlashCommandUI
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
isRemoteMode={isRemoteMode}
/>
)}
<SlashCommandsMaybe
show={showSlashCommands}
inputMode={inputMode}
hideNormalUI={!!hideNormalUI}
isRemoteMode={!!isRemoteMode}
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
/>
{/* File search UI - only show in local mode */}
{showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && (
<FileSearchUI
filter={fileSearchFilter}
selectedIndex={selectedFileIndex}
onSelect={selectFile}
onFilesUpdated={setCurrentFiles}
/>
)}
<FileSearchMaybe
show={showFileSearch}
inputMode={inputMode}
hideNormalUI={!!hideNormalUI}
isRemoteMode={!!isRemoteMode}
filter={fileSearchFilter}
selectedIndex={selectedFileIndex}
onSelect={selectFile}
onFilesUpdated={setCurrentFiles}
/>
</Box>
);
};

View file

@ -74,14 +74,12 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
}, [chatHistory]);
// Split chat history into stable and pending items
// Only put items in pending if they contain tool calls with "calling" status
// Everything else goes into static content
// The last two items may have pending tool calls
const { staticItems, pendingItems } = React.useMemo(() => {
const items: React.ReactElement[] = [];
// Add intro message as first item if it should be shown
const staticItems: React.ReactElement[] = [];
if (showIntroMessage) {
items.push(
staticItems.push(
<IntroMessage
key="intro"
config={config}
@ -91,48 +89,27 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
);
}
// Helper function to check if an item has pending tool calls
const hasPendingToolCalls = (item: ChatHistoryItem): boolean => {
return !!(
item.toolCallStates &&
item.toolCallStates.some(
(toolState) =>
toolState.status === "calling" ||
toolState.status === "generating" ||
toolState.status === "generated",
)
);
};
// Find the first message with pending tool calls from the end
let pendingStartIndex = filteredChatHistory.length;
for (let i = filteredChatHistory.length - 1; i >= 0; i--) {
if (hasPendingToolCalls(filteredChatHistory[i])) {
pendingStartIndex = i;
// If there's a message after this one, include it too as it might be related
if (i + 1 < filteredChatHistory.length) {
// Keep the pending start index as is, so we include the next message
}
break;
}
}
const stableHistory = filteredChatHistory.slice(0, pendingStartIndex);
const pendingHistory = filteredChatHistory.slice(pendingStartIndex);
const PENDING_ITEMS_COUNT = 2;
const stableCount = Math.max(
0,
filteredChatHistory.length - PENDING_ITEMS_COUNT,
);
const stableHistory = filteredChatHistory.slice(0, stableCount);
const pendingHistory = filteredChatHistory.slice(stableCount);
// Add stable messages to static items
stableHistory.forEach((item, index) => {
items.push(renderMessage(item, index));
staticItems.push(renderMessage(item, index));
});
// Pending items will be rendered dynamically outside Static
const pendingElements = pendingHistory.map((item, index) =>
renderMessage(item, pendingStartIndex + index),
const pendingItems = pendingHistory.map((item, index) =>
renderMessage(item, stableCount + index),
);
return {
staticItems: items,
pendingItems: pendingElements,
staticItems,
pendingItems,
};
}, [
showIntroMessage,

View file

@ -0,0 +1,148 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
import { services } from "../../services/index.js";
import { handleBashModeProcessing } from "./useChat.shellMode.js";
// Mock the runTerminalCommandTool with the correct path for the import in shellMode.ts
vi.mock("src/tools/runTerminalCommand.js", () => ({
runTerminalCommandTool: {
run: vi.fn(),
},
}));
// Mock the services
vi.mock("../../services/index.js", () => ({
services: {
chatHistory: {
addAssistantMessage: vi.fn(),
updateToolStatus: vi.fn(),
addToolResult: vi.fn(),
},
},
}));
describe("handleBashModeProcessing", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should detect bash mode when message starts with !", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockResolvedValue(
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
);
const result = await handleBashModeProcessing("!ls -la");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
expect.any(String),
"calling",
);
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
"done",
);
},
{ timeout: 1000 },
);
});
it("should handle bash command errors", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockRejectedValue(new Error("Command not found"));
const result = await handleBashModeProcessing("!invalidcommand");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
expect.any(String),
"calling",
);
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"Bash command failed: Command not found",
"errored",
);
},
{ timeout: 1000 },
);
});
it("should not trigger bash mode for regular messages", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
const result = await handleBashModeProcessing("Hello! How are you?");
expect(result).toBe("Hello! How are you?"); // Pass through unchanged
expect(mockRun).not.toHaveBeenCalled();
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
});
it("should handle empty bash command", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
const result = await handleBashModeProcessing("!");
expect(result).toBe("!"); // Pass through unchanged for empty command
expect(mockRun).not.toHaveBeenCalled();
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
});
it("should handle bash command with leading whitespace", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockResolvedValue("echo test output");
const result = await handleBashModeProcessing(" !echo hello");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"echo test output",
"done",
);
},
{ timeout: 1000 },
);
});
});

View file

@ -0,0 +1,51 @@
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
import { getErrorString } from "src/util/error.js";
import { services } from "../../services/index.js";
export const handleBashModeProcessing = async (
message: string,
): Promise<string | null> => {
// Handle shell mode commands (starting with !)
if (!message.trimStart().startsWith("!")) {
return message;
}
// Extract the command after the !
const bashCommand = message.trimStart().slice(1).trim();
if (!bashCommand) {
return message; // No command provided, treat as regular message
}
// Show tool call immediately, then run asynchronously and populate result
const toolCallId = `shell-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const toolCall = {
id: toolCallId,
type: "function" as const,
function: {
name: "Bash",
arguments: JSON.stringify({ command: bashCommand }),
},
};
// Add assistant message with tool call immediately
services.chatHistory.addAssistantMessage("", [toolCall]);
// Mark as calling for immediate UI feedback
services.chatHistory.updateToolStatus(toolCallId, "calling");
// Execute the bash command asynchronously - don't block UI
void runTerminalCommandTool
.run({
command: bashCommand,
})
.then((result) => {
services.chatHistory.addToolResult(toolCallId, result, "done");
})
.catch((error) => {
const errorMessage = `Bash command failed: ${getErrorString(error)}`;
services.chatHistory.addToolResult(toolCallId, errorMessage, "errored");
});
return null; // Processed, no further message handling needed
};

View file

@ -30,6 +30,7 @@ import {
handleRemoteMessage,
setupRemotePolling,
} from "./useChat.remote.helpers.js";
import { handleBashModeProcessing } from "./useChat.shellMode.js";
import {
createStreamCallbacks,
executeStreaming,
@ -423,6 +424,13 @@ export function useChat({
if (handled) return;
// Handle shell mode commands (before slash commands)
const bashProcessedMessage = await handleBashModeProcessing(message);
if (bashProcessedMessage === null) {
return; // Bash command was handled and no further processing needed
}
message = bashProcessedMessage;
// Handle slash commands
const processedMessage = await handleSlashCommandProcessing(message);
if (processedMessage === null) {

View file

@ -104,6 +104,7 @@ interface TextBufferStateOptions {
setCursorPosition: (pos: number) => void;
updateSlashCommandState: (text: string, cursor: number) => void;
updateFileSearchState: (text: string, cursor: number) => void;
updateBashModeState: (text: string) => void;
inputHistory: any;
}
@ -115,6 +116,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) {
setCursorPosition,
updateSlashCommandState,
updateFileSearchState,
updateBashModeState,
inputHistory,
} = options;
@ -126,6 +128,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) {
setCursorPosition(newCursor);
updateSlashCommandState(newText, newCursor);
updateFileSearchState(newText, newCursor);
updateBashModeState(newText);
inputHistory.resetNavigation();
}
}

View file

@ -199,7 +199,9 @@ class IntelliJIDE(
}
override suspend fun openFile(path: String) =
fileUtils.openFile(path)
withContext(Dispatchers.EDT) {
fileUtils.openFile(path)
}
override suspend fun openUrl(url: String) {
withContext(Dispatchers.IO) {

View file

@ -43,10 +43,14 @@ class ContinueProcessHandler(
}
scope.launch(Dispatchers.IO) {
for (message in pendingWrites) {
log.debug("Write: $message")
writer.write(message)
writer.write("\r\n")
writer.flush()
try {
log.debug("Write: $message")
writer.write(message)
writer.write("\r\n")
writer.flush()
} catch (e: IOException) {
log.warn(e)
}
}
}
}

View file

@ -21,6 +21,7 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() {
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
try {
// todo: IdeaReportingEvent is deprecated; migrate to IdeaLoggingEvent + figure out how to read attachments
val event = events.filterIsInstance<IdeaReportingEvent>()
.firstOrNull() ?: return false
service<ContinueSentryService>().report(

View file

@ -5,22 +5,27 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
class AddLicenseKey : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val dialog = AddLicenseKeyDialog(e.project)
performAddLicenseKey(e.project)
}
private fun performAddLicenseKey(project: Project?) {
if (project == null)
return
val dialog = AddLicenseKeyDialog(project)
dialog.show()
if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE)
return
val messenger = e.project?.service<ContinuePluginService>()?.coreMessenger
val messenger = project.service<ContinuePluginService>().coreMessenger
?: return
messenger.request("mdm/setLicenseKey", mapOf("licenseKey" to dialog.licenseKey), null) { response ->
val isValid = response.castNestedOrNull<Boolean>("content") ?: false
@ -28,7 +33,7 @@ class AddLicenseKey : AnAction() {
createSuccessAction()
else
createErrorAction()
notification.notify(e.project)
notification.notify(project)
}
}
@ -37,7 +42,7 @@ class AddLicenseKey : AnAction() {
"License key is valid. A restart is required for it to take effect.",
NotificationType.INFORMATION
).addAction(
NotificationAction.create("Restart IDE") { event, notification ->
NotificationAction.create("Restart IDE") { _, _ ->
ApplicationManager.getApplication().restart()
}
)
@ -49,17 +54,7 @@ class AddLicenseKey : AnAction() {
).addAction(
NotificationAction.create("Try again") { event, notification ->
notification.expire()
val action = this@AddLicenseKey
action.actionPerformed(
AnActionEvent(
null,
event.dataContext,
ActionPlaces.UNKNOWN,
action.templatePresentation.clone(),
ActionManager.getInstance(),
0
)
)
performAddLicenseKey(event.project)
}
)

View file

@ -3,9 +3,9 @@ package com.github.continuedev.continueintellijextension.license
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.bindText
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import javax.swing.JComponent
class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) {
@ -22,7 +22,7 @@ class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) {
panel {
row {
textField().bindText(::licenseKey)
.horizontalAlign(HorizontalAlign.FILL)
.align(AlignX.FILL)
.focused()
.validationOnApply {
if (it.text.isBlank())

View file

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

View file

@ -1,5 +1,7 @@
import { InformationCircleIcon } from "@heroicons/react/24/outline";
import React, { ReactNode } from "react";
import { vscButtonBackground } from "..";
import { ToolTip } from "./Tooltip";
type ToggleSwitchProps = {
isToggled: boolean;
@ -8,6 +10,7 @@ type ToggleSwitchProps = {
size?: number;
showIfToggled?: ReactNode;
disabled?: boolean;
tooltip?: string;
};
const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
@ -17,12 +20,20 @@ const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
size = 16,
showIfToggled,
disabled = false,
tooltip,
}) => {
return (
<div
className={`flex select-none items-center justify-between gap-3 ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}
>
<span className="truncate-right">{text}</span>
<span className="truncate-right flex items-center gap-x-1">
{text}{" "}
{tooltip && (
<ToolTip content={tooltip}>
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
)}
</span>
<div className="flex flex-row items-center gap-1">
{isToggled && !!showIfToggled && showIfToggled}
<div

View file

@ -2,6 +2,7 @@ import {
CheckIcon,
ChevronRightIcon,
ExclamationTriangleIcon,
InformationCircleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import {
@ -177,6 +178,7 @@ export function UserSettingsForm() {
})
}
text="Show Session Tabs"
tooltip="If on, displays tabs above the chat as an alternative way to organize and access your sessions."
/>
<ToggleSwitch
isToggled={codeWrap}
@ -186,6 +188,7 @@ export function UserSettingsForm() {
})
}
text="Wrap Codeblocks"
tooltip="If on, displays tabs above the chat as an alternative way to organize and access your sessions."
/>
<ToggleSwitch
@ -196,6 +199,7 @@ export function UserSettingsForm() {
})
}
text="Show Chat Scrollbar"
tooltip="If on, enables a scrollbar in the chat window."
/>
<ToggleSwitch
isToggled={readResponseTTS}
@ -205,6 +209,7 @@ export function UserSettingsForm() {
})
}
text="Text-to-Speech Output"
tooltip="If on, reads LLM responses aloud with TTS."
/>
{/* <ToggleSwitch
isToggled={useChromiumForDocsCrawling}
@ -223,6 +228,7 @@ export function UserSettingsForm() {
})
}
text="Enable Session Titles"
tooltip="If on, generates summary titles for each chat session after the first message, using the current Chat model."
/>
<ToggleSwitch
isToggled={!displayRawMarkdown}
@ -232,6 +238,7 @@ export function UserSettingsForm() {
})
}
text="Format Markdown"
tooltip="If off, shows responses as raw text."
/>
<ToggleSwitch
@ -243,6 +250,7 @@ export function UserSettingsForm() {
})
}
text="Allow Anonymous Telemetry"
tooltip="If on, allows Continue to send anonymous telemetry."
/>
<ToggleSwitch
@ -267,7 +275,12 @@ export function UserSettingsForm() {
/> */}
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<span className="flex items-center gap-x-1 text-left">
Font Size{" "}
<ToolTip content="Specifies base font size for UI elements">
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
</span>
<NumberInput
value={fontSize}
onChange={(val) => {
@ -281,8 +294,11 @@ export function UserSettingsForm() {
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="lines lines-1 text-left">
<span className="lines lines-1 flex items-center gap-x-1 text-left">
Multiline Autocompletions
<ToolTip content="Controls multiline completions for autocomplete.">
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
</span>
<Select
value={useAutocompleteMultilineCompletions}
@ -301,7 +317,12 @@ export function UserSettingsForm() {
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-left">Autocomplete Timeout (ms)</span>
<span className="flex items-center gap-x-1 text-left">
Autocomplete Timeout (ms)
<ToolTip content="Maximum time in milliseconds for autocomplete request/retrieval.">
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
</span>
<NumberInput
value={modelTimeout}
onChange={(val) =>
@ -314,7 +335,12 @@ export function UserSettingsForm() {
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-left">Autocomplete Debounce (ms)</span>
<span className="flex items-center gap-x-1 text-left">
Autocomplete Debounce (ms)
<ToolTip content="Minimum time in milliseconds to trigger an autocomplete request after a change.">
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
</span>
<NumberInput
value={debounceDelay}
onChange={(val) =>
@ -334,7 +360,12 @@ export function UserSettingsForm() {
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<span className="flex items-center gap-x-1">
Disable autocomplete in files
<ToolTip content="List of comma-separated glob pattern to disable autocomplete in matching files. E.g., **/*.{txt,md}">
<InformationCircleIcon className="h-3 w-3" />
</ToolTip>
</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
@ -401,6 +432,8 @@ export function UserSettingsForm() {
})
}
text="Auto-Accept Agent Edits"
tooltip="If on, diffs generated by the edit tool are
automatically accepted and Agent proceeds with the next conversational turn."
showIfToggled={
<>
<ToolTip
@ -420,6 +453,7 @@ export function UserSettingsForm() {
})
}
text="Add Current File by Default"
tooltip="If on, the currently open file is added as context in every new conversation."
/>
<ToggleSwitch
@ -439,6 +473,7 @@ export function UserSettingsForm() {
onlyUseSystemMessageTools: !onlyUseSystemMessageTools,
})
}
tooltip="If on, Continue will not attempt to use native tool calling and will only use system message tools."
text="Only use system message tools"
/>
@ -460,6 +495,7 @@ export function UserSettingsForm() {
})
}
text="Stream after tool rejection"
tooltip="If on, streaming will continue after the tool call is rejected."
/>
{hasContinueEmail && (

View file

@ -14,6 +14,7 @@ import {
selectToolCallById,
} from "../../../redux/selectors/selectToolCalls";
import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils";
import { cn } from "../../../util/cn";
import { getStatusIcon } from "./utils";
interface FindAndReplaceDisplayProps {
@ -25,6 +26,48 @@ interface FindAndReplaceDisplayProps {
historyIndex: number;
}
const MAX_SAME_LINES = 2;
function EllipsisLine() {
return (
<div className="text-description-muted px-3 py-1 text-center font-mono">
⋯
</div>
);
}
function DiffLines({
lines,
className = "",
diffChar = " ",
diffCharClass = "text-description-muted",
}: {
lines: string[];
diffChar?: string;
diffCharClass?: string;
className?: string;
}) {
return (
<>
{lines.map((line, lineIndex) => {
const isLastPartLine = lineIndex === lines.length - 1;
if (line === "" && isLastPartLine) return null;
return (
<div
key={lineIndex}
className={cn("text-foreground px-3 py-px font-mono", className)}
>
<span className={cn("mr-2 select-none", diffCharClass)}>
{diffChar}
</span>
{line}
</div>
);
})}
</>
);
}
export function FindAndReplaceDisplay({
fileUri,
relativeFilePath,
@ -200,70 +243,52 @@ export function FindAndReplaceDisplay({
<pre
className={`bg-editor m-0 w-full text-xs leading-tight ${config?.ui?.codeWrap ? "whitespace-pre-wrap" : "whitespace-pre"}`}
>
{diffResult.diff.map((part, index) => {
{diffResult.diff?.map((part, index) => {
if (part.removed) {
return (
<div
<DiffLines
key={index}
className="text-foreground border-l-4 border-red-900 bg-red-900/30"
>
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div key={lineIndex} className="px-3 py-px font-mono">
<span className="mr-2 select-none text-red-600">-</span>
{line}
</div>
);
})}
</div>
lines={part.value.split("\n")}
className="border-l-4 border-red-900 bg-red-900/30"
diffCharClass="text-red-600"
diffChar="-"
/>
);
} else if (part.added) {
return (
<div
<DiffLines
key={index}
className="text-foreground border-l-4 border-green-600 bg-green-600/20"
>
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div key={lineIndex} className="px-3 py-px font-mono">
<span className="mr-2 select-none text-green-600">+</span>
{line}
</div>
);
})}
</div>
lines={part.value.split("\n")}
diffCharClass="text-green-600"
className="border-l-4 border-green-600 bg-green-600/20"
diffChar="+"
/>
);
} else {
const isFirst = index === 0;
const isLast = index === diffResult.diff.length - 1;
const lines = part.value.split("\n");
const showStartEllipsis = isFirst && lines.length > MAX_SAME_LINES;
const showEndEllipsis = isLast && lines.length > MAX_SAME_LINES;
const showMiddleEllipses =
!isFirst && !isLast && lines.length > MAX_SAME_LINES * 2 + 1;
const startLines = showStartEllipsis
? lines.slice(-MAX_SAME_LINES)
: showMiddleEllipses || showEndEllipsis
? lines.slice(0, MAX_SAME_LINES)
: lines;
const endLines = showMiddleEllipses
? lines.slice(-MAX_SAME_LINES)
: [];
return (
<div key={index}>
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div
key={lineIndex}
className="text-foreground px-3 py-px font-mono"
>
<span className="text-description-muted mr-2 select-none">
{" "}
</span>
{line}
</div>
);
})}
{showStartEllipsis && <EllipsisLine />}
<DiffLines lines={startLines} />
{showMiddleEllipses && <EllipsisLine />}
<DiffLines lines={endLines} />
{showEndEllipsis && <EllipsisLine />}
</div>
);
}

View file

@ -10,6 +10,7 @@ import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CompletionUsage,
CreateEmbeddingResponse,
EmbeddingCreateParams,
Model,
@ -22,6 +23,7 @@ import {
chatChunkFromDelta,
customFetch,
embedding,
usageChatChunk,
} from "../util.js";
import {
convertOpenAIToolToGeminiFunction,
@ -37,6 +39,11 @@ import {
RerankCreateParams,
} from "./base.js";
type UsageInfo = Pick<
CompletionUsage,
"total_tokens" | "completion_tokens" | "prompt_tokens"
>;
export class GeminiApi implements BaseLlmApi {
apiBase: string = "https://generativelanguage.googleapis.com/v1beta/";
@ -240,6 +247,7 @@ export class GeminiApi implements BaseLlmApi {
signal: AbortSignal,
): Promise<ChatCompletion> {
let completion = "";
let usage: UsageInfo | undefined = undefined;
for await (const chunk of this.chatCompletionStream(
{
...body,
@ -247,7 +255,12 @@ export class GeminiApi implements BaseLlmApi {
},
signal,
)) {
completion += chunk.choices[0].delta.content;
if (chunk.choices.length > 0) {
completion += chunk.choices[0].delta.content || "";
}
if (chunk.usage) {
usage = chunk.usage;
}
}
return {
id: "",
@ -266,12 +279,13 @@ export class GeminiApi implements BaseLlmApi {
},
},
],
usage: undefined,
usage,
};
}
async *handleStreamResponse(response: any, model: string) {
let buffer = "";
let usage: UsageInfo | undefined = undefined;
for await (const chunk of streamResponse(response as any)) {
buffer += chunk;
if (buffer.startsWith("[")) {
@ -300,6 +314,15 @@ export class GeminiApi implements BaseLlmApi {
throw new Error(data.error.message);
}
// Check for usage metadata
if (data.usageMetadata) {
usage = {
prompt_tokens: data.usageMetadata.promptTokenCount || 0,
completion_tokens: data.usageMetadata.candidatesTokenCount || 0,
total_tokens: data.usageMetadata.totalTokenCount || 0,
};
}
// In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
const contentParts = data?.candidates?.[0]?.content?.parts;
if (contentParts) {
@ -338,6 +361,14 @@ export class GeminiApi implements BaseLlmApi {
buffer = "";
}
}
// Emit usage at the end if we have it
if (usage) {
yield usageChatChunk({
model,
usage,
});
}
}
async *chatCompletionStream(

View file

@ -35,6 +35,11 @@ export class OpenAIApi implements BaseLlmApi {
});
}
modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
// Add stream_options to include usage in streaming responses
if (body.stream) {
(body as any).stream_options = { include_usage: true };
}
// o-series models - only apply for official OpenAI API
const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
if (isOfficialOpenAIAPI) {

View file

@ -2,6 +2,7 @@ import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CompletionUsage,
} from "openai/resources/completions.mjs";
import {
CreateEmbeddingResponse,
@ -16,7 +17,12 @@ import {
import { Model } from "openai/resources/models.mjs";
import { z } from "zod";
import { OpenAIConfigSchema } from "../types.js";
import { chatChunk, chatCompletion, customFetch } from "../util.js";
import {
chatChunk,
chatCompletion,
customFetch,
usageChatChunk,
} from "../util.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -24,6 +30,11 @@ import {
RerankCreateParams,
} from "./base.js";
type UsageInfo = Pick<
CompletionUsage,
"total_tokens" | "completion_tokens" | "prompt_tokens"
>;
// Relace only supports apply through a /v1/apply endpoint
export class RelaceApi implements BaseLlmApi {
private apiBase = "https://instantapply.endpoint.relace.run/v1/";
@ -41,6 +52,7 @@ export class RelaceApi implements BaseLlmApi {
signal: AbortSignal,
): Promise<ChatCompletion> {
let content = "";
let usage: UsageInfo | undefined = undefined;
// Convert the non-streaming params to streaming params
const streamingBody: ChatCompletionCreateParamsStreaming = {
@ -52,12 +64,18 @@ export class RelaceApi implements BaseLlmApi {
streamingBody,
signal,
)) {
content += chunk.choices[0]?.delta?.content || "";
if (chunk.choices.length > 0) {
content += chunk.choices[0]?.delta?.content || "";
}
if (chunk.usage) {
usage = chunk.usage;
}
}
return chatCompletion({
content,
model: body.model,
usage,
});
}
@ -115,6 +133,15 @@ export class RelaceApi implements BaseLlmApi {
content: mergedCode,
model: body.model,
});
yield usageChatChunk({
model: body.model,
usage: {
prompt_tokens: result.usage.prompt_tokens || 0,
completion_tokens: result.usage.completion_tokens || 0,
total_tokens: result.usage.total_tokens,
},
});
}
completionNonStream(

View file

@ -258,6 +258,7 @@ export const createAdapterTests = (testConfig: AdapterTestConfig) => {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
stream_options: { include_usage: true },
...testConfig.customBodyOptions,
},
},

View file

@ -51,6 +51,20 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "openai",
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "anthropic",
@ -67,14 +81,31 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "gemini-1.5-flash-latest",
apiKey: process.env.GEMINI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "gemini",
model: "gemini-2.5-flash",
apiKey: process.env.GEMINI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "mistral",
model: "codestral",
apiKey: process.env.MISTRAL_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
// {
// provider: "mistral",
// model: "codestral-latest",
// apiKey: process.env.MISTRAL_API_KEY!,
// apiBase: "https://api.mistral.ai/v1",
// roles: ["autocomplete"],
// },
// {
// provider: "deepseek",
// model: "deepseek-coder",
@ -111,6 +142,26 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
apiKey: process.env.VOYAGE_API_KEY!,
roles: ["rerank"],
},
{
provider: "relace",
model: "instant-apply",
apiKey: process.env.RELACE_API_KEY!,
roles: ["chat"],
options: {
skipTools: true,
expectUsage: true,
},
},
{
provider: "inception",
model: "mercury-coder",
apiKey: process.env.INCEPTION_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
// {
// provider: "cohere",
// model: "rerank-v3.5",

View file

@ -106,9 +106,17 @@ export function testChat(
expect(usage).toBeDefined();
expect(usage!.completion_tokens).toBeGreaterThan(0);
expect(usage!.prompt_tokens).toBeGreaterThan(0);
expect(usage!.total_tokens).toEqual(
usage!.prompt_tokens + usage!.completion_tokens,
);
// Gemini 2.5 models have thinking tokens, so total_tokens >= prompt + completion
// Other models should have total_tokens = prompt + completion
if (model.includes("gemini-2.5") || model.includes("gemini-2.0")) {
expect(usage!.total_tokens).toBeGreaterThanOrEqual(
usage!.prompt_tokens + usage!.completion_tokens,
);
} else {
expect(usage!.total_tokens).toEqual(
usage!.prompt_tokens + usage!.completion_tokens,
);
}
}
});