diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml new file mode 100644 index 000000000..13dbdc9f3 --- /dev/null +++ b/.github/workflows/compliance.yaml @@ -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:", + "```", + "[optional scope]: ", + "", + "[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 diff --git a/core/config/load.ts b/core/config/load.ts index a084bbd38..a5da010f9 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -643,6 +643,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { template: llm.template, completionOptions: llm.completionOptions, baseAgentSystemMessage: llm.baseAgentSystemMessage, + basePlanSystemMessage: llm.basePlanSystemMessage, baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, promptTemplates: serializePromptTemplates(llm.promptTemplates), @@ -650,6 +651,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { roles: llm.roles, configurationStatus: llm.getConfigurationStatus(), apiKeyLocation: llm.apiKeyLocation, + envSecretLocations: llm.envSecretLocations, }; } diff --git a/core/config/types.ts b/core/config/types.ts index df29d6071..406f40ddd 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1004,6 +1004,8 @@ declare global { type: "stdio"; command: string; args: string[]; + env?: Record; + cwd?: string; } interface WebSocketOptions { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f1546e255..935e8b984 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -69,6 +69,7 @@ function convertYamlMcpToContinueMcp( command: server.command, args: server.args ?? [], env: server.env, + cwd: server.cwd, } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) timeout: server.connectionTimeout, }; diff --git a/core/config/yaml/loadYaml.vitest.ts b/core/config/yaml/loadYaml.vitest.ts new file mode 100644 index 000000000..fd6769f70 --- /dev/null +++ b/core/config/yaml/loadYaml.vitest.ts @@ -0,0 +1,128 @@ +import { describe, it, expect } from "vitest"; +import { + validateConfigYaml, + AssistantUnrolledNonNullable, +} from "@continuedev/config-yaml"; + +describe("MCP Server cwd configuration", () => { + describe("YAML schema validation", () => { + it("should accept valid MCP server with cwd", () => { + const config: AssistantUnrolledNonNullable = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "test-server", + command: "node", + args: ["server.js"], + env: { NODE_ENV: "production" }, + cwd: "/path/to/project", + connectionTimeout: 5000, + }, + ], + }; + + const errors = validateConfigYaml(config); + expect(errors).toHaveLength(0); + }); + + it("should accept MCP server without cwd", () => { + const config: AssistantUnrolledNonNullable = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "test-server", + command: "python", + args: ["-m", "server"], + }, + ], + }; + + const errors = validateConfigYaml(config); + expect(errors).toHaveLength(0); + }); + + it("should accept relative paths in cwd", () => { + const config: AssistantUnrolledNonNullable = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "test-server", + command: "cargo", + args: ["run"], + cwd: "./rust-project", + }, + ], + }; + + const errors = validateConfigYaml(config); + expect(errors).toHaveLength(0); + }); + + it("should accept empty string cwd", () => { + const config: AssistantUnrolledNonNullable = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "test-server", + command: "deno", + args: ["run", "server.ts"], + cwd: "", + }, + ], + }; + + const errors = validateConfigYaml(config); + expect(errors).toHaveLength(0); + }); + }); + + describe("MCP server configuration examples", () => { + it("should support common MCP server patterns with cwd", () => { + const configs = [ + { + name: "Local project MCP server", + server: { + name: "project-mcp", + command: "npm", + args: ["run", "mcp-server"], + cwd: "/Users/developer/my-project", + }, + }, + { + name: "Python MCP with virtual environment", + server: { + name: "python-mcp", + command: "python", + args: ["-m", "my_mcp_server"], + env: { PYTHONPATH: "./src" }, + cwd: "/home/user/python-project", + }, + }, + { + name: "Relative path MCP server", + server: { + name: "relative-mcp", + command: "node", + args: ["index.js"], + cwd: "../mcp-servers/filesystem", + }, + }, + ]; + + configs.forEach(({ name, server }) => { + const config: AssistantUnrolledNonNullable = { + name: "test-assistant", + version: "1.0.0", + mcpServers: [server], + }; + + const errors = validateConfigYaml(config); + expect(errors).toHaveLength(0); + }); + }); + }); +}); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index edb47f59e..3f571c3fb 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -63,6 +63,7 @@ async function modelConfigToBaseLLM({ template: model.promptTemplates?.chat, promptTemplates: model.promptTemplates, baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage, + basePlanSystemMessage: model.chatOptions?.basePlanSystemMessage, baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { tools: model.capabilities?.includes("tool_use"), @@ -126,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; } diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index c66a93ed3..af971d813 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -329,6 +329,7 @@ class MCPConnection { command, args, env, + cwd: options.transport.cwd, stderr: "pipe", }); diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index 7736ebec9..0933ec020 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -1,6 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { beforeEach, describe, expect, it, vi } from "vitest"; import MCPConnection from "./MCPConnection"; +import { StdioOptions } from "../../index.d.js"; describe("MCPConnection", () => { beforeEach(() => { @@ -25,6 +26,27 @@ describe("MCPConnection", () => { expect(conn.status).toBe("not-connected"); }); + it("should create instance with stdio transport including cwd", () => { + const options = { + name: "test-mcp", + id: "test-id", + transport: { + type: "stdio" as const, + command: "test-cmd", + args: ["--test"], + env: { TEST: "true" }, + cwd: "/path/to/working/directory", + }, + }; + + const conn = new MCPConnection(options); + expect(conn).toBeInstanceOf(MCPConnection); + expect(conn.status).toBe("not-connected"); + if (conn.options.transport.type === "stdio") { + expect(conn.options.transport.cwd).toBe("/path/to/working/directory"); + } + }); + it("should create instance with websocket transport", () => { const options = { name: "test-mcp", diff --git a/core/index.d.ts b/core/index.d.ts index 3d6f1602c..1ace46141 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -428,7 +428,7 @@ export interface PromptLog { completion: string; } -export type MessageModes = "chat" | "agent"; +export type MessageModes = "chat" | "agent" | "plan"; export type ToolStatus = | "generating" @@ -568,6 +568,7 @@ export interface LLMOptions { title?: string; uniqueId?: string; baseAgentSystemMessage?: string; + basePlanSystemMessage?: string; baseChatSystemMessage?: string; autocompleteOptions?: Partial; contextLength?: number; @@ -583,6 +584,7 @@ export interface LLMOptions { // continueProperties apiKeyLocation?: string; + envSecretLocations?: Record; apiBase?: string; orgScopeId?: string | null; @@ -611,6 +613,8 @@ export interface LLMOptions { // AWS options profile?: string; modelArn?: string; + accessKeyId?: string; + secretAccessKey?: string; // AWS and VertexAI Options region?: string; @@ -1082,6 +1086,7 @@ export interface ModelDescription { apiBase?: string; apiKeyLocation?: string; + envSecretLocations?: Record; orgScopeId?: string | null; onPremProxyUrl?: string | null; @@ -1091,6 +1096,7 @@ export interface ModelDescription { template?: TemplateType; completionOptions?: BaseCompletionOptions; baseAgentSystemMessage?: string; + basePlanSystemMessage?: string; baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; @@ -1162,6 +1168,7 @@ export interface StdioOptions { command: string; args: string[]; env?: Record; + cwd?: string; requestOptions?: RequestOptions; } @@ -1636,9 +1643,11 @@ export interface TerminalOptions { export type RuleSource = | "default-chat" + | "default-plan" | "default-agent" - | "model-chat-options" - | "model-agent-options" + | "model-options-chat" + | "model-options-plan" + | "model-options-agent" | "rules-block" | "json-systemMessage" | ".continuerules"; diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 0975fc142..90de5c64d 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -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 { diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index c2f82bac4..a6b3afc6c 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -1,7 +1,4 @@ -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = +export const DEFAULT_SYSTEM_MESSAGES_URL = "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ @@ -66,3 +63,17 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; + +// The note about read-only tools is for MCP servers +// For now, all MCP tools are included so model can decide if they are read-only +export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\ + + You are in plan mode, in which you help the user understand and construct a plan. + Only use read-only tools. Do not use any tools that would write to non-temporary files. + If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates. + +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +${EDIT_CODE_INSTRUCTIONS} + + In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan. +`; diff --git a/core/llm/index.ts b/core/llm/index.ts index 47fdf8011..8872281d6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -141,6 +141,7 @@ export abstract class BaseLLM implements ILLM { title?: string; baseChatSystemMessage?: string; + basePlanSystemMessage?: string; baseAgentSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; @@ -155,6 +156,7 @@ export abstract class BaseLLM implements ILLM { // continueProperties apiKeyLocation?: string; + envSecretLocations?: Record; apiBase?: string; orgScopeId?: string | null; @@ -172,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; @@ -209,6 +213,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; this.baseAgentSystemMessage = options.baseAgentSystemMessage; + this.basePlanSystemMessage = options.basePlanSystemMessage; this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; @@ -246,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; @@ -270,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(); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 1c1c61ed3..11d772b7b 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -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 // diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index e45828c40..0522bbda6 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -8,7 +8,6 @@ import { LLMOptions, } from "../.."; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; @@ -141,9 +140,9 @@ export async function llmFromDescription( let baseChatSystemMessage: string | undefined = undefined; if (desc.systemMessage !== undefined) { - baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; - baseChatSystemMessage += "\n\n"; - baseChatSystemMessage += await renderTemplatedString( + // baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; + // baseChatSystemMessage += "\n\n"; + baseChatSystemMessage = await renderTemplatedString( Handlebars, desc.systemMessage, {}, @@ -163,6 +162,7 @@ export async function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens, }, baseChatSystemMessage, + basePlanSystemMessage: baseChatSystemMessage, baseAgentSystemMessage: baseChatSystemMessage, logger: llmLogger, uniqueId, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index b49d00548..d7f788a33 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -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 { 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; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 9c3db3e74..ccaf906ce 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -19,6 +19,7 @@ export const PROVIDER_TOOL_SUPPORT: Record 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 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 boolean> = "claude-3-7-sonnet", "claude-3.7-sonnet", "claude-sonnet-4", + "claude-4-sonnet", "claude-opus-4", "nova-lite", "nova-pro", diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index b654f9c32..f4c601009 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -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 diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts index d2c031d4e..16259780a 100644 --- a/core/tools/implementations/fetchUrlContent.ts +++ b/core/tools/implementations/fetchUrlContent.ts @@ -1,6 +1,34 @@ import { ToolImpl } from "."; import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { - return getUrlContextItems(args.url, extras.fetch); + const contextItems = await getUrlContextItems(args.url, extras.fetch); + + // Track truncated content + const truncatedUrls: string[] = []; + + // Check and truncate each context item + const processedItems = contextItems.map((item) => { + if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) { + truncatedUrls.push(args.url); + return { + ...item, + content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT), + }; + } + return item; + }); + + // Add truncation warning if needed + if (truncatedUrls.length > 0) { + processedItems.push({ + name: "URL content truncation warning", + description: "Informs that URL content was truncated", + content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`, + }); + } + + return processedItems; }; diff --git a/core/tools/implementations/fetchUrlContent.vitest.ts b/core/tools/implementations/fetchUrlContent.vitest.ts new file mode 100644 index 000000000..9d103893d --- /dev/null +++ b/core/tools/implementations/fetchUrlContent.vitest.ts @@ -0,0 +1,91 @@ +import { expect, test, vi } from "vitest"; +import { fetchUrlContentImpl } from "./fetchUrlContent"; + +vi.mock("../../context/providers/URLContextProvider", () => ({ + getUrlContextItems: vi.fn(), +})); + +import { ToolExtras } from "../.."; +import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +test("fetchUrlContent should not truncate content under character limit", async () => { + const shortContent = "This is a short content"; + const mockContextItems = [ + { + name: "Test URL", + description: "Test URL description", + content: shortContent, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(1); + expect(result[0].content).toBe(shortContent); +}); + +test("fetchUrlContent should truncate content exceeding character limit", async () => { + const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + // Create a string exceeding the character limit + const longContent = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000); + const mockContextItems = [ + { + name: "Test URL", + description: "Test URL description", + content: longContent, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(2); // Original item + warning + expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[1].name).toBe("URL content truncation warning"); + expect(result[1].content).toContain("was truncated"); + expect(result[1].content).toContain("20000 character limit"); +}); + +test("fetchUrlContent should add truncation warning with multiple truncated items", async () => { + const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + // Create strings exceeding the character limit + const longContent1 = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 500); + const longContent2 = "b".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000); + const mockContextItems = [ + { + name: "Test URL 1", + description: "Test URL description 1", + content: longContent1, + }, + { + name: "Test URL 2", + description: "Test URL description 2", + content: longContent2, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(3); // Two original items + warning + expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[2].name).toBe("URL content truncation warning"); +}); diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts index 4a7f8bcb5..0418b37f6 100644 --- a/core/tools/implementations/lsTool.ts +++ b/core/tools/implementations/lsTool.ts @@ -2,30 +2,59 @@ import { ToolImpl } from "."; import { walkDir } from "../../indexing/walkDir"; import { resolveRelativePathInDir } from "../../util/ideUtils"; +export function resolveLsToolDirPath(dirPath: string | undefined) { + if (!dirPath || dirPath === ".") { + return "/"; + } + if (dirPath.startsWith(".")) { + return dirPath.slice(1); + } + return dirPath.replace(/\\/g, "/"); +} + +const MAX_LS_TOOL_LINES = 200; + export const lsToolImpl: ToolImpl = async (args, extras) => { - const uri = await resolveRelativePathInDir(args.dirPath, extras.ide); + const dirPath = resolveLsToolDirPath(args?.dirPath); + const uri = await resolveRelativePathInDir(dirPath, extras.ide); if (!uri) { throw new Error( - `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`, + `Directory ${args.dirPath} not found. Make sure to use forward-slash paths`, ); } const entries = await walkDir(uri, extras.ide, { returnRelativeUrisPaths: true, include: "both", - recursive: args.recursive ?? false, + recursive: args?.recursive ?? false, }); - const content = - entries.length > 0 - ? entries.join("\n") - : `No files/folders found in ${args.dirPath}`; + const lines = entries.slice(0, MAX_LS_TOOL_LINES); - return [ + let content = + lines.length > 0 + ? lines.join("\n") + : `No files/folders found in ${dirPath}`; + + const contextItems = [ { name: "File/folder list", - description: `Files/folders in ${args.dirPath}`, + description: `Files/folders in ${dirPath}`, content, }, ]; + + if (entries.length > MAX_LS_TOOL_LINES) { + let warningContent = `${entries.length - MAX_LS_TOOL_LINES} ls entries were truncated`; + if (args?.recursive) { + warningContent += ". Try using a non-recursive search"; + } + contextItems.push({ + name: "ls truncation warning", + description: "Informs the model that ls results were truncated", + content: warningContent, + }); + } + + return contextItems; }; diff --git a/core/tools/implementations/lsTool.vitest.ts b/core/tools/implementations/lsTool.vitest.ts new file mode 100644 index 000000000..b697a90c5 --- /dev/null +++ b/core/tools/implementations/lsTool.vitest.ts @@ -0,0 +1,96 @@ +import { expect, test, vi } from "vitest"; +import { ToolExtras } from "../.."; +import * as walkDirModule from "../../indexing/walkDir"; +import { lsToolImpl, resolveLsToolDirPath } from "./lsTool"; + +vi.mock("../../indexing/walkDir"); + +const mockExtras = { + ide: { + fileExists: async (path: string) => true, + getWorkspaceDirs: async () => ["dir1"], + }, +} as unknown as ToolExtras; + +test("resolveLsToolDirPath handles undefined path", () => { + expect(resolveLsToolDirPath(undefined)).toBe("/"); +}); + +test("resolveLsToolDirPath handles empty string", () => { + expect(resolveLsToolDirPath("")).toBe("/"); +}); + +test("resolveLsToolDirPath handles dot", () => { + expect(resolveLsToolDirPath(".")).toBe("/"); +}); + +test("resolveLsToolDirPath handles dot relative", () => { + expect(resolveLsToolDirPath("./hi")).toBe("/hi"); +}); + +test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => { + expect(resolveLsToolDirPath("path\\to\\dir")).toBe("path/to/dir"); +}); + +test("resolveLsToolDirPath preserves forward slashes", () => { + expect(resolveLsToolDirPath("path/to/dir")).toBe("path/to/dir"); +}); + +test("lsToolImpl truncates output when entries exceed MAX_LS_TOOL_LINES", async () => { + // Generate more than MAX_LS_TOOL_LINES entries (which is 200) + const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`); + + // Mock walkDir to return our large array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries); + + const result = await lsToolImpl( + { dirPath: "testDir", recursive: true }, + mockExtras, + ); + + // Check that the result contains the truncation message + expect(result.length).toBe(2); + expect(result[0].content).toContain("file1.txt"); + expect(result[0].content).toContain("file199.txt"); + expect(result[1].content).toContain("Try using a non-recursive search"); + expect(result[1].content).toContain("50 ls entries were truncated"); + + // Check that only MAX_LS_TOOL_LINES entries are included + const contentLines = result[0].content.split("\n"); + // Account for the truncation message line + expect(contentLines.length).toBe(200); + + // Check the suggestion to use non-recursive search is included + expect(result[1].content).toContain("Try using a non-recursive search"); +}); + +test("lsToolImpl shows truncation message without suggestion for non-recursive search", async () => { + // Generate more than MAX_LS_TOOL_LINES entries + const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`); + + // Mock walkDir to return our large array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries); + + const result = await lsToolImpl( + { dirPath: "testDir", recursive: false }, + mockExtras, + ); + + // Check that the result contains the truncation message + expect(result.length).toBe(2); + expect(result[1].content).toContain("50 ls entries were truncated"); + + // Check that the suggestion to use non-recursive search is NOT included + expect(result[1].content).not.toContain("Try using a non-recursive search"); +}); + +test("lsToolImpl shows message when no files are found", async () => { + // Mock walkDir to return empty array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue([]); + + const result = await lsToolImpl({ dirPath: "emptyDir" }, mockExtras); + + // Check that the result contains the "no files found" message + expect(result.length).toBe(1); + expect(result[0].content).toBe("No files/folders found in emptyDir"); +}); diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts index a01212659..c7b64feb3 100644 --- a/core/tools/implementations/searchWeb.ts +++ b/core/tools/implementations/searchWeb.ts @@ -1,8 +1,36 @@ +import { ToolImpl } from "."; import { fetchSearchResults } from "../../context/providers/WebContextProvider"; -import { ToolImpl } from "."; +const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; export const searchWebImpl: ToolImpl = async (args, extras) => { const webResults = await fetchSearchResults(args.query, 5, extras.fetch); - return webResults; + + // Track truncated results + const truncatedResults: string[] = []; + + // Check and truncate each result + const processedResults = webResults.map((result, index) => { + if (result.content.length > DEFAULT_WEB_SEARCH_CHAR_LIMIT) { + truncatedResults.push( + result.name || result.description || `Result #${index + 1}`, + ); + return { + ...result, + content: result.content.substring(0, DEFAULT_WEB_SEARCH_CHAR_LIMIT), + }; + } + return result; + }); + + // Add truncation warning if needed + if (truncatedResults.length > 0) { + processedResults.push({ + name: "Web search truncation warning", + description: "Informs that search results were truncated", + content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`, + }); + } + + return processedResults; }; diff --git a/core/tools/implementations/searchWeb.vitest.ts b/core/tools/implementations/searchWeb.vitest.ts new file mode 100644 index 000000000..17ddd4925 --- /dev/null +++ b/core/tools/implementations/searchWeb.vitest.ts @@ -0,0 +1,107 @@ +import { expect, test, vi } from "vitest"; +import { searchWebImpl } from "./searchWeb"; + +// Mock the fetchSearchResults function +vi.mock("../../context/providers/WebContextProvider", () => ({ + fetchSearchResults: vi.fn(), +})); +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +import { ToolExtras } from "../.."; +import { fetchSearchResults } from "../../context/providers/WebContextProvider"; + +test("searchWeb should not truncate results under character limit", async () => { + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: shortContent, + }, + { + name: "Result 2", + description: "Search result description 2", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(2); + expect(result[0].content).toBe(shortContent); + expect(result[1].content).toBe(shortContent); +}); + +test("searchWeb should truncate results exceeding character limit", async () => { + const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; + // Create a string exceeding the character limit + const longContent = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000); + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: longContent, + }, + { + name: "Result 2", + description: "Search result description 2", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(3); // Two results + warning + expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[1].content).toBe(shortContent); + expect(result[2].name).toBe("Web search truncation warning"); + expect(result[2].content).toContain("truncated"); + expect(result[2].content).toContain("Result 1"); + expect(result[2].content).not.toContain("Result 2"); +}); + +test("searchWeb should include all truncated results in the warning", async () => { + const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; + // Create strings exceeding the character limit + const longContent1 = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 500); + const longContent2 = "b".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000); + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: longContent1, + }, + { + name: "Result 2", + description: "Search result description 2", + content: longContent2, + }, + { + name: "Result 3", + description: "Search result description 3", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(4); // Three results + warning + expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[2].content).toBe(shortContent); + expect(result[3].name).toBe("Web search truncation warning"); + expect(result[3].content).toContain("Result 1"); + expect(result[3].content).toContain("Result 2"); + expect(result[3].content).not.toContain("Result 3"); +}); diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts index fd1dfdb8a..2b5da1ab8 100644 --- a/core/tools/implementations/viewDiff.ts +++ b/core/tools/implementations/viewDiff.ts @@ -1,15 +1,39 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; +export const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000; + export const viewDiffImpl: ToolImpl = async (args, extras) => { const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true); // TODO includeUnstaged should be an option - return [ + const combinedDiff = diffs.join("\n"); + const diffLines = combinedDiff.split("\n"); + + let truncated = false; + let processedDiff = combinedDiff; + + if (diffLines.length > DEFAULT_GIT_DIFF_LINE_LIMIT) { + truncated = true; + processedDiff = diffLines.slice(0, DEFAULT_GIT_DIFF_LINE_LIMIT).join("\n"); + } + + const contextItems: ContextItem[] = [ { name: "Diff", description: "The current git diff", - content: diffs.join("\n"), + content: processedDiff, }, ]; + + if (truncated) { + contextItems.push({ + name: "Diff truncation warning", + description: "Informs that git diff was truncated", + content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`, + }); + } + + return contextItems; }; diff --git a/core/tools/implementations/viewDiff.vitest.ts b/core/tools/implementations/viewDiff.vitest.ts new file mode 100644 index 000000000..914e3a014 --- /dev/null +++ b/core/tools/implementations/viewDiff.vitest.ts @@ -0,0 +1,87 @@ +import { expect, test, vi } from "vitest"; +import { DEFAULT_GIT_DIFF_LINE_LIMIT, viewDiffImpl } from "./viewDiff"; + +// Mock the getDiffsFromCache function +vi.mock("../../autocomplete/snippets/gitDiffCache", () => ({ + getDiffsFromCache: vi.fn(), +})); + +import { ToolExtras } from "../.."; +import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +test("viewDiff should not truncate diffs under line limit", async () => { + // Create a small diff with just a few lines + const smallDiff = [ + "diff --git a/file1.txt b/file1.txt", + "index 1234..5678 100644", + "--- a/file1.txt", + "+++ b/file1.txt", + "@@ -1,3 +1,4 @@", + " line1", + "-line2", + "+line2 modified", + "+line3 added", + ]; + + (getDiffsFromCache as any).mockResolvedValue(smallDiff); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(1); // Just the diff, no warning + expect(result[0].name).toBe("Diff"); + expect(result[0].content).toBe(smallDiff.join("\n")); +}); + +test("viewDiff should truncate diffs exceeding line limit", async () => { + // Create a large diff that exceeds the line limit + const largeDiffLines = Array(DEFAULT_GIT_DIFF_LINE_LIMIT + 1000).fill( + "line content", + ); + const largeDiff = [ + "diff --git a/file1.txt b/file1.txt", + "index 1234..5678 100644", + ...largeDiffLines, + ]; + + (getDiffsFromCache as any).mockResolvedValue([largeDiff.join("\n")]); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(2); // Diff + warning + + // Count the number of lines in the result + const resultLines = result[0].content.split("\n"); + expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); + + // Check the warning + expect(result[1].name).toBe("Diff truncation warning"); + expect(result[1].content).toContain("truncated"); + expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`); +}); + +test("viewDiff should handle multiple diffs correctly", async () => { + const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000; + + // Create multiple diffs that together exceed the line limit + const diff1Lines = Array(3000).fill("diff1 line"); + const diff2Lines = Array(3000).fill("diff2 line"); + const diff1 = diff1Lines.join("\n"); + const diff2 = diff2Lines.join("\n"); + + (getDiffsFromCache as any).mockResolvedValue([diff1, diff2]); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(2); // Diff + warning + + // Count the number of lines in the result + const resultLines = result[0].content.split("\n"); + expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); + + // Check the warning + expect(result[1].name).toBe("Diff truncation warning"); +}); diff --git a/core/tools/index.ts b/core/tools/index.ts index 198438eb1..95e0ac50f 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -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 => diff --git a/docs/docs/customize/deep-dives/mcp.mdx b/docs/docs/customize/deep-dives/mcp.mdx index 9899518e7..589b04798 100644 --- a/docs/docs/customize/deep-dives/mcp.mdx +++ b/docs/docs/customize/deep-dives/mcp.mdx @@ -110,6 +110,7 @@ MCP blocks follow the established syntax for blocks, with a few additional prope - `type` (optional): The type of the MCP server: `sse`, `stdio`, `streamable-http` - `args` (optional): Arguments to pass to the command. - `env` (optional): Secrets to be injected into the command as environment variables. +- `cwd` (optional): Working directory to run the command in. Can be absolute or relative path. ### Transport Types @@ -132,12 +133,22 @@ For local MCP servers that communicate via standard input and output: ```yaml mcpServers: - - name: Name + - name: SQLite Server type: stdio command: npx args: - "@modelcontextprotocol/server-sqlite" - - "/path/to/your/database.db" + - "./database.db" + cwd: "/path/to/project" + + - name: Local Project Server + command: npm + args: + - "run" + - "mcp-server" + cwd: "./my-project" + env: + NODE_ENV: "production" ``` #### Streamable HTTP Transport diff --git a/docs/docs/customize/yaml-migration.mdx b/docs/docs/customize/yaml-migration.mdx index 5ffd50e7c..444d54b62 100644 --- a/docs/docs/customize/yaml-migration.mdx +++ b/docs/docs/customize/yaml-migration.mdx @@ -288,6 +288,7 @@ docs: - `command` (**required**): The command used to start the server. - `args`: An optional array of arguments for the command. - `env`: An optional map of environment variables for the server process. +- `cwd`: An optional working directory to run the command in. Can be absolute or relative path. **Before** diff --git a/docs/docs/reference.mdx b/docs/docs/reference.mdx index 8f9db1347..f685dac4b 100644 --- a/docs/docs/reference.mdx +++ b/docs/docs/reference.mdx @@ -384,6 +384,7 @@ prompts, context, and tool use. Continue supports any MCP server with the MCP co - `command` (**required**): The command used to start the server. - `args`: An optional array of arguments for the command. - `env`: An optional map of environment variables for the server process. +- `cwd`: An optional working directory to run the command in. Can be absolute or relative path. - `connectionTimeout`: An optional connection timeout number to the server in milliseconds. **Example:** @@ -395,7 +396,10 @@ mcpServers: args: - mcp-server-sqlite - --db-path - - /Users/NAME/test.db + - ./test.db + cwd: /Users/NAME/project + env: + NODE_ENV: production ``` ### `data` diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt index b1fdae571..21f920ef9 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt @@ -21,6 +21,7 @@ class ContinueErrorService { init { Sentry.init { config -> config.dsn = SENTRY_DSN + config.environment = recognizeEnvironment() config.isSendDefaultPii = false config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) config.setTag("jcef_supported", JBCefApp.isSupported().toString()) @@ -45,6 +46,12 @@ class ContinueErrorService { private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension" private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" - } + private fun recognizeEnvironment() = + when { + System.getProperty("robot-server.port") != null -> "e2e" + System.getProperty("idea.is.internal").toBoolean() -> "dev" + else -> "production" + } + } } \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 29d882489..86675a1ac 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -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"], diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index a709266ec..8eae48307 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -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( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index fce37e516..d62caf298 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -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", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 7d5c2a12a..cb33e7a31 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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" diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 68c3436e8..339f9e84b 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -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; + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index b59abe665..f8914f31e 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -77,6 +77,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { { promise: Promise; cancel: EventEmitter } >(); 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; } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts index 55cac92df..f0a7b746d 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts @@ -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])); diff --git a/gui/src/components/ModeSelect/ModeIcon.tsx b/gui/src/components/ModeSelect/ModeIcon.tsx index 83201d5ae..92dfc1723 100644 --- a/gui/src/components/ModeSelect/ModeIcon.tsx +++ b/gui/src/components/ModeSelect/ModeIcon.tsx @@ -1,4 +1,8 @@ -import { ChatBubbleLeftIcon, SparklesIcon } from "@heroicons/react/24/outline"; +import { + ChatBubbleLeftIcon, + SparklesIcon, + SwatchIcon, +} from "@heroicons/react/24/outline"; import { MessageModes } from "core"; interface ModeIconProps { @@ -13,6 +17,8 @@ export function ModeIcon({ switch (mode) { case "agent": return ; + case "plan": + return ; case "chat": return ; } diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 9e1b5afef..9de391852 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,4 +1,8 @@ -import { CheckIcon, ChevronDownIcon } from "@heroicons/react/24/outline"; +import { + CheckIcon, + ChevronDownIcon, + InformationCircleIcon, +} from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { useCallback, useEffect, useMemo } from "react"; @@ -6,6 +10,7 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; +import { ToolTip } from "../gui/Tooltip"; import { useMainEditor } from "../mainInput/TipTapEditor"; import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; import { ModeIcon } from "./ModeIcon"; @@ -27,13 +32,19 @@ export function ModeSelect() { if (!selectedModel) { return; } - if (mode === "agent" && !agentModeSupported) { + if (mode !== "chat" && !agentModeSupported) { dispatch(setMode("chat")); } }, [mode, agentModeSupported, dispatch, selectedModel]); const cycleMode = useCallback(() => { - dispatch(setMode(mode === "chat" ? "agent" : "chat")); + if (mode === "chat") { + dispatch(setMode("plan")); + } else if (mode === "plan") { + dispatch(setMode("agent")); + } else { + dispatch(setMode("chat")); + } // Only focus main editor if another one doesn't already have focus if (!document.activeElement?.classList?.contains("ProseMirror")) { mainEditor?.commands.focus(); @@ -74,7 +85,7 @@ export function ModeSelect() { > - {mode.charAt(0).toUpperCase() + mode.slice(1)} + {mode === "chat" ? "Chat" : mode === "agent" ? "Agent" : "Plan"} {mode === "chat" && } - + +
+ + Plan + + + In Plan mode, only read-only and MCP tools are enabled + +
+ {agentModeSupported ? ( + + ) : ( + (Not supported) + )} +
Agent + + + All tools are enabled based on policies + {agentModeSupported ? ( - mode === "agent" && + ) : ( (Not supported) )} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 58f05ef0c..f8293cd50 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -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 ( <> - - + + {tooltipContent} - + ); } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 1d252dbdb..03aa1c4f5 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -219,7 +219,6 @@ export function StepContainerPreToolbar({ if (isGeneratingCodeBlock) { return ( - {!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index 7004ae9d8..2422c6cd5 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -7,6 +7,7 @@ type ToggleSwitchProps = { text: string; size?: number; showIfToggled?: ReactNode; + disabled?: boolean; }; const ToggleSwitch: React.FC = ({ @@ -15,15 +16,18 @@ const ToggleSwitch: React.FC = ({ text, size = 16, showIfToggled, + disabled = false, }) => { return ( -
+
{text}
{isToggled && !!showIfToggled && showIfToggled}
= ({ rule }) => { ideMessenger.post("openFile", { path: rule.ruleFile, }); - } else if (rule.source === "default-chat" && mode === "chat") { - ideMessenger.post("openUrl", DEFAULT_CHAT_SYSTEM_MESSAGE_URL); - } else if (rule.source === "default-agent" && mode === "agent") { - ideMessenger.post("openUrl", DEFAULT_AGENT_SYSTEM_MESSAGE_URL); + } else if ( + rule.source === "default-chat" || + rule.source === "default-plan" || + rule.source === "default-agent" + ) { + ideMessenger.post("openUrl", DEFAULT_SYSTEM_MESSAGES_URL); } else { ideMessenger.post("config/openProfile", { profileId: undefined, @@ -81,9 +82,11 @@ const RuleCard: React.FC = ({ rule }) => { return "Default agent system message"; } else if (rule.source === "json-systemMessage") { return "JSON systemMessage)"; - } else if (rule.source === "model-agent-options") { + } else if (rule.source === "model-options-agent") { return "Base System Agent Message"; - } else if (rule.source === "model-chat-options") { + } else if (rule.source === "model-options-plan") { + return "Base System Plan Message"; + } else if (rule.source === "model-options-chat") { return "Base System Chat Message"; } else { return "Assistant rule"; @@ -215,11 +218,24 @@ export function RulesSection() { } } - if (mode === "agent") { + if (mode === "chat") { + if (config.selectedModelByRole.chat?.baseChatSystemMessage) { + rules.unshift({ + rule: config.selectedModelByRole.chat?.baseChatSystemMessage, + source: "model-options-chat", + }); + } else { + rules.unshift({ + rule: DEFAULT_CHAT_SYSTEM_MESSAGE, + source: "default-chat", + }); + } + } else if (mode === "agent") { + // agent if (config.selectedModelByRole.chat?.baseAgentSystemMessage) { rules.unshift({ rule: config.selectedModelByRole.chat?.baseAgentSystemMessage, - source: "model-agent-options", + source: "model-options-agent", }); } else { rules.unshift({ @@ -228,15 +244,16 @@ export function RulesSection() { }); } } else { - if (config.selectedModelByRole.chat?.baseChatSystemMessage) { + // plan + if (config.selectedModelByRole.chat?.basePlanSystemMessage) { rules.unshift({ - rule: config.selectedModelByRole.chat?.baseChatSystemMessage, - source: "model-chat-options", + rule: config.selectedModelByRole.chat?.basePlanSystemMessage, + source: "model-options-plan", }); } else { rules.unshift({ - rule: DEFAULT_CHAT_SYSTEM_MESSAGE, - source: "default-chat", + rule: DEFAULT_AGENT_SYSTEM_MESSAGE, + source: "default-agent", }); } } diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx index c6e96c16b..9303f3392 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx @@ -1,3 +1,4 @@ +import { InformationCircleIcon } from "@heroicons/react/24/outline"; import { Tool } from "core"; import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -6,7 +7,26 @@ import { fontSize } from "../../../../../util"; import ToggleSwitch from "../../../../gui/Switch"; import ToolPolicyItem from "./ToolPolicyItem"; +interface ModeBadgeProps { + text: string; + icon: React.ReactNode; + onClick: () => void; + isSelected: boolean; +} +const ModeBadge = ({ text, onClick, isSelected, icon }: ModeBadgeProps) => { + return ( +
+ {icon} + {text} +
+ ); +}; + export const ToolPoliciesSection = () => { + const mode = useAppSelector((state) => state.session.mode); const availableTools = useAppSelector((state) => state.config.config.tools); const toolGroupSettings = useAppSelector( (store) => store.ui.toolGroupSettings, @@ -39,38 +59,56 @@ export const ToolPoliciesSection = () => { ); }, [availableTools]); + const allToolsOff = mode === "chat"; + + const message = + mode === "chat" + ? "All tools are disabled in Chat mode" + : mode === "plan" + ? "Plan mode: only read-only and MCP tools" + : "Agent mode: all tool policies apply"; + return ( <> - {toolsByGroup.map(([groupName, tools]) => ( -
-
-

- {groupName} -

- dispatch(toggleToolGroupSetting(groupName))} - text="" - size={10} - /> -
-
- {tools.map((tool) => ( - + + {message} +
+ {toolsByGroup.map(([groupName, tools]) => { + const isGroupEnabled = + !allToolsOff && toolGroupSettings[groupName] !== "exclude"; + return ( +
+
+

+ {groupName} +

+ dispatch(toggleToolGroupSetting(groupName))} + text="" + size={10} + disabled={allToolsOff} /> - ))} +
+
+ {tools.map((tool) => ( + + ))} +
-
- ))} + ); + })} ); }; diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx index b92816839..edccf3923 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx @@ -3,6 +3,7 @@ import { InformationCircleIcon, } from "@heroicons/react/24/outline"; import { Tool } from "core"; +import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn"; import { useEffect, useMemo, useState } from "react"; import { useDispatch } from "react-redux"; import { useAppSelector } from "../../../../../redux/hooks"; @@ -16,7 +17,7 @@ import { useFontSize } from "../../../../ui/font"; interface ToolDropdownItemProps { tool: Tool; duplicatesDetected: boolean; - excluded: boolean; + isGroupEnabled: boolean; } function ToolPolicyItem(props: ToolDropdownItemProps) { @@ -25,6 +26,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { (state) => state.ui.toolSettings[props.tool.function.name], ); const [isExpanded, setIsExpanded] = useState(false); + const mode = useAppSelector((state) => state.session.mode); useEffect(() => { if (!policy) { @@ -44,6 +46,12 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { const fontSize = useFontSize(-2); + const disabled = + !props.isGroupEnabled || + (mode === "plan" && + props.tool.group === BUILT_IN_GROUP_NAME && + !props.tool.readonly); + if (!policy) { return null; } @@ -106,16 +114,21 @@ function ToolPolicyItem(props: ToolDropdownItemProps) {
+
{ - dispatch(toggleToolSetting(props.tool.function.name)); - e.stopPropagation(); - e.preventDefault(); - }} + onClick={ + disabled + ? undefined + : (e) => { + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + } + } > - {props.excluded || policy === "disabled" ? ( + {disabled || policy === "disabled" ? ( <> Off diff --git a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx index 992d5b491..c9c60acc7 100644 --- a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx @@ -19,9 +19,11 @@ const getSourceLabel = (source: RuleSource): string => { return "Default Chat"; case "default-agent": return "Default Agent"; - case "model-chat-options": + case "model-options-chat": return "Model Chat Options"; - case "model-agent-options": + case "model-options-plan": + return "Model Plan Options"; + case "model-options-agent": return "Model Agent Options"; case "rules-block": return "Rules Block"; diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index 0065552a8..1b73751b9 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -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 ( 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 && ( - (Missing API key) + {invalidMessage} )} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 700e5352e..09a3884b7 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -33,6 +33,7 @@ import { selectCurrentToolCallApplyState, } from "../../redux/selectors/selectCurrentToolCall"; import { + cancelToolCall, newSession, updateToolCallOutput, } from "../../redux/slices/sessionSlice"; @@ -108,7 +109,6 @@ export function Chat() { (state) => state.config.config.ui?.showChatScrollbar, ); const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); - const toolCallState = useAppSelector(selectCurrentToolCall); const mode = useAppSelector((store) => store.session.mode); const isInEdit = useAppSelector((store) => store.session.isInEdit); @@ -147,6 +147,7 @@ export function Chat() { isStreaming, ); + const currentToolCallState = useAppSelector(selectCurrentToolCall); const currentToolCallApplyState = useAppSelector( selectCurrentToolCallApplyState, ); @@ -158,20 +159,19 @@ export function Chat() { index?: number, editorToClearOnSend?: Editor, ) => { - if (toolCallState?.status === "generated") { - return console.error( - "Cannot submit message while awaiting tool confirmation", + if (currentToolCallState) { + dispatch( + cancelToolCall({ + toolCallId: currentToolCallState.toolCallId, + }), ); } if ( currentToolCallApplyState && currentToolCallApplyState.status !== "closed" ) { - return console.error( - "Cannot submit message while awaiting tool call apply", - ); + ideMessenger.post("rejectDiff", currentToolCallApplyState); } - const model = isInEdit ? (selectedModels?.edit ?? selectedModels?.chat) : selectedModels?.chat; @@ -241,7 +241,7 @@ export function Chat() { mode, isInEdit, codeToEdit, - toolCallState, + currentToolCallState, currentToolCallApplyState, ], ); diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 27b093799..dae07c549 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -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 ( -
+
diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx index 0c5c188e4..c1b1ec0c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx @@ -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 ( - <> -
{ - 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"}`} - > - -
- - {isShowing ? "Hide args" : "Show args"} - - + { + setIsShowing(!isShowing); + }} + > + + ); }; diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx index 12000042d..d28cd9328 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx @@ -19,9 +19,11 @@ export function ToolTruncateHistoryIcon({ }, [history]); const dispatch = useAppDispatch(); const { mainEditor } = useMainEditor(); + if (historyIndex === lastMessageIndex) { return null; } + return ( ); diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index f573a45a0..158b653c3 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -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 ( + + ); + } + return ( { test("should be able to toggle modes", async () => { await renderWithProviders(); - await getElementByText("Chat"); + await getElementByText("Agent"); // Simulate cmd+. keyboard shortcut to toggle modes act(() => { @@ -27,8 +27,8 @@ test("should be able to toggle modes", async () => { ); }); - // Check that it switched to Agent mode - await getElementByText("Agent"); + // Check that it switched to Chat mode + await getElementByText("Chat"); act(() => { document.dispatchEvent( @@ -39,7 +39,19 @@ test("should be able to toggle modes", async () => { ); }); - await getElementByText("Chat"); + // Check that it switched to Plan mode + await getElementByText("Plan"); + + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + + await getElementByText("Agent"); }); test("should send a message and receive a response", async () => { diff --git a/gui/src/redux/selectors/selectActiveTools.ts b/gui/src/redux/selectors/selectActiveTools.ts index 7aae43765..2e90bbfd5 100644 --- a/gui/src/redux/selectors/selectActiveTools.ts +++ b/gui/src/redux/selectors/selectActiveTools.ts @@ -1,5 +1,6 @@ import { createSelector } from "@reduxjs/toolkit"; import { Tool } from "core"; +import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn"; import { RootState } from "../store"; export const selectActiveTools = createSelector( @@ -12,14 +13,18 @@ export const selectActiveTools = createSelector( (mode, tools, policies, groupPolicies): Tool[] => { if (mode === "chat") { return []; - } else if (mode === "agent") { - return tools.filter( + } else { + const enabledTools = tools.filter( (tool) => policies[tool.function.name] !== "disabled" && groupPolicies[tool.group] !== "exclude", ); - } else { - return []; + if (mode === "plan") { + return enabledTools.filter( + (t) => t.group !== BUILT_IN_GROUP_NAME || t.readonly, + ); + } + return enabledTools; } }, ); diff --git a/gui/src/redux/slices/sessionSlice.test.ts b/gui/src/redux/slices/sessionSlice.test.ts new file mode 100644 index 000000000..f332d74cc --- /dev/null +++ b/gui/src/redux/slices/sessionSlice.test.ts @@ -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: + "I should send the user a response. 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: "I should use a tool call.", + 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: "I should use a tool call.", + 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: "", + }, + { + 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: "", + }, + { + 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!"); + }); + }); +}); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 45d68b456..dbf019a22 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -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) => { 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( + /([\s\S]*)<\/think>([\s\S]*)/, + ); + if (thinkMatches) { + // The order that they seem to consistently use is: + // + // Thinking text + // 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("")) { - lastItem.reasoning = { - startAt: Date.now(), - active: true, - text: messageContent.replace("", "").trim(), - }; - } else if ( - lastItem.reasoning?.active && - messageContent.includes("") + lastItem = state.history[state.history.length - 1]; + lastMessage = lastItem.message; + } + + // Add to the existing message + if (messageContent) { + if (messageContent.includes("")) { + lastItem.reasoning = { + startAt: Date.now(), + active: true, + text: messageContent.replace("", "").trim(), + }; + } else if ( + lastItem.reasoning?.active && + messageContent.includes("") + ) { + const [reasoningEnd, answerStart] = + messageContent.split(""); + 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(""); - 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]; } } } diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 059b285ce..806b88fa7 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -75,52 +75,49 @@ export const streamEditThunk = createAsyncThunk< export const exitEdit = createAsyncThunk< void, - { goToMode?: MessageModes; openNewSession?: boolean }, + { openNewSession?: boolean }, ThunkApiType ->( - "edit/exit", - async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => { - const state = getState(); - const codeToEdit = state.editModeState.codeToEdit; - const isInEdit = state.session.isInEdit; - const previousModeEditorContent = - state.editModeState.previousModeEditorContent; +>("edit/exit", async ({ openNewSession }, { dispatch, extra, getState }) => { + const state = getState(); + const codeToEdit = state.editModeState.codeToEdit; + const isInEdit = state.session.isInEdit; + const previousModeEditorContent = + state.editModeState.previousModeEditorContent; - if (!isInEdit) { - return; - } + if (!isInEdit) { + return; + } - if (codeToEdit[0] && state.editModeState.applyState.numDiffs) { - extra.ideMessenger.post("rejectDiff", { - filepath: codeToEdit[0].filepath, - }); - } + if (codeToEdit[0] && state.editModeState.applyState.numDiffs) { + extra.ideMessenger.post("rejectDiff", { + filepath: codeToEdit[0].filepath, + }); + } - extra.ideMessenger.post("edit/clearDecorations", undefined); + extra.ideMessenger.post("edit/clearDecorations", undefined); - dispatch(clearCodeToEdit()); - dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); - dispatch(setIsInEdit(false)); + dispatch(clearCodeToEdit()); + dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); + dispatch(setIsInEdit(false)); - // Restore the previous editor content if available - if (previousModeEditorContent) { - dispatch(setMainEditorContentTrigger(previousModeEditorContent)); - dispatch(setPreviousModeEditorContent(undefined)); - } + // Restore the previous editor content if available + if (previousModeEditorContent) { + dispatch(setMainEditorContentTrigger(previousModeEditorContent)); + dispatch(setPreviousModeEditorContent(undefined)); + } - if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { - dispatch(newSession()); - } else { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - } + if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { + dispatch(newSession()); + } else { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + } - dispatch(setMode(goToMode ?? state.editModeState.returnToMode)); - }, -); + dispatch(setMode(state.editModeState.returnToMode)); +}); export const enterEdit = createAsyncThunk< void, diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index c7c4de02d..37910c105 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -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 @@ -115,21 +160,19 @@ export const streamNormalInput = createAsyncThunk< dispatch(addPromptCompletionPair([next.value])); try { - if (state.session.mode === "chat" || state.session.mode === "agent") { - extra.ideMessenger.post("devdata/log", { - name: "chatInteraction", - data: { - prompt: next.value.prompt, - completion: next.value.completion, - modelProvider: selectedChatModel.underlyingProviderName, - modelTitle: selectedChatModel.title, - sessionId: state.session.id, - ...(state.session.mode === "agent" && { - tools: activeTools.map((tool) => tool.function.name), - }), - }, - }); - } + extra.ideMessenger.post("devdata/log", { + name: "chatInteraction", + data: { + prompt: next.value.prompt, + completion: next.value.completion, + modelProvider: selectedChatModel.underlyingProviderName, + modelTitle: selectedChatModel.title, + sessionId: state.session.id, + ...(!!activeTools.length && { + tools: activeTools.map((tool) => tool.function.name), + }), + }, + }); // else if (state.session.mode === "edit") { // extra.ideMessenger.post("devdata/log", { // name: "editInteraction", diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 6e5c032d4..0a29f3a8f 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -17,7 +17,7 @@ export const streamThunkWrapper = createAsyncThunk< try { await runStream(); const state = getState(); - if (state.session.mode === "chat" || state.session.mode === "agent") { + if (!state.session.isInEdit) { await dispatch( saveCurrentSession({ openNewSession: false, diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index 18ab0ed45..b1d808662 100644 --- a/gui/src/redux/util/constructMessages.test.ts +++ b/gui/src/redux/util/constructMessages.test.ts @@ -12,6 +12,7 @@ import { import { DEFAULT_AGENT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE, + DEFAULT_PLAN_SYSTEM_MESSAGE, } from "core/llm/defaultSystemMessages"; import { renderChatMessage } from "core/util/messageContent"; import { beforeEach, describe, expect, test, vi } from "vitest"; @@ -90,8 +91,9 @@ vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => { test("getBaseSystemMessage should return the correct system message based on mode", () => { const mockModel = { - baseAgentSystemMessage: "Custom Agent System Message", baseChatSystemMessage: "Custom Chat System Message", + basePlanSystemMessage: "Custom Plan System Message", + baseAgentSystemMessage: "Custom Agent System Message", } as ModelDescription; // Test agent mode with custom message @@ -99,6 +101,11 @@ test("getBaseSystemMessage should return the correct system message based on mod "Custom Agent System Message", ); + // Test plan mode with custom message + expect(getBaseSystemMessage("plan", mockModel)).toBe( + "Custom Plan System Message", + ); + // Test chat mode with custom message expect(getBaseSystemMessage("chat", mockModel)).toBe( "Custom Chat System Message", @@ -109,6 +116,11 @@ test("getBaseSystemMessage should return the correct system message based on mod DEFAULT_AGENT_SYSTEM_MESSAGE, ); + // Test agent mode with default message + expect(getBaseSystemMessage("plan", {} as ModelDescription)).toBe( + DEFAULT_PLAN_SYSTEM_MESSAGE, + ); + // Test chat mode with default message expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( DEFAULT_CHAT_SYSTEM_MESSAGE, diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 15f8120db..566608d67 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -11,6 +11,7 @@ import { import { DEFAULT_AGENT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE, + DEFAULT_PLAN_SYSTEM_MESSAGE, } from "core/llm/defaultSystemMessages"; import { chatMessageIsEmpty } from "core/llm/messages"; import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; @@ -167,6 +168,8 @@ export function getBaseSystemMessage( ): string { if (messageMode === "agent") { return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + } else if (messageMode === "plan") { + return model.basePlanSystemMessage ?? DEFAULT_PLAN_SYSTEM_MESSAGE; } else { return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; } diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index aaadfe13a..e0cb53693 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -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", diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index 46001b847..760ae48a6 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -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 | 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(), diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 1424b2aea..7802be705 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -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 = { diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 917cb9866..b3d7782f4 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -22,6 +22,7 @@ const mcpServerSchema = z.object({ faviconUrl: z.string().optional(), args: z.array(z.string()).optional(), env: z.record(z.string()).optional(), + cwd: z.string().optional(), connectionTimeout: z.number().gt(0).optional(), requestOptions: requestOptionsSchema.optional(), }); diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 99d324ac2..8bdb6b66d 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -85,6 +85,7 @@ export type EmbedOptions = z.infer; export const chatOptionsSchema = z.object({ baseSystemMessage: z.string().optional(), baseAgentSystemMessage: z.string().optional(), + basePlanSystemMessage: z.string().optional(), }); export type ChatOptions = z.infer; @@ -154,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(), }), @@ -169,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 diff --git a/packages/continue-sdk/typescript/src/createOpenAIClient.ts b/packages/continue-sdk/typescript/src/createOpenAIClient.ts index cd3cd0ce5..6f693d8c9 100644 --- a/packages/continue-sdk/typescript/src/createOpenAIClient.ts +++ b/packages/continue-sdk/typescript/src/createOpenAIClient.ts @@ -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, }; diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 0782d06d8..2c71d9e7f 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -9,6 +9,8 @@ "version": "1.0.44", "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", @@ -42,6 +44,827 @@ "node": ">=6.0.0" } }, + "node_modules/@aws-crypto/crc32": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", + "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-bedrock-runtime": { + "version": "3.842.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.842.0.tgz", + "integrity": "sha512-CrGuU9YGqYZPm2hjjqJYC5+HMjky/HuvlUmboFDdpH96mwm/RrUQAO6sXYojeUPy9ceidUiHd3HskqvpiMTl2Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/credential-provider-node": "3.840.0", + "@aws-sdk/eventstream-handler-node": "3.840.0", + "@aws-sdk/middleware-eventstream": "3.840.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.840.0", + "@aws-sdk/middleware-websocket": "3.840.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/token-providers": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.840.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.840.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.6.0", + "@smithy/eventstream-serde-browser": "^4.0.4", + "@smithy/eventstream-serde-config-resolver": "^4.1.2", + "@smithy/eventstream-serde-node": "^4.0.4", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.13", + "@smithy/middleware-retry": "^4.1.14", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.21", + "@smithy/util-defaults-mode-node": "^4.0.21", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "@smithy/util-stream": "^4.2.2", + "@smithy/util-utf8": "^4.0.0", + "@types/uuid": "^9.0.1", + "tslib": "^2.6.2", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-bedrock-runtime/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@aws-sdk/client-cognito-identity": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.840.0.tgz", + "integrity": "sha512-0sn/X63Xqqh5D1FYmdSHiS9SkDzTitoGO++/8IFik4xf/jpn4ZQkIoDPvpxFZcLvebMuUa6jAQs4ap4RusKGkg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/credential-provider-node": "3.840.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.840.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.840.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.840.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.6.0", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.13", + "@smithy/middleware-retry": "^4.1.14", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.21", + "@smithy/util-defaults-mode-node": "^4.0.21", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.840.0.tgz", + "integrity": "sha512-3Zp+FWN2hhmKdpS0Ragi5V2ZPsZNScE3jlbgoJjzjI/roHZqO+e3/+XFN4TlM0DsPKYJNp+1TAjmhxN6rOnfYA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.840.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.840.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.840.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.6.0", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.13", + "@smithy/middleware-retry": "^4.1.14", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.21", + "@smithy/util-defaults-mode-node": "^4.0.21", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.840.0.tgz", + "integrity": "sha512-x3Zgb39tF1h2XpU+yA4OAAQlW6LVEfXNlSedSYJ7HGKXqA/E9h3rWQVpYfhXXVVsLdYXdNw5KBUkoAoruoZSZA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@aws-sdk/xml-builder": "3.821.0", + "@smithy/core": "^3.6.0", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/property-provider": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/signature-v4": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-utf8": "^4.0.0", + "fast-xml-parser": "4.4.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.840.0.tgz", + "integrity": "sha512-p1RaMVd6+6ruYjKsWRCZT/jWhrYfDKbXY+/ScIYTvcaOOf9ArMtVnhFk3egewrC7kPXFGRYhg2GPmxRotNYMng==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.840.0.tgz", + "integrity": "sha512-EzF6VcJK7XvQ/G15AVEfJzN2mNXU8fcVpXo4bRyr1S6t2q5zx6UPH/XjDbn18xyUmOq01t+r8gG+TmHEVo18fA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.840.0.tgz", + "integrity": "sha512-wbnUiPGLVea6mXbUh04fu+VJmGkQvmToPeTYdHE8eRZq3NRDi3t3WltT+jArLBKD/4NppRpMjf2ju4coMCz91g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/property-provider": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/util-stream": "^4.2.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.840.0.tgz", + "integrity": "sha512-7F290BsWydShHb+7InXd+IjJc3mlEIm9I0R57F/Pjl1xZB69MdkhVGCnuETWoBt4g53ktJd6NEjzm/iAhFXFmw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/credential-provider-env": "3.840.0", + "@aws-sdk/credential-provider-http": "3.840.0", + "@aws-sdk/credential-provider-process": "3.840.0", + "@aws-sdk/credential-provider-sso": "3.840.0", + "@aws-sdk/credential-provider-web-identity": "3.840.0", + "@aws-sdk/nested-clients": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/credential-provider-imds": "^4.0.6", + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.840.0.tgz", + "integrity": "sha512-KufP8JnxA31wxklLm63evUPSFApGcH8X86z3mv9SRbpCm5ycgWIGVCTXpTOdgq6rPZrwT9pftzv2/b4mV/9clg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.840.0", + "@aws-sdk/credential-provider-http": "3.840.0", + "@aws-sdk/credential-provider-ini": "3.840.0", + "@aws-sdk/credential-provider-process": "3.840.0", + "@aws-sdk/credential-provider-sso": "3.840.0", + "@aws-sdk/credential-provider-web-identity": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/credential-provider-imds": "^4.0.6", + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.840.0.tgz", + "integrity": "sha512-HkDQWHy8tCI4A0Ps2NVtuVYMv9cB4y/IuD/TdOsqeRIAT12h8jDb98BwQPNLAImAOwOWzZJ8Cu0xtSpX7CQhMw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.840.0.tgz", + "integrity": "sha512-2qgdtdd6R0Z1y0KL8gzzwFUGmhBHSUx4zy85L2XV1CXhpRNwV71SVWJqLDVV5RVWVf9mg50Pm3AWrUC0xb0pcA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.840.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/token-providers": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.840.0.tgz", + "integrity": "sha512-dpEeVXG8uNZSmVXReE4WP0lwoioX2gstk4RnUgrdUE3YaPq8A+hJiVAyc3h+cjDeIqfbsQbZm9qFetKC2LF9dQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/nested-clients": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-providers": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.840.0.tgz", + "integrity": "sha512-+CxYdGd+uM4NZ9VUvFTU1c/H61qhDB4q362k8xKU+bz24g//LDQ5Mpwksv8OUD1en44v4fUwgZ4SthPZMs+eFQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.840.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/credential-provider-cognito-identity": "3.840.0", + "@aws-sdk/credential-provider-env": "3.840.0", + "@aws-sdk/credential-provider-http": "3.840.0", + "@aws-sdk/credential-provider-ini": "3.840.0", + "@aws-sdk/credential-provider-node": "3.840.0", + "@aws-sdk/credential-provider-process": "3.840.0", + "@aws-sdk/credential-provider-sso": "3.840.0", + "@aws-sdk/credential-provider-web-identity": "3.840.0", + "@aws-sdk/nested-clients": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.6.0", + "@smithy/credential-provider-imds": "^4.0.6", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-handler-node": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.840.0.tgz", + "integrity": "sha512-m/zVrSSAEHq+6h4sy0JUEBScB1pGgs/1+iRVhfzfbnf+/gTr4ut2jRq4tDiNEX9pQ1oFVvw+ntPua5qfquQeRQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/eventstream-codec": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-eventstream": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.840.0.tgz", + "integrity": "sha512-4khgf7AjJ4llh3aiNmZ+x4PGl4vkKNxRHn0xTgi6Iw1J3SChsF2mnNaLXK8hoXeydx756rw+JhqOuZH91i5l4w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.840.0.tgz", + "integrity": "sha512-ub+hXJAbAje94+Ya6c6eL7sYujoE8D4Bumu1NUI8TXjUhVVn0HzVWQjpRLshdLsUp1AW7XyeJaxyajRaJQ8+Xg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.840.0.tgz", + "integrity": "sha512-lSV8FvjpdllpGaRspywss4CtXV8M7NNNH+2/j86vMH+YCOZ6fu2T/TyFd/tHwZ92vDfHctWkRbQxg0bagqwovA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.840.0.tgz", + "integrity": "sha512-Gu7lGDyfddyhIkj1Z1JtrY5NHb5+x/CRiB87GjaSrKxkDaydtX2CU977JIABtt69l9wLbcGDIQ+W0uJ5xPof7g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.840.0.tgz", + "integrity": "sha512-hiiMf7BP5ZkAFAvWRcK67Mw/g55ar7OCrvrynC92hunx/xhMkrgSLM0EXIZ1oTn3uql9kH/qqGF0nqsK6K555A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.840.0", + "@smithy/core": "^3.6.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-websocket": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.840.0.tgz", + "integrity": "sha512-v9jJD1zjKMUg8iEZlFP5TLY7+DdwKodLgkNtls34+LMRbW+7Bue+H3gPi1VML5sks2o/+PJ6fz58Wo3bXZ8XHA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-format-url": "3.840.0", + "@smithy/eventstream-codec": "^4.0.4", + "@smithy/eventstream-serde-browser": "^4.0.4", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/signature-v4": "^5.1.2", + "@smithy/types": "^4.3.1", + "@smithy/util-hex-encoding": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.840.0.tgz", + "integrity": "sha512-LXYYo9+n4hRqnRSIMXLBb+BLz+cEmjMtTudwK1BF6Bn2RfdDv29KuyeDRrPCS3TwKl7ZKmXUmE9n5UuHAPfBpA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.840.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.840.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.840.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.840.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.6.0", + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.13", + "@smithy/middleware-retry": "^4.1.14", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.21", + "@smithy/util-defaults-mode-node": "^4.0.21", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.840.0.tgz", + "integrity": "sha512-Qjnxd/yDv9KpIMWr90ZDPtRj0v75AqGC92Lm9+oHXZ8p1MjG5JE2CW0HL8JRgK9iKzgKBL7pPQRXI8FkvEVfrA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/types": "^4.3.1", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.840.0.tgz", + "integrity": "sha512-6BuTOLTXvmgwjK7ve7aTg9JaWFdM5UoMolLVPMyh3wTv9Ufalh8oklxYHUBIxsKkBGO2WiHXytveuxH6tAgTYg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.840.0", + "@aws-sdk/nested-clients": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.840.0.tgz", + "integrity": "sha512-xliuHaUFZxEx1NSXeLLZ9Dyu6+EJVQKEoD+yM+zqUo3YDZ7medKJWY6fIOKiPX/N7XbLdBYwajb15Q7IL8KkeA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.840.0.tgz", + "integrity": "sha512-eqE9ROdg/Kk0rj3poutyRCFauPDXIf/WSvCqFiRDDVi6QOnCv/M0g2XW8/jSvkJlOyaXkNCptapIp6BeeFFGYw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/types": "^4.3.1", + "@smithy/util-endpoints": "^3.0.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-format-url": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-format-url/-/util-format-url-3.840.0.tgz", + "integrity": "sha512-VB1PWyI1TQPiPvg4w7tgUGGQER1xxXPNUqfh3baxUSFi1Oh8wHrDnFywkxLm3NMmgDmnLnSZ5Q326qAoyqKLSg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/querystring-builder": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.804.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.804.0.tgz", + "integrity": "sha512-zVoRfpmBVPodYlnMjgVjfGoEZagyRF5IPn3Uo6ZvOZp24chnW/FRstH7ESDHDDRga4z3V+ElUQHKpFDXWyBW5A==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.840.0.tgz", + "integrity": "sha512-JdyZM3EhhL4PqwFpttZu1afDpPJCCc3eyZOLi+srpX11LsGj6sThf47TYQN75HT1CarZ7cCdQHGzP2uy3/xHfQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/types": "^4.3.1", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.840.0.tgz", + "integrity": "sha512-Fy5JUEDQU1tPm2Yw/YqRYYc27W5+QD/J4mYvQvdWjUGZLB5q3eLFMGD35Uc28ZFoGMufPr4OCxK/bRfWROBRHQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.821.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.821.0.tgz", + "integrity": "sha512-DIIotRnefVL6DiaHtO6/21DhJ4JZnnIwdNbpwiAhdt/AVbttcE4yw925gsjur0OGv5BTYXQXU3YnANBYnZjuQA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@babel/code-frame": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", @@ -1022,6 +1845,656 @@ "@sinonjs/commons": "^3.0.0" } }, + "node_modules/@smithy/abort-controller": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.4.tgz", + "integrity": "sha512-gJnEjZMvigPDQWHrW3oPrFhQtkrgqBkyjj3pCIdF3A5M6vsZODG93KNlfJprv6bp4245bdT32fsHK4kkH3KYDA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.1.4.tgz", + "integrity": "sha512-prmU+rDddxHOH0oNcwemL+SwnzcG65sBF2yXRO7aeXIn/xTlq2pX7JLVbkBnVLowHLg4/OL4+jBmv9hVrVGS+w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.1.3", + "@smithy/types": "^4.3.1", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.6.0.tgz", + "integrity": "sha512-Pgvfb+TQ4wUNLyHzvgCP4aYZMh16y7GcfF59oirRHcgGgkH1e/s9C0nv/v3WP+Quymyr5je71HeFQCwh+44XLg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/middleware-serde": "^4.0.8", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-stream": "^4.2.2", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.6.tgz", + "integrity": "sha512-hKMWcANhUiNbCJouYkZ9V3+/Qf9pteR1dnwgdyzR09R4ODEYx8BbUysHwRSyex4rZ9zapddZhLFTnT4ZijR4pw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.1.3", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-codec": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.4.tgz", + "integrity": "sha512-7XoWfZqWb/QoR/rAU4VSi0mWnO2vu9/ltS6JZ5ZSZv0eovLVfDfu0/AX4ub33RsJTOth3TiFWSHS5YdztvFnig==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@smithy/types": "^4.3.1", + "@smithy/util-hex-encoding": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-browser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.0.4.tgz", + "integrity": "sha512-3fb/9SYaYqbpy/z/H3yIi0bYKyAa89y6xPmIqwr2vQiUT2St+avRt8UKwsWt9fEdEasc5d/V+QjrviRaX1JRFA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-config-resolver": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.1.2.tgz", + "integrity": "sha512-JGtambizrWP50xHgbzZI04IWU7LdI0nh/wGbqH3sJesYToMi2j/DcoElqyOcqEIG/D4tNyxgRuaqBXWE3zOFhQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-node": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.0.4.tgz", + "integrity": "sha512-RD6UwNZ5zISpOWPuhVgRz60GkSIp0dy1fuZmj4RYmqLVRtejFqQ16WmfYDdoSoAjlp1LX+FnZo+/hkdmyyGZ1w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-universal": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.4.tgz", + "integrity": "sha512-UeJpOmLGhq1SLox79QWw/0n2PFX+oPRE1ZyRMxPIaFEfCqWaqpB7BU9C8kpPOGEhLF7AwEqfFbtwNxGy4ReENA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-codec": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.4.tgz", + "integrity": "sha512-AMtBR5pHppYMVD7z7G+OlHHAcgAN7v0kVKEpHuTO4Gb199Gowh0taYi9oDStFeUhetkeP55JLSVlTW1n9rFtUw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.1.2", + "@smithy/querystring-builder": "^4.0.4", + "@smithy/types": "^4.3.1", + "@smithy/util-base64": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-node": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.4.tgz", + "integrity": "sha512-qnbTPUhCVnCgBp4z4BUJUhOEkVwxiEi1cyFM+Zj6o+aY8OFGxUQleKWq8ltgp3dujuhXojIvJWdoqpm6dVO3lQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.4.tgz", + "integrity": "sha512-bNYMi7WKTJHu0gn26wg8OscncTt1t2b8KcsZxvOv56XA6cyXtOAAAaNP7+m45xfppXfOatXF3Sb1MNsLUgVLTw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.0.0.tgz", + "integrity": "sha512-saYhF8ZZNoJDTvJBEWgeBccCg+yvp1CX+ed12yORU3NilJScfc6gfch2oVb4QgxZrGUx3/ZJlb+c/dJbyupxlw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.4.tgz", + "integrity": "sha512-F7gDyfI2BB1Kc+4M6rpuOLne5LOcEknH1n6UQB69qv+HucXBR1rkzXBnQTB2q46sFy1PM/zuSJOB532yc8bg3w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.1.13.tgz", + "integrity": "sha512-xg3EHV/Q5ZdAO5b0UiIMj3RIOCobuS40pBBODguUDVdko6YK6QIzCVRrHTogVuEKglBWqWenRnZ71iZnLL3ZAQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.6.0", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-middleware": "^4.0.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "4.1.14", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.1.14.tgz", + "integrity": "sha512-eoXaLlDGpKvdmvt+YBfRXE7HmIEtFF+DJCbTPwuLunP0YUnrydl+C4tS+vEM0+nyxXrX3PSUFqC+lP1+EHB1Tw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.1.3", + "@smithy/protocol-http": "^5.1.2", + "@smithy/service-error-classification": "^4.0.6", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "tslib": "^2.6.2", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-retry/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.8.tgz", + "integrity": "sha512-iSSl7HJoJaGyMIoNn2B7czghOVwJ9nD7TMvLhMWeSB5vt0TnEYyRRqPJu/TqW76WScaNvYYB8nRoiBHR9S1Ddw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.4.tgz", + "integrity": "sha512-kagK5ggDrBUCCzI93ft6DjteNSfY8Ulr83UtySog/h09lTIOAJ/xUSObutanlPT0nhoHAkpmW9V5K8oPyLh+QA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.1.3.tgz", + "integrity": "sha512-HGHQr2s59qaU1lrVH6MbLlmOBxadtzTsoO4c+bF5asdgVik3I8o7JIOzoeqWc5MjVa+vD36/LWE0iXKpNqooRw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.0.4", + "@smithy/shared-ini-file-loader": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.6.tgz", + "integrity": "sha512-NqbmSz7AW2rvw4kXhKGrYTiJVDHnMsFnX4i+/FzcZAfbOBauPYs2ekuECkSbtqaxETLLTu9Rl/ex6+I2BKErPA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/querystring-builder": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.4.tgz", + "integrity": "sha512-qHJ2sSgu4FqF4U/5UUp4DhXNmdTrgmoAai6oQiM+c5RZ/sbDwJ12qxB1M6FnP+Tn/ggkPZf9ccn4jqKSINaquw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.1.2.tgz", + "integrity": "sha512-rOG5cNLBXovxIrICSBm95dLqzfvxjEmuZx4KK3hWwPFHGdW3lxY0fZNXfv2zebfRO7sJZ5pKJYHScsqopeIWtQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.4.tgz", + "integrity": "sha512-SwREZcDnEYoh9tLNgMbpop+UTGq44Hl9tdj3rf+yeLcfH7+J8OXEBaMc2kDxtyRHu8BhSg9ADEx0gFHvpJgU8w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "@smithy/util-uri-escape": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.4.tgz", + "integrity": "sha512-6yZf53i/qB8gRHH/l2ZwUG5xgkPgQF15/KxH0DdXMDHjesA9MeZje/853ifkSY0x4m5S+dfDZ+c4x439PF0M2w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.6.tgz", + "integrity": "sha512-RRoTDL//7xi4tn5FrN2NzH17jbgmnKidUqd4KvquT0954/i6CXXkh1884jBiunq24g9cGtPBEXlU40W6EpNOOg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.4.tgz", + "integrity": "sha512-63X0260LoFBjrHifPDs+nM9tV0VMkOTl4JRMYNuKh/f5PauSjowTfvF3LogfkWdcPoxsA9UjqEOgjeYIbhb7Nw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.1.2.tgz", + "integrity": "sha512-d3+U/VpX7a60seHziWnVZOHuEgJlclufjkS6zhXvxcJgkJq4UWdH5eOBLzHRMx6gXjsdT9h6lfpmLzbrdupHgQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.0.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "@smithy/util-hex-encoding": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-uri-escape": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.4.5.tgz", + "integrity": "sha512-+lynZjGuUFJaMdDYSTMnP/uPBBXXukVfrJlP+1U/Dp5SFTEI++w6NMga8DjOENxecOF71V9Z2DllaVDYRnGlkg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.6.0", + "@smithy/middleware-endpoint": "^4.1.13", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/types": "^4.3.1", + "@smithy/util-stream": "^4.2.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.3.1.tgz", + "integrity": "sha512-UqKOQBL2x6+HWl3P+3QqFD4ncKq0I8Nuz9QItGv5WuKuMHuuwlhvqcZCoXGfc+P1QmfJE7VieykoYYmrOoFJxA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.4.tgz", + "integrity": "sha512-eMkc144MuN7B0TDA4U2fKs+BqczVbk3W+qIvcoCY6D1JY3hnAdCuhCZODC+GAeaxj0p6Jroz4+XMUn3PCxQQeQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/querystring-parser": "^4.0.4", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-base64": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.0.0.tgz", + "integrity": "sha512-CvHfCmO2mchox9kjrtzoHkWHxjHZzaFojLc8quxXY7WAAMAg43nuxwv95tATVgQFNDwd4M9S1qFzj40Ul41Kmg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.0.0.tgz", + "integrity": "sha512-sNi3DL0/k64/LO3A256M+m3CDdG6V7WKWHdAiBBMUN8S3hK3aMPhwnPik2A/a2ONN+9doY9UxaLfgqsIRg69QA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.0.0.tgz", + "integrity": "sha512-q0iDP3VsZzqJyje8xJWEJCNIu3lktUGVoSy1KB0UWym2CL1siV3artm+u1DFYTLejpsrdGyCSWBdGNjJzfDPjg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.0.0.tgz", + "integrity": "sha512-9TOQ7781sZvddgO8nxueKi3+yGvkY35kotA0Y6BWRajAv8jjmigQ1sBwz0UX47pQMYXJPahSKEKYFgt+rXdcug==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.0.0.tgz", + "integrity": "sha512-L1RBVzLyfE8OXH+1hsJ8p+acNUSirQnWQ6/EgpchV88G6zGBTDPdXiiExei6Z1wR2RxYvxY/XLw6AMNCCt8H3w==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "4.0.21", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.21.tgz", + "integrity": "sha512-wM0jhTytgXu3wzJoIqpbBAG5U6BwiubZ6QKzSbP7/VbmF1v96xlAbX2Am/mz0Zep0NLvLh84JT0tuZnk3wmYQA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.0.4", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "4.0.21", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.21.tgz", + "integrity": "sha512-/F34zkoU0GzpUgLJydHY8Rxu9lBn8xQC/s/0M0U9lLBkYbA1htaAFjWYJzpzsbXPuri5D1H8gjp2jBum05qBrA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/config-resolver": "^4.1.4", + "@smithy/credential-provider-imds": "^4.0.6", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/property-provider": "^4.0.4", + "@smithy/smithy-client": "^4.4.5", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.6.tgz", + "integrity": "sha512-YARl3tFL3WgPuLzljRUnrS2ngLiUtkwhQtj8PAL13XZSyUiNLQxwG3fBBq3QXFqGFUXepIN73pINp3y8c2nBmA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.1.3", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.0.0.tgz", + "integrity": "sha512-Yk5mLhHtfIgW2W2WQZWSg5kuMZCVbvhFmC7rV4IO2QqnZdbEFPmQnCcGMAX2z/8Qj3B9hYYNjZOhWym+RwhePw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.4.tgz", + "integrity": "sha512-9MLKmkBmf4PRb0ONJikCbCwORACcil6gUWojwARCClT7RmLzF04hUR4WdRprIXal7XVyrddadYNfp2eF3nrvtQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.6.tgz", + "integrity": "sha512-+YekoF2CaSMv6zKrA6iI/N9yva3Gzn4L6n35Luydweu5MMPYpiGZlWqehPHDHyNbnyaYlz/WJyYAZnC+loBDZg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/service-error-classification": "^4.0.6", + "@smithy/types": "^4.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.2.2.tgz", + "integrity": "sha512-aI+GLi7MJoVxg24/3J1ipwLoYzgkB4kUfogZfnslcYlynj3xsQ0e7vk4TnTro9hhsS5PvX1mwmkRqqHQjwcU7w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/fetch-http-handler": "^5.0.4", + "@smithy/node-http-handler": "^4.0.6", + "@smithy/types": "^4.3.1", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-hex-encoding": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.0.0.tgz", + "integrity": "sha512-77yfbCbQMtgtTylO9itEAdpPXSog3ZxMe09AEhm0dU0NLTalV70ghDZFR+Nfi1C60jnJoh/Re4090/DuZh2Omg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.0.0.tgz", + "integrity": "sha512-b+zebfKCfRdgNJDknHCob3O7FpeYQN6ZG6YLExMcasDHsCXlsXCEuiPZeLnJLpwa5dvPetGlnGCiMHuLwGvFow==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@tsconfig/node10": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", @@ -1173,6 +2646,12 @@ "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", "dev": true }, + "node_modules/@types/uuid": { + "version": "9.0.8", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", + "integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==", + "license": "MIT" + }, "node_modules/@types/yargs": { "version": "17.0.32", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz", @@ -1446,6 +2925,12 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/bowser": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.11.0.tgz", + "integrity": "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -2004,6 +3489,28 @@ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, + "node_modules/fast-xml-parser": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz", + "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.0.5" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, "node_modules/fb-watchman": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", @@ -3974,6 +5481,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -4151,6 +5670,12 @@ } } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index ed24b5ef8..f7c7d3133 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -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", diff --git a/packages/openai-adapters/src/apis/Bedrock.ts b/packages/openai-adapters/src/apis/Bedrock.ts new file mode 100644 index 000000000..2a580456a --- /dev/null +++ b/packages/openai-adapters/src/apis/Bedrock.ts @@ -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 ``; +} + +/** + * Interface for tool use state tracking + */ +interface ToolUseState { + toolUseId: string; + name: string; + input: string; +} + +export class BedrockApi implements BaseLlmApi { + private _currentToolResponse: Partial | 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 { + 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, + ): Message[] { + let currentRole: "user" | "assistant" = "user"; + let currentBlocks: ContentBlock[] = []; + const converted: Message[] = []; + const hasAddedToolCallIds = new Set(); + + 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(); + 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 { + 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 { + 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 { + throw new Error("Bedrock does not support completions API"); + } + + completionStream( + body: CompletionCreateParamsStreaming, + ): AsyncGenerator { + throw new Error("Bedrock does not support completions API"); + } + + fimStream( + body: FimCreateParamsStreaming, + ): AsyncGenerator { + 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 { + 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 { + 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 { + throw new Error("Method not implemented."); + } +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index b4254046e..2114f4f34 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -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": diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index 3c79db7bf..7a6ce37cf 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -71,6 +71,21 @@ export const DeepseekConfigSchema = OpenAIConfigSchema.extend({ }); export type DeepseekConfig = z.infer; +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; + export const LlamastackConfigSchema = OpenAIConfigSchema.extend({ provider: z.literal("llamastack"), }); @@ -142,6 +157,7 @@ export type InceptionConfig = z.infer; // Discriminated union export const LLMConfigSchema = z.discriminatedUnion("provider", [ OpenAIConfigSchema, + BedrockConfigSchema, MoonshotConfigSchema, DeepseekConfigSchema, CohereConfigSchema,