Merge branch 'main' into jacob/feature/nextedit-jetbrains

This commit is contained in:
Jacob Kim 2025-07-09 11:17:15 -07:00 • committed by GitHub
commit 9c57a22200
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 5290 additions and 492 deletions

197
.github/workflows/compliance.yaml vendored Normal file
View file

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

View file

@ -168,7 +168,7 @@ jobs:
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
run: cd ../.. && ./scripts/build-packages.sh
# npm install core
- name: Install core node_modules

View file

@ -651,6 +651,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
};
}

View file

@ -127,6 +127,12 @@ async function modelConfigToBaseLLM({
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;
}

View file

@ -72,6 +72,10 @@ class HttpContextProvider extends BaseContextProvider {
description: item.description ?? "HTTP Context Item",
content: item.content ?? "",
name: item.name ?? this.options.title ?? "HTTP",
uri: {
type: item.uri.type,
value: item.uri.value,
},
});
return Array.isArray(json)

4
core/index.d.ts vendored
View file

@ -584,6 +584,7 @@ export interface LLMOptions {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -612,6 +613,8 @@ export interface LLMOptions {
// AWS options
profile?: string;
modelArn?: string;
accessKeyId?: string;
secretAccessKey?: string;
// AWS and VertexAI Options
region?: string;
@ -1083,6 +1086,7 @@ export interface ModelDescription {
apiBase?: string;
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;

View file

@ -15,6 +15,7 @@ const DEFAULT_MAX_BATCH_SIZE = 64;
export enum LLMConfigurationStatuses {
VALID = "valid",
MISSING_API_KEY = "missing-api-key",
MISSING_ENV_SECRET = "missing-env-secret",
}
export {

View file

@ -51,7 +51,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}

View file

@ -156,6 +156,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -173,6 +174,8 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
profile?: string | undefined;
accessKeyId?: string;
secretAccessKey?: string;
// For IBM watsonx
deploymentId?: string;
@ -248,6 +251,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
@ -272,6 +276,8 @@ export abstract class BaseLLM implements ILLM {
this.region = options.region;
this.projectId = options.projectId;
this.profile = options.profile;
this.accessKeyId = options.accessKeyId;
this.secretAccessKey = options.secretAccessKey;
this.openaiAdapter = this.createOpenAiAdapter();

View file

@ -71,11 +71,7 @@ class Bedrock extends BaseLLM {
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
this.requestOptions = {
region: options.region,
headers: {},
@ -609,17 +605,24 @@ class Bedrock extends BaseLLM {
}
private async _getCredentials() {
if (this.accessKeyId && this.secretAccessKey) {
return {
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
};
}
const profile = this.profile ?? "bedrock";
try {
return await fromNodeProviderChain({
profile: this.profile,
profile: profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
`AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromNodeProviderChain()();
}
return await fromNodeProviderChain()();
}
// EMBED //

View file

@ -40,6 +40,7 @@ class ContinueProxy extends OpenAI {
this.apiType = undefined;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.onPremProxyUrl = options.onPremProxyUrl;
if (this.onPremProxyUrl) {
@ -60,6 +61,7 @@ class ContinueProxy extends OpenAI {
protected extraBodyProperties(): Record<string, any> {
const continueProperties: ContinueProperties = {
apiKeyLocation: this.apiKeyLocation,
envSecretLocations: this.envSecretLocations,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
@ -70,13 +72,24 @@ class ContinueProxy extends OpenAI {
}
getConfigurationStatus() {
if (!this.apiKeyLocation) {
if (!this.apiKeyLocation && !this.envSecretLocations) {
return LLMConfigurationStatuses.VALID;
}
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
if (this.apiKeyLocation) {
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
}
}
if (this.envSecretLocations) {
for (const secretLocation of Object.values(this.envSecretLocations)) {
const decoded = decodeSecretLocation(secretLocation);
if (decoded.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_ENV_SECRET;
}
}
}
return LLMConfigurationStatuses.VALID;

View file

@ -19,6 +19,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-4-sonnet",
"gpt-4",
"o3",
"gemini",
@ -33,6 +34,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-4-sonnet",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part))
) {
@ -95,6 +97,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7-sonnet",
"claude-3.7-sonnet",
"claude-sonnet-4",
"claude-4-sonnet",
"claude-opus-4",
"nova-lite",
"nova-pro",

View file

@ -56,7 +56,11 @@ Critical rules:
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
4. Special operations:
4. Splitting up tool calls:
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
5. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section

View file

@ -39,14 +39,13 @@ export const getConfigDependentToolDefinitions = (
params: ConfigDependentToolParams,
): Tool[] => [
requestRuleTool(params),
// Search and replace is now generally available
searchAndReplaceInFileTool,
// Keep edit file tool available for models that need it
editFileTool,
...(params.enableExperimentalTools
? [
searchAndReplaceInFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
codebaseTool,
]
: [editFileTool]),
? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
: []),
];
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>

View file

@ -987,6 +987,33 @@ The response 200 OK should be a JSON object with the following structure:
"description": "",
"content": ""
}
// For response context items with hyperlinks
[
{
"name": "",
"description": "",
"content": "",
"uri": {
"type": "file" or "url",
"value": "file:///path/to/file" or "https://example.com",
}
}
]
// OR
{
"name": "",
"description": "",
"content": "",
"uri": {
"type": "file" or "url",
"value": "file:///path/to/file" or "https://example.com",
}
}
```
### `@Commits`

View file

@ -7,6 +7,12 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
class RestartContinueProcess : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val pluginService = getContinuePluginService(e.project) ?: return
pluginService.coreMessengerManager?.restart()
}
}
class AcceptDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {

View file

@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.constants
class MessageTypes {
companion object {
val ideMessageTypes = listOf(
val IDE_MESSAGE_TYPES = listOf(
"readRangeInFile",
"isTelemetryEnabled",
"getUniqueId",

View file

@ -1,51 +1,40 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import java.io.*
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
import kotlinx.coroutines.*
class CoreMessenger(
private val project: Project,
continueCorePath: String,
private val ideProtocolClient: IdeProtocolClient,
val coroutineScope: CoroutineScope
val coroutineScope: CoroutineScope,
private val onExit: () -> Unit
) {
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false
private fun write(message: String) {
try {
writer?.write(message + "\r\n")
writer?.flush()
} catch (e: Exception) {
println("Error writing to Continue core: $e")
}
}
private val process = startContinueProcess()
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
val message =
gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
val message = gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
responseListeners[id] = onResponse
coroutineScope.launch(Dispatchers.IO) {
write(message)
}
process.write(message)
}
private fun startContinueProcess(): ContinueProcessHandler {
val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false
val process = if (isTcp)
ContinueSocketProcess()
else
ContinueBinaryProcess(onExit)
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
}
private fun handleMessage(json: String) {
@ -55,13 +44,10 @@ class CoreMessenger(
val data = responseMap["data"]
// IDE listeners
if (MessageTypes.ideMessageTypes.contains(messageType)) {
if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message =
gson.toJson(
mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)
)
write(message)
val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
process.write(message)
}
}
@ -82,148 +68,7 @@ class CoreMessenger(
}
}
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start().waitFor()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux")) {
setFilePermissions(destination, "rwxr-xr-x")
}
}
private fun setFilePermissions(path: String, posixPermissions: String) {
val perms = HashSet<PosixFilePermission>()
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
Files.setPosixFilePermissions(Paths.get(path), perms)
}
private val exitCallbacks: MutableList<() -> Unit> = mutableListOf()
fun onDidExit(callback: () -> Unit) {
exitCallbacks.add(callback)
}
init {
if (useTcp) {
try {
val socket = Socket("127.0.0.1", 3000)
val writer = PrintWriter(socket.getOutputStream(), true)
this.writer = writer
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
this.reader = reader
Thread {
try {
while (true) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
Thread.sleep(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader.close()
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
.start()
} catch (e: Exception) {
println("TCP Connection Error: Unable to connect to 127.0.0.1:3000")
println("Reason: ${e.message}")
e.printStackTrace()
}
} else {
// Set proper permissions synchronously
runBlocking(Dispatchers.IO) {
setPermissions(continueCorePath)
}
// Start the subprocess
val processBuilder =
ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
val inputStream = process!!.inputStream
writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
process!!.onExit().thenRun {
exitCallbacks.forEach { it() }
var err = process?.errorStream?.bufferedReader()?.readText()?.trim()
if (err != null) {
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
val delimiter = "⚡ Done in"
val doneIndex = err.lastIndexOf(delimiter)
if (doneIndex != -1) {
err = err.substring(doneIndex + delimiter.length)
}
}
println("Core process exited with output: $err")
// Log the cause of the failure
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
// Clean up all resources
writer?.close()
reader?.close()
process?.destroy()
}
coroutineScope.launch(Dispatchers.IO) {
try {
while (true) {
val line = reader?.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
delay(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader?.close()
writer?.close()
outputStream.close()
inputStream.close()
process?.destroy()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
}
fun killSubProcess() {
process?.isAlive?.let {
exitCallbacks.clear()
process?.destroy()
}
process.close()
}
}

View file

@ -2,53 +2,50 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class CoreMessengerManager(
private val project: Project,
private val ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) {
var coreMessenger: CoreMessenger? = null
var coreMessenger: CoreMessenger = createCoreMessenger()
private var lastBackoffInterval = 0.5
private val log = Logger.getInstance(CoreMessengerManager::class.java)
init {
setupAnonymousTelemetry()
}
fun restart() {
coroutineScope.launch {
val continueBinaryPath = getContinueBinaryPath()
setupCoreMessenger(continueBinaryPath)
try {
coreMessenger.killSubProcess()
lastBackoffInterval *= 2
log.warn("Continue process exited, retrying in $lastBackoffInterval seconds")
delay((lastBackoffInterval * 1000).toLong())
coreMessenger = createCoreMessenger()
} catch (e: Exception) {
service<TelemetryService>().capture("jetbrains_core_start_error", mapOf("error" to e))
}
}
}
private fun setupCoreMessenger(continueCorePath: String) {
try {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
private fun createCoreMessenger() =
CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val allowAnonymousTelemetry = response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())
}
}
// On exit, use exponential backoff to create another CoreMessenger
coreMessenger?.onDidExit {
lastBackoffInterval *= 2
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
Thread.sleep((lastBackoffInterval * 1000).toLong())
setupCoreMessenger(continueCorePath)
}
} catch (err: Throwable) {
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err))
err.printStackTrace()
private fun setupAnonymousTelemetry() {
coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
val allowAnonymousTelemetry =
response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null)
service<TelemetryService>().setup(getMachineUniqueID())
}
}
}

View file

@ -0,0 +1,81 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
import com.github.continuedev.continueintellijextension.utils.getOS
import com.intellij.openapi.components.service
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
private val process = startBinaryProcess()
override val input: InputStream = process.inputStream
override val output: OutputStream = process.outputStream
override fun close() =
process.destroy()
private fun startBinaryProcess(): Process {
val path = getContinueBinaryPath()
runBlocking(Dispatchers.IO) {
setPermissions()
}
return ProcessBuilder(path).directory(File(path).parentFile)
.start()
.apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } }
}
private fun reportErrorTelemetry() {
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
if (err != null) {
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
val delimiter = "⚡ Done in"
val doneIndex = err.lastIndexOf(delimiter)
if (doneIndex != -1) {
err = err.substring(doneIndex + delimiter.length)
}
}
println("Core process exited with output: $err")
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
}
private companion object {
private fun setPermissions() {
val os = getOS()
when (os) {
OS.MAC -> setMacOsPermissions()
OS.WINDOWS -> {}
OS.LINUX -> elevatePermissions()
}
}
private fun setMacOsPermissions() {
ProcessBuilder("xattr", "-dr", "com.apple.quarantine", getContinueBinaryPath()).start().waitFor()
elevatePermissions()
}
private fun elevatePermissions() {
val path = getContinueBinaryPath()
val permissions = setOf(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE
)
Files.setPosixFilePermissions(Paths.get(path), permissions)
}
}
}

View file

@ -0,0 +1,13 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import java.io.InputStream
import java.io.OutputStream
interface ContinueProcess {
val input: InputStream
val output: OutputStream
fun close()
}

View file

@ -0,0 +1,61 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.intellij.openapi.components.service
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
class ContinueProcessHandler(
parentScope: CoroutineScope,
private val process: ContinueProcess,
handleMessage: (String) -> (Unit)
) {
private val innerJob = Job()
private val scope = CoroutineScope(parentScope.coroutineContext + innerJob)
private val pendingWrites = Channel<String>(Channel.UNLIMITED)
private val writer = OutputStreamWriter(process.output)
private val reader = BufferedReader(InputStreamReader(process.input))
init {
scope.launch(Dispatchers.IO) {
try {
while (isActive) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
service<ContinueErrorService>().report(e, "Error handling message: $line")
}
} else
delay(100)
}
} catch (e: IOException) {
service<ContinueErrorService>().report(e)
}
}
scope.launch(Dispatchers.IO) {
for (message in pendingWrites) {
writer.write(message)
writer.write("\r\n")
writer.flush()
}
}
}
fun write(message: String) =
pendingWrites.trySend(message)
fun close() {
innerJob.cancel()
scope.launch(Dispatchers.IO) {
reader.close()
writer.close()
process.close()
}
}
}

View file

@ -0,0 +1,16 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket
class ContinueSocketProcess : ContinueProcess {
private val socket = Socket("127.0.0.1", 3000)
override val input: InputStream = socket.inputStream
override val output: OutputStream = socket.outputStream
override fun close() =
socket.close()
}

View file

@ -70,6 +70,13 @@
<override-text place="GoToAction" text="Continue: Accept Diff"/>
</action>
<action id="continue.restartProcess"
class="com.github.continuedev.continueintellijextension.actions.RestartContinueProcess"
text="Restart Process"
description="Restart Process">
<override-text place="GoToAction" text="Continue: Restart Process"/>
</action>
<action id="continue.rejectDiff"
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Diff">

View file

@ -0,0 +1,51 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.RepeatedTest
import java.io.InputStream
import java.io.OutputStream
class ContinueProcessHandlerTest {
@RepeatedTest(5)
fun `test concurrent writes with queue`() = runTest {
val process = StringContinueProcess()
val handler = ContinueProcessHandler(this, process) {}
(0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } }
.joinAll()
handler.close()
// assert all message lines are present (order is not important)
val lines = process.string.split("\r\n").filter { it.isNotBlank() }
for (i in 0..100)
Assertions.assertTrue(lines.contains("message number $i"))
// note: this test will fail if the handler writes messages directly to the output stream
// this problem can be easily reproduced by removing the channel<string> from the handler code
}
class StringContinueProcess : ContinueProcess {
val string = StringBuilder()
override val input: InputStream = InputStream.nullInputStream()
override val output: OutputStream = object : OutputStream() {
override fun write(b: Int) {
string.append(b.toChar())
}
override fun write(b: ByteArray, off: Int, len: Int) {
string.append(String(b, off, len))
}
}
override fun close() {
}
}
}

View file

@ -359,8 +359,18 @@
"description": "The AWS security profile to use",
"type": "string"
},
"accessKeyId": {
"title": "Access Key ID",
"description": "AWS access key id (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"secretAccessKey": {
"title": "Secret Access Key",
"description": "AWS secret access key (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"modelArn": {
"title": "Profile",
"title": "Model ARN",
"description": "The AWS arn for the imported model",
"type": "string"
},
@ -2903,6 +2913,16 @@
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"accessKeyId": {
"title": "Access Key ID",
"description": "AWS access key id (can be used together with secretAccessKey in place of profile)",
"type": "string"
},
"secretAccessKey": {
"title": "Secret Access Key",
"description": "AWS secret access key (can be used together with secretAccessKey in place of profile)",
"type": "string"
}
},
"required": ["provider"],

View file

@ -357,20 +357,6 @@ describe("GUI Test", () => {
await messageInput.sendKeys(Key.ENTER);
await messageInput.sendKeys(Key.ENTER);
// Open the context items peek
const contextItemsPeek = await GUISelectors.getContextItemsPeek(view);
await contextItemsPeek.click();
await TestUtils.waitForSuccess(async () => {
const firstContextItemInPeek =
await GUISelectors.getFirstContextItemsPeekItem(view);
await firstContextItemInPeek.click();
// Check that item is there with correct name
const description = await firstContextItemInPeek.getText();
expect(description).to.include("Terminal");
});
// Check that the contents match what we expect (repeated back by the mock LLM)
await TestUtils.waitForSuccess(() => {
return GUISelectors.getThreadMessageByText(

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.57",
"version": "1.1.58",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.57",
"version": "1.1.58",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

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

View file

@ -174,9 +174,12 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Clear deletion buffer
await this.insertDeletionBuffer();
await this.reapplyWithMyersDiff(diffLines);
const myersDiffs = await this.reapplyWithMyersDiff(diffLines);
const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
// Scroll to the first diff
const scrollToLine =
this.getFirstChangedLine(myersDiffs) ?? this.startLine;
const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0);
this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
this.options.onStatusUpdate(
@ -370,6 +373,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
this.refreshCodeLens();
return myersDiffs;
}
private async insertDeletionBuffer() {
@ -550,4 +555,17 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.refreshCodeLens();
}
/**
* Gets the first line number that was changed in a diff
*/
private getFirstChangedLine(diff: DiffLine[]): number | null {
for (let i = 0; i < diff.length; i++) {
const item = diff[i];
if (item.type === "old" || item.type === "new") {
return this.startLine + i;
}
}
return null;
}
}

View file

@ -77,6 +77,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
{ promise: Promise<string>; cancel: EventEmitter<void> }
>();
private _refreshInterval: NodeJS.Timeout | null = null;
private _isRefreshing = false;
private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes
private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes
@ -100,11 +101,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
this.secretStorage = new SecretStorage(context);
// Immediately refresh any existing sessions
this.refreshSessions();
void this.refreshSessions();
// Set up a regular interval to refresh tokens
this._refreshInterval = setInterval(() => {
this.refreshSessions();
void this.refreshSessions();
}, WorkOsAuthProvider.REFRESH_INTERVAL_MS);
}
@ -182,10 +183,18 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
}
async refreshSessions() {
// Prevent concurrent refresh operations
if (this._isRefreshing) {
return;
}
try {
this._isRefreshing = true;
await this._refreshSessions();
} catch (e) {
console.error(`Error refreshing sessions: ${e}`);
} finally {
this._isRefreshing = false;
}
}
@ -198,12 +207,9 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
const finalSessions = [];
for (const session of sessions) {
try {
// For expired tokens, don't use retries - if refresh fails, we drop the session
const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken)
? this._refreshSession.bind(this) // Direct refresh for expired tokens
: this._refreshSessionWithRetry.bind(this); // Retry for valid tokens
const newSession = await refreshMethod(session.refreshToken);
const newSession = await this._refreshSessionWithRetry(
session.refreshToken,
);
finalSessions.push({
...session,
accessToken: newSession.accessToken,
@ -232,7 +238,6 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
private async _refreshSessionWithRetry(
refreshToken: string,
attempt = 1,
maxAttempts = 3,
baseDelay = 1000,
): Promise<{
accessToken: string;
@ -242,30 +247,25 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
try {
return await this._refreshSession(refreshToken);
} catch (error: any) {
// Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts
// Don't retry for auth errors
if (
error.message?.includes("401") ||
error.message?.includes("Invalid refresh token") ||
error.message?.includes("Unauthorized") ||
attempt >= maxAttempts
error.message?.includes("Unauthorized")
) {
throw error;
}
// For network errors or transient server issues, retry with backoff
// Calculate exponential backoff delay with jitter
const delay =
baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);
const delay = Math.min(
baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5),
2 * 60 * 1000, // 2 minutes
);
// Schedule retry after delay
return new Promise((resolve, reject) => {
setTimeout(() => {
this._refreshSessionWithRetry(
refreshToken,
attempt + 1,
maxAttempts,
baseDelay,
)
this._refreshSessionWithRetry(refreshToken, attempt + 1, baseDelay)
.then(resolve)
.catch(reject);
}, delay);
@ -360,7 +360,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
return session;
} catch (e) {
window.showErrorMessage(`Sign in failed: ${e}`);
void window.showErrorMessage(`Sign in failed: ${e}`);
throw e;
}
}

View file

@ -641,7 +641,7 @@ it("should preserve valid tokens during network errors by retrying", async () =>
}
});
it("should remove expired tokens when refresh fails", async () => {
it("should remove expired tokens when refresh fails with a 401 error", async () => {
// Mock Date.now to return a time that makes tokens appear expired
const originalDateNow = Date.now;
const futureTime = Date.now() + 7200000; // 2 hours in the future
@ -675,7 +675,7 @@ it("should remove expired tokens when refresh fails", async () => {
global.setInterval = vi.fn().mockReturnValue(123 as any);
// Refresh will fail with network error
fetchMock.mockRejectedValueOnce(new Error("Network error"));
fetchMock.mockRejectedValueOnce(new Error("401"));
// Setup storage
mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession]));

1306
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -19,6 +19,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@headlessui/react": "^2.2.0",
"@heroicons/react": "^2.0.18",
"@panzoom/panzoom": "^4.6.0",
"@reduxjs/toolkit": "^2.3.0",
"@tiptap/core": "^2.3.2",
"@tiptap/extension-document": "^2.3.2",
@ -43,6 +44,7 @@
"handlebars": "^4.7.8",
"lodash": "^4.17.21",
"lowlight": "^3.3.0",
"mermaid": "^11.6.0",
"minisearch": "^7.0.2",
"mustache": "^4.2.0",
"posthog-js": "^1.130.1",

View file

@ -0,0 +1,175 @@
import {
ArrowPathRoundedSquareIcon,
MagnifyingGlassMinusIcon,
MagnifyingGlassPlusIcon,
} from "@heroicons/react/24/outline";
import Panzoom from "@panzoom/panzoom";
import mermaid from "mermaid";
import { useEffect, useId, useRef, useState } from "react";
import { useDebouncedEffect } from "../find/useDebounce";
import { ToolTip } from "../gui/Tooltip";
const MINIMUM_ZOOM_STEP = 0.05;
const MERMAID_THEME_COLORS = {
background: "#1e1e1e",
primaryColor: "#4d8bf0",
primaryTextColor: "#ffffff",
primaryBorderColor: "#4d8bf0",
secondaryColor: "#3a6db3",
secondaryTextColor: "#ffffff",
secondaryBorderColor: "#3a6db3",
tertiaryColor: "#59bc89",
tertiaryTextColor: "#ffffff",
tertiaryBorderColor: "#59bc89",
noteBkgColor: "#2d2d2d",
noteTextColor: "#e6e6e6",
noteBorderColor: "#555555",
lineColor: "#8c8c8c",
textColor: "#e6e6e6",
mainBkg: "#252525",
errorBkgColor: "#f44336",
errorTextColor: "#ffffff",
nodeBorder: "#555555",
clusterBkg: "#2a2a2a",
clusterBorder: "#555555",
defaultLinkColor: "#8c8c8c",
titleColor: "#e6e6e6",
edgeLabelBackground: "#252525",
activeTaskBkgColor: "#4caf50",
activeTaskBorderColor: "#388e3c",
doneTaskBkgColor: "#388e3c",
doneTaskBorderColor: "#2e7d32",
critBkgColor: "#f44336",
critBorderColor: "#d32f2f",
taskTextColor: "#e6e6e6",
taskTextOutsideColor: "#e6e6e6",
taskTextLightColor: "#b3b3b3",
sectionBkgColor: "#2a2a2a",
altSectionBkgColor: "#303030",
sectionBkgColor2: "#252525",
excludeBkgColor: "#2d2d2d",
fillType0: "#264f78",
fillType1: "#3a6db3",
fillType2: "#59bc89",
fillType3: "#4d8bf0",
fillType4: "#3a6db3",
fillType5: "#264f78",
fillType6: "#59bc89",
fillType7: "#4d8bf0",
};
mermaid.initialize({
startOnLoad: false,
securityLevel: "loose",
theme: "dark",
themeVariables: {
...MERMAID_THEME_COLORS,
fontSize: "14px",
fontFamily: "var(--vscode-font-family)",
},
});
export default function MermaidDiagram({ code }: { code: string }) {
const mermaidRenderContainerRef = useRef<HTMLDivElement>(null);
const zoomInButtonRef = useRef<SVGSVGElement>(null);
const zoomOutButtonRef = useRef<SVGSVGElement>(null);
const resetZoomButtonRef = useRef<SVGSVGElement>(null);
const zoomInButtonId = useId();
const zoomOutButtonId = useId();
const resetZoomButtonId = useId();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
setIsLoading(true);
}, [code]);
useDebouncedEffect(
() => {
if (mermaidRenderContainerRef.current) {
mermaidRenderContainerRef.current.innerHTML = "";
}
const diagramId = `mermaid-id-${Math.random().toString(36).substring(2)}`;
void (async () => {
if (!mermaidRenderContainerRef.current) return;
try {
await mermaid.parse(code);
const renderedSVG = await mermaid.render(diagramId, code);
mermaidRenderContainerRef.current.innerHTML = renderedSVG.svg;
setError("");
const panzoom = Panzoom(mermaidRenderContainerRef.current, {
step: MINIMUM_ZOOM_STEP,
});
zoomInButtonRef.current?.addEventListener("click", () =>
panzoom.zoomIn({ step: MINIMUM_ZOOM_STEP * 4 }),
);
zoomOutButtonRef.current?.addEventListener("click", () =>
panzoom.zoomOut({ step: MINIMUM_ZOOM_STEP * 4 }),
);
resetZoomButtonRef.current?.addEventListener("click", () =>
panzoom.reset(),
);
mermaidRenderContainerRef.current.parentElement?.addEventListener(
"wheel",
(event) => {
if (!event.shiftKey) return;
panzoom.zoomWithWheel(event);
},
);
} catch (err: any) {
if (err.message) {
setError(err.message);
} else {
setError(
"Unknown error when parsing or rendering the Mermaid diagram.",
);
}
}
setIsLoading(false);
})();
},
500,
[code],
);
return (
<>
{isLoading && (
<div className="text-vsc-foreground text-xs">Generating diagram...</div>
)}
{!!error ? (
<div className="text-error whitespace-pre text-sm">{error}</div>
) : (
<div className="relative">
<div className="absolute right-0 z-10 m-2 flex items-center gap-x-1">
<MagnifyingGlassPlusIcon
data-tooltip-id={zoomInButtonId}
ref={zoomInButtonRef}
className="h-4 w-4 cursor-pointer"
/>
<ToolTip id={zoomInButtonId}>Zoom In</ToolTip>
<MagnifyingGlassMinusIcon
data-tooltip-id={zoomOutButtonId}
ref={zoomOutButtonRef}
className="h-4 w-4 cursor-pointer"
/>
<ToolTip id={zoomOutButtonId}>Zoom Out</ToolTip>
<ArrowPathRoundedSquareIcon
data-tooltip-id={resetZoomButtonId}
ref={resetZoomButtonRef}
className="h-4 w-4 cursor-pointer"
/>
<ToolTip id={resetZoomButtonId}>Reset Zoom</ToolTip>
</div>
<div
className="flex min-h-5 justify-center"
ref={mermaidRenderContainerRef}
/>
</div>
)}
</>
);
}

View file

@ -1,6 +1,5 @@
import { ReactNode, useMemo } from "react";
import { Tooltip } from "react-tooltip";
import { getFontSize } from "../../../util";
import { ToolTip } from "../../gui/Tooltip";
interface ToolbarButtonWithTooltipProps {
onClick: () => void;
@ -22,20 +21,20 @@ export function ToolbarButtonWithTooltip({
return (
<>
<button
onClick={onClick}
style={{
fontSize: `${getFontSize() - 2}px`,
<div
onClick={(e) => {
e.stopPropagation();
onClick();
}}
data-tooltip-id={tooltipId}
data-testid={testId}
className="text-foreground flex items-center border-none bg-transparent px-0.5 outline-none hover:cursor-pointer hover:brightness-125"
className="hover:description-muted/30 cursor-pointer select-none rounded bg-transparent px-1 py-0.5 hover:opacity-80"
>
{children}
</button>
<Tooltip id={tooltipId} place="top">
</div>
<ToolTip id={tooltipId} place="top">
{tooltipContent}
</Tooltip>
</ToolTip>
</>
);
}

View file

@ -219,7 +219,6 @@ export function StepContainerPreToolbar({
if (isGeneratingCodeBlock) {
return (
<span className="text-lightgray inline-flex items-center gap-2 text-right">
{!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
<div>
<Spinner />
</div>

View file

@ -21,6 +21,7 @@ import { ToolTip } from "../gui/Tooltip";
import FilenameLink from "./FilenameLink";
import "./katex.css";
import "./markdown.css";
import MermaidBlock from "./MermaidBlock";
import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin";
import { StepContainerPreToolbar } from "./StepContainerPreToolbar";
import SymbolLink from "./SymbolLink";
@ -333,6 +334,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
}
}
}
if (codeProps.className?.includes("language-mermaid")) {
const codeText = String(codeProps.children || "");
return <MermaidBlock code={codeText} />;
}
return <code {...codeProps}>{codeProps.children}</code>;
},
},

View file

@ -18,7 +18,7 @@ import {
SearchMatch,
searchWithinContainer,
} from "./findWidgetSearch";
import useDebounceValue from "./useDebounce";
import { useDebounceValue } from "./useDebounce";
import { useElementSize } from "./useElementSize";
interface HighlightOverlayProps {

View file

@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
function useDebounceValue<T>(value: T, delay: number = 500): T {
export function useDebounceValue<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
@ -16,4 +16,32 @@ function useDebounceValue<T>(value: T, delay: number = 500): T {
return debouncedValue;
}
export default useDebounceValue;
export function useDebouncedEffect(
effect: () => void,
delay: number,
deps: unknown[],
) {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const callBackRef = useRef(() => {});
useEffect(() => {
// do not want the timeout to reset on effect dep change
callBackRef.current = effect;
}, [effect]);
useEffect(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callBackRef.current();
}, delay);
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [delay, ...deps]);
}

View file

@ -28,7 +28,7 @@ export function EditToolbar() {
Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
</span>
<span className="truncate">
Editing{" "}
Editing:{" "}
<span className="italic">
{getEditFilenameAndRangeText(codeToEdit)}
</span>

View file

@ -119,19 +119,32 @@ const ModelRoleSelector = ({
{[...models]
.sort((a, b) => a.title.localeCompare(b.title))
.map((option, idx) => {
const showMissingApiKeyMsg =
const isConfigInvalid =
option.configurationStatus !==
LLMConfigurationStatuses.VALID;
let invalidMessage = "(Invalid config)";
if (
option.configurationStatus ===
LLMConfigurationStatuses.MISSING_API_KEY;
LLMConfigurationStatuses.MISSING_ENV_SECRET
) {
invalidMessage = "(Missing env secret)";
}
if (
option.configurationStatus ===
LLMConfigurationStatuses.MISSING_API_KEY
) {
invalidMessage = "(Missing API Key)";
}
return (
<ListboxOption
key={idx}
value={option.title}
disabled={showMissingApiKeyMsg}
disabled={isConfigInvalid}
onMouseEnter={() => setHoveredIdx(idx)}
onMouseLeave={() => setHoveredIdx(null)}
onClick={(e: any) =>
handleOptionClick(showMissingApiKeyMsg, e)
handleOptionClick(isConfigInvalid, e)
}
className=""
>
@ -144,9 +157,9 @@ const ModelRoleSelector = ({
style={{ fontSize: fontSize(-3) }}
>
{option.title}
{showMissingApiKeyMsg && (
{isConfigInvalid && (
<span className="ml-2 text-[10px] italic">
(Missing API key)
{invalidMessage}
</span>
)}
</span>

View file

@ -6,15 +6,14 @@ type EditToolCallProps = {
changes: string;
historyIndex: number;
toolCallId?: string;
expandCodeblocks?: boolean;
};
export function EditFile(props: EditToolCallProps) {
if (!props.relativeFilePath || !props.changes) {
if (!props.relativeFilePath) {
return null;
}
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath)} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
return (
<StyledMarkdownPreview

View file

@ -36,7 +36,6 @@ function FunctionSpecificToolCallDiv({
case BuiltInToolNames.SearchAndReplaceInFile:
return (
<EditFile
expandCodeblocks
relativeFilePath={args.filepath ?? ""}
changes={args.diff ?? ""}
toolCallId={toolCall.id}

View file

@ -1,6 +1,5 @@
import { CodeBracketIcon } from "@heroicons/react/24/outline";
import { useMemo } from "react";
import { ToolTip } from "../../../components/gui/Tooltip";
import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip";
interface ArgsToggleIconProps {
isShowing: boolean;
@ -13,26 +12,15 @@ export const ArgsToggleIcon = ({
setIsShowing,
toolCallId,
}: ArgsToggleIconProps) => {
const argsTooltipId = useMemo(() => {
return "args-hover-" + toolCallId;
}, [toolCallId]);
return (
<>
<div
data-tooltip-id={argsTooltipId}
onClick={(e) => {
e.stopPropagation();
setIsShowing(!isShowing);
}}
className={`hover:description-muted/30 cursor-pointer select-none rounded px-1 py-0.5 hover:opacity-80 ${isShowing ? "bg-description-muted/30" : "bg-transparent"}`}
>
<CodeBracketIcon className="h-3 w-3 flex-shrink-0 opacity-60" />
</div>
<ToolTip id={argsTooltipId}>
{isShowing ? "Hide args" : "Show args"}
</ToolTip>
</>
<ToolbarButtonWithTooltip
tooltipContent={isShowing ? "Hide args" : "Show args"}
onClick={() => {
setIsShowing(!isShowing);
}}
>
<CodeBracketIcon className="h-3 w-3 flex-shrink-0 opacity-60" />
</ToolbarButtonWithTooltip>
);
};

View file

@ -19,9 +19,11 @@ export function ToolTruncateHistoryIcon({
}, [history]);
const dispatch = useAppDispatch();
const { mainEditor } = useMainEditor();
if (historyIndex === lastMessageIndex) {
return null;
}
return (
<ToolbarButtonWithTooltip
tooltipContent={isStreaming ? "" : "Trim chat to this message"}
@ -38,7 +40,7 @@ export function ToolTruncateHistoryIcon({
}}
>
<BarsArrowUpIcon
className={`h-3 w-3 flex-shrink-0 ${isStreaming ? "cursor-not-allowed" : "cursor-pointer"}`}
className={`h-3 w-3 flex-shrink-0 opacity-60 ${isStreaming ? "cursor-not-allowed" : ""}`}
/>
</ToolbarButtonWithTooltip>
);

View file

@ -85,6 +85,22 @@ export function ToolCallDiv(props: ToolCallDivProps) {
);
}
// Trying this out while it's an experimental feature
// Obviously missing the truncate and args buttons
// All the info from args is displayed here
// But we'd need a nicer place to put the truncate button and the X icon when tool call fails
if (
props.toolCall.function?.name === BuiltInToolNames.SearchAndReplaceInFile
) {
return (
<FunctionSpecificToolCallDiv
toolCall={props.toolCall}
toolCallState={props.toolCallState}
historyIndex={props.historyIndex}
/>
);
}
return (
<ToolCallDisplay
icon={getStatusIcon(props.toolCallState.status)}

View file

@ -15,7 +15,7 @@ test("should render input box", async () => {
test("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
await getElementByText("Chat");
await getElementByText("Agent");
// Simulate cmd+. keyboard shortcut to toggle modes
act(() => {
@ -27,6 +27,18 @@ test("should be able to toggle modes", async () => {
);
});
// Check that it switched to Chat mode
await getElementByText("Chat");
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched to Plan mode
await getElementByText("Plan");
@ -39,19 +51,7 @@ test("should be able to toggle modes", async () => {
);
});
// Check that it switched to Agent mode
await getElementByText("Agent");
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
await getElementByText("Chat");
});
test("should send a message and receive a response", async () => {

View file

@ -0,0 +1,418 @@
import { ChatMessage } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { v4 as uuidv4 } from "uuid";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { addToolCallDeltaToState } from "../../util/toolCallState";
import { ChatHistoryItemWithMessageId, sessionSlice } from "./sessionSlice";
// Mock dependencies
vi.mock("uuid");
vi.mock("core/util/messageContent");
vi.mock("../../util/toolCallState");
const mockUuidv4 = vi.mocked(uuidv4);
const mockRenderChatMessage = vi.mocked(renderChatMessage);
const mockAddToolCallDeltaToState = vi.mocked(addToolCallDeltaToState);
describe("sessionSlice streamUpdate", () => {
beforeEach(() => {
// Reset mocks before each test
vi.clearAllMocks();
// Mock uuidv4 to return predictable values
let callCount = 0;
mockUuidv4.mockImplementation(() => `mock-uuid-${++callCount}`);
// Mock renderChatMessage to return content as is
mockRenderChatMessage.mockImplementation((message: ChatMessage) => {
if (typeof message.content === "string") {
return message.content;
}
return "";
});
// Mock addToolCallDeltaToState
mockAddToolCallDeltaToState.mockImplementation((delta, state) => {
return {
status: "generating" as const,
toolCall: {
id: delta.id || "mock-tool-id",
type: "function" as const,
function: {
name: delta.function?.name || "mock-function",
arguments: delta.function?.arguments || "{}",
},
},
toolCallId: delta.id || "mock-tool-id",
parsedArgs: {},
};
});
});
const createInitialState = () => ({
lastSessionId: undefined,
allSessionMetadata: [],
history: [
{
message: {
role: "user" as const,
content: "This is a test.",
id: "initial-user-message",
},
contextItems: [],
},
] as ChatHistoryItemWithMessageId[],
isStreaming: false,
title: "Test Session",
id: "test-session-id",
streamAborter: new AbortController(),
symbols: {},
mode: "chat" as const,
isInEdit: false,
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
isSessionMetadataLoading: false,
});
describe("Basic Chat Message", () => {
it("should append assistant message to history", () => {
const initialState = createInitialState();
const action = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content: "Here is a response to your message without thinking.",
},
],
};
const newState = sessionSlice.reducer(initialState, action);
expect(newState.history).toHaveLength(2);
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe(
"Here is a response to your message without thinking.",
);
expect(newState.history[1].message.id).toBe("mock-uuid-1");
expect(newState.history[1].contextItems).toEqual([]);
});
});
describe("Chat Message With Thinking", () => {
it("should split thinking and assistant content correctly", () => {
const initialState = createInitialState();
const action = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content:
"<think>I should send the user a response.</think> Here is a response to your message with thinking.",
},
],
};
const newState = sessionSlice.reducer(initialState, action);
expect(newState.history).toHaveLength(2);
// Check reasoning
expect(newState.history[0].reasoning?.text).toBe(
"I should send the user a response.",
);
// Check assistant message
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe(
"Here is a response to your message with thinking.",
);
expect(newState.history[1].message.id).toBe("mock-uuid-1");
});
});
describe("Tool Call With Response", () => {
it("should handle tool call followed by tool response and assistant message", () => {
const initialState = createInitialState();
const toolCallAction = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content: "<think>I should use a tool call.</think>",
toolCalls: [
{
id: "1234",
type: "function" as const,
function: {
name: "builtin_ls",
arguments: '{"dirPath":".","recursive":false}',
},
},
],
},
],
};
let newState = sessionSlice.reducer(initialState, toolCallAction);
expect(newState.history).toHaveLength(2);
// Check reasoning
expect(newState.history[0].reasoning?.text).toBe(
"I should use a tool call.",
);
// Check generating message
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe("");
expect(newState.history[1].toolCallState?.status).toBe("generating");
expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
const toolResponseAction = {
type: "session/streamUpdate",
payload: [
{
role: "tool" as const,
toolCallId: "1234",
content: "foo.txt\nbar.txt\nexample.php",
},
{
role: "assistant" as const,
content: "I see, the tool found 3 files.",
},
],
};
newState = sessionSlice.reducer(newState, toolResponseAction);
expect(newState.history).toHaveLength(4);
// Check tool message
expect(newState.history[2].message.role).toBe("tool");
expect(newState.history[2].message.content).toBe(
"foo.txt\nbar.txt\nexample.php",
);
expect((newState.history[2].message as any).toolCallId).toBe("1234");
// Check final assistant message
expect(newState.history[3].message.role).toBe("assistant");
expect(newState.history[3].message.content).toBe(
"I see, the tool found 3 files.",
);
});
});
describe("Tool Call With Streaming Response", () => {
it("should handle streaming assistant response after tool call", () => {
const initialState = createInitialState();
const toolCallAction = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content: "<think>I should use a tool call.</think>",
toolCalls: [
{
id: "1234",
type: "function" as const,
function: {
name: "builtin_ls",
arguments: '{"dirPath":".","recursive":false}',
},
},
],
},
],
};
let newState = sessionSlice.reducer(initialState, toolCallAction);
expect(newState.history).toHaveLength(2);
// Check reasoning
expect(newState.history[0].reasoning?.text).toBe(
"I should use a tool call.",
);
// Check generating message
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe("");
expect(newState.history[1].toolCallState?.status).toBe("generating");
expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
const toolResponseAction = {
type: "session/streamUpdate",
payload: [
{
role: "tool" as const,
toolCallId: "1234",
content: "foo.txt\nbar.txt\nexample.php",
},
{
role: "assistant" as const,
content: "<think>",
},
{
role: "assistant" as const,
content: "Good, ",
},
{
role: "assistant" as const,
content: "I received a list",
},
{
role: "assistant" as const,
content: " of files.",
},
{
role: "assistant" as const,
content: "</think>",
},
{
role: "assistant" as const,
content: "\n",
},
{
role: "assistant" as const,
content: "I see, ",
},
{
role: "assistant" as const,
content: "the tool ",
},
{
role: "assistant" as const,
content: "found 3 ",
},
{
role: "assistant" as const,
content: "files.",
},
],
};
newState = sessionSlice.reducer(newState, toolResponseAction);
expect(newState.history).toHaveLength(4);
// Check tool message
expect(newState.history[2].message.role).toBe("tool");
expect(newState.history[2].message.content).toBe(
"foo.txt\nbar.txt\nexample.php",
);
// Check response message
expect(newState.history[3].message.role).toBe("assistant");
expect(newState.history[3].message.content).toBe(
"I see, the tool found 3 files.",
);
expect(newState.history[3].reasoning?.text).toBe(
"Good, I received a list of files.",
);
expect(newState.history[3].reasoning?.active).toBe(false);
});
});
describe("Edge Cases", () => {
it("should handle empty history gracefully", () => {
const initialState = createInitialState();
initialState.history = [];
const action = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content: "Hello",
},
],
};
const newState = sessionSlice.reducer(initialState, action);
// Should not crash and history should remain empty
expect(newState.history).toHaveLength(0);
});
it("should handle redacted thinking messages", () => {
const initialState = createInitialState();
const action = {
type: "session/streamUpdate",
payload: [
{
role: "thinking" as const,
content: "This should be hidden",
redactedThinking: true,
},
],
};
const newState = sessionSlice.reducer(initialState, action);
expect(newState.history).toHaveLength(2);
expect(newState.history[1].message.role).toBe("thinking");
expect(newState.history[1].message.content).toBe(
"internal reasoning is hidden due to safety reasons",
);
expect((newState.history[1].message as any).redactedThinking).toBe(true);
});
it("should handle signature updates for thinking messages", () => {
const initialState = createInitialState();
// First add a thinking message
initialState.history.push({
message: {
role: "thinking",
content: "Some thinking",
id: "thinking-message",
},
contextItems: [],
});
const action = {
type: "session/streamUpdate",
payload: [
{
role: "thinking" as const,
signature: "test-signature",
},
],
};
const newState = sessionSlice.reducer(initialState, action);
expect(newState.history).toHaveLength(2);
expect((newState.history[1].message as any).signature).toBe(
"test-signature",
);
});
it("should accumulate content for same role messages", () => {
const initialState = createInitialState();
// Add an assistant message first
initialState.history.push({
message: {
role: "assistant",
content: "Hello ",
id: "assistant-message",
},
contextItems: [],
});
const action = {
type: "session/streamUpdate",
payload: [
{
role: "assistant" as const,
content: "world!",
},
],
};
const newState = sessionSlice.reducer(initialState, action);
expect(newState.history).toHaveLength(2);
expect(newState.history[1].message.content).toBe("Hello world!");
});
});
});

View file

@ -8,6 +8,7 @@ import {
import { JSONContent } from "@tiptap/react";
import {
ApplyState,
AssistantChatMessage,
ChatHistoryItem,
ChatMessage,
ContextItem,
@ -18,6 +19,7 @@ import {
RuleWithSource,
Session,
SessionMetadata,
ThinkingChatMessage,
Tool,
} from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
@ -72,7 +74,7 @@ const initialState: SessionState = {
id: uuidv4(),
streamAborter: new AbortController(),
symbols: {},
mode: "chat",
mode: "agent",
isInEdit: false,
codeBlockApplyStates: {
states: [],
@ -330,12 +332,10 @@ export const sessionSlice = createSlice({
streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
if (state.history.length) {
for (const message of action.payload) {
const lastItem = state.history[state.history.length - 1];
const lastMessage = lastItem.message;
let lastItem = state.history[state.history.length - 1];
let lastMessage = lastItem.message;
if (message.role === "thinking" && message.redactedThinking) {
console.log("add redacted_thinking blocks");
state.history.push({
message: {
role: "thinking",
@ -348,6 +348,74 @@ export const sessionSlice = createSlice({
continue;
}
const messageContent = message.content
? renderChatMessage(message)
: "";
// OpenAI-compatible models in agent mode sometimes send
// all of their data in one message, so we handle that case early.
if (messageContent) {
const thinkMatches = messageContent.match(
/<think>([\s\S]*)<\/think>([\s\S]*)/,
);
if (thinkMatches) {
// The order that they seem to consistently use is:
//
// <think>Thinking text</think>
// Text to show to the user
lastItem.reasoning = {
text: thinkMatches[1].trim(),
startAt: Date.now(),
endAt: Date.now(),
active: false,
};
// This is the chat message that we should show to the user.
// We always need to push this even if it is empty,
// because we cannot attach tool calls to a Thinking message.
// That would break `messageHasToolCallId`.
state.history.push({
message: {
role: "assistant",
content: thinkMatches[2].trim(),
id: uuidv4(),
},
contextItems: [],
});
lastItem = state.history[state.history.length - 1];
lastMessage = lastItem.message;
if (
(message.role === "assistant" || message.role === "thinking") &&
message.toolCalls?.[0]
) {
// Only support one tool call for now.
// There are further changes required throughout the system
// to support multiple tool calls in a single message from
// OpenAI-compatible providers.
const toolCallDelta = message.toolCalls[0];
const newToolCallState = addToolCallDeltaToState(
toolCallDelta,
lastItem.toolCallState,
);
lastItem.toolCallState = newToolCallState;
// We know this is one of these two types because we just added it
const curMessage = lastMessage as
| AssistantChatMessage
| ThinkingChatMessage;
if (curMessage.toolCalls) {
curMessage.toolCalls.push(newToolCallState.toolCall);
} else {
curMessage.toolCalls = [newToolCallState.toolCall];
}
}
return;
}
}
// The remainder of this function handles streaming messages
if (
lastMessage.role !== message.role ||
// This is for when a tool call comes immediately before/after tool call
@ -363,7 +431,7 @@ export const sessionSlice = createSlice({
const historyItem: ChatHistoryItemWithMessageId = {
message: {
...message,
content: renderChatMessage(message),
content: "",
id: uuidv4(),
},
contextItems: [],
@ -376,51 +444,62 @@ export const sessionSlice = createSlice({
);
}
state.history.push(historyItem);
} else {
// Add to the existing message
if (message.content) {
const messageContent = renderChatMessage(message);
if (messageContent.includes("<think>")) {
lastItem.reasoning = {
startAt: Date.now(),
active: true,
text: messageContent.replace("<think>", "").trim(),
};
} else if (
lastItem.reasoning?.active &&
messageContent.includes("</think>")
lastItem = state.history[state.history.length - 1];
lastMessage = lastItem.message;
}
// Add to the existing message
if (messageContent) {
if (messageContent.includes("<think>")) {
lastItem.reasoning = {
startAt: Date.now(),
active: true,
text: messageContent.replace("<think>", "").trim(),
};
} else if (
lastItem.reasoning?.active &&
messageContent.includes("</think>")
) {
const [reasoningEnd, answerStart] =
messageContent.split("</think>");
lastItem.reasoning.text += reasoningEnd.trimEnd();
lastItem.reasoning.active = false;
lastItem.reasoning.endAt = Date.now();
lastMessage.content += answerStart.trimStart();
} else if (lastItem.reasoning?.active) {
if (
lastItem.reasoning.text.length > 0 ||
messageContent.trim().length > 0
) {
const [reasoningEnd, answerStart] =
messageContent.split("</think>");
lastItem.reasoning.text += reasoningEnd.trimEnd();
lastItem.reasoning.active = false;
lastItem.reasoning.endAt = Date.now();
lastMessage.content += answerStart.trimStart();
} else if (lastItem.reasoning?.active) {
lastItem.reasoning.text += messageContent;
} else {
// Note this only works because new message above
// was already rendered from parts to string
}
} else {
// Note this only works because new message above
// was already rendered from parts to string
if (
lastMessage.content.length > 0 ||
messageContent.trim().length > 0
) {
lastMessage.content += messageContent;
}
} else if (message.role === "thinking" && message.signature) {
if (lastMessage.role === "thinking") {
lastMessage.signature = message.signature;
}
} else if (
message.role === "assistant" &&
message.toolCalls?.[0] &&
lastMessage.role === "assistant"
) {
// Intentionally only supporting one tool call for now.
const toolCallDelta = message.toolCalls[0];
const newToolCallState = addToolCallDeltaToState(
toolCallDelta,
lastItem.toolCallState,
);
lastItem.toolCallState = newToolCallState;
lastMessage.toolCalls = [newToolCallState.toolCall];
}
} else if (message.role === "thinking" && message.signature) {
if (lastMessage.role === "thinking") {
lastMessage.signature = message.signature;
}
} else if (
message.role === "assistant" &&
message.toolCalls?.[0] &&
lastMessage.role === "assistant"
) {
// Intentionally only supporting one tool call for now.
const toolCallDelta = message.toolCalls[0];
const newToolCallState = addToolCallDeltaToState(
toolCallDelta,
lastItem.toolCallState,
);
lastItem.toolCallState = newToolCallState;
lastMessage.toolCalls = [newToolCallState.toolCall];
}
}
}

View file

@ -133,6 +133,14 @@ export const enterEdit = createAsyncThunk<
return;
}
if (!state.editModeState.codeToEdit[0]) {
extra.ideMessenger.post("showToast", [
"info",
"Please open a file to use Edit mode",
]);
return;
}
dispatch(setMainEditorContentTrigger({}));
dispatch(setPreviousModeEditorContent(editorContent));
@ -148,9 +156,5 @@ export const enterEdit = createAsyncThunk<
);
dispatch(setIsInEdit(true));
if (!state.editModeState.codeToEdit[0]) {
extra.ideMessenger.post("edit/addCurrentSelection", undefined);
}
},
);

View file

@ -10,9 +10,10 @@ import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
/**
* This thunk is used to move a terminal command to the background
* when the user clicks the "Continue" button in the UI
* when the user clicks the "Move to background" link in the UI
*
* It marks the command as visually complete without stopping
* It preserves all existing terminal output, marks the command as
* visually complete, and stops listening to further output from
* the already running process
*/
export const moveTerminalProcessToBackground = createAsyncThunk<
@ -39,6 +40,12 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
return;
}
// Find existing terminal output to preserve it
const existingOutput = toolCall.output?.find(
(item) => item.name === "Terminal",
);
const existingContent = existingOutput?.content || "";
const status =
"Command moved to background. Further output will be ignored.";
@ -46,7 +53,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
{
name: "Terminal",
description: "Terminal command output",
content: "\n" + status,
content: existingContent + (existingContent ? "\n\n" : "") + status,
status: status,
},
];

View file

@ -1,7 +1,8 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { LLMFullCompletionOptions } from "core";
import { LLMFullCompletionOptions, ModelDescription, Tool } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { ToCoreProtocol } from "core/protocol";
import { BuiltInToolNames } from "core/tools/builtIn";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../slices/configSlice";
@ -21,6 +22,49 @@ import {
} from "../util/constructMessages";
import { callCurrentTool } from "./callCurrentTool";
/**
* Filters tools based on the selected model's capabilities.
* Returns either the edit file tool or search and replace tool, but not both.
*/
function filterToolsForModel(
tools: Tool[],
selectedModel: ModelDescription,
): Tool[] {
const editFileTool = tools.find(
(tool) => tool.function.name === BuiltInToolNames.EditExistingFile,
);
const searchAndReplaceTool = tools.find(
(tool) => tool.function.name === BuiltInToolNames.SearchAndReplaceInFile,
);
// If we don't have both tools, return tools as-is
if (!editFileTool || !searchAndReplaceTool) {
return tools;
}
// Determine which tool to use based on the model
const shouldUseFindReplace = shouldUseFindReplaceEdits(selectedModel);
// Filter out the unwanted tool
return tools.filter((tool) => {
if (tool.function.name === BuiltInToolNames.EditExistingFile) {
return !shouldUseFindReplace;
}
if (tool.function.name === BuiltInToolNames.SearchAndReplaceInFile) {
return shouldUseFindReplace;
}
return true;
});
}
/**
* Determines whether to use search and replace tool instead of edit file
* Right now we only know that this is reliable with Claude models
*/
function shouldUseFindReplaceEdits(model: ModelDescription): boolean {
return model.model.includes("claude");
}
export const streamNormalInput = createAsyncThunk<
void,
{
@ -37,8 +81,9 @@ export const streamNormalInput = createAsyncThunk<
throw new Error("No chat model selected");
}
// Get tools
const activeTools = selectActiveTools(state);
// Get tools and filter them based on the selected model
const allActiveTools = selectActiveTools(state);
const activeTools = filterToolsForModel(allActiveTools, selectedChatModel);
const toolsSupported = modelSupportsTools(selectedChatModel);
// Construct completion options

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.95",
"version": "1.0.96",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -133,7 +133,27 @@ export function useProxyForUnrenderedSecrets(
const apiKeyLocation = getUnrenderedSecretLocation(
config.models[i]?.apiKey,
);
if (apiKeyLocation) {
const encodedApiKeyLocation = apiKeyLocation
? encodeSecretLocation(apiKeyLocation)
: undefined;
let encodedEnvSecretLocations: Record<string, string> | undefined =
undefined;
if (config.models[i]?.env) {
Object.entries(config.models[i]?.env!).forEach(([key, value]) => {
if (typeof value === "string") {
const secretLocation = getUnrenderedSecretLocation(value);
if (secretLocation) {
encodedEnvSecretLocations = {
...encodedEnvSecretLocations,
[key]: encodeSecretLocation(secretLocation),
};
}
}
});
}
if (encodedApiKeyLocation || encodedEnvSecretLocations) {
config.models[i] = {
...config.models[i],
name: config.models[i]?.name ?? "",
@ -143,7 +163,8 @@ export function useProxyForUnrenderedSecrets(
config.models[i]?.provider ?? "",
config.models[i]?.model ?? "",
),
apiKeyLocation: encodeSecretLocation(apiKeyLocation),
apiKeyLocation: encodedApiKeyLocation,
envSecretLocations: encodedEnvSecretLocations,
orgScopeId,
onPremProxyUrl,
apiKey: undefined,
@ -158,6 +179,7 @@ export function useProxyForUnrenderedSecrets(
/** The additional properties that are added to the otherwise OpenAI-compatible body when requesting a Continue proxy */
export const continuePropertiesSchema = z.object({
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
apiBase: z.string().optional(),
orgScopeId: z.string().nullable(),
env: z.record(z.string(), z.any()).optional(),

View file

@ -24,7 +24,7 @@ import {
packageIdentifierToShorthandSlug,
useProxyForUnrenderedSecrets,
} from "./clientRender.js";
import { getBlockType } from "./getBlockType.js";
import { BlockType, getBlockType } from "./getBlockType.js";
export function parseConfigYaml(configYaml: string): ConfigYaml {
try {
@ -322,12 +322,15 @@ export async function unrollBlocks(
"name" | "version" | "rules" | "schema" | "metadata"
>)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"];
// For each section, replace "uses/with" blocks with the real thing
for (const section of sections) {
if (assistant[section]) {
const sectionBlocks: any[] = [];
// Process all sections in parallel
const sectionPromises = sections.map(async (section) => {
if (!assistant[section]) {
return { section, blocks: null };
}
for (const unrolledBlock of assistant[section]) {
// Process all blocks in this section in parallel
const blockPromises = assistant[section].map(
async (unrolledBlock, index) => {
// "uses/with" block
if ("uses" in unrolledBlock) {
try {
@ -338,10 +341,13 @@ export async function unrollBlocks(
);
const block = blockConfigYaml[section]?.[0];
if (block) {
sectionBlocks.push(
mergeOverrides(block, unrolledBlock.override ?? {}),
);
return {
index,
block: mergeOverrides(block, unrolledBlock.override ?? {}),
error: null,
};
}
return { index, block: null, error: null };
} catch (err) {
let msg = "";
if (
@ -353,99 +359,190 @@ export async function unrollBlocks(
msg = `${(err as Error).message}.\n> ${JSON.stringify(unrolledBlock.uses)}`;
}
errors.push({
fatal: false,
message: msg,
});
console.error(
`Failed to unroll block ${JSON.stringify(unrolledBlock.uses)}: ${(err as Error).message}`,
);
sectionBlocks.push(null);
return {
index,
block: null,
error: {
fatal: false,
message: msg,
},
};
}
} else {
// Normal block
sectionBlocks.push(unrolledBlock);
return { index, block: unrolledBlock, error: null };
}
}
},
);
unrolledAssistant[section] = sectionBlocks;
const blockResults = await Promise.all(blockPromises);
// Collect errors and maintain order
const sectionBlocks: any[] = [];
const sectionErrors: ConfigValidationError[] = [];
for (const result of blockResults) {
if (result.error) {
sectionErrors.push(result.error);
}
sectionBlocks[result.index] = result.block;
}
return { section, blocks: sectionBlocks, errors: sectionErrors };
});
// Process rules in parallel
const rulesPromise = assistant.rules
? (async () => {
const rulePromises = assistant.rules!.map(async (rule, index) => {
if (typeof rule === "string" || !("uses" in rule)) {
return { index, rule, error: null };
} else if ("uses" in rule) {
try {
const blockConfigYaml = await resolveBlock(
decodePackageIdentifier(rule.uses),
rule.with,
registry,
);
const block = blockConfigYaml.rules?.[0];
return { index, rule: block || null, error: null };
} catch (err) {
console.error(
`Failed to unroll block ${rule.uses}: ${(err as Error).message}`,
);
return {
index,
rule: null,
error: {
fatal: false,
message: `${(err as Error).message}:\n${rule.uses}`,
},
};
}
}
return { index, rule: null, error: null };
});
const ruleResults = await Promise.all(rulePromises);
const rules: (Rule | null)[] = [];
const ruleErrors: ConfigValidationError[] = [];
for (const result of ruleResults) {
if (result.error) {
ruleErrors.push(result.error);
}
rules[result.index] = result.rule;
}
return { rules, errors: ruleErrors };
})()
: Promise.resolve({ rules: undefined, errors: [] });
// Process injected blocks in parallel
const injectedBlocksPromise = injectBlocks
? (async () => {
const injectedBlockPromises = injectBlocks.map(async (injectBlock) => {
try {
const blockConfigYaml = await registry.getContent(injectBlock);
const parsedBlock = parseMarkdownRuleOrConfigYaml(
blockConfigYaml,
injectBlock,
);
const blockType = getBlockType(parsedBlock);
const resolvedBlock = await resolveBlock(
injectBlock,
undefined,
registry,
);
return {
blockType,
resolvedBlock,
error: null,
};
} catch (err) {
let msg = "";
if (injectBlock.uriType === "file") {
msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`;
} else {
msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`;
}
console.error(
`Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`,
);
return {
blockType: null,
resolvedBlock: null,
error: {
fatal: false,
message: msg,
},
};
}
});
const injectedResults = await Promise.all(injectedBlockPromises);
const injectedErrors: ConfigValidationError[] = [];
const injectedBlocks: { blockType: string; resolvedBlock: any }[] = [];
for (const result of injectedResults) {
if (result.error) {
injectedErrors.push(result.error);
} else if (result.blockType && result.resolvedBlock) {
injectedBlocks.push({
blockType: result.blockType,
resolvedBlock: result.resolvedBlock,
});
}
}
return { injectedBlocks, errors: injectedErrors };
})()
: Promise.resolve({ injectedBlocks: [], errors: [] });
// Wait for all parallel operations to complete
const [sectionResults, rulesResult, injectedResult] = await Promise.all([
Promise.all(sectionPromises),
rulesPromise,
injectedBlocksPromise,
]);
// Collect all errors
for (const sectionResult of sectionResults) {
if (sectionResult.errors) {
errors.push(...sectionResult.errors);
}
}
errors.push(...rulesResult.errors);
errors.push(...injectedResult.errors);
// Assign section results
for (const sectionResult of sectionResults) {
if (sectionResult.blocks) {
unrolledAssistant[sectionResult.section] = sectionResult.blocks;
}
}
// Rules are a bit different because they can be strings, so handle separately
if (assistant.rules) {
const rules: (Rule | null)[] = [];
for (const rule of assistant.rules) {
if (typeof rule === "string" || !("uses" in rule)) {
rules.push(rule);
} else if ("uses" in rule) {
try {
const blockConfigYaml = await resolveBlock(
decodePackageIdentifier(rule.uses),
rule.with,
registry,
);
const block = blockConfigYaml.rules?.[0];
if (block) {
rules.push(block);
}
} catch (err) {
errors.push({
fatal: false,
message: `${(err as Error).message}:\n${rule.uses}`,
});
console.error(
`Failed to unroll block ${rule.uses}: ${(err as Error).message}`,
);
rules.push(null);
}
}
}
unrolledAssistant.rules = rules;
// Assign rules result
if (rulesResult.rules) {
unrolledAssistant.rules = rulesResult.rules;
}
// Add injected blocks
for (const injectBlock of injectBlocks ?? []) {
try {
const blockConfigYaml = await registry.getContent(injectBlock);
const parsedBlock = parseMarkdownRuleOrConfigYaml(
blockConfigYaml,
injectBlock,
);
const blockType = getBlockType(parsedBlock);
const resolvedBlock = await resolveBlock(
injectBlock,
undefined,
registry,
);
if (blockType) {
if (!unrolledAssistant[blockType]) {
unrolledAssistant[blockType] = [];
}
unrolledAssistant[blockType]?.push(
...(resolvedBlock[blockType] as any),
);
}
} catch (err) {
let msg = "";
if (injectBlock.uriType === "file") {
msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`;
} else {
msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`;
}
errors.push({
fatal: false,
message: msg,
});
console.error(
`Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`,
);
for (const { blockType, resolvedBlock } of injectedResult.injectedBlocks) {
const key = blockType as BlockType;
if (!unrolledAssistant[key]) {
unrolledAssistant[key] = [];
}
unrolledAssistant[key]?.push(...((resolvedBlock[blockType] ?? []) as any));
}
const configResult: ConfigResult<AssistantUnrolled> = {

View file

@ -155,7 +155,8 @@ export const modelSchema = z.union([
z.object({
...baseModelFields,
provider: z.literal("continue-proxy"),
apiKeyLocation: z.string(),
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
orgScopeId: z.string().nullable(),
onPremProxyUrl: z.string().nullable(),
}),
@ -170,7 +171,8 @@ export const partialModelSchema = z.union([
.object({
...baseModelFields,
provider: z.literal("continue-proxy"),
apiKeyLocation: z.string(),
apiKeyLocation: z.string().optional(),
envSecretLocations: z.record(z.string(), z.string()).optional(),
})
.partial(),
z

View file

@ -71,14 +71,15 @@ export function createOpenAIClient({
);
}
if (!("apiKeyLocation" in modelConfig)) {
if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) {
throw new Error(
`Model ${modelName} does not have an apiKeyLocation defined`,
`Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`,
);
}
const continueProperties: ContinueProperties = {
apiKeyLocation: modelConfig.apiKeyLocation,
envSecretLocations: modelConfig.envSecretLocations,
orgScopeId: organizationId ?? null,
};

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.44",
"version": "1.0.45",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -12,6 +12,8 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.15",

View file

@ -0,0 +1,691 @@
import {
BedrockRuntimeClient,
ContentBlock,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandInput,
ImageFormat,
InvokeModelCommand,
Message,
ToolConfiguration,
} from "@aws-sdk/client-bedrock-runtime";
import { OpenAI } from "openai/index";
import { v4 as uuidv4 } from "uuid";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParams,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
ChatCompletionMessageToolCall,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
Model,
} from "openai/resources/index";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import { BedrockConfig } from "../types.js";
import { chatChunk, chatChunkFromDelta, embedding, rerank } from "../util.js";
import { safeParseArgs } from "../util/parseArgs.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
// Utility function to get or generate UUID for prompt caching
function getSecureID(): string {
// Adding a type declaration for the static property
if (!(getSecureID as any).uuid) {
(getSecureID as any).uuid = crypto.randomUUID();
}
return `<!-- SID: ${(getSecureID as any).uuid} -->`;
}
/**
* Interface for tool use state tracking
*/
interface ToolUseState {
toolUseId: string;
name: string;
input: string;
}
export class BedrockApi implements BaseLlmApi {
private _currentToolResponse: Partial<ToolUseState> | null = null;
constructor(protected config: BedrockConfig) {
if (config.env?.accessKeyId || config?.env?.secretAccessKey) {
if (!config.env?.accessKeyId) {
throw new Error(
"accessKeyId is required for Bedrock API. Only found secretAccessKey",
);
}
if (!config.env?.secretAccessKey) {
throw new Error(
"secretAccessKey is required for Bedrock API. Only found accessKeyId",
);
}
}
}
async getCreds() {
if (this.config?.env?.accessKeyId && this.config?.env?.secretAccessKey) {
return {
accessKeyId: this.config.env.accessKeyId,
secretAccessKey: this.config.env.secretAccessKey,
};
}
const profile = this.config.env.profile ?? "bedrock";
try {
return await fromNodeProviderChain({
profile: profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
);
}
return await fromNodeProviderChain()();
}
async getClient(): Promise<BedrockRuntimeClient> {
const creds = await this.getCreds();
return new BedrockRuntimeClient({
region: this.config.env.region,
credentials: creds,
});
}
private _oaiPartToBedrockPart(
part:
| OpenAI.Chat.Completions.ChatCompletionContentPart
| OpenAI.Chat.Completions.ChatCompletionContentPartRefusal,
): ContentBlock {
switch (part.type) {
case "refusal":
return {
text: part.refusal,
};
case "text":
return {
text: part.text,
};
case "input_audio":
throw new Error("Unsupported part type: input_audio");
case "image_url":
default:
try {
const [mimeType, base64Data] = part.image_url.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
if (
format === ImageFormat.JPEG ||
format === ImageFormat.PNG ||
format === ImageFormat.WEBP ||
format === ImageFormat.GIF
) {
return {
image: {
format,
source: {
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
},
},
};
} else {
console.warn(
`Bedrock: skipping unsupported image part format: ${format}`,
);
return { text: "[Unsupported image format]" };
}
} catch (error) {
console.warn("Bedrock: failed to process image part", error);
return { text: "[Failed to process image]" };
}
}
}
private _convertMessages(
oaiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
availableTools: Set<string>,
): Message[] {
let currentRole: "user" | "assistant" = "user";
let currentBlocks: ContentBlock[] = [];
const converted: Message[] = [];
const hasAddedToolCallIds = new Set<string>();
const pushCurrentMessage = () => {
if (currentBlocks.length > 0) {
converted.push({
role: currentRole,
content: currentBlocks,
});
currentBlocks = [];
}
};
const nonSystemMessages = oaiMessages.filter((m) => m.role !== "system");
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
const message = nonSystemMessages[idx];
if (message.role === "user" || message.role === "tool") {
// Detect conversational turn change
if (currentRole !== ConversationRole.USER) {
pushCurrentMessage();
currentRole = ConversationRole.USER;
}
// USER messages
if (message.role === "user") {
const content = message.content;
if (content) {
if (typeof content === "string") {
currentBlocks.push({ text: content });
} else {
content.forEach((part) => {
currentBlocks.push(this._oaiPartToBedrockPart(part));
});
}
}
}
// TOOL messages
else if (message.role === "tool") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content
.map((c) => c.text)
.join("\n")
.trim();
if (hasAddedToolCallIds.has(message.tool_call_id)) {
currentBlocks.push({
toolResult: {
toolUseId: message.tool_call_id,
content: [
{
text: trimmedContent || "No tool output",
},
],
},
});
} else {
currentBlocks.push({
text: `Tool call output for Tool Call ID ${message.tool_call_id}:\n\n${trimmedContent || "No tool output"}`,
});
}
}
} else if (message.role === "assistant") {
// Detect conversational turn change
if (currentRole !== ConversationRole.ASSISTANT) {
pushCurrentMessage();
currentRole = ConversationRole.ASSISTANT;
}
// ASSISTANT messages
if (typeof message.content === "string") {
const trimmedText = message.content.trim();
if (trimmedText) {
currentBlocks.push({ text: trimmedText });
}
} else {
message.content?.forEach((part) => {
const text = part.type === "text" ? part.text : part.refusal;
const trimmedText = text.trim();
if (trimmedText) {
currentBlocks.push({ text: trimmedText });
}
});
}
// TOOL CALLS
if (message.tool_calls) {
for (const toolCall of message.tool_calls) {
if (toolCall.id && toolCall.function?.name) {
if (availableTools.has(toolCall.function.name)) {
currentBlocks.push({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function.name,
input: safeParseArgs(
toolCall.function.arguments,
`Call: ${toolCall.function.name} ${toolCall.id}`,
),
},
});
hasAddedToolCallIds.add(toolCall.id);
} else {
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
currentBlocks.push({
text: toolCallText,
});
}
}
}
}
}
}
if (currentBlocks.length > 0) {
pushCurrentMessage();
}
// If caching is enabled, add cache points
// if (this.config.cacheBehavior?.cacheConversation) {
// this._addCachingToLastTwoUserMessages(converted);
// }
return converted;
}
private _addCachingToLastTwoUserMessages(converted: Message[]) {
let numCached = 0;
for (let i = converted.length - 1; i >= 0; i--) {
const message = converted[i];
if (message.role === "user") {
message.content?.forEach((block) => {
if (block.text) {
block.text += getSecureID();
}
});
message.content?.push({ cachePoint: { type: "default" } });
numCached++;
}
if (numCached === 2) {
break;
}
}
}
private _convertBody(
oaiBody: ChatCompletionCreateParams,
): ConverseStreamCommandInput {
// Extract system message
const systemMessage =
oaiBody.messages.find((msg) => msg.role === "system")?.content || "";
const systemMessageText =
typeof systemMessage === "string"
? systemMessage
: systemMessage
.map((part) =>
part.type === "text" ? part.text : "[Non-text content]",
)
.join(" ");
// Check for tools
const availableTools = new Set<string>();
let toolConfig: ToolConfiguration | undefined = undefined;
if (oaiBody.tools && oaiBody.tools.length > 0) {
toolConfig = {
tools: oaiBody.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration;
// Add cache point if needed
// if (this.config.cacheBehavior?.cacheSystemMessage) {
// toolConfig!.tools!.push({ cachePoint: { type: "default" } });
// }
oaiBody.tools.forEach((tool) => {
availableTools.add(tool.function.name);
});
}
// Convert messages
const convertedMessages = this._convertMessages(
oaiBody.messages,
availableTools,
);
// Build final request body
const body: any = {
modelId: oaiBody.model,
messages: convertedMessages,
inferenceConfig: {
temperature: oaiBody.temperature,
topP: oaiBody.top_p,
maxTokens: oaiBody.max_tokens,
stopSequences: Array.isArray(oaiBody.stop)
? oaiBody.stop.filter((s) => s.trim() !== "").slice(0, 4)
: oaiBody.stop
? [oaiBody.stop].filter((s) => s.trim() !== "")
: undefined,
},
};
// Add system message if present
if (systemMessageText) {
body.system = false // this.config.cacheBehavior?.cacheSystemMessage // TODO
? [{ text: systemMessageText }, { cachePoint: { type: "default" } }]
: [{ text: systemMessageText }];
}
// Add tool config if present
if (toolConfig) {
body.toolConfig = toolConfig;
}
// Add reasoning if needed
// TODO REASONING
// if (this.c) {
// body.additionalModelRequestFields = {
// thinking: {
// type: "enabled",
// budget_tokens:
// oaiBody.additionalModelRequestFields.reasoningBudgetTokens,
// },
// };
// }
return body;
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
let completion = "";
const toolCalls: ChatCompletionMessageToolCall[] = [];
for await (const chunk of this.chatCompletionStream(
{
...body,
stream: true,
},
signal,
)) {
if (chunk.choices[0].delta.content) {
completion += chunk.choices[0].delta.content;
}
// TODO tool calls not supported
}
return {
id: uuidv4(),
object: "chat.completion",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: completion,
tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
refusal: null,
},
},
],
usage: undefined,
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk> {
const requestBody = this._convertBody(body);
try {
const command = new ConverseStreamCommand({
...requestBody,
});
const client = await this.getClient();
const response = await client.send(command, { abortSignal: signal });
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
}
this._currentToolResponse = null;
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta) {
const delta: any = chunk.contentBlockDelta.delta;
// Handle text content
if (delta.text) {
yield chatChunk({
content: delta.text,
model: body.model,
});
continue;
}
// Handle thinking content (if reasoning enabled)
if (delta.reasoningContent?.text) {
// TODO reasoning
// Reasoning is not directly supported in OpenAI format,
// but we could add it as a special message
continue;
}
// Handle tool use
if (delta.toolUse?.input && this._currentToolResponse) {
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const start: any = chunk.contentBlockStart.start;
// Handle tool start
const toolUse = start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: "",
};
}
continue;
}
if (chunk.contentBlockStop) {
// End of a content block
if (this._currentToolResponse) {
yield chatChunkFromDelta({
model: body.model,
delta: {
tool_calls: [
{
index: 0,
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input,
},
},
],
},
});
this._currentToolResponse = null;
}
continue;
}
}
} catch (error) {
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
throw new Error(
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error(
"Error processing Bedrock stream: Unknown error occurred",
);
}
}
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Bedrock does not support completions API");
}
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
throw new Error("Bedrock does not support completions API");
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Bedrock does not support FIM directly");
}
private async getInvokeModelResponseBody(model: string, jsonBody: object) {
const payload = {
body: JSON.stringify(jsonBody),
modelId: model,
accept: "*/*",
contentType: "application/json",
};
const command = new InvokeModelCommand(payload);
const client = await this.getClient();
const response = await client.send(command);
if (!response.body) {
throw new Error("No response body");
}
const decoder = new TextDecoder();
const decoded = decoder.decode(response.body);
return JSON.parse(decoded);
}
private getEmbedTexts(body: EmbeddingCreateParams): string[] {
const texts: string[] = [];
if (typeof body.input === "string") {
texts.push(body.input);
} else if (body.input.length > 0) {
const firstVal = body.input[0];
if (Array.isArray(firstVal)) {
throw new Error("Unsupported embeddings type received: number[][]");
}
if (typeof firstVal === "string") {
texts.push(...(body.input as string[]));
} else {
throw new Error("Unsupported embeddings type received: number[]");
}
}
return texts;
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
const texts = this.getEmbedTexts(body);
let embeddings: number[][];
if (body.model.startsWith("cohere")) {
const payload = {
texts,
input_type: "search_document",
truncate: "END",
};
const output = await this.getInvokeModelResponseBody(body.model, payload);
embeddings = [output.embedding];
} else if (body.model.startsWith("amazon.titan-embed")) {
embeddings = await Promise.all(
texts.map(async (text) => {
const payload = {
inputText: text,
};
const output = await this.getInvokeModelResponseBody(
body.model,
payload,
);
return output.embeddings || [];
}),
);
} else {
throw new Error(`Unsupported model: ${body.model}`);
}
return embedding({
data: embeddings,
model: body.model,
usage: {
prompt_tokens: 0,
total_tokens: 0,
},
});
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
if (!body.query || !body.documents.length) {
throw new Error("Query and chunks must not be empty");
}
// Base payload for both models
const payload: any = {
query: body.query,
documents: body.documents,
top_n: body.top_k ?? body.documents.length,
};
// Add api_version for Cohere model
if (body.model.startsWith("cohere.rerank")) {
payload.api_version = 2;
}
try {
const responseBody = await this.getInvokeModelResponseBody(
body.model,
payload,
);
const scores = responseBody.results
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.relevance_score);
return rerank({
model: body.model,
usage: {
total_tokens: 0,
},
data: scores,
});
} catch (error) {
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
}
throw new Error(
"Error in BedrockReranker.rerank: Unknown error occurred",
);
}
}
list(): Promise<Model[]> {
throw new Error("Method not implemented.");
}
}

View file

@ -2,6 +2,7 @@ import dotenv from "dotenv";
import { z } from "zod";
import { AnthropicApi } from "./apis/Anthropic.js";
import { AzureApi } from "./apis/Azure.js";
import { BedrockApi } from "./apis/Bedrock.js";
import { CohereApi } from "./apis/Cohere.js";
import { DeepSeekApi } from "./apis/DeepSeek.js";
import { GeminiApi } from "./apis/Gemini.js";
@ -34,6 +35,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
return new OpenAIApi(config);
case "azure":
return new AzureApi(config);
case "bedrock":
return new BedrockApi(config);
case "cohere":
return new CohereApi(config);
case "anthropic":

View file

@ -71,6 +71,21 @@ export const DeepseekConfigSchema = OpenAIConfigSchema.extend({
});
export type DeepseekConfig = z.infer<typeof DeepseekConfigSchema>;
export const BedrockConfigSchema = OpenAIConfigSchema.extend({
provider: z.literal("bedrock"),
// cacheBehavior: z.object({
// cacheSystemMessage: z.boolean().optional(),
// cacheConversation: z.boolean().optional(),
// }).optional(),
env: z.object({
region: z.string().optional(),
accessKeyId: z.string().optional(),
secretAccessKey: z.string().optional(),
profile: z.string().optional(),
}),
});
export type BedrockConfig = z.infer<typeof BedrockConfigSchema>;
export const LlamastackConfigSchema = OpenAIConfigSchema.extend({
provider: z.literal("llamastack"),
});
@ -142,6 +157,7 @@ export type InceptionConfig = z.infer<typeof InceptionConfigSchema>;
// Discriminated union
export const LLMConfigSchema = z.discriminatedUnion("provider", [
OpenAIConfigSchema,
BedrockConfigSchema,
MoonshotConfigSchema,
DeepseekConfigSchema,
CohereConfigSchema,