diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml index 8a93c3285..8fc4d4bdd 100644 --- a/.github/workflows/cla.yaml +++ b/.github/workflows/cla.yaml @@ -27,5 +27,5 @@ jobs: path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md" branch: cla-signatures # Bots and CLAs signed outside of GitHub - allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com + allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com,snyk-bot signed-commit-message: "CLA signed in $pullRequestNo" diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 54f617534..3ccc262c5 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -294,44 +294,44 @@ jobs: # Store already-built plugin as an artifact for downloading - name: Upload artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ steps.artifact.outputs.filename }} path: ./extensions/intellij/build/distributions/content/*/* # Upload binaries as artifacts - name: Upload artifact (darwin-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-darwin-arm64 path: ./binary/bin/darwin-arm64/ - name: Upload artifact (darwin-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-darwin-x64 path: ./binary/bin/darwin-x64/ - name: Upload artifact (win32-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-win32-x64 path: ./binary/bin/win32-x64/ - name: Upload artifact (win32-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-win32-arm64 path: ./binary/bin/win32-arm64/ - name: Upload artifact (linux-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-linux-arm64 path: ./binary/bin/linux-arm64/ - name: Upload artifact (linux-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-linux-x64 path: ./binary/bin/linux-x64/ @@ -398,7 +398,7 @@ jobs: # Download the binary artifact - name: Download binary artifact - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ @@ -420,7 +420,7 @@ jobs: - name: Upload logs if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} path: ~/.continue/logs/core.log @@ -455,7 +455,7 @@ jobs: # Collect Tests Result of failed tests - name: Collect Tests Result if: ${{ failure() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: tests-result path: ${{ github.workspace }}/extensions/intellij/build/reports/tests @@ -540,7 +540,7 @@ jobs: # Collect Plugin Verifier Result - name: Collect Plugin Verifier Result if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: pluginVerifier-result path: ${{ github.workspace }}/build/reports/pluginVerifier @@ -563,7 +563,7 @@ jobs: # ./gradlew patchChangelog --release-note="$CHANGELOG" - name: Download the plugin - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: ${{ steps.artifact.outputs.filename }} path: ./build/distributions/ diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index 808373096..3f4f91582 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -101,7 +101,7 @@ jobs: echo "βœ… Successfully downloaded artifact" - name: Republish as main branch artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-${{ matrix.platform }} path: ./temp-download/* diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index cd4e96d06..1166c9734 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -99,7 +99,7 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" @@ -120,7 +120,7 @@ jobs: git config --local user.name "GitHub Action" # Download the .vsix artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts @@ -156,7 +156,7 @@ jobs: run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts diff --git a/.github/workflows/metrics.yaml b/.github/workflows/metrics.yaml index ba4e1cd4a..37193b729 100644 --- a/.github/workflows/metrics.yaml +++ b/.github/workflows/metrics.yaml @@ -69,7 +69,7 @@ jobs: ${{ steps.read-metrics.outputs.metrics_content }} - name: Upload metrics report as artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: issue-metrics-report path: ./issue_metrics.md diff --git a/.github/workflows/pr-build-upload-vsix.yaml b/.github/workflows/pr-build-upload-vsix.yaml index 926855b7c..f1e4f648b 100644 --- a/.github/workflows/pr-build-upload-vsix.yaml +++ b/.github/workflows/pr-build-upload-vsix.yaml @@ -39,13 +39,13 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }} path: extensions/vscode/build - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 8e1a63386..422759fa7 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -303,7 +303,7 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-Linux path: extensions/vscode/build diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 6f82464b5..0f7e8c23c 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -83,7 +83,7 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" @@ -104,7 +104,7 @@ jobs: git config --local user.name "GitHub Action" # Download the .vsix artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts @@ -142,7 +142,7 @@ jobs: run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts diff --git a/README.md b/README.md index f2e19d7b2..6ad3b5c01 100644 --- a/README.md +++ b/README.md @@ -27,35 +27,29 @@ **Ship faster with Continuous AI** -**Build and run custom agents across your IDE, terminal, and CI** +**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff** -Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli) +Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode) -## Agent +## Background Agents -[Agent](https://docs.continue.dev/ide-extensions/agent/quick-start) to work on development tasks together with AI +Set workflows to run automatically on [PR opens](https://docs.continue.dev/guides/continuous-ai#pattern-2-the-pr-review-agent), [schedules](https://docs.continue.dev/guides/continuous-ai#pattern-1-the-async-triage-bot), or [any event trigger](https://docs.continue.dev/cli/quick-start#headless-mode) -![agent](docs/images/agent.gif) +![Background Agents](docs/images/background-agent.gif) -## Chat +## CLI Agents -[Chat](https://docs.continue.dev/ide-extensions/chat/quick-start) to ask general questions and clarify code sections +Watch workflows execute in real-time and approve decisions step-by-step from your [terminal](https://docs.continue.dev/cli/quick-start#tui-mode) -![chat](docs/images/chat.gif) +![CLI Agents](docs/images/cli-agent.gif) -## Edit +## IDE Agents -[Edit](https://docs.continue.dev/ide-extensions/edit/quick-start) to modify a code section without leaving your current file +Trigger workflows from [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)β€”let agents handle the refactoring while you keep coding -![edit](docs/images/edit.gif) - -## Autocomplete - -[Autocomplete](https://docs.continue.dev/ide-extensions/autocomplete/quick-start) to receive inline code suggestions as you type - -![autocomplete](docs/images/autocomplete.gif) +![IDE Agents](docs/images/agent.gif) diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index d5e6a7b17..109378e53 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -115,6 +115,45 @@ runs: shell: bash run: npm install -g @continuedev/cli@latest + - name: Setup Action Scripts + if: env.SHOULD_RUN == 'true' + shell: bash + run: | + # Create directory for scripts + mkdir -p .continue-action-scripts + + # Check if we're running in the Continue repo itself (scripts exist locally) + if [ -f "actions/general-review/scripts/buildPrompt.js" ] && [ -f "actions/general-review/scripts/writeMarkdown.js" ]; then + echo "Running in Continue repo - using local scripts from current checkout" + cp actions/general-review/scripts/buildPrompt.js .continue-action-scripts/buildPrompt.js + cp actions/general-review/scripts/writeMarkdown.js .continue-action-scripts/writeMarkdown.js + else + echo "Running in external repo - downloading scripts from Continue repo" + + # Download scripts from Continue repo + echo "Downloading buildPrompt.js..." + curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/buildPrompt.js \ + -o .continue-action-scripts/buildPrompt.js + + echo "Downloading writeMarkdown.js..." + curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/writeMarkdown.js \ + -o .continue-action-scripts/writeMarkdown.js + fi + + # Verify scripts exist + if [ ! -f .continue-action-scripts/buildPrompt.js ]; then + echo "Error: buildPrompt.js not found" + exit 1 + fi + + if [ ! -f .continue-action-scripts/writeMarkdown.js ]; then + echo "Error: writeMarkdown.js not found" + exit 1 + fi + + echo "Scripts ready:" + ls -lh .continue-action-scripts/ + - name: Post Initial Comment if: env.SHOULD_RUN == 'true' id: initial-comment @@ -218,7 +257,7 @@ runs: # Gather PR context and build prompt without heredocs gh pr diff "$PR_NUMBER" > pr_diff.txt gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json - node actions/general-review/scripts/buildPrompt.js "$PR_NUMBER" + node .continue-action-scripts/buildPrompt.js "$PR_NUMBER" rm -f pr_data.json - name: Run Continue CLI Review @@ -241,7 +280,7 @@ runs: if [ -z "$CONTINUE_API_KEY" ]; then echo "Warning: CONTINUE_API_KEY environment variable is not set" # Create fallback review and continue - node actions/general-review/scripts/writeMarkdown.js code_review.md missing_api_key + node .continue-action-scripts/writeMarkdown.js code_review.md missing_api_key echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "SKIP_CLI=false" >> $GITHUB_ENV @@ -263,7 +302,7 @@ runs: echo "Testing Continue CLI..." if ! which cn > /dev/null 2>&1; then echo "Warning: Continue CLI not found or not working" - node actions/general-review/scripts/writeMarkdown.js code_review.md cli_install_failed + node .continue-action-scripts/writeMarkdown.js code_review.md cli_install_failed echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "Continue CLI found at: $(which cn)" @@ -299,7 +338,7 @@ runs: # Check if output is empty if [ ! -s code_review.md ]; then echo "Warning: Continue CLI returned empty output" - node actions/general-review/scripts/writeMarkdown.js code_review.md empty_output + node .continue-action-scripts/writeMarkdown.js code_review.md empty_output fi else echo "Error: Continue CLI command failed with exit code $?" @@ -308,13 +347,13 @@ runs: # Check for specific error patterns if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then - node actions/general-review/scripts/writeMarkdown.js code_review.md cli_not_found + node .continue-action-scripts/writeMarkdown.js code_review.md cli_not_found elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then - node actions/general-review/scripts/writeMarkdown.js code_review.md config_error + node .continue-action-scripts/writeMarkdown.js code_review.md config_error elif grep -q "api\|auth" cli_error.log 2>/dev/null; then - node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error + node .continue-action-scripts/writeMarkdown.js code_review.md auth_error else - node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure + node .continue-action-scripts/writeMarkdown.js code_review.md generic_failure fi fi diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 254437889..1407e5af5 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = { }, }; +// https://www.ibm.com/granite/docs/models/granite#fim +const granite4FimTemplate: AutocompleteTemplate = { + template: + "<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>", + completionOptions: { + stop: [ + "<|end_of_text|>", + "<|fim_prefix|>", + "<|fim_middle|>", + "<|fim_suffix|>", + "<|fim_pad|>", + ], + }, +}; + const seedCoderFimTemplate: AutocompleteTemplate = { template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>", @@ -442,6 +457,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { return qwenCoderFimTemplate; } + if (lowerCaseModel.includes("granite") && lowerCaseModel.includes("4")) { + return granite4FimTemplate; + } + if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) { return seedCoderFimTemplate; } diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 91ed72164..d77313b92 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -79,7 +79,13 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ uriType: "file", fileUri: file.path, }); - rules.push({ ...rule, source: "rules-block", sourceFile: file.path }); + if (!rule.invokable) { + rules.push({ + ...rule, + source: "rules-block", + sourceFile: file.path, + }); + } } catch (e) { errors.push({ fatal: false, diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index e27a631dc..8b18b4142 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -173,13 +173,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { effected = true; } - const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI; - if (autoAcceptEditToolDiffs !== undefined) { - shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs; - migratedUI = withoutAutoApply; - effected = true; - } - const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI; if (showChatScrollbar !== undefined) { shareConfigUpdates.showChatScrollbar = showChatScrollbar; diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 52b96061a..87306a2ae 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -31,7 +31,6 @@ export const sharedConfigSchema = z codeWrap: z.boolean(), displayRawMarkdown: z.boolean(), showChatScrollbar: z.boolean(), - autoAcceptEditToolDiffs: z.boolean(), continueAfterToolRejection: z.boolean(), // `tabAutocompleteOptions` in `ContinueConfig` @@ -140,10 +139,6 @@ export function modifyAnyConfigWithSharedConfig< if (sharedConfig.showChatScrollbar !== undefined) { configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar; } - if (sharedConfig.autoAcceptEditToolDiffs !== undefined) { - configCopy.ui.autoAcceptEditToolDiffs = - sharedConfig.autoAcceptEditToolDiffs; - } if (sharedConfig.allowAnonymousTelemetry !== undefined) { configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 2ae0ca423..ef6994b13 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -352,7 +352,6 @@ export class ControlPlaneClient { /** * Check if remote sessions should be enabled based on feature flags - * Requires: PostHog feature flag AND @continue.dev email */ public async shouldEnableRemoteSessions(): Promise { // Check if user is signed in @@ -360,17 +359,13 @@ export class ControlPlaneClient { return false; } - // Check if user has @continue.dev email try { const sessionInfo = await this.sessionInfoPromise; if (isOnPremSession(sessionInfo) || !sessionInfo) { return false; } - const hubSession = sessionInfo as HubSessionInfo; - const email = hubSession.account?.id; - - return email ? email.includes("@continue.dev") : false; + return true; } catch (e) { Logger.error(e, { context: "control_plane_check_remote_sessions_enabled", @@ -388,7 +383,6 @@ export class ControlPlaneClient { /** * Fetch remote agents/sessions from the control plane - * Currently restricted to @continue.dev emails for internal use */ public async listRemoteSessions(): Promise { if (!(await this.isSignedIn())) { @@ -396,8 +390,6 @@ export class ControlPlaneClient { } try { - // Note: This endpoint is currently restricted to internal @continue.dev users - // In the future, this may be expanded to support broader remote session access const resp = await this.requestAndHandleError("agents/devboxes", { method: "GET", }); diff --git a/core/core.ts b/core/core.ts index 636de2840..c73996a49 100644 --- a/core/core.ts +++ b/core/core.ts @@ -70,6 +70,7 @@ import { import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; +import { myersDiff } from "./diff/myers"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; @@ -796,6 +797,10 @@ export class Core { ); }); + on("getDiffLines", (msg) => { + return myersDiff(msg.data.oldContent, msg.data.newContent); + }); + on("cancelApply", async (msg) => { const abortManager = ApplyAbortManager.getInstance(); abortManager.clear(); // for now abort all streams diff --git a/core/index.d.ts b/core/index.d.ts index ed6237f7a..8416b5af0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1404,7 +1404,6 @@ export interface ContinueUIConfig { showChatScrollbar?: boolean; codeWrap?: boolean; showSessionTabs?: boolean; - autoAcceptEditToolDiffs?: boolean; continueAfterToolRejection?: boolean; } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 2930678e8..a2e13a75d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -185,6 +185,14 @@ function modelSupportsReasoning( if (!model) { return false; } + if (model.completionOptions?.reasoning !== undefined) { + // Reasoning support is forced at the config level. Model might not necessarily support it though! + return model.completionOptions.reasoning; + } + // Seems our current way of disabling reasoning is not working for grok code so results in useless lightbulb + // if (model.model.includes("grok-code")) { + // return true; + // } // do not turn reasoning on by default for claude 3 models if ( model.model.includes("claude") && @@ -196,10 +204,7 @@ function modelSupportsReasoning( if (model.model.includes("deepseek-r")) { return true; } - if (model.completionOptions?.reasoning) { - // Reasoning support is forced at the config level. Model might not necessarily support it though! - return true; - } + return false; } diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index 43ab7990e..430a6777d 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -63,7 +63,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. - If you need to use multiple tools, you can call multiple read only tools simultaneously. + If you need to use multiple tools, you can call multiple read-only tools simultaneously. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 41a0904e0..52d7a6b80 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -101,9 +101,18 @@ class ContinueProxy extends OpenAI { protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; + headers["user-agent"] = this._getUserAgent(); return headers; } + private _getUserAgent(): string { + const ideInfo = Telemetry.ideInfo; + const extensionVersion = ideInfo?.extensionVersion ?? "unknown"; + const ideName = ideInfo?.name ?? "unknown"; + const ideType = ideInfo?.ideType ?? "unknown"; + return `Continue/${extensionVersion} (${ideName}; ${ideType})`; + } + supportsCompletions(): boolean { // This was a hotfix and contains duplicate logic from class-specific completion support methods if (this.underlyingProviderName === "vllm") { @@ -129,6 +138,7 @@ class ContinueProxy extends OpenAI { headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, + "user-agent": this._getUserAgent(), }, body: JSON.stringify({ query, diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 7cdbd02cd..5e4f26241 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -29,6 +29,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = ].some((part) => model.toLowerCase().startsWith(part)); }, anthropic: (model) => { + const lower = model.toLowerCase(); if ( [ "claude-3-5", @@ -38,10 +39,13 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-sonnet-4", "claude-4-sonnet", "claude-opus-4", - ].some((part) => model.toLowerCase().startsWith(part)) + ].some((part) => lower.startsWith(part)) ) { return true; } + if (lower.includes("claude") && lower.includes("4-5")) { + return true; + } return false; }, @@ -112,7 +116,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = }, xAI: (model) => { const lowerCaseModel = model.toLowerCase(); - return ["grok-3", "grok-4"].some((val) => lowerCaseModel.includes(val)); + return ["grok-3", "grok-4", "grok-code"].some((val) => + lowerCaseModel.includes(val), + ); }, bedrock: (model) => { if ( @@ -189,6 +195,8 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "llama3-groq", "granite3", "granite-3", + "granite4", + "granite-4", "aya-expanse", "firefunction-v2", "mistral", @@ -383,6 +391,8 @@ export function isRecommendedAgentModel(modelName: string): boolean { [/gpt-5/], [/claude/, /sonnet/, /3\.7|3-7|-4/], [/claude/, /opus/, /-4/], + [/grok-code/], + [/claude/, /4-5/], ]; for (const combo of recs) { if (combo.every((regex) => modelName.toLowerCase().match(regex))) { diff --git a/core/package-lock.json b/core/package-lock.json index 8ba3256b3..57518a6eb 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -225,7 +225,7 @@ "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index 6a3837e3a..da6628d2f 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -24,7 +24,9 @@ export async function getPromptFilesFromDir( const uris = await walkDir(dir, ide, { source: "get dir prompt files", }); - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const promptFilePaths = uris.filter( + (p) => p.endsWith(".prompt") || p.endsWith(".md"), + ); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch return { path: uri, content }; @@ -68,10 +70,11 @@ export async function getAllPromptFiles( ); promptFiles.push(...promptFilesFromRulesDirectory); - return await Promise.all( + const result = await Promise.all( promptFiles.map(async (file) => { const content = await ide.readFile(file.path); return { path: file.path, content }; }), ); + return result; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 82542caee..b03b0e11a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -241,6 +241,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { AsyncGenerator, ]; streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator]; + getDiffLines: [{ oldContent: string; newContent: string }, DiffLine[]]; "llm/compileChat": [ { messages: ChatMessage[]; options: LLMFullCompletionOptions }, CompiledMessagesResult, diff --git a/core/util/chatDescriber.test.ts b/core/util/chatDescriber.test.ts index 315cb3fea..64ba68314 100644 --- a/core/util/chatDescriber.test.ts +++ b/core/util/chatDescriber.test.ts @@ -30,7 +30,7 @@ describe("ChatDescriber", () => { expect(result).toBeUndefined(); }); - it("should set completionOptions.maxTokens to 12", async () => { + it("should set completionOptions.maxTokens to 16", async () => { const message = "Test message"; const completionOptions: LLMFullCompletionOptions = { temperature: 0.7 }; diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 873d07327..33a2b31ba 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -8,7 +8,7 @@ import { renderChatMessage } from "./messageContent"; import { convertFromUnifiedHistory } from "./messageConversion"; export class ChatDescriber { - static maxTokens = 12; + static maxTokens = 16; // Increased from 12 to meet GPT-5 minimum requirement static prompt: string | undefined = "Given the following... please reply with a title for the chat that is 3-4 words in length, all words used should be directly related to the content of the chat, avoid using verbs unless they are directly related to the content of the chat, no additional text or explanation, you don't need ending punctuation.\n\n"; static messenger: IMessenger; diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdx index 154c4638f..f0b56c642 100644 --- a/docs/cli/overview.mdx +++ b/docs/cli/overview.mdx @@ -77,6 +77,21 @@ cn -p "Update documentation based on recent code changes" - **CI/CD and pipeline integration** - **Git hooks and automated workflows** + + **Tool Permissions in TUI vs Headless Mode** + + Continue CLI tools have three permission levels: + - **allow**: Executes automatically without confirmation + - **ask**: Prompts for user confirmation before execution (e.g., `writeFile`, `runTerminalCommand`) + - **exclude**: Tool is not available to the AI + + **In headless mode**, tools with "ask" permission are automatically excluded to prevent the AI from seeing tools it cannot call. This ensures reliable automation without user intervention. + + **In TUI mode**, tools with "ask" permission are available and will prompt for confirmation when the AI attempts to use them. + + πŸ’‘ **Tip**: If your workflow requires tools that need confirmation (like file writes or terminal commands), use TUI mode. For fully automated workflows with read-only operations, use headless mode. + + ### Development Workflow: TUI β†’ Headless diff --git a/docs/cli/quick-start.mdx b/docs/cli/quick-start.mdx index 79a481ecd..c663af1f1 100644 --- a/docs/cli/quick-start.mdx +++ b/docs/cli/quick-start.mdx @@ -121,6 +121,16 @@ cn -p "Update version numbers and create release branch" βœ… **Git hooks** for automated checks βœ… **Scheduled tasks** that run unattended + + **Tool Permission Differences Between Modes** + + Tools requiring user confirmation ("ask" permission) like `writeFile` and `runTerminalCommand` are: + - **Available in TUI mode** - AI can use them with your approval + - **Excluded in headless mode** - AI cannot see or call them + + This prevents the AI from attempting operations that require user interaction when running in automated environments. Choose TUI mode if your workflow needs tools that modify files or run commands. + + ### Available Slash Commands Common slash commands available in CLI: diff --git a/docs/customization/models.mdx b/docs/customization/models.mdx index f42e88672..7c9fd9f44 100644 --- a/docs/customization/models.mdx +++ b/docs/customization/models.mdx @@ -88,6 +88,10 @@ Read more about [model roles](/customize/model-roles), [model capabilities](/cus ### Local Models + +Need a quick setup walkthrough? Check out [Using Ollama with Continue: A Developer's Guide](https://docs.continue.dev/guides/ollama-guide). + + These models can be run on your computer if you have enough VRAM. Their limited tool calling and reasoning capabilities will make it challenging to use agent mode. diff --git a/docs/docs.json b/docs/docs.json index bc10f9e84..9d33cc92a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -29,7 +29,7 @@ "hub/introduction", { "group": "Configs", - "icon": "robot", + "icon": "book", "pages": [ "hub/configs/intro", "hub/configs/use-a-config", @@ -260,6 +260,7 @@ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", "guides/github-mcp-continue-cookbook", + "guides/atlassian-mcp-continue-cookbook", "guides/sanity-mcp-continue-cookbook", "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", @@ -342,7 +343,8 @@ "x": "https://twitter.com/continuedev", "github": "https://github.com/continuedev/continue", "linkedin": "https://linkedin.com/company/continuedev", - "discord": "https://discord.gg/vapESyrFmJ" + "discord": "https://discord.gg/vapESyrFmJ", + "youtube": "https://www.youtube.com/@continuedev" } }, "contextual": { diff --git a/docs/guides/atlassian-mcp-continue-cookbook.mdx b/docs/guides/atlassian-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..9b4b8cc9c --- /dev/null +++ b/docs/guides/atlassian-mcp-continue-cookbook.mdx @@ -0,0 +1,511 @@ +--- +title: "Jira Issues and Confluence Pages with Atlassian MCP and Continue" +description: "Use Continue and the Atlassian Rovo MCP to search, summarize, and manage Jira issues, Confluence pages, and Compass components with natural language prompts." +sidebarTitle: "Atlassian Workflows with Continue" +--- + + + An Atlassian workflow assistant that uses Continue with the Atlassian Rovo MCP to: + - Search and summarize Jira issues across projects + - Find and digest Confluence documentation + - Create and update Jira issues with natural language + - Query Compass components and service dependencies + - Automate Atlassian workflows with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs β€” How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Node.js 18+ installed locally +- An Atlassian Cloud site with Jira, Confluence, and/or Compass +- Access to the Atlassian products you want to integrate with + + + The Atlassian Rovo MCP Server is currently in **Beta**. Core functionality is available, but some features are still under development. + + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + The Atlassian MCP uses **OAuth 2.1** for authentication. The first time you connect, you'll complete a browser-based authorization flow that respects your existing Atlassian permissions. + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + All data access respects your existing Jira, Confluence, and Compass user permissions. + + +## Choose Your Atlassian Agent + + + We've created two ready-to-use agents to help you get started fast - they come pre-configured with optimized prompts, rules, and the Atlassian MCP. You don't have to use these agents, but they're designed to give you the best experience right away. Choose the agent that matches your needs, or create your own custom agent. + + +### Agent Quick Reference + +| Agent | Best For | Use Cases | Link | +|-------|----------|-----------|------| +| **Jira Agent** | Issue Management | Search issues, create stories, sprint planning, status updates, bulk operations | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) | +| **Confluence Agent** | Documentation | Search pages, summarize docs, create/update pages, manage spaces | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) | + + + **Cross-product workflows**: Both agents can work with Jira, Confluence, and Compass. Choose based on your primary focus area, or create your own agent using the [Atlassian MCP](https://hub.continue.dev/atlassian/atlassian-mcp). The Atlassian MCP can work with Jira, Compass, or Confluence. + + + + + + + Visit the [Atlassian Continuous AI - Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) on Continue Hub. This agent is optimized for: + - Searching and filtering Jira issues + - Creating and updating issues + - Sprint planning and workload analysis + - Issue transitions and status updates + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me my open issues assigned to me" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Jira agent: + ```bash + alias jira-ai='cn --agent continuedev/atlassian-continuous-ai-jira-agent' + ``` + Then use: `jira-ai "your prompt"` + + + + + + + Visit the [Atlassian Continuous AI - Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) on Continue Hub. This agent is optimized for: + - Searching and summarizing documentation + - Creating and updating Confluence pages + - Managing spaces and content + - Documentation discovery + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Confluence agent: + ```bash + alias confluence-ai='cn --agent continuedev/atlassian-continuous-ai-confluence-agent' + ``` + Then use: `confluence-ai "your prompt"` + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: Atlassian Rovo MCP + type: sse + url: https://mcp.atlassian.com/v1/sse + connectionTimeout: 30 + ``` + + Notes: + - The Atlassian MCP uses **Server-Sent Events (SSE)** transport type + - OAuth is handled automatically on first connection + - No API keys or tokens needed in the config + + + + Launch Continue and ask: + ``` + List my Jira projects + ``` + You'll be prompted to authorize in your browser if this is your first time. + + + + + + + To use Atlassian MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the Atlassian MCP for Jira, Confluence, and Compass operations. + + + +--- + +## Jira Workflows + + + **Using the Jira Agent**: All examples below use the [Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) which is optimized for issue management. + + +Use natural language to explore, triage, and manage Jira issues. The agent calls Atlassian MCP tools under the hood. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Discovery + + + + Search for bugs across your projects. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Find all open bugs in Project Alpha" + ``` + + + + Get a list of issues assigned to you. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me all issues assigned to me that are in progress" + ``` + + + + Analyze sprint workload and priorities. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "List all issues in the current sprint. Group by assignee and priority. Summarize the workload distribution and flag any overloaded team members." + ``` + + + +### Create and Update + + + + Turn natural language into a Jira story. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a story titled 'Redesign onboarding flow' in Project Alpha. Description: We need to simplify the user registration process by reducing steps from 5 to 3. Target completion: Q3." + ``` + + + + Create multiple issues from meeting notes or specs. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create five Jira issues from these meeting notes: 1) Fix login timeout bug 2) Update API documentation 3) Implement dark mode toggle 4) Review security audit findings 5) Optimize database queries" + ``` + + + + Transition issues with natural language. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Move PROJ-123 to In Progress and add a comment: Starting work on this today. ETA: end of week." + ``` + + + +--- + +## Confluence Workflows + + + **Using the Confluence Agent**: All examples below use the [Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) which is optimized for documentation management. + + +Access, search, and manage your team's documentation directly from Continue. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Summarize + + + + Get a quick summary of a Confluence page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page from the Engineering space" + ``` + + + + Search for specific information across Confluence. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Find all pages about API authentication in our developer docs" + ``` + + + + Discover what Confluence spaces you have access to. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "What Confluence spaces do I have access to?" + ``` + + + +### Create and Update + + + + Generate a new Confluence page with structured content. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Create a page titled 'Team Goals Q3' in the Engineering space. Include sections for: Objectives, Key Results, and Timeline." + ``` + + + + Modify content on an existing page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Update the 'Onboarding Guide' page to add a new section about our code review process" + ``` + + + +--- + +## Compass Workflows + + + **Using Either Agent**: Compass workflows work with both agents. Use the Jira agent for component-to-issue workflows, or the Confluence agent for component-to-docs workflows. + + +Query and manage your service architecture with Compass integration. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + +### Service Discovery + + + + Understand service relationships. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "What services depend on the api-gateway component?" + ``` + + + + Register a new service in Compass. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a service component for the current repository. Use the package.json to infer details." + ``` + + + + Import multiple components from structured data. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components and custom fields from this CSV: [paste CSV data]" + ``` + + Or reference a file: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components from services.csv in the current directory" + ``` + + + +--- + +## Combined Workflows + + + **Cross-Product Workflows**: These workflows span multiple Atlassian products. Choose the agent based on your primary focus: + - Use **Jira Agent** when the workflow is issue-centric + - Use **Confluence Agent** when the workflow is documentation-centric + + +Integrate actions across Jira, Confluence, and Compass for powerful cross-product workflows. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + + + + Connect related content across products. + + ```bash + # Using Jira Agent for issue-centric workflow + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Link Jira tickets PROJ-123, PROJ-456, and PROJ-789 to the 'Sprint 23 Release Plan' Confluence page" + ``` + + + + Find documentation for a specific component. + + ```bash + # Using Confluence Agent for docs-centric workflow + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Fetch the Confluence documentation page linked to the user-authentication Compass component" + ``` + + + + Create release documentation from completed work. + + ```bash + # Using Jira Agent to pull issue data and create in Confluence + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Generate release notes for all Jira issues completed in Sprint 23. Create a Confluence page in the Release Notes space with: New features (grouped by epic), Bug fixes, Known issues, Deployment instructions" + ``` + + + +--- + +## Troubleshooting + + + + - **"Your site admin must authorize this app"**: A site admin needs to complete the OAuth flow first before other users can connect + - **Can't complete browser authorization**: Ensure you're logged into the correct Atlassian Cloud site and have necessary permissions + - **Connection timeout**: Increase `connectionTimeout` in your MCP config or check your network connection + + + + - **"Access denied" or "Forbidden"**: The MCP respects your existing Atlassian permissions. Verify you have access to the project/space/component you're trying to access + - **Can't create issues**: Ensure you have "Create issues" permission in the target Jira project + - **Can't edit Confluence pages**: Verify you have edit permissions in the target Confluence space + + + + - **Standard plan**: Moderate usage thresholds + - **Premium/Enterprise plans**: Higher quotas (1,000 requests/hour plus per-user limits) + - If you hit rate limits, reduce query frequency or batch operations + + + + - Bulk operations may be constrained by rate limits + - Custom Jira fields may not be recognized without explicit setup + - Workspace/site switching not available within a single session + - Check [Atlassian Community](https://community.atlassian.com/) for known issues + + + +### Admin Considerations + + + **Installation**: The Atlassian Rovo MCP is automatically installed on first OAuth authorization (JIT installation) - no Marketplace installation needed. + + **Managing Access**: + - View connected apps in [Admin Hub](https://admin.atlassian.com) + - Users can revoke access from their [profile settings](https://id.atlassian.com/manage-profile/apps) + - Block user-installed apps via "user-installed apps" control in Admin Hub + + **Security**: All traffic is encrypted via HTTPS (TLS 1.2+), and access respects existing user permissions. + + +--- + +## What You've Built + +After completing this guide, you have a complete **AI-powered Atlassian workflow system** that: + +- βœ… Uses natural language β€” Simple prompts for complex Atlassian operations +- βœ… Spans multiple products β€” Seamlessly works across Jira, Confluence, and Compass +- βœ… Respects permissions β€” Secure OAuth-based access with existing role enforcement +- βœ… Runs headlessly β€” Integrate into CI/CD pipelines and automation scripts + + + Your Atlassian workflows now operate at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine project management tasks with human oversight through + review and approval. + + +## Next Steps + +1. **Explore your projects** - Try the Jira search and triage prompts +2. **Organize documentation** - Use Confluence workflows to summarize and create pages +3. **Map your services** - Query Compass for service dependencies +4. **Customize prompts** - Tailor workflows to your team's specific needs +5. **Monitor usage** - Track how AI improves your Atlassian workflows + +## Additional Resources + + + + Official Atlassian MCP documentation + + + How MCP works with Continue agents + + + Create and manage your agents + + + Get help and share feedback + + + +## Example Use Cases + + + + Automate release notes generation, link issues to documentation, and track deployment status across Jira and Confluence. + + + Analyze workload distribution, identify blockers, and generate sprint summaries automatically. + + + Map service dependencies in Compass, link to technical documentation in Confluence, and track related issues in Jira. + + + Create standardized Jira onboarding tickets, link to Confluence guides, and track new hire progress. + + diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index c2e0f8078..214c9d996 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -21,16 +21,51 @@ description: "Comprehensive collection of practical guides for Continue includin Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue: -- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows -- [GitHub MCP Cookbook](/guides/github-mcp-continue-cookbook) - Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments -- [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation -- [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP -- [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets -- [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP -- [Sentry Error Monitoring Cookbook](/guides/sentry-mcp-error-monitoring) - Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues -- [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers -- [Supabase Database Workflow Cookbook](/guides/supabase-mcp-database-workflow) - Audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Supabase MCP -- [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging + + + Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows + + + + Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments + + + + Use Atlassian Rovo MCP to search and manage Jira issues, Confluence pages, and Compass components with natural language + + + + Analyze user behavior data to optimize your codebase with automatic issue creation + + + + Optimize web performance with A/B testing and automated monitoring using Netlify MCP + + + + Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets + + + + Manage headless CMS content with AI-powered workflows using Sanity MCP + + + + Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues + + + + Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers + + + + Audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Supabase MCP + + + + Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging + + ## What Advanced Tutorials Are Available diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx index b353f395b..2aae35908 100644 --- a/docs/guides/snyk-mcp-continue-cookbook.mdx +++ b/docs/guides/snyk-mcp-continue-cookbook.mdx @@ -10,6 +10,18 @@ sidebarTitle: "Snyk Security Scanning with Continue" containers - all through simple natural language prompts +## Demo Video + + + ## Prerequisites Before starting, ensure you have: diff --git a/docs/guides/understanding-configs.mdx b/docs/guides/understanding-configs.mdx index 5a18fedb9..115e21140 100644 --- a/docs/guides/understanding-configs.mdx +++ b/docs/guides/understanding-configs.mdx @@ -3,6 +3,16 @@ title: "How to Understand Hub vs Local Configuration" description: "Learn how to choose between cloud-managed Hub and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach" --- + + Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow. ## What Are the Two Paths to AI Assistance? diff --git a/docs/hub/sharing.mdx b/docs/hub/sharing.mdx index 657019912..93a7a9de3 100644 --- a/docs/hub/sharing.mdx +++ b/docs/hub/sharing.mdx @@ -7,7 +7,7 @@ description: "Connect with the Continue community to discover, share, and collab Join thousands of developers using Continue. Share experiences, get help, and contribute to the ecosystem. -[Join our Discord Community β†’](https://discord.gg/continue) +[Join our Discord Community β†’](https://discord.gg/vapESyrFmJ) ## Publishing diff --git a/docs/images/background-agent.gif b/docs/images/background-agent.gif new file mode 100644 index 000000000..b45757fa3 Binary files /dev/null and b/docs/images/background-agent.gif differ diff --git a/docs/images/cli-agent.gif b/docs/images/cli-agent.gif new file mode 100644 index 000000000..35d49a17b Binary files /dev/null and b/docs/images/cli-agent.gif differ diff --git a/docs/index.mdx b/docs/index.mdx index a8ce41c72..343eef56e 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -1,7 +1,7 @@ --- title: "Welcome to Continue" icon: book-open -description: "Practice Continuous AI with an open-source CLI, open-source IDE extensions, and a Hub for custom agents" +description: "Kick off agents from the terminal, IDE, or Mission Control" --- @@ -9,8 +9,7 @@ description: "Practice Continuous AI with an open-source CLI, open-source IDE ex - **Build faster with AI across your IDE, terminal, and CI/CD pipelines with - Continue.** + **Launch background agents, iterate in terminal, and deploy workflows in CI/CD** ## Continue CLI diff --git a/extensions/cli/.gitignore b/extensions/cli/.gitignore index f3e655274..67557ca37 100644 --- a/extensions/cli/.gitignore +++ b/extensions/cli/.gitignore @@ -13,4 +13,5 @@ config.yaml .continue-debug/ *.expect -!demo.expect \ No newline at end of file +!demo.expect +*.cast \ No newline at end of file diff --git a/extensions/cli/README.md b/extensions/cli/README.md index 9f12eada0..324d3d7be 100644 --- a/extensions/cli/README.md +++ b/extensions/cli/README.md @@ -44,6 +44,10 @@ cn ls --json - `--resume`: Resume the last session for this terminal - ``: Optional prompt to start with +## Environment Variables + +- `CONTINUE_CLI_DISABLE_COMMIT_SIGNATURE`: Disable adding the Continue commit signature to generated commit messages + ## Commands - `cn`: Start an interactive chat session diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 5ee422523..e645f4394 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -184,6 +184,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -274,7 +275,7 @@ "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts index 90734d835..fcfd68a96 100644 --- a/extensions/cli/src/config.ts +++ b/extensions/cli/src/config.ts @@ -15,6 +15,30 @@ import { getOrganizationId, } from "./auth/workos.js"; import { env } from "./env.js"; +import { getVersion } from "./version.js"; + +/** + * Creates User-Agent header value for CLI requests + */ +function getUserAgent(): string { + const version = getVersion(); + return `Continue-CLI/${version}`; +} + +/** + * Merges User-Agent header into request options + */ +function mergeUserAgentIntoRequestOptions( + requestOptions: ModelConfig["requestOptions"], +): ModelConfig["requestOptions"] { + return { + ...requestOptions, + headers: { + ...requestOptions?.headers, + "User-Agent": getUserAgent(), + }, + }; +} /** * Creates an LLM API instance from a ModelConfig and auth configuration @@ -31,7 +55,9 @@ export function createLlmApi( model.provider === "continue-proxy" ? { provider: model.provider, - requestOptions: model.requestOptions, + requestOptions: mergeUserAgentIntoRequestOptions( + model.requestOptions, + ), apiBase: model.apiBase, apiKey: accessToken ?? undefined, env: { @@ -46,7 +72,9 @@ export function createLlmApi( provider: model.provider as any, apiKey: model.apiKey, apiBase: model.apiBase, - requestOptions: model.requestOptions, + requestOptions: mergeUserAgentIntoRequestOptions( + model.requestOptions, + ), env: model.env, }; diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 15e30e50c..62f9e37dd 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -50,6 +50,7 @@ export class MCPService private connections: Map = new Map(); private assistant: AssistantConfig | null = null; private isShuttingDown = false; + private isHeadless = false; getDependencies(): string[] { return [SERVICE_NAMES.CONFIG]; @@ -77,6 +78,9 @@ export class MCPService serverCount: assistant.mcpServers?.length || 0, }); + // Store headless mode flag + this.isHeadless = waitForConnections; + await this.shutdownConnections(); this.assistant = assistant; @@ -103,6 +107,19 @@ export class MCPService ); if (waitForConnections) { await connectionInit; + + // In headless mode, throw error if any MCP server failed to connect + const failedConnections = Array.from(this.connections.values()).filter( + (c) => c.status === "error", + ); + if (failedConnections.length > 0) { + const errorMessages = failedConnections.map( + (c) => `${c.config?.name}: ${c.error}`, + ); + throw new Error( + `MCP server(s) failed to load in headless mode:\n${errorMessages.join("\n")}`, + ); + } } else { this.updateState(); } @@ -259,6 +276,13 @@ export class MCPService name: serverName, error: errorMessage, }); + + // In headless mode, throw error on capability failures + if (this.isHeadless) { + throw new Error( + `Failed to load prompts from MCP server ${serverName}: ${errorMessage}`, + ); + } } } @@ -276,18 +300,30 @@ export class MCPService name: serverName, error: errorMessage, }); + + // In headless mode, throw error on capability failures + if (this.isHeadless) { + throw new Error( + `Failed to load tools from MCP server ${serverName}: ${errorMessage}`, + ); + } } } - logger.debug("MCP server restarted successfully", { name: serverName }); + logger.debug("MCP server connected successfully", { name: serverName }); } catch (error) { const errorMessage = getErrorString(error); connection.status = "error"; connection.error = errorMessage; - logger.error("Failed to restart MCP server", { + logger.error("Failed to connect to MCP server", { name: serverName, error: errorMessage, }); + + // In headless mode, re-throw the error to fail fast + if (this.isHeadless) { + throw error; + } } this.updateState(); diff --git a/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts b/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts new file mode 100644 index 000000000..883640485 --- /dev/null +++ b/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts @@ -0,0 +1,675 @@ +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; + +import { ToolPermissionService } from "./ToolPermissionService.js"; +import { AgentFileServiceState, MCPServiceState } from "./types.js"; + +describe("ToolPermissionService - Agent File Integration", () => { + let service: ToolPermissionService; + + beforeEach(() => { + service = new ToolPermissionService(); + }); + + describe("generateAgentFilePolicies - No parsed tools", () => { + it("should allow all tools when agent file is present but parsedTools is null", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: null, // No parsed tools + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should allow all tools when agent file is present but parsedTools is undefined", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: undefined as any, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should allow all tools when agentFileServiceState is undefined", () => { + const policies = service.generateAgentFilePolicies(undefined); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + }); + + describe("generateAgentFilePolicies - With MCP servers", () => { + it("should allow specific MCP tools when explicitly listed", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "specific_tool" } as any, + { name: "other_tool" } as any, + { name: "another_tool" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should allow the specific tool + expect(policies).toContainEqual({ + tool: "specific_tool", + permission: "allow", + }); + + // Should exclude the other tools from the same server + expect(policies).toContainEqual({ + tool: "other_tool", + permission: "exclude", + }); + expect(policies).toContainEqual({ + tool: "another_tool", + permission: "exclude", + }); + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow all tools from MCP server when server is listed without specific tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [ + { mcpServer: "owner/mcp-server" }, // No toolName = all tools from this server + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "tool1" } as any, + { name: "tool2" } as any, + { name: "tool3" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Since no specific tools were mentioned, MCP logic doesn't explicitly allow/exclude + // The wildcard allow at the end covers all MCP tools + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle multiple MCP servers with mixed specific and blanket access", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/server1", "owner/server2"], + tools: [ + { mcpServer: "owner/server1", toolName: "specific_tool" }, + { mcpServer: "owner/server2" }, // All tools from server2 + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/server1" } as any, + status: "connected", + tools: [ + { name: "specific_tool" } as any, + { name: "other_tool" } as any, + ], + prompts: [], + warnings: [], + }, + { + config: { sourceSlug: "owner/server2" } as any, + status: "connected", + tools: [{ name: "tool_a" } as any, { name: "tool_b" } as any], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Server1: Should allow specific_tool and exclude other_tool + expect(policies).toContainEqual({ + tool: "specific_tool", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "other_tool", + permission: "exclude", + }); + + // Server2: No specific tools, so wildcard covers them + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle MCP server not found in connections", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/missing-server"], + tools: [ + { mcpServer: "owner/missing-server", toolName: "specific_tool" }, + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [], // No connections + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should still have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); + + describe("generateAgentFilePolicies - With built-in tools", () => { + it("should allow only specific built-in tools when listed", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Bash" }, { toolName: "Read" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // Should allow the specific built-in tools + expect(policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Should exclude all other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notListed = allBuiltInNames.filter( + (name) => name !== "Bash" && name !== "Read", + ); + + for (const toolName of notListed) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow all built-in tools when allBuiltIn is true", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [], + allBuiltIn: true, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // Should NOT have any exclude policies for built-in tools + const excludePolicies = policies.filter( + (p) => p.permission === "exclude", + ); + expect(excludePolicies).toEqual([]); + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should exclude built-in tools when MCP servers are present but allBuiltIn is false", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [{ name: "mcp_tool" } as any], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should exclude all built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + for (const toolName of allBuiltInNames) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow both built-in tools and MCP tools when both are specified", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [ + { toolName: "Bash" }, + { toolName: "Read" }, + { mcpServer: "owner/mcp-server", toolName: "mcp_tool" }, + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "mcp_tool" } as any, + { name: "other_mcp_tool" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should allow the specific MCP tool + expect(policies).toContainEqual({ + tool: "mcp_tool", + permission: "allow", + }); + + // Should exclude the other MCP tool + expect(policies).toContainEqual({ + tool: "other_mcp_tool", + permission: "exclude", + }); + + // Should allow the specific built-in tools + expect(policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Should exclude other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notListed = allBuiltInNames.filter( + (name) => name !== "Bash" && name !== "Read", + ); + + for (const toolName of notListed) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); + + describe("initializeSync with agent file", () => { + it("should use agent file policies when agent file is present with no parsed tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: null, // No parsed tools + parsedRules: null, + }; + + const state = service.initializeSync(undefined, agentFileState); + + // Should have wildcard allow policy + expect(state.permissions.policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should use agent file policies when agent file is present with parsed tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Bash" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const state = service.initializeSync(undefined, agentFileState); + + // Should have specific policies for Bash and exclusions for others + expect(state.permissions.policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + + // Should exclude other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notBash = allBuiltInNames.filter((name) => name !== "Bash"); + + for (const toolName of notBash) { + expect(state.permissions.policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + const lastPolicy = + state.permissions.policies[state.permissions.policies.length - 1]; + expect(lastPolicy).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should use normal resolution when agent file is not present", () => { + const state = service.initializeSync(undefined, undefined); + + // Should have normal policies (not just wildcard allow) + expect(state.permissions.policies.length).toBeGreaterThan(1); + // Should not be just wildcard allow + expect(state.permissions.policies).not.toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should prioritize agent file over runtime overrides", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Read" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const runtimeOverrides = { + allow: ["Bash", "Write"], + exclude: ["Read"], + }; + + const state = service.initializeSync( + runtimeOverrides, + agentFileState, + undefined, + ); + + // Agent file should take precedence, so Read should be allowed (not excluded) + expect(state.permissions.policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Bash should be excluded (not in agent file) + expect(state.permissions.policies).toContainEqual({ + tool: "Bash", + permission: "exclude", + }); + }); + }); + + describe("Edge cases and boundary conditions", () => { + it("should handle empty parsed tools arrays - allows everything", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // With empty tools array and no MCP servers, the logic doesn't enter + // the exclusion path, so it just returns wildcard allow + // This is the "blank = all built-in tools" case from the comments + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should handle MCP state with empty connections array", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should still generate policies and have wildcard allow + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle MCP state being undefined", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + undefined, + ); + + // Should still generate policies and have wildcard allow + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); +}); diff --git a/extensions/cli/src/services/ToolPermissionService.test.ts b/extensions/cli/src/services/ToolPermissionService.test.ts index 1cd898ae9..2f63ab4fd 100644 --- a/extensions/cli/src/services/ToolPermissionService.test.ts +++ b/extensions/cli/src/services/ToolPermissionService.test.ts @@ -30,7 +30,6 @@ describe("ToolPermissionService", () => { currentMode: "normal", isHeadless: false, modePolicyCount: 0, - agentFilePolicyCount: 0, }); }); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 3b0af61d8..4e0802272 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -30,7 +30,6 @@ export interface ToolPermissionServiceState { currentMode: PermissionMode; isHeadless: boolean; modePolicyCount?: number; // Track how many policies are from mode vs other sources - agentFilePolicyCount?: number; originalPolicies?: ToolPermissions; // Store original policies when switching modes } @@ -74,10 +73,16 @@ export class ToolPermissionService generateAgentFilePolicies( agentFileServiceState?: AgentFileServiceState, mcpServiceState?: MCPServiceState, - ): undefined | ToolPermissionPolicy[] { + ): ToolPermissionPolicy[] { + // With --agent, all available tools are allowed if not specified const parsedTools = agentFileServiceState?.parsedTools; - if (!parsedTools?.tools.length) { - return undefined; + if (!parsedTools) { + return [ + { + tool: "*", + permission: "allow", + }, + ]; } const policies: ToolPermissionPolicy[] = []; @@ -222,23 +227,20 @@ export class ToolPermissionService this.setState({ isHeadless: runtimeOverrides.isHeadless }); } - const agentFilePolicies = this.generateAgentFilePolicies( - agentFileServiceState, - mcpServiceState, - ); const modePolicies = this.generateModePolicies(); - // For plan and auto modes, use ONLY mode policies (absolute override) - // For normal mode, combine with user configuration let allPolicies: ToolPermissionPolicy[]; - if (agentFilePolicies) { + if (agentFileServiceState?.agentFile) { // Agent file policies take full precedence on init - allPolicies = agentFilePolicies; + allPolicies = this.generateAgentFilePolicies( + agentFileServiceState, + mcpServiceState, + ); } else if ( this.currentState.currentMode === "plan" || this.currentState.currentMode === "auto" ) { - // Absolute override: ignore all user configuration + // For plan and auto modes, use ONLY mode policies (absolute override) allPolicies = modePolicies; } else { // Normal mode: combine mode policies with user configuration @@ -255,7 +257,6 @@ export class ToolPermissionService currentMode: this.currentState.currentMode, isHeadless: this.currentState.isHeadless, modePolicyCount: modePolicies.length, - agentFilePolicyCount: (agentFilePolicies ?? []).length, }); (this as any).isInitialized = true; diff --git a/extensions/cli/src/services/UpdateService.ts b/extensions/cli/src/services/UpdateService.ts index 6d1c893bc..cdf197134 100644 --- a/extensions/cli/src/services/UpdateService.ts +++ b/extensions/cli/src/services/UpdateService.ts @@ -50,6 +50,15 @@ export class UpdateService extends BaseService { }); try { + // skip checking for updates in dev + if (this.currentState.currentVersion === "0.0.0-dev") { + this.setState({ + status: UpdateStatus.IDLE, + message: `Continue CLI`, + }); + return; // Uncomment to test auto-update behavior in dev + } + // Check for updates this.setState({ status: UpdateStatus.CHECKING, @@ -79,16 +88,6 @@ export class UpdateService extends BaseService { isUpdateAvailable, }); - if (this.currentState.currentVersion === "0.0.0-dev") { - this.setState({ - status: UpdateStatus.IDLE, - message: `Continue CLI`, - isUpdateAvailable, - latestVersion, - }); - return; // Uncomment to test auto-update behavior in dev - } - // If update is available, automatically update if ( autoUpdate && diff --git a/extensions/cli/src/session.test.ts b/extensions/cli/src/session.test.ts index 0fb5f4525..9ca3b4bd5 100644 --- a/extensions/cli/src/session.test.ts +++ b/extensions/cli/src/session.test.ts @@ -360,7 +360,7 @@ describe("SessionManager", () => { const firstSession = createSession(); const firstSessionId = firstSession.sessionId; - vi.mocked(uuidv4).mockReturnValue("new-uuid-456" as any); + vi.mocked(uuidv4).mockReturnValue("new-uuid-456"); const secondSession = startNewSession(); @@ -381,7 +381,7 @@ describe("SessionManager", () => { }, ]; - vi.mocked(uuidv4).mockReturnValue("new-uuid-789" as any); + vi.mocked(uuidv4).mockReturnValue("new-uuid-789"); const session = startNewSession(history); @@ -392,7 +392,7 @@ describe("SessionManager", () => { it("should set the new session as current", () => { const originalSession = createSession(); - vi.mocked(uuidv4).mockReturnValue("new-session-id" as any); + vi.mocked(uuidv4).mockReturnValue("new-session-id"); const newSession = startNewSession(); const currentSession = getCurrentSession(); @@ -401,4 +401,100 @@ describe("SessionManager", () => { expect(currentSession).not.toBe(originalSession); }); }); + + describe("session isolation", () => { + it("should not pollute new sessions with previous session history", () => { + // Simulate first CLI session + vi.mocked(uuidv4).mockReturnValue("session-1"); + const session1 = createSession(); + const history1: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: "Tell me about dogs", + }, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "Dogs are loyal companions...", + }, + contextItems: [], + }, + ]; + updateSessionHistory(history1); + + // Simulate starting a new CLI session (without --resume) + vi.mocked(uuidv4).mockReturnValue("session-2"); + const session2 = startNewSession([]); + + // New session should have clean state + expect(session2.sessionId).toBe("session-2"); + expect(session2.sessionId).not.toBe(session1.sessionId); + expect(session2.history).toEqual([]); + expect(session2.history.length).toBe(0); + }); + + it("should create independent sessions for concurrent operations", () => { + // Create first session with some data + vi.mocked(uuidv4).mockReturnValue("concurrent-1"); + const session1 = createSession(); + updateSessionTitle("Session 1"); + updateSessionHistory([ + { + message: { + role: "user", + content: "First session message", + }, + contextItems: [], + }, + ]); + + // Start a new session + vi.mocked(uuidv4).mockReturnValue("concurrent-2"); + const session2 = startNewSession([]); + + // Verify session2 is clean + expect(session2.title).toBe("Untitled Session"); + expect(session2.history).toEqual([]); + expect(session2.sessionId).not.toBe(session1.sessionId); + }); + + it("should properly clear session state when transitioning between sessions", () => { + // First session with complex history + vi.mocked(uuidv4).mockReturnValue("complex-session-1"); + const session1 = createSession(); + updateSessionTitle("Complex Session"); + const complexHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: "What were we discussing?", + }, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "We were discussing dogs earlier.", + }, + contextItems: [], + }, + ]; + updateSessionHistory(complexHistory); + + // Verify first session has data + expect(getCurrentSession().history.length).toBe(2); + + // Start fresh session + vi.mocked(uuidv4).mockReturnValue("fresh-session-2"); + const session2 = startNewSession([]); + + // Verify clean state + expect(session2.history.length).toBe(0); + expect(session2.title).toBe("Untitled Session"); + expect(getCurrentSession().sessionId).toBe("fresh-session-2"); + }); + }); }); diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index c22ce9762..94b60d823 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -337,11 +337,7 @@ export async function getRemoteSessions(): Promise { const authConfig = loadAuthConfig(); const accessToken = getAccessToken(authConfig); - if ( - !accessToken || - !isAuthenticatedConfig(authConfig) || - !authConfig.userEmail.endsWith("@continue.dev") - ) { + if (!accessToken || !isAuthenticatedConfig(authConfig)) { return []; } diff --git a/extensions/cli/src/slashCommands.info.test.ts b/extensions/cli/src/slashCommands.info.test.ts index 637edcf92..e98788038 100644 --- a/extensions/cli/src/slashCommands.info.test.ts +++ b/extensions/cli/src/slashCommands.info.test.ts @@ -9,7 +9,11 @@ import * as versionModule from "./version.js"; // Mock all dependencies vi.mock("./auth/workos.js"); -vi.mock("./version.js"); +vi.mock("./version.js", () => ({ + getVersion: vi.fn(() => "1.2.3"), + getLatestVersion: vi.fn(() => Promise.resolve(null)), + compareVersions: vi.fn(() => "same"), +})); vi.mock("./session.js"); vi.mock("./telemetry/posthogService.js"); diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index 4e4ec89d8..c4df3af65 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -123,26 +123,18 @@ export async function handleToolCalls( return true; // Signal early return needed } - // Convert tool results and add them to the chat history with per-result status + // Convert tool results and add them to the chat history with status from execution toolResults.forEach((toolResult) => { const resultContent = typeof toolResult.content === "string" ? toolResult.content : ""; - // Derive per-result status instead of applying batch-wide hasRejection - let status: ToolStatus = "done"; - const lower = resultContent.toLowerCase(); - if ( - lower.includes("permission denied by user") || - lower.includes("cancelled due to previous tool rejection") || - lower.includes("canceled due to previous tool rejection") - ) { - status = "canceled"; - } else if ( - lower.startsWith("error executing tool") || - lower.startsWith("error:") - ) { - status = "errored" as ToolStatus; - } + // Use the status from the tool execution result instead of text matching + const status = toolResult.status; + + logger.debug("Tool result status", { + status, + toolCallId: toolResult.tool_call_id, + }); if (useService) { chatHistorySvc.addToolResult( diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 6121e3426..e85cc2e7d 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -1,5 +1,6 @@ // Helper functions extracted from streamChatResponse.ts to reduce file size +import type { ToolStatus } from "core/index.js"; import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; @@ -27,6 +28,10 @@ import { logger } from "../util/logger.js"; import { StreamCallbacks } from "./streamChatResponse.types.js"; +export interface ToolResultWithStatus extends ChatCompletionToolMessageParam { + status: ToolStatus; +} + // Helper function to handle permission denied export function handlePermissionDenied( toolCall: PreprocessedToolCall, @@ -389,7 +394,7 @@ export async function preprocessStreamedToolCalls( * Executes preprocessed tool calls, handling permissions and results * @param preprocessedCalls - The preprocessed tool calls ready for execution * @param callbacks - Optional callbacks for notifying of events - * @returns - Chat history entries with tool results + * @returns - Chat history entries with tool results and status information */ export async function executeStreamedToolCalls( preprocessedCalls: PreprocessedToolCall[], @@ -397,7 +402,7 @@ export async function executeStreamedToolCalls( isHeadless?: boolean, ): Promise<{ hasRejection: boolean; - chatHistoryEntries: ChatCompletionToolMessageParam[]; + chatHistoryEntries: ToolResultWithStatus[]; }> { // Strategy: queue permissions (preserve order), then run approved tools in parallel. // If any permission is rejected, cancel the remaining tools in this batch. @@ -408,7 +413,7 @@ export async function executeStreamedToolCalls( call, })); - const entriesByIndex = new Map(); + const entriesByIndex = new Map(); const execPromises: Promise[] = []; let hasRejection = false; @@ -439,17 +444,18 @@ export async function executeStreamedToolCalls( ); if (!permissionResult.approved) { - // Permission denied: record and mark rejection + // Permission denied: create entry with canceled status const denialReason = permissionResult.denialReason || "user"; const deniedMessage = denialReason === "policy" ? `Command blocked by security policy` : `Permission denied by user`; - const deniedEntry: ChatCompletionToolMessageParam = { + const deniedEntry: ToolResultWithStatus = { role: "tool", tool_call_id: call.id, content: deniedMessage, + status: "canceled", }; entriesByIndex.set(index, deniedEntry); callbacks?.onToolResult?.( @@ -484,10 +490,11 @@ export async function executeStreamedToolCalls( arguments: call.arguments, }); const toolResult = await executeToolCall(call); - const entry: ChatCompletionToolMessageParam = { + const entry: ToolResultWithStatus = { role: "tool", tool_call_id: call.id, content: toolResult, + status: "done", }; entriesByIndex.set(index, entry); callbacks?.onToolResult?.(toolResult, call.name, "done"); @@ -511,6 +518,7 @@ export async function executeStreamedToolCalls( role: "tool", tool_call_id: call.id, content: errorMessage, + status: "errored", }); callbacks?.onToolError?.(errorMessage, call.name); // Immediate service update for UI feedback @@ -536,6 +544,7 @@ export async function executeStreamedToolCalls( role: "tool", tool_call_id: call.id, content: errorMessage, + status: "errored", }); callbacks?.onToolError?.(errorMessage, call.name); // Treat permission errors like execution errors but do not stop the batch @@ -552,9 +561,9 @@ export async function executeStreamedToolCalls( await Promise.all(execPromises); // Assemble final entries in original order - const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls + const chatHistoryEntries: ToolResultWithStatus[] = preprocessedCalls .map((_, index) => entriesByIndex.get(index)) - .filter((e): e is ChatCompletionToolMessageParam => !!e); + .filter((e): e is ToolResultWithStatus => !!e); return { hasRejection, diff --git a/extensions/cli/src/stream/streamChatResponse.test.ts b/extensions/cli/src/stream/streamChatResponse.test.ts index ccff36d0f..685bf04d5 100644 --- a/extensions/cli/src/stream/streamChatResponse.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.test.ts @@ -252,6 +252,135 @@ describe("processStreamingResponse - content preservation", () => { expect(result.finalContent).toBe("Hello world!"); }); + it("routes gpt-5 models through responsesStream and preserves streaming tool updates", async () => { + const gpt5Chunks: ChatCompletionChunk[] = [ + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { role: "assistant" }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { content: "Analyzing repository…" }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: 0, + id: "call_final", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"unit', + }, + }, + ], + }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: 0, + type: "function", + function: { + arguments: ' tests"}', + }, + }, + ], + }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: {}, + finish_reason: "tool_calls", + }, + ], + }, + ]; + + const responsesStream = vi.fn().mockImplementation(async function* () { + for (const chunk of gpt5Chunks) { + yield chunk; + } + }); + const chatCompletionStream = vi.fn().mockImplementation(async function* () { + throw new Error("chatCompletionStream should not be used for gpt-5"); + }); + + mockLlmApi = { + responsesStream, + chatCompletionStream, + } as unknown as BaseLlmApi; + + mockModel = { + model: "gpt-5-preview", + provider: "openai", + } as unknown as ModelConfig; + + const result = await processStreamingResponse({ + chatHistory, + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); + + expect(responsesStream).toHaveBeenCalledTimes(1); + expect(chatCompletionStream).not.toHaveBeenCalled(); + expect(result.content).toBe("Analyzing repository…"); + expect(result.toolCalls).toHaveLength(1); + expect(result.toolCalls[0]).toMatchObject({ + id: "call_final", + name: "searchDocs", + arguments: { query: "unit tests" }, + }); + expect(result.shouldContinue).toBe(true); + }); + it("handles provider that only sends tool ID in first chunk then uses index", async () => { chunks = [ contentChunk("I'll read the README.md file for you and then say hello!"), diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index d5dee238f..1673914c4 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -173,12 +173,14 @@ export async function constructSystemMessage( systemMessage += '\nYou are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.\n'; } else { - // TODO - make including this coauthor commit configurable - systemMessage += `\nWhen creating commits using any CLI or tool, include the following in the commit message: + // Check if commit signature is disabled via environment variable + if (!process.env.CONTINUE_CLI_DISABLE_COMMIT_SIGNATURE) { + systemMessage += `\nWhen creating commits using any CLI or tool, include the following in the commit message: Generated with [Continue](https://continue.dev) Co-Authored-By: Continue \n`; + } } // In headless mode, add instructions to be concise and only provide final answers diff --git a/extensions/cli/src/tools/ToolCallTitle.tsx b/extensions/cli/src/tools/ToolCallTitle.tsx index 90c5dea3f..50f69833f 100644 --- a/extensions/cli/src/tools/ToolCallTitle.tsx +++ b/extensions/cli/src/tools/ToolCallTitle.tsx @@ -43,7 +43,7 @@ export function ToolCallTitle(props: { toolName: string; args?: any }) { } return ( - + {displayName}({formattedValue}) ); diff --git a/extensions/cli/src/tools/fetch.test.ts b/extensions/cli/src/tools/fetch.test.ts index dc8e84ea6..9a1aec105 100644 --- a/extensions/cli/src/tools/fetch.test.ts +++ b/extensions/cli/src/tools/fetch.test.ts @@ -96,23 +96,21 @@ describe("fetchTool", () => { expect(result).toBe("Content from page 1\n\nContent from page 2"); }); - it("should return error message when no content items returned", async () => { + it("should throw error when no content items returned", async () => { mockFetchUrlContentImpl.mockResolvedValue([]); - const result = await fetchTool.run({ url: "https://example.com" }); - - expect(result).toBe( - "Error: Could not fetch content from https://example.com", + await expect(fetchTool.run({ url: "https://example.com" })).rejects.toThrow( + "Could not fetch content from https://example.com", ); }); - it("should handle errors from core implementation", async () => { + it("should throw errors from core implementation", async () => { const error = new Error("Network error"); mockFetchUrlContentImpl.mockRejectedValue(error); - const result = await fetchTool.run({ url: "https://example.com" }); - - expect(result).toBe("Error: Network error"); + await expect(fetchTool.run({ url: "https://example.com" })).rejects.toThrow( + "Error: Network error", + ); }); it("should call fetchUrlContentImpl with correct arguments", async () => { diff --git a/extensions/cli/src/tools/fetch.ts b/extensions/cli/src/tools/fetch.ts index 9a04a7a05..eaa7d1056 100644 --- a/extensions/cli/src/tools/fetch.ts +++ b/extensions/cli/src/tools/fetch.ts @@ -1,5 +1,6 @@ import type { ContextItem } from "core/index.js"; import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { Tool } from "./types.js"; @@ -46,7 +47,10 @@ export const fetchTool: Tool = { console.error = originalConsoleError; if (contextItems.length === 0) { - return `Error: Could not fetch content from ${url}`; + throw new ContinueError( + ContinueErrorReason.Unspecified, + `Could not fetch content from ${url}`, + ); } // Format the results for CLI display @@ -59,7 +63,12 @@ export const fetchTool: Tool = { }) .join("\n\n"); } catch (error) { - return `Error: ${error instanceof Error ? error.message : String(error)}`; + if (error instanceof ContinueError) { + throw error; + } + throw new Error( + `Error: ${error instanceof Error ? error.message : String(error)}`, + ); } }, }; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 21da49321..aed31f998 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -228,7 +228,7 @@ export async function executeToolCall( errorReason, }); - return `Error executing tool "${toolCall.name}": ${errorMessage}`; + throw error; } } diff --git a/extensions/cli/src/tools/listFiles.ts b/extensions/cli/src/tools/listFiles.ts index e90f6039b..3af33c14f 100644 --- a/extensions/cli/src/tools/listFiles.ts +++ b/extensions/cli/src/tools/listFiles.ts @@ -61,9 +61,11 @@ export const listFilesTool: Tool = { return `Files in ${args.dirpath}:\n${fileDetails.join("\n")}`; } catch (error) { - return `Error listing files: ${ - error instanceof Error ? error.message : String(error) - }`; + throw new Error( + `Error listing files: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index e62413e46..9bcf18329 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { formatToolArgument } from "./formatters.js"; import { Tool } from "./types.js"; @@ -51,7 +52,10 @@ export const readFileTool: Tool = { } if (!fs.existsSync(filepath)) { - return `Error: File does not exist: ${filepath}`; + throw new ContinueError( + ContinueErrorReason.Unspecified, + `File does not exist: ${filepath}`, + ); } const realPath = fs.realpathSync(filepath); const content = fs.readFileSync(realPath, "utf-8"); @@ -66,9 +70,14 @@ export const readFileTool: Tool = { return `Content of ${filepath}:\n${content}`; } catch (error) { - return `Error reading file: ${ - error instanceof Error ? error.message : String(error) - }`; + if (error instanceof ContinueError) { + throw error; + } + throw new Error( + `Error reading file: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/searchCode.ts b/extensions/cli/src/tools/searchCode.ts index 53e0f7a30..76b500ce6 100644 --- a/extensions/cli/src/tools/searchCode.ts +++ b/extensions/cli/src/tools/searchCode.ts @@ -2,6 +2,8 @@ import * as child_process from "child_process"; import * as fs from "fs"; import * as util from "util"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; + import { Tool } from "./types.js"; const execPromise = util.promisify(child_process.exec); @@ -53,64 +55,66 @@ export const searchCodeTool: Tool = { path?: string; file_pattern?: string; }): Promise => { + const searchPath = args.path || process.cwd(); + if (!fs.existsSync(searchPath)) { + throw new ContinueError( + ContinueErrorReason.Unspecified, + `Path does not exist: ${searchPath}`, + ); + } + + let command = `rg --line-number --with-filename --color never "${args.pattern}"`; + + if (args.file_pattern) { + command += ` -g "${args.file_pattern}"`; + } + + command += ` "${searchPath}"`; try { - const searchPath = args.path || process.cwd(); - if (!fs.existsSync(searchPath)) { - return `Error: Path does not exist: ${searchPath}`; + const { stdout, stderr } = await execPromise(command); + + if (stderr) { + return `Warning during search: ${stderr}\n\n${stdout}`; } - let command = `rg --line-number --with-filename --color never "${args.pattern}"`; - - if (args.file_pattern) { - command += ` -g "${args.file_pattern}"`; - } - - command += ` "${searchPath}"`; - try { - const { stdout, stderr } = await execPromise(command); - - if (stderr) { - return `Warning during search: ${stderr}\n\n${stdout}`; - } - - if (!stdout.trim()) { - return `No matches found for pattern "${args.pattern}"${ - args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }.`; - } - - // Split the results into lines and limit the number of results - const lines = stdout.split("\n"); - const truncated = lines.length > DEFAULT_MAX_RESULTS; - const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS); - const resultText = limitedLines.join("\n"); - - const truncationMessage = truncated - ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` - : ""; - - return `Search results for pattern "${args.pattern}"${ + if (!stdout.trim()) { + return `No matches found for pattern "${args.pattern}"${ args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }:\n\n${resultText}${truncationMessage}`; - } catch (error: any) { - if (error.code === 1) { - return `No matches found for pattern "${args.pattern}"${ - args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }.`; - } - if (error instanceof Error) { - if (error.message.includes("command not found")) { - return `Error: ripgrep is not installed.`; - } - } - return `Error executing ripgrep: ${ - error instanceof Error ? error.message : String(error) - }`; + }.`; } - } catch (error) { - return `Error searching code: ${ - error instanceof Error ? error.message : String(error) - }`; + + // Split the results into lines and limit the number of results + const lines = stdout.split("\n"); + const truncated = lines.length > DEFAULT_MAX_RESULTS; + const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS); + const resultText = limitedLines.join("\n"); + + const truncationMessage = truncated + ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` + : ""; + + return `Search results for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }:\n\n${resultText}${truncationMessage}`; + } catch (error: any) { + if (error instanceof ContinueError) { + throw error; + } + if (error.code === 1) { + return `No matches found for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }.`; + } + if (error instanceof Error) { + if (error.message.includes("command not found")) { + throw new Error(`ripgrep is not installed.`); + } + } + throw new Error( + `Error executing ripgrep: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/status.ts b/extensions/cli/src/tools/status.ts index 3cdaf6a62..c75eec837 100644 --- a/extensions/cli/src/tools/status.ts +++ b/extensions/cli/src/tools/status.ts @@ -1,3 +1,5 @@ +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; + import { ApiRequestError, AuthenticationRequiredError, @@ -53,7 +55,7 @@ You should use this tool to notify the user whenever the state of your work chan const errorMessage = "Agent ID is required. Please use the --id flag with cn serve."; logger.error(errorMessage); - return `Error: ${errorMessage}`; + throw new ContinueError(ContinueErrorReason.Unspecified, errorMessage); } // Call the API endpoint using shared client @@ -62,19 +64,25 @@ You should use this tool to notify the user whenever the state of your work chan logger.info(`Status: ${args.status}`); return `Status set: ${args.status}`; } catch (error) { + if (error instanceof ContinueError) { + throw error; + } + if (error instanceof AuthenticationRequiredError) { logger.error(error.message); - return "Error: Authentication required"; + throw new Error("Error: Authentication required"); } if (error instanceof ApiRequestError) { - return `Error setting status: ${error.status} ${error.response || error.statusText}`; + throw new Error( + `Error setting status: ${error.status} ${error.response || error.statusText}`, + ); } const errorMessage = error instanceof Error ? error.message : String(error); logger.error(`Error setting status: ${errorMessage}`); - return `Error setting status: ${errorMessage}`; + throw new Error(`Error setting status: ${errorMessage}`); } }, }; diff --git a/extensions/cli/src/tools/writeFile.ts b/extensions/cli/src/tools/writeFile.ts index 55ef4f44c..0efdab13f 100644 --- a/extensions/cli/src/tools/writeFile.ts +++ b/extensions/cli/src/tools/writeFile.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as path from "path"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { createTwoFilesPatch } from "diff"; import { telemetryService } from "../telemetry/telemetryService.js"; @@ -159,10 +160,15 @@ export const writeFileTool: Tool = { return `Successfully created file: ${args.filepath}`; } } catch (error) { - const errorMessage = - error instanceof Error ? error.message : String(error); - - return `Error writing to file: ${errorMessage}`; + if (error instanceof ContinueError) { + throw error; + } + throw new ContinueError( + ContinueErrorReason.FileWriteError, + `Error writing to file: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index b3d5765e3..66107c048 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -4,6 +4,18 @@ import React, { useMemo } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; +const MAX_DESCRIPTION_LENGTH = 80; + +const truncateDescription = (description: string): string => { + if (description.length <= MAX_DESCRIPTION_LENGTH) { + return description; + } + return ( + Array.from(description).slice(0, MAX_DESCRIPTION_LENGTH).join("").trim() + + "…" + ); +}; + interface SlashCommandUIProps { assistant?: AssistantConfig; filter: string; @@ -74,7 +86,7 @@ const SlashCommandUI: React.FC = ({ {paddedCommandName} {" "} - {command.description} + {truncateDescription(command.description)} diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index d874dba11..0dc6d2c2c 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -64,7 +64,7 @@ export const BottomStatusBar: React.FC = ({ )} - {contextPercentage !== undefined && contextPercentage > 75 && ( + {contextPercentage !== undefined && contextPercentage > 0 && ( {" "} diff --git a/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx b/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx index c1e53a6a0..94894e104 100644 --- a/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx +++ b/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx @@ -7,14 +7,12 @@ interface ContextPercentageDisplayProps { /** * Component to display the current context usage percentage - * Shows the percentage in gray color for consistency with other status indicators - * Only displays when percentage exceeds 75% threshold + * Shows the non-zero percentage in gray color for consistency with other status indicators */ export const ContextPercentageDisplay: React.FC< ContextPercentageDisplayProps > = ({ percentage }) => { - // Only show if percentage is greater than 75% - if (percentage <= 75) { + if (percentage === 0) { return null; } diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 64dd99da9..7ff592439 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -56,13 +56,6 @@ export const MemoizedMessage = memo( // Handle system messages if (isSystem) { - // TODO: Properly separate LLM system messages from UI informational messages - // using discriminated union types. For now, skip displaying the first system - // message which is typically the LLM's system prompt. - if (index === 0) { - return null; - } - return ( @@ -116,24 +109,28 @@ export const MemoizedMessage = memo( flexDirection="column" marginBottom={1} > - - - {isCompleted || isErrored ? "●" : "β—‹"} - - - {" "} - - + + + + {isCompleted || isErrored ? "●" : "β—‹"} + + + + + {" "} + + + {isErrored ? ( diff --git a/extensions/cli/src/util/exponentialBackoff.ts b/extensions/cli/src/util/exponentialBackoff.ts index 926049efa..c44aee6e8 100644 --- a/extensions/cli/src/util/exponentialBackoff.ts +++ b/extensions/cli/src/util/exponentialBackoff.ts @@ -1,4 +1,4 @@ -import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { BaseLlmApi, isResponsesModel } from "@continuedev/openai-adapters"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; import { error, warn } from "../logging.js"; @@ -173,6 +173,14 @@ export async function chatCompletionStreamWithBackoff( throw new Error("Request aborted"); } + const useResponses = + typeof llmApi.responsesStream === "function" && + isResponsesModel(params.model); + + if (useResponses) { + return llmApi.responsesStream!(params, abortSignal); + } + return llmApi.chatCompletionStream(params, abortSignal); } catch (err: any) { lastError = err; @@ -189,6 +197,14 @@ export async function chatCompletionStreamWithBackoff( // Only retry if the error is retryable if (!isRetryableError(err)) { + // Log full error details for non-retryable errors + logger.error("Non-retryable LLM API error", err, { + status: err.status, + statusText: err.statusText, + message: err.message, + error: err.error, + model: params.model, + }); throw err; } diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index a7a7119e6..1eea37b85 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -16,9 +16,15 @@

+
+ **Ship faster with Continuous AI** -**Build and run custom agents across your IDE, terminal, and CI** +**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff** + +
+ +Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode) ## Agent diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 417f12cdb..9254537e2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -122,6 +122,7 @@ class MessageTypes { "llm/listModels", "llm/compileChat", "streamDiffLines", + "getDiffLines", "chatDescriber/describe", "conversation/compact", "stats/getTokensPerDay", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index a5ae5eb67..11231983a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -83,17 +83,7 @@ class ApplyToFileHandler( val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine) diffStreamService.register(diffStreamHandler, editorUtils.editor) - // Stream the diffs between current and new content - // For search/replace, we pass the new content as "input" and current as "highlighted" - diffStreamHandler.streamDiffLinesToEditor( - input = newContent, // The new content (full rewrite) - prefix = "", // No prefix since we're rewriting the whole file - highlighted = currentContent, // Current file content - suffix = "", // No suffix since we're rewriting the whole file - modelTitle = null, // No model needed for search/replace instant apply - includeRulesInSystemMessage = false, // No LLM involved, just diff generation - isApply = true - ) + diffStreamHandler.instantApplyDiffLines(currentContent, newContent) } private fun notifyStreamStarted() { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 7792397e3..3f620c120 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.ApplyState import com.github.continuedev.continueintellijextension.ApplyStateStatus import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload +import com.github.continuedev.continueintellijextension.GetDiffLinesPayload import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.application.ApplicationManager @@ -131,6 +132,138 @@ class DiffStreamHandler( } } + fun instantApplyDiffLines( + currentContent: String, + newContent: String + ) { + isRunning = true + sendUpdate(ApplyStateStatus.STREAMING) + + project.service().coreMessenger?.request( + "getDiffLines", + GetDiffLinesPayload( + oldContent=currentContent, + newContent=newContent + ), + null + ) { response -> + if (!isRunning) return@request + + val diffLines = parseDiffLinesResponse(response) ?: run { + println("Error: Invalid response format for getDiffLines") + ApplicationManager.getApplication().invokeLater { + setClosed() + } + return@request + } + + ApplicationManager.getApplication().invokeLater { + WriteCommandAction.runWriteCommandAction(project) { + applyAllDiffLines(diffLines) + + createDiffBlocksFromDiffLines(diffLines) + + cleanupProgressHighlighters() + + if (diffBlocks.isEmpty()) { + setClosed() + } else { + sendUpdate(ApplyStateStatus.DONE) + } + + onFinish() + } + } + } + } + + private fun parseDiffLinesResponse(response: Any?): List>? { + if (response !is Map<*, *>) return null + + val success = response["status"] as? String + if (success != "success") return null + + val content = response["content"] as? List<*> ?: return null + + val result = mutableListOf>() + for (item in content) { + if (item !is Map<*, *>) return null + + val type = item["type"] as? String ?: return null + val line = item["line"] as? String ?: return null + + result.add(mapOf("type" to type, "line" to line)) + } + + return result + } + + private fun applyAllDiffLines(diffLines: List>) { + var currentLine = startLine + + diffLines.forEach { line -> + val type = getDiffLineType(line["type"] as String) + val text = line["line"] as String + + when (type) { + DiffLineType.OLD -> { + // Delete line + val document = editor.document + val start = document.getLineStartOffset(currentLine) + val end = document.getLineEndOffset(currentLine) + document.deleteString(start, if (currentLine < document.lineCount - 1) end + 1 else end) + } + DiffLineType.NEW -> { + // Insert line + val offset = if (currentLine >= editor.document.lineCount) editor.document.textLength else editor.document.getLineStartOffset(currentLine) + editor.document.insertString(offset, text + "\n") + currentLine++ + } + DiffLineType.SAME -> { + currentLine++ + } + } + } + } + + private fun createDiffBlocksFromDiffLines(diffLines: List>) { + var currentBlock: VerticalDiffBlock? = null + var currentLine = startLine + + diffLines.forEach { line -> + val type = getDiffLineType(line["type"] as String) + val text = line["line"] as String + + when (type) { + DiffLineType.OLD -> { + if (currentBlock == null) { + currentBlock = createDiffBlock() + currentBlock!!.startLine = currentLine + } + currentBlock!!.deletedLines.add(text) + } + DiffLineType.NEW -> { + if (currentBlock == null) { + currentBlock = createDiffBlock() + currentBlock!!.startLine = currentLine + } + currentBlock!!.addedLines.add(text) + currentLine++ + } + DiffLineType.SAME -> { + if (currentBlock != null) { + currentBlock!!.onLastDiffLine() + currentBlock = null + } + currentLine++ + } + } + } + + // Handle last block if it doesn't end with SAME + currentBlock?.onLastDiffLine() + } + private fun initUnfinishedRangeHighlights() { val editorUtils = EditorUtils(editor) val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index d937b0add..19d7c1200 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -310,6 +310,11 @@ data class StreamDiffLinesPayload( val isApply: Boolean ) +data class GetDiffLinesPayload( + val oldContent: String, + val newContent: String, +) + data class AcceptOrRejectDiffPayload( val filepath: String? = null, val streamId: String? = null diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index c4eed42d3..7481b8aba 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -41,7 +41,6 @@ displayType="BALLOON"/> - diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 28568c7fe..3849a2a80 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.3.23", + "version": "1.3.24", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index e79d8fe16..db0c87c1b 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -58,13 +58,9 @@ export class ApplyManager { // Currently `isSearchAndReplace` will always provide a full file rewrite // as the contents of `text`, so we can just instantly apply if (isSearchAndReplace) { - const diffLinesGenerator = generateLines( - myersDiff(activeTextEditor.document.getText(), text), - ); - - await this.verticalDiffManager.streamDiffLines( - diffLinesGenerator, - true, + await this.verticalDiffManager.instantApplyDiff( + originalFileContent, + text, streamId, toolCallId, ); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 3f3806a7c..e6f239007 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -11,6 +11,7 @@ import { import type { ApplyState, DiffLine } from "core"; import type { VerticalDiffCodeLens } from "./manager"; +import { getFirstChangedLine } from "./util"; export interface VerticalDiffHandlerOptions { input?: string; @@ -211,7 +212,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Scroll to the first diff const scrollToLine = - this.getFirstChangedLine(myersDiffs) ?? this.startLine; + getFirstChangedLine(myersDiffs, this.startLine) ?? this.startLine; const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0); this.editor.revealRange(range, vscode.TextEditorRevealType.Default); @@ -605,13 +606,4 @@ export class VerticalDiffHandler implements vscode.Disposable { /** * 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/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index cdcf30000..059efe0ae 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -10,12 +10,14 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { myersDiff } from "core/diff/myers"; import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { stripImages } from "core/util/messageContent"; import { getLastNPathParts } from "core/util/uri"; import { editOutcomeTracker } from "../../extension/EditOutcomeTracker"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; +import { getFirstChangedLine } from "./util"; export interface VerticalDiffCodeLens { start: number; @@ -293,6 +295,65 @@ export class VerticalDiffManager { } } + async instantApplyDiff( + oldContent: string, + newContent: string, + streamId: string, + toolCallId?: string, + ) { + vscode.commands.executeCommand("setContext", "continue.diffVisible", true); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const fileUri = editor.document.uri.toString(); + + const myersDiffs = myersDiff(oldContent, newContent); + + const diffHandler = this.createVerticalDiffHandler( + fileUri, + 0, + editor.document.lineCount - 1, + { + instant: true, + onStatusUpdate: (status, numDiffs, fileContent) => + void this.webviewProtocol.request("updateApplyState", { + streamId, + status, + numDiffs, + fileContent, + filepath: fileUri, + toolCallId, + }), + streamId, + }, + ); + + if (!diffHandler) { + console.warn("Issue occurred while creating vertical diff handler"); + return; + } + + await diffHandler.reapplyWithMyersDiff(myersDiffs); + + const scrollToLine = getFirstChangedLine(myersDiffs, 0) ?? 0; + const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0); + editor.revealRange(range, vscode.TextEditorRevealType.Default); + + this.enableDocumentChangeListener(); + + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "done", + numDiffs: this.fileUriToCodeLens.get(fileUri)?.length ?? 0, + fileContent: editor.document.getText(), + filepath: fileUri, + toolCallId, + }); + } + async streamEdit({ input, llm, diff --git a/extensions/vscode/src/diff/vertical/util.ts b/extensions/vscode/src/diff/vertical/util.ts new file mode 100644 index 000000000..83b99946c --- /dev/null +++ b/extensions/vscode/src/diff/vertical/util.ts @@ -0,0 +1,14 @@ +import { DiffLine } from "core"; + +export function getFirstChangedLine( + diff: DiffLine[], + startLine: number, +): number | null { + for (let i = 0; i < diff.length; i++) { + const item = diff[i]; + if (item.type === "old" || item.type === "new") { + return startLine + i; + } + } + return null; +} diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 4a9c2616a..8b69bca20 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -6,7 +6,6 @@ import { } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { isRecommendedAgentModel } from "core/llm/toolSupport"; -import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; import { useAuth } from "../../context/Auth"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -89,14 +88,14 @@ export function ModeSelect() { } }, [mode, isLocalAgent, dispatch]); - const notGreatAtAgent = ( + const notGreatAtAgent = (mode: string) => ( <> @@ -162,7 +161,7 @@ export function ModeSelect() { - {!isGoodAtAgentMode && notGreatAtAgent} + {!isGoodAtAgentMode && notGreatAtAgent("Plan")} @@ -181,7 +180,7 @@ export function ModeSelect() { - {!isGoodAtAgentMode && notGreatAtAgent} + {!isGoodAtAgentMode && notGreatAtAgent("Agent")} diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index da04a273b..b1785b866 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -115,9 +115,11 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
{props.isMainInput && } diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 31bed5723..2ecd4d41a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -350,7 +350,7 @@ export function createEditorConfig(options: { if (!editor) { return; } - if (isStreaming || (codeToEdit.length === 0 && isInEdit)) { + if (isStreamingRef.current || (codeToEdit.length === 0 && isInEdit)) { return; } diff --git a/gui/src/context/LocalStorage.tsx b/gui/src/context/LocalStorage.tsx index 4e5df8c1b..bcda2698e 100644 --- a/gui/src/context/LocalStorage.tsx +++ b/gui/src/context/LocalStorage.tsx @@ -18,13 +18,41 @@ export const LocalStorageProvider: React.FC<{ children: React.ReactNode }> = ({ }) => { const [values, setValues] = useState(DEFAULT_LOCAL_STORAGE); - // TODO setvalue - useEffect(() => { + // Helper function to sync state with localStorage + const syncWithLocalStorage = () => { const isJetbrains = getLocalStorage("ide") === "jetbrains"; - let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14); - setValues({ + const fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14); + + setValues((prev) => ({ + ...prev, fontSize, - }); + })); + }; + + // Initialize with values from localStorage + useEffect(() => { + syncWithLocalStorage(); + }, []); + + // Listen for current tab changes using CustomEvent + useEffect(() => { + const handleLocalStorageChange = (event: CustomEvent) => { + if (event.detail?.key === "fontSize") { + syncWithLocalStorage(); + } + }; + + window.addEventListener( + "localStorageChange", + handleLocalStorageChange as EventListener, + ); + + return () => { + window.removeEventListener( + "localStorageChange", + handleLocalStorageChange as EventListener, + ); + }; }, []); return ( diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index b470389e4..941b0be46 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -1079,6 +1079,19 @@ export const models: { [key: string]: ModelPackage } = { icon: "openai.png", isOpenSource: false, }, + gpt5Codex: { + title: "GPT-5 Codex", + description: + "OpenAI's most advanced code generation model, optimized for programming tasks", + params: { + model: "gpt-5-codex", + contextLength: 400_000, + title: "GPT-5 Codex", + }, + providerOptions: ["openai"], + icon: "openai.png", + isOpenSource: false, + }, gpt4turbo: { title: "GPT-4 Turbo", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 88e091ce7..1bab7abeb 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -118,6 +118,7 @@ export const providers: Partial> = { tags: [ModelProviderTags.RequiresApiKey], packages: [ models.gpt5, + models.gpt5Codex, models.gpt4o, models.gpt4omini, models.gpt4turbo, diff --git a/gui/src/pages/config/components/ToolPoliciesGroup.tsx b/gui/src/pages/config/components/ToolPoliciesGroup.tsx index 796b715f6..3561f9e73 100644 --- a/gui/src/pages/config/components/ToolPoliciesGroup.tsx +++ b/gui/src/pages/config/components/ToolPoliciesGroup.tsx @@ -2,6 +2,7 @@ import { ChevronDownIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; +import { Tool } from "core"; import { useMemo, useState } from "react"; import ToggleSwitch from "../../../components/gui/Switch"; import { ToolTip } from "../../../components/gui/Tooltip"; @@ -28,7 +29,9 @@ export function ToolPoliciesGroup({ const dispatch = useAppDispatch(); const [isExpanded, setIsExpanded] = useState(false); - const availableTools = useAppSelector((state) => state.config.config.tools); + const availableTools = useAppSelector( + (state) => state.config.config.tools as Tool[], + ); const tools = useMemo(() => { return availableTools.filter((t) => t.group === groupName); }, [availableTools, groupName]); diff --git a/gui/src/pages/config/components/ToolPolicyItem.tsx b/gui/src/pages/config/components/ToolPolicyItem.tsx index 2971e015d..5d81c5908 100644 --- a/gui/src/pages/config/components/ToolPolicyItem.tsx +++ b/gui/src/pages/config/components/ToolPolicyItem.tsx @@ -19,7 +19,6 @@ import { import { useFontSize } from "../../../components/ui/font"; import { useAppSelector } from "../../../redux/hooks"; import { addTool, setToolPolicy } from "../../../redux/slices/uiSlice"; -import { isEditTool } from "../../../util/toolCallState"; interface ToolPolicyItemProps { tool: Tool; @@ -29,22 +28,12 @@ interface ToolPolicyItemProps { export function ToolPolicyItem(props: ToolPolicyItemProps) { const dispatch = useDispatch(); - const toolPolicy = useAppSelector( + const policy = useAppSelector( (state) => state.ui.toolSettings[props.tool.function.name], ); const [isExpanded, setIsExpanded] = useState(false); const mode = useAppSelector((state) => state.session.mode); - const autoAcceptEditToolDiffs = useAppSelector( - (state) => state.config.config.ui?.autoAcceptEditToolDiffs, - ); - const isAutoAcceptedToolCall = - isEditTool(props.tool.function.name) && autoAcceptEditToolDiffs; - - const policy = isAutoAcceptedToolCall - ? "allowedWithoutPermission" - : toolPolicy; - useEffect(() => { if (!policy) { dispatch(addTool(props.tool)); @@ -64,7 +53,6 @@ export function ToolPolicyItem(props: ToolPolicyItemProps) { const fontSize = useFontSize(-2); const disabled = - isAutoAcceptedToolCall || !props.isGroupEnabled || (mode === "plan" && props.tool.group === BUILT_IN_GROUP_NAME && @@ -112,19 +100,6 @@ export function ToolPolicyItem(props: ToolPolicyItemProps) { ) : null} - {isAutoAcceptedToolCall ? ( - - Auto-Accept Agent Edits setting is on -

- } - > - -
- ) : null} {props.tool.faviconUrl && ( - {isAutoAcceptedToolCall - ? "Automatic" - : disabled || policy === "disabled" - ? "Excluded" - : policy === "allowedWithoutPermission" - ? "Automatic" - : "Ask First"} + {disabled || policy === "disabled" + ? "Excluded" + : policy === "allowedWithoutPermission" + ? "Automatic" + : "Ask First"} diff --git a/gui/src/pages/config/components/UserSetting.tsx b/gui/src/pages/config/components/UserSetting.tsx index 522a55c58..8f49657da 100644 --- a/gui/src/pages/config/components/UserSetting.tsx +++ b/gui/src/pages/config/components/UserSetting.tsx @@ -79,7 +79,40 @@ export function UserSetting(props: UserSettingProps) { props.onChange(Number(e.target.value))} + onChange={(e) => { + const value = Number(e.target.value); + // Allow temporary invalid values during input + props.onChange(value); + }} + onBlur={(e) => { + // Apply min/max constraints when input loses focus + const value = Number(e.target.value); + const min = props.min ?? 0; + const max = props.max ?? 100; + + if (value < min) { + props.onChange(min); + } else if (value > max) { + props.onChange(max); + } + }} + onKeyDown={(e) => { + // Apply constraints when user presses Enter + if (e.key === "Enter") { + const value = Number(e.currentTarget.value); + const min = props.min ?? 0; + const max = props.max ?? 100; + + if (value < min) { + props.onChange(min); + } else if (value > max) { + props.onChange(max); + } + + // Blur the input to complete the editing + e.currentTarget.blur(); + } + }} min={props.min ?? 0} max={props.max ?? 100} disabled={disabled} diff --git a/gui/src/pages/config/sections/ConfigsSection.tsx b/gui/src/pages/config/sections/ConfigsSection.tsx index b7a6eaad8..ac8ba308f 100644 --- a/gui/src/pages/config/sections/ConfigsSection.tsx +++ b/gui/src/pages/config/sections/ConfigsSection.tsx @@ -73,7 +73,7 @@ export function ConfigsSection() { error.fatal ? "text-error bg-error/10" : "bg-yellow-500/10 text-yellow-500" - } rounded border border-solid border-transparent px-2 py-1 text-xs ${error.uri ? "cursor-pointer " + (error.fatal ? "hover:border-error" : "hover:border-yellow-500") : ""}`} + } break-all rounded border border-solid border-transparent px-2 py-1 text-xs ${error.uri ? "cursor-pointer " + (error.fatal ? "hover:border-error" : "hover:border-yellow-500") : ""}`} > {error.message}
diff --git a/gui/src/pages/config/sections/UserSettingsSection.tsx b/gui/src/pages/config/sections/UserSettingsSection.tsx index afa56aca4..27b7f9bb1 100644 --- a/gui/src/pages/config/sections/UserSettingsSection.tsx +++ b/gui/src/pages/config/sections/UserSettingsSection.tsx @@ -64,7 +64,6 @@ export function UserSettingsSection() { const codeWrap = config.ui?.codeWrap ?? false; const showChatScrollbar = config.ui?.showChatScrollbar ?? false; const readResponseTTS = config.experimental?.readResponseTTS ?? false; - const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false; const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; const disableSessionTitles = config.disableSessionTitles ?? false; const useCurrentFileAsContext = @@ -163,15 +162,6 @@ export function UserSettingsSection() { handleUpdate({ displayRawMarkdown: !value }) } /> - - handleUpdate({ autoAcceptEditToolDiffs: value }) - } - /> diff --git a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx index dd95e09a9..b06264f8d 100644 --- a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +++ b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx @@ -1,9 +1,4 @@ import { BuiltInToolNames } from "core/tools/builtIn"; -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; -import { - addAndSelectMockLlm, - triggerConfigUpdate, -} from "../../../util/test/config"; import { updateConfig } from "../../../redux/slices/configSlice"; import { renderWithProviders } from "../../../util/test/render"; import { Chat } from "../Chat"; @@ -11,7 +6,6 @@ import { Chat } from "../Chat"; import { waitFor } from "@testing-library/dom"; import { act } from "@testing-library/react"; import { ChatMessage } from "core"; -import { setToolPolicy } from "../../../redux/slices/uiSlice"; import { setInactive } from "../../../redux/slices/sessionSlice"; import { getElementByTestId, @@ -133,12 +127,6 @@ test( await user.click(toggleCodeblockChevron); await getElementByText(EDIT_CHANGES); - // Pending tool call - find and click the accept button - const acceptToolCallButton = await getElementByTestId( - generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), - ); - await user.click(acceptToolCallButton); - // Tool call, check that applyToFile was called for edit await waitFor(() => { expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { diff --git a/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx deleted file mode 100644 index c13d46773..000000000 --- a/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx +++ /dev/null @@ -1,228 +0,0 @@ -import { BuiltInToolNames } from "core/tools/builtIn"; -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; -import { triggerConfigUpdate } from "../../../util/test/config"; -import { updateConfig } from "../../../redux/slices/configSlice"; -import { renderWithProviders } from "../../../util/test/render"; -import { Chat } from "../Chat"; - -import { waitFor } from "@testing-library/dom"; -import { act } from "@testing-library/react"; -import { ChatMessage } from "core"; -import { setToolPolicy } from "../../../redux/slices/uiSlice"; -import { setInactive } from "../../../redux/slices/sessionSlice"; -import { - getElementByTestId, - getElementByText, - sendInputWithMockedResponse, - verifyNotPresentByTestId, -} from "../../../util/test/utils"; - -const EDIT_WORKSPACE_DIR = "file:///workspace"; -const EDIT_FILEPATH = "test.txt"; -const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`; -const EDIT_CHANGES = "New content"; -const EDIT_TOOL_CALL_ID = "known-id"; -const EDIT_MESSAGES: ChatMessage[] = [ - { - role: "assistant", - content: "I'll edit the file for you.", - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: EDIT_TOOL_CALL_ID, - function: { - name: BuiltInToolNames.EditExistingFile, - arguments: JSON.stringify({ - filepath: EDIT_FILEPATH, - changes: EDIT_CHANGES, - }), - }, - }, - ], - }, -]; - -const POST_EDIT_RESPONSE = "Edit applied successfully"; -beforeEach(async () => { - vi.clearAllMocks(); - // Clear any persisted state to ensure test isolation - localStorage.clear(); - sessionStorage.clear(); - - // Add a small delay to ensure cleanup is complete - await new Promise((resolve) => setTimeout(resolve, 50)); -}); - -test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { - // Additional cleanup before test starts - localStorage.clear(); - sessionStorage.clear(); - await new Promise((resolve) => setTimeout(resolve, 100)); - - // Setup - const { ideMessenger, store, user } = await renderWithProviders(); - - // Reset mocks to ensure clean state - ideMessenger.resetMocks(); - - // Reset streaming state to prevent test interference - store.dispatch(setInactive()); - - // Additional delay to ensure state is fully reset - await new Promise((resolve) => setTimeout(resolve, 100)); - - ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithoutPermission", - }; - - // Mock context/getSymbolsForFiles to prevent errors during streaming - ideMessenger.responses["context/getSymbolsForFiles"] = {}; - - const messengerPostSpy = vi.spyOn(ideMessenger, "post"); - const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); - - // Instead of using addAndSelectMockLlm (which relies on events that might be failing), - // directly dispatch the config update to set the selected model - const currentConfig = store.getState().config.config; - store.dispatch( - updateConfig({ - ...currentConfig, - selectedModelByRole: { - ...currentConfig.selectedModelByRole, - chat: { - model: "mock", - provider: "mock", - title: "Mock LLM", - underlyingProviderName: "mock", - }, - }, - modelsByRole: { - ...currentConfig.modelsByRole, - chat: [ - ...(currentConfig.modelsByRole.chat || []), - { - model: "mock", - provider: "mock", - title: "Mock LLM", - underlyingProviderName: "mock", - }, - ], - }, - }), - ); - - // Enable automatic edit and yolo mode - store.dispatch( - setToolPolicy({ - toolName: BuiltInToolNames.EditExistingFile, - policy: "allowedWithoutPermission", - }), - ); - triggerConfigUpdate({ - store, - ideMessenger, - editConfig: (current) => { - current.ui = { - ...current.ui, - autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs - }; - return current; - }, - }); - expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true); - - // Send the input that will respond with an edit tool call - await sendInputWithMockedResponse( - ideMessenger, - "Edit this file", - EDIT_MESSAGES, - ); - - // Wait for streaming to complete and tool calls to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 1000)); - }); - - // Toggle the codeblock and make sure the changes show - const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); - - await user.click(toggleCodeblockChevron); - await getElementByText(EDIT_CHANGES); - - // Make sure there's no pending tool call - await verifyNotPresentByTestId( - generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), - ); - // Tool call, check that applyToFile was called for edit - await waitFor(() => { - expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { - streamId: expect.any(String), - filepath: EDIT_FILE_URI, - text: EDIT_CHANGES, - toolCallId: EDIT_TOOL_CALL_ID, - }); - }); - - // Extract stream ID and initiate mock streaming - const streamId = messengerRequestSpy.mock.calls.find( - (call) => call[0] === "applyToFile", - )?.[1]?.streamId; - expect(streamId).toBeDefined(); - - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "streaming", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Mid stream, should show applying in notch - await getElementByTestId("notch-applying-text"); - await getElementByTestId("notch-applying-cancel-button"); - - // Close the stream - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "done", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Set the chat response text before the auto-accept triggers - ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); - - await waitFor(() => { - expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { - streamId, - filepath: EDIT_FILE_URI, - }); - }); - - // Close the stream, ensure response is shown and diff buttons are not present - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "closed", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Allow time for the auto-streaming to complete - await new Promise((resolve) => setTimeout(resolve, 1000)); - - await verifyNotPresentByTestId("edit-accept-button"); - await verifyNotPresentByTestId("edit-reject-button"); - - // Try to manually trigger the streaming by checking if the response is set - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - // TODO: Fix this test - the POST_EDIT_RESPONSE is not being displayed - // await waitFor(() => getElementByText(POST_EDIT_RESPONSE), { - // timeout: 8000, - // }); -}); diff --git a/gui/src/redux/thunks/evaluateToolPolicies.ts b/gui/src/redux/thunks/evaluateToolPolicies.ts index af02ce128..7874edabd 100644 --- a/gui/src/redux/thunks/evaluateToolPolicies.ts +++ b/gui/src/redux/thunks/evaluateToolPolicies.ts @@ -21,13 +21,9 @@ async function evaluateToolPolicy( activeTools: Tool[], toolCallState: ToolCallState, toolPolicies: ToolPolicies, - autoAcceptEditToolDiffs: boolean | undefined, ): Promise { - // allow edit tool calls without permission if auto-accept is enabled - if ( - isEditTool(toolCallState.toolCall.function.name) && - autoAcceptEditToolDiffs - ) { + // allow edit tool calls without permission + if (isEditTool(toolCallState.toolCall.function.name)) { return { policy: "allowedWithoutPermission", toolCallState }; } @@ -81,7 +77,6 @@ export async function evaluateToolPolicies( activeTools: Tool[], generatedToolCalls: ToolCallState[], toolPolicies: ToolPolicies, - autoAcceptEditToolDiffs: boolean | undefined, ): Promise { // Check if ALL tool calls are auto-approved using dynamic evaluation const policyResults = await Promise.all( @@ -91,7 +86,6 @@ export async function evaluateToolPolicies( activeTools, toolCallState, toolPolicies, - autoAcceptEditToolDiffs, ), ), ); diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.test.ts b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts index 46ae54c35..2e426b7d7 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.test.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts @@ -161,61 +161,6 @@ describe("handleApplyStateUpdate", () => { expect.objectContaining({ type: "session/updateApplyState" }), ); }); - - it("should auto-accept diffs when configured and status is done", async () => { - mockGetState.mockReturnValue({ - config: { - config: { - ui: { - autoAcceptEditToolDiffs: true, - }, - }, - }, - session: { history: [] }, - }); - - const applyState: ApplyState = { - streamId: "chat-stream", - toolCallId: "test-tool-call", - status: "done", - filepath: "test.txt", - numDiffs: 1, - }; - - const thunk = handleApplyStateUpdate(applyState); - await thunk(mockDispatch, mockGetState, mockExtra); - - expect(mockExtra.ideMessenger.post).toHaveBeenCalledWith("acceptDiff", { - streamId: "chat-stream", - filepath: "test.txt", - }); - }); - - it("should not auto-accept when config is disabled", async () => { - mockGetState.mockReturnValue({ - config: { - config: { - ui: { - autoAcceptEditToolDiffs: false, - }, - }, - }, - session: { history: [] }, - }); - - const applyState: ApplyState = { - streamId: "chat-stream", - toolCallId: "test-tool-call", - status: "done", - filepath: "test.txt", - numDiffs: 1, - }; - - const thunk = handleApplyStateUpdate(applyState); - await thunk(mockDispatch, mockGetState, mockExtra); - - expect(mockExtra.ideMessenger.post).not.toHaveBeenCalled(); - }); }); describe("closed status handling", () => { diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 1cc2c35d0..a220af51f 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -44,22 +44,24 @@ export const handleApplyStateUpdate = createAsyncThunk< // Handle apply status updates - use toolCallId from event payload if (applyState.toolCallId) { + const toolCallState = findToolCallById( + getState().session.history, + applyState.toolCallId, + ); + if ( applyState.status === "done" && - getState().config.config?.ui?.autoAcceptEditToolDiffs + toolCallState?.toolCall.function.name && + getState().ui.toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" ) { extra.ideMessenger.post("acceptDiff", { streamId: applyState.streamId, filepath: applyState.filepath, }); } - if (applyState.status === "closed") { - // Find the tool call to check if it was canceled - const toolCallState = findToolCallById( - getState().session.history, - applyState.toolCallId, - ); + if (applyState.status === "closed") { if (toolCallState) { const accepted = toolCallState.status !== "canceled"; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 226146e07..96cd2bb16 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -317,7 +317,6 @@ export const streamNormalInput = createAsyncThunk< activeTools, generatedCalls3, toolPolicies, - state3.config.config.ui?.autoAcceptEditToolDiffs, ); const anyRequireApproval = policies.find( ({ policy }) => policy === "allowedWithPermission", diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index 182cf486d..cab68d7b6 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -49,4 +49,11 @@ export function setLocalStorage( value: LocalStorageTypes[T], ): void { localStorage.setItem(key, JSON.stringify(value)); + + // Dispatch custom event to notify current tab listeners + window.dispatchEvent( + new CustomEvent("localStorageChange", { + detail: { key, value }, + }), + ); } diff --git a/packages/config-yaml/src/index.ts b/packages/config-yaml/src/index.ts index c87d689ee..b14b455a7 100644 --- a/packages/config-yaml/src/index.ts +++ b/packages/config-yaml/src/index.ts @@ -1,2 +1,3 @@ export * from "./browser.js"; export * from "./registryClient.js"; +export { parseAgentFileRules } from "./markdown/agentFiles.js"; diff --git a/packages/hub/package-lock.json b/packages/hub/package-lock.json index 163312360..e719bb396 100644 --- a/packages/hub/package-lock.json +++ b/packages/hub/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.7", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.14.0" + "@continuedev/config-yaml": "^1.26.0" }, "devDependencies": { "@types/jest": "^29.5.14", @@ -544,9 +544,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.14.0.tgz", - "integrity": "sha512-MRi2SKTLkXme/lyFZruXGhWsaH9eMHvgkj/gAQcAhe6LxvbEOt2SyG7IS/t/8fDRJ2pXIjK/FtJpdKarXokJpA==", + "version": "1.26.0", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.26.0.tgz", + "integrity": "sha512-v+JWNpB8ufsRcsmzsGolo+hqOpZNQQfqKXyY945XZDrctfpUdw1COBR9td2LTaAXhaqOPUqOWThanGV+lOy2Gw==", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/hub/package.json b/packages/hub/package.json index 29f56463b..8ba936f24 100644 --- a/packages/hub/package.json +++ b/packages/hub/package.json @@ -12,7 +12,7 @@ "author": "Continue Dev, Inc.", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.14.0" + "@continuedev/config-yaml": "^1.26.0" }, "devDependencies": { "@types/jest": "^29.5.14", diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index 820559308..730495e9c 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -79,9 +79,17 @@ export const OpenAi: ModelProvider = { { model: "gpt-5", displayName: "GPT-5", + contextLength: 128000, + maxCompletionTokens: 16384, + regex: /^gpt-5$/, + recommendedFor: ["chat"], + }, + { + model: "gpt-5-codex", + displayName: "GPT-5 Codex", contextLength: 400000, maxCompletionTokens: 128000, - regex: /gpt-5/, + regex: /gpt-5-codex/, recommendedFor: ["chat"], }, // gpt-4o diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index abfe53446..0a7bc573c 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -366,9 +366,13 @@ export class AnthropicApi implements BaseLlmApi { const startEvent = rawEvent as RawMessageStartEvent; usage.prompt_tokens = startEvent.message.usage?.input_tokens ?? 0; usage.prompt_tokens_details = { + cache_write_tokens: + startEvent.message.usage?.cache_creation_input_tokens ?? 0, + cache_read_tokens: + startEvent.message.usage?.cache_read_input_tokens ?? 0, cached_tokens: startEvent.message.usage?.cache_read_input_tokens ?? 0, - }; + } as any; break; case "message_delta": const deltaEvent = rawEvent as RawMessageDeltaEvent; diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 86452706a..4d154ea97 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -11,9 +11,20 @@ import { CompletionCreateParamsStreaming, Model, } from "openai/resources/index"; +import type { + Response, + ResponseStreamEvent, +} from "openai/resources/responses/responses.js"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; import { customFetch } from "../util.js"; +import { + createResponsesStreamState, + fromResponsesChunk, + isResponsesModel, + responseToChatCompletion, + toResponsesParams, +} from "./openaiResponses.js"; import { BaseLlmApi, CreateRerankResponse, @@ -63,6 +74,11 @@ export class OpenAIApi implements BaseLlmApi { return body; } + protected shouldUseResponsesEndpoint(model: string): boolean { + const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; + return isOfficialOpenAIAPI && isResponsesModel(model); + } + modifyCompletionBody< T extends | CompletionCreateParamsNonStreaming @@ -98,6 +114,10 @@ export class OpenAIApi implements BaseLlmApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { + if (this.shouldUseResponsesEndpoint(body.model)) { + const response = await this.responsesNonStream(body, signal); + return responseToChatCompletion(response); + } const response = await this.openai.chat.completions.create( this.modifyChatBody(body), { @@ -111,6 +131,12 @@ export class OpenAIApi implements BaseLlmApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { + if (this.shouldUseResponsesEndpoint(body.model)) { + for await (const chunk of this.responsesStream(body, signal)) { + yield chunk; + } + return; + } const response = await this.openai.chat.completions.create( this.modifyChatBody(body), { @@ -209,4 +235,42 @@ export class OpenAIApi implements BaseLlmApi { async list(): Promise { return (await this.openai.models.list()).data; } + + async responsesNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const params = toResponsesParams({ + ...(body as ChatCompletionCreateParams), + stream: false, + }); + return (await this.openai.responses.create(params, { + signal, + })) as Response; + } + + async *responsesStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const params = toResponsesParams({ + ...(body as ChatCompletionCreateParams), + stream: true, + }); + + const state = createResponsesStreamState({ + model: body.model, + }); + + const stream = this.openai.responses.stream(params as any, { + signal, + }); + + for await (const event of stream as AsyncIterable) { + const chunk = fromResponsesChunk(state, event); + if (chunk) { + yield chunk; + } + } + } } diff --git a/packages/openai-adapters/src/apis/base.ts b/packages/openai-adapters/src/apis/base.ts index 5079aedef..cf5904d51 100644 --- a/packages/openai-adapters/src/apis/base.ts +++ b/packages/openai-adapters/src/apis/base.ts @@ -10,6 +10,7 @@ import { EmbeddingCreateParams, Model, } from "openai/resources/index"; +import type { Response } from "openai/resources/responses/responses.js"; export interface FimCreateParamsStreaming extends CompletionCreateParamsStreaming { @@ -50,6 +51,16 @@ export interface BaseLlmApi { signal: AbortSignal, ): AsyncGenerator; + responsesNonStream?( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise; + + responsesStream?( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator; + // Completion, no stream completionNonStream( body: CompletionCreateParamsNonStreaming, diff --git a/packages/openai-adapters/src/apis/openaiResponses.ts b/packages/openai-adapters/src/apis/openaiResponses.ts new file mode 100644 index 000000000..997651be4 --- /dev/null +++ b/packages/openai-adapters/src/apis/openaiResponses.ts @@ -0,0 +1,779 @@ +import type { CompletionUsage } from "openai/resources/index.js"; +import { + ChatCompletion, + ChatCompletionAssistantMessageParam, + ChatCompletionChunk, + ChatCompletionContentPart, + ChatCompletionContentPartImage, + ChatCompletionContentPartInputAudio, + ChatCompletionContentPartRefusal, + ChatCompletionContentPartText, + ChatCompletionCreateParams, + ChatCompletionCreateParamsStreaming, + ChatCompletionMessageParam, + ChatCompletionMessageToolCall, + ChatCompletionTool, +} from "openai/resources/index.js"; +import { + Response, + ResponseCreateParams, + ResponseFunctionCallArgumentsDoneEvent, + ResponseIncompleteEvent, + ResponseInput, + ResponseInputAudio, + ResponseInputContent, + ResponseInputFile, + ResponseInputImage, + ResponseInputText, + ResponseOutputItem, + ResponseOutputMessage, + ResponseOutputRefusal, + ResponseOutputText, + ResponseReasoningSummaryTextDeltaEvent, + ResponseStreamEvent, + ResponseUsage, +} from "openai/resources/responses/responses.js"; + +const RESPONSES_MODEL_REGEX = /^(?:gpt-5|gpt-5-codex|o)/i; + +export function isResponsesModel(model: string): boolean { + return !!model && RESPONSES_MODEL_REGEX.test(model); +} + +function convertTextPart(text: string): ResponseInputText { + return { + text, + type: "input_text", + }; +} + +function convertImagePart( + image: ChatCompletionContentPartImage, +): ResponseInputImage { + const converted: ResponseInputImage = { + type: "input_image", + image_url: image.image_url.url, + detail: image.image_url.detail ?? "auto", + }; + if ((image.image_url as any).file_id) { + (converted as any).file_id = (image.image_url as any).file_id; + } + return converted; +} + +function convertAudioPart( + part: ChatCompletionContentPartInputAudio, +): ResponseInputAudio { + return { + type: "input_audio", + input_audio: { + data: part.input_audio.data, + format: part.input_audio.format, + }, + }; +} + +function convertFilePart( + part: ChatCompletionContentPart.File, +): ResponseInputFile { + return { + type: "input_file", + file_id: part.file.file_id ?? undefined, + file_data: part.file.file_data ?? undefined, + filename: part.file.filename ?? undefined, + file_url: (part.file as any).file_url ?? undefined, + }; +} + +function convertMessageContentPart( + part: ChatCompletionContentPart | ChatCompletionContentPartRefusal, +): ResponseInputContent | undefined { + switch (part.type) { + case "text": + return convertTextPart(part.text); + case "image_url": + return convertImagePart(part); + case "input_audio": + return convertAudioPart(part); + case "file": + return convertFilePart(part); + case "refusal": + // Skip refusal parts - they're not input content + return undefined; + default: + return undefined; + } +} + +function collectMessageContentParts( + content: ChatCompletionMessageParam["content"], +): ResponseInputContent[] { + if (typeof content === "string") { + return [convertTextPart(content)]; + } + if (!Array.isArray(content)) { + return []; + } + + const parts: ResponseInputContent[] = []; + for (const part of content) { + const converted = convertMessageContentPart(part); + if (!converted) { + continue; + } + parts.push(converted); + } + return parts; +} + +type AssistantContentPart = ResponseOutputText | ResponseOutputRefusal; + +function createOutputTextPart( + text: string, + source?: Partial, +): AssistantContentPart { + const annotations = + Array.isArray(source?.annotations) && source.annotations.length > 0 + ? source.annotations + : []; + const part: ResponseOutputText = { + text, + type: "output_text", + annotations, + }; + if (Array.isArray(source?.logprobs) && source.logprobs.length > 0) { + part.logprobs = source.logprobs; + } + return part; +} + +function createRefusalPart(refusal: string): AssistantContentPart { + return { + refusal, + type: "refusal", + }; +} + +function collectAssistantContentParts( + content: ChatCompletionMessageParam["content"], + refusal?: string | null, +): AssistantContentPart[] { + const parts: AssistantContentPart[] = []; + + if (typeof content === "string") { + if (content.trim().length > 0) { + parts.push(createOutputTextPart(content)); + } + } else if (Array.isArray(content)) { + for (const rawPart of content) { + // Content array should be ChatCompletionContentPartText | ChatCompletionContentPartRefusal + // but we handle "output_text" type which may come from Response API conversions + const part = rawPart as + | ChatCompletionContentPartText + | ChatCompletionContentPartRefusal + | { type: "output_text"; text: string }; + if (!part) { + continue; + } + + const partType = part.type; + if (partType === "text") { + const textPart = part as ChatCompletionContentPartText; + if ( + typeof textPart.text === "string" && + textPart.text.trim().length > 0 + ) { + parts.push(createOutputTextPart(textPart.text)); + } + } else if (partType === "output_text") { + const textValue = (part as { type: "output_text"; text: string }).text; + if (typeof textValue === "string" && textValue.trim().length > 0) { + parts.push(createOutputTextPart(textValue)); + } + } else if (partType === "refusal") { + const refusalPart = part as ChatCompletionContentPartRefusal; + const refusalText = refusalPart.refusal; + if (typeof refusalText === "string" && refusalText.trim().length > 0) { + parts.push(createRefusalPart(refusalText)); + } + } + } + } + + if (typeof refusal === "string" && refusal.trim().length > 0) { + parts.push(createRefusalPart(refusal)); + } + + return parts; +} + +function extractToolResultContent( + content: ChatCompletionMessageParam["content"], +): string { + if (typeof content === "string") { + return content; + } + if (!Array.isArray(content)) { + return ""; + } + + return content + .map((part) => { + if (part.type === "text") { + return part.text; + } + return ""; + }) + .join(""); +} + +function convertTools( + tools?: ChatCompletionTool[] | null, + legacyFunctions?: ChatCompletionCreateParams["functions"], +): ResponseCreateParams["tools"] | undefined { + if (tools?.length) { + return tools.map((tool) => { + if (tool.type === "function") { + return { + type: "function" as const, + name: tool.function.name, + description: tool.function.description ?? null, + parameters: tool.function.parameters ?? null, + strict: + tool.function.strict !== undefined ? tool.function.strict : null, + }; + } + return tool as any; + }); + } + + if (legacyFunctions?.length) { + return legacyFunctions.map((fn) => ({ + type: "function" as const, + name: fn.name, + description: fn.description ?? null, + parameters: fn.parameters ?? null, + strict: null, + })); + } + + return undefined; +} + +function resolveToolChoice( + params: ChatCompletionCreateParams, +): ResponseCreateParams["tool_choice"] | undefined { + if (params.tool_choice) { + return params.tool_choice as any; + } + if (params.function_call) { + if (typeof params.function_call === "string") { + if (params.function_call === "none") { + return "none"; + } + if (params.function_call === "auto") { + return "auto"; + } + } else if (params.function_call?.name) { + return { + type: "function", + name: params.function_call.name, + }; + } + } + return undefined; +} + +export function toResponsesInput( + messages: ChatCompletionMessageParam[], +): ResponseInput { + const inputItems: ResponseInput = []; + let assistantMessageCounter = 0; + + for (const message of messages) { + if (message.role === "tool") { + if (!message.tool_call_id) { + continue; + } + const rawContent = extractToolResultContent(message.content); + inputItems.push({ + type: "function_call_output", + call_id: message.tool_call_id, + output: rawContent, + }); + continue; + } + + if (message.role === "system" || message.role === "developer") { + const contentParts = collectMessageContentParts(message.content); + if (contentParts.length === 0) { + continue; + } + inputItems.push({ + type: "message", + role: "developer", + content: contentParts, + }); + continue; + } + + if (message.role === "user") { + const contentParts = collectMessageContentParts(message.content); + if (contentParts.length === 0) { + continue; + } + inputItems.push({ + type: "message", + role: "user", + content: contentParts, + }); + continue; + } + + if (message.role === "assistant") { + const assistantMessage = message as ChatCompletionAssistantMessageParam; + const assistantContentParts = collectAssistantContentParts( + assistantMessage.content, + assistantMessage.refusal ?? null, + ); + if (assistantContentParts.length > 0) { + const providedId = (message as any).id; + const assistantId = + typeof providedId === "string" && providedId.startsWith("msg_") + ? providedId + : `msg_${(assistantMessageCounter++).toString().padStart(4, "0")}`; + inputItems.push({ + type: "message", + role: "assistant", + content: assistantContentParts, + id: assistantId, + status: "completed", + } as ResponseOutputMessage as any); + } + if (assistantMessage.tool_calls?.length) { + assistantMessage.tool_calls.forEach((toolCall, index) => { + if (toolCall.type === "function") { + const callId = toolCall.id ?? `tool_call_${index}`; + const functionCall: any = { + type: "function_call", + call_id: callId, + name: toolCall.function.name ?? "", + arguments: toolCall.function.arguments ?? "{}", + }; + if ( + typeof toolCall.id === "string" && + toolCall.id.startsWith("fc_") + ) { + functionCall.id = toolCall.id; + } + inputItems.push(functionCall); + } + }); + } + continue; + } + } + + return inputItems; +} + +export function toResponsesParams( + params: ChatCompletionCreateParams, +): ResponseCreateParams { + const input = toResponsesInput(params.messages); + + const responsesParams: ResponseCreateParams = { + model: params.model, + input, + stream: + (params as ChatCompletionCreateParamsStreaming).stream === true + ? true + : false, + tool_choice: resolveToolChoice(params), + tools: convertTools(params.tools, params.functions), + }; + + if (params.temperature !== undefined && params.temperature !== null) { + responsesParams.temperature = params.temperature; + } + if (params.top_p !== undefined && params.top_p !== null) { + responsesParams.top_p = params.top_p; + } + if (params.metadata !== undefined) { + responsesParams.metadata = params.metadata ?? null; + } + if (params.prompt_cache_key !== undefined) { + responsesParams.prompt_cache_key = params.prompt_cache_key; + } + const maxOutputTokens = + params.max_completion_tokens ?? params.max_tokens ?? null; + if (maxOutputTokens !== null) { + responsesParams.max_output_tokens = maxOutputTokens; + } + if (params.parallel_tool_calls !== undefined) { + responsesParams.parallel_tool_calls = params.parallel_tool_calls; + } else if (params.tools?.length) { + responsesParams.parallel_tool_calls = false; + } + if (params.reasoning_effort) { + responsesParams.reasoning = { + effort: params.reasoning_effort, + }; + } + + // Remove undefined properties to avoid overriding server defaults + Object.keys(responsesParams).forEach((key) => { + const typedKey = key as keyof ResponseCreateParams; + if (responsesParams[typedKey] === undefined) { + delete responsesParams[typedKey]; + } + }); + + return responsesParams; +} + +function mapUsage(usage?: ResponseUsage | null): CompletionUsage | undefined { + if (!usage) { + return undefined; + } + + const mapped: CompletionUsage = { + completion_tokens: usage.output_tokens, + prompt_tokens: usage.input_tokens, + total_tokens: usage.total_tokens, + }; + + return mapped; +} + +interface ToolCallState { + id: string; + callId: string; + index: number; + name?: string; + arguments: string; +} + +interface MessageState { + content: string; + refusal: string | null; +} + +export interface ResponsesStreamState { + context: { + id?: string; + model: string; + created?: number; + pendingFinish?: ChatCompletionChunk.Choice["finish_reason"]; + }; + messages: Map; + toolCalls: Map; + indexToToolCallId: Map; +} + +export function createResponsesStreamState(context: { + model: string; + responseId?: string; + created?: number; +}): ResponsesStreamState { + return { + context: { + id: context.responseId, + model: context.model, + created: context.created, + pendingFinish: null, + }, + messages: new Map(), + toolCalls: new Map(), + indexToToolCallId: new Map(), + }; +} + +function buildChunk( + state: ResponsesStreamState, + delta: Partial = {}, + finishReason: ChatCompletionChunk.Choice["finish_reason"] = null, + usage?: CompletionUsage, + options?: { includeChoices?: boolean }, +): ChatCompletionChunk { + const includeChoices = options?.includeChoices ?? true; + const created = state.context.created ?? Math.floor(Date.now() / 1000); + const id = state.context.id ?? ""; + + const chunk: ChatCompletionChunk = { + id, + object: "chat.completion.chunk", + created, + model: state.context.model, + choices: includeChoices + ? [ + { + index: 0, + delta: delta as ChatCompletionChunk.Choice["delta"], + finish_reason: finishReason, + logprobs: null, + }, + ] + : [], + }; + + if (usage) { + chunk.usage = usage; + } + + return chunk; +} + +function mapIncompleteReason( + event: ResponseIncompleteEvent, +): ChatCompletionChunk.Choice["finish_reason"] { + const reason = event.response.incomplete_details?.reason; + if (reason === "max_output_tokens") { + return "length"; + } + if (reason === "content_filter") { + return "content_filter"; + } + return "stop"; +} + +function upsertToolCallState( + state: ResponsesStreamState, + item: ResponseOutputItem, + outputIndex: number, +): ToolCallState { + const callId = + (item as any).call_id ?? item.id ?? `tool_call_${state.toolCalls.size}`; + const toolState: ToolCallState = { + id: item.id ?? callId, + callId, + index: outputIndex, + name: (item as any).name ?? undefined, + arguments: (item as any).arguments ?? "", + }; + state.toolCalls.set(item.id ?? callId, toolState); + state.indexToToolCallId.set(outputIndex, callId); + return toolState; +} + +function getToolCallState( + state: ResponsesStreamState, + itemId: string, + outputIndex: number, +): ToolCallState | undefined { + const existing = state.toolCalls.get(itemId); + if (existing) { + return existing; + } + const byIndex = state.indexToToolCallId.get(outputIndex); + if (!byIndex) { + return undefined; + } + return state.toolCalls.get(byIndex); +} + +export function fromResponsesChunk( + state: ResponsesStreamState, + event: ResponseStreamEvent, +): ChatCompletionChunk | undefined { + switch (event.type) { + case "response.created": { + state.context.id = event.response.id; + state.context.created = event.response.created_at; + if (event.response.model) { + state.context.model = event.response.model; + } + return undefined; + } + case "response.output_item.added": { + const item = event.item; + if (item.type === "message") { + state.messages.set(item.id, { content: "", refusal: null }); + } else if (item.type === "function_call") { + upsertToolCallState(state, item, event.output_index); + } + return undefined; + } + case "response.output_text.delta": { + const messageState = state.messages.get(event.item_id); + if (messageState) { + messageState.content += event.delta; + } + return buildChunk(state, { content: event.delta }); + } + case "response.reasoning_text.delta": { + return buildChunk(state, { + reasoning: { + content: [ + { + type: "reasoning_text", + text: event.delta, + }, + ], + }, + } as any); + } + case "response.reasoning_summary_text.delta": { + const summaryEvent = event as ResponseReasoningSummaryTextDeltaEvent; + return buildChunk(state, { + reasoning: { + content: [ + { + type: "reasoning_text", + text: summaryEvent.delta, + }, + ], + }, + } as any); + } + case "response.refusal.delta": { + const messageState = state.messages.get(event.item_id); + if (messageState) { + messageState.refusal = (messageState.refusal ?? "") + event.delta; + } + return buildChunk(state, { refusal: event.delta }); + } + case "response.function_call_arguments.delta": { + const callState = getToolCallState( + state, + event.item_id, + event.output_index, + ); + if (!callState) { + return undefined; + } + callState.arguments += event.delta; + return buildChunk(state, { + tool_calls: [ + { + index: callState.index, + id: callState.callId, + type: "function", + function: { + name: callState.name, + arguments: event.delta, + }, + }, + ], + }); + } + case "response.function_call_arguments.done": { + const doneEvent = event as ResponseFunctionCallArgumentsDoneEvent; + const callState = getToolCallState( + state, + doneEvent.item_id, + doneEvent.output_index, + ); + if (callState) { + callState.arguments = doneEvent.arguments; + } + return undefined; + } + case "response.output_item.done": { + if (event.item.type === "function_call") { + return buildChunk(state, {}, "tool_calls"); + } + if (event.item.type === "message") { + return buildChunk(state, {}, state.context.pendingFinish ?? "stop"); + } + return undefined; + } + case "response.completed": { + state.context.id = event.response.id; + state.context.created = event.response.created_at; + state.context.model = event.response.model ?? state.context.model; + const usage = mapUsage(event.response.usage); + if (usage) { + return buildChunk(state, {}, null, usage, { + includeChoices: false, + }); + } + return undefined; + } + case "response.incomplete": { + const reason = mapIncompleteReason(event as ResponseIncompleteEvent); + state.context.pendingFinish = reason; + const usage = mapUsage((event as ResponseIncompleteEvent).response.usage); + if (usage) { + return buildChunk(state, {}, null, usage, { + includeChoices: false, + }); + } + return buildChunk(state, {}, reason); + } + case "response.failed": + case "error": { + state.context.pendingFinish = "content_filter"; + return undefined; + } + default: + return undefined; + } +} + +export function responseToChatCompletion(response: Response): ChatCompletion { + const usage = mapUsage(response.usage); + let finishReason: ChatCompletionChunk.Choice["finish_reason"] = "stop"; + if (response.incomplete_details?.reason === "max_output_tokens") { + finishReason = "length"; + } else if (response.incomplete_details?.reason === "content_filter") { + finishReason = "content_filter"; + } + + const messageContent: string[] = []; + let refusal: string | null = null; + const toolCalls: ChatCompletion["choices"][0]["message"]["tool_calls"] = []; + + response.output.forEach((item) => { + if (item.type === "message") { + item.content.forEach((contentPart) => { + if (contentPart.type === "output_text") { + messageContent.push(contentPart.text); + } else if (contentPart.type === "refusal") { + refusal = (refusal ?? "") + contentPart.refusal; + } + }); + } else if (item.type === "function_call") { + toolCalls.push({ + id: item.call_id ?? item.id, + type: "function", + function: { + name: item.name, + arguments: item.arguments, + }, + }); + } + }); + + if (toolCalls.length > 0) { + finishReason = "tool_calls"; + } + + const message = { + role: "assistant" as const, + content: messageContent.length ? messageContent.join("") : null, + refusal, + tool_calls: toolCalls.length ? toolCalls : undefined, + }; + + const chatCompletion: ChatCompletion = { + id: response.id, + object: "chat.completion", + created: response.created_at, + model: response.model, + choices: [ + { + index: 0, + message, + finish_reason: finishReason, + logprobs: null, + }, + ], + }; + + if (usage) { + chatCompletion.usage = usage; + } + + return chatCompletion; +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 29121dab8..a7ee579f9 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -188,3 +188,5 @@ export { getAnthropicHeaders, getAnthropicMediaTypeFromDataUrl, } from "./apis/AnthropicUtils.js"; + +export { isResponsesModel } from "./apis/openaiResponses.js"; diff --git a/packages/openai-adapters/src/test/openai-responses.vitest.ts b/packages/openai-adapters/src/test/openai-responses.vitest.ts new file mode 100644 index 000000000..68173da89 --- /dev/null +++ b/packages/openai-adapters/src/test/openai-responses.vitest.ts @@ -0,0 +1,487 @@ +import { describe, expect, it } from "vitest"; + +import type { ChatCompletionChunk } from "openai/resources/index.js"; +import type { + ChatCompletionAssistantMessageParam, + ChatCompletionMessageParam, +} from "openai/resources/index.js"; +import type { + Response, + ResponseCompletedEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseReasoningTextDeltaEvent, + ResponseStreamEvent, + ResponseTextDeltaEvent, +} from "openai/resources/responses/responses.js"; + +import { + createResponsesStreamState, + fromResponsesChunk, + responseToChatCompletion, + toResponsesInput, +} from "../apis/openaiResponses.js"; + +describe("toResponsesInput", () => { + it("maps assistant text content to output_text with generated msg ids", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: "Hello there!", + }, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toHaveLength(1); + const assistant = inputItems[0] as any; + expect(assistant).toMatchObject({ + type: "message", + role: "assistant", + id: "msg_0000", + }); + expect(assistant.content).toMatchObject([ + { + type: "output_text", + text: "Hello there!", + }, + ]); + }); + + it("maps assistant refusal content to refusal output items", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: "", + refusal: "I must decline.", + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toHaveLength(1); + const assistant = inputItems[0] as any; + expect(assistant.content).toEqual([ + { + type: "refusal", + refusal: "I must decline.", + }, + ]); + }); + + it("converts assistant structured content into output_text items", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: [{ type: "text", text: "Structured hello." }], + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + + const assistant = inputItems[0] as any; + expect(assistant.content).toMatchObject([ + { + type: "output_text", + text: "Structured hello.", + }, + ]); + }); + + it("converts chat messages, multimodal content, and tool interactions into Responses input items", () => { + const messages: ChatCompletionMessageParam[] = [ + { role: "system", content: "Stay concise." }, + { + role: "user", + content: [ + { type: "text", text: "Look at this image" }, + { + type: "image_url", + image_url: { url: "https://example.com/cat.png", detail: "auto" }, + }, + ], + }, + { + role: "assistant", + tool_calls: [ + { + id: "fc_call_1", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"vitest expectations"}', + }, + }, + ], + content: "", + } as ChatCompletionAssistantMessageParam, + { + role: "tool", + tool_call_id: "call_1", + content: "Found 3 relevant documents.", + }, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toMatchObject([ + { + type: "message", + role: "developer", + content: [{ type: "input_text", text: "Stay concise." }], + }, + { + type: "message", + role: "user", + content: [ + { type: "input_text", text: "Look at this image" }, + { + type: "input_image", + image_url: "https://example.com/cat.png", + detail: "auto", + }, + ], + }, + { + type: "function_call", + call_id: "fc_call_1", + id: "fc_call_1", + name: "searchDocs", + arguments: '{"query":"vitest expectations"}', + }, + { + type: "function_call_output", + call_id: "call_1", + output: "Found 3 relevant documents.", + }, + ]); + }); +}); + +it("omits function_call id when tool call id lacks fc_ prefix", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + tool_calls: [ + { + id: "call_custom", + type: "function", + function: { + name: "lookup", + arguments: "{}", + }, + }, + ], + content: "", + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + const functionCall = inputItems.find( + (item: any) => item.type === "function_call", + ) as any; + + expect(functionCall).toBeTruthy(); + expect(functionCall.call_id).toBe("call_custom"); + expect(functionCall).not.toHaveProperty("id"); +}); + +describe("fromResponsesChunk", () => { + function collectChunks(events: ResponseStreamEvent[]): ChatCompletionChunk[] { + const state = createResponsesStreamState({ + created: 1710000000, + model: "gpt-5-preview", + responseId: "resp_123", + }); + + const chunks: ChatCompletionChunk[] = []; + for (const event of events) { + const result = fromResponsesChunk(state, event); + if (result) { + chunks.push(result); + } + } + return chunks; + } + + it("emits incremental assistant content and finish_reason from Responses text deltas", () => { + const messageAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + output_index: 0, + sequence_number: 1, + item: { + id: "msg_1", + type: "message", + role: "assistant", + content: [], + } as any, + }; + const firstDelta: ResponseTextDeltaEvent = { + type: "response.output_text.delta", + sequence_number: 2, + item_id: "msg_1", + output_index: 0, + content_index: 0, + delta: "Hello", + logprobs: [], + }; + const secondDelta: ResponseTextDeltaEvent = { + type: "response.output_text.delta", + sequence_number: 3, + item_id: "msg_1", + output_index: 0, + content_index: 0, + delta: " world", + logprobs: [], + }; + const messageDone: ResponseOutputItemDoneEvent = { + type: "response.output_item.done", + sequence_number: 4, + output_index: 0, + item: { + id: "msg_1", + type: "message", + role: "assistant", + content: [ + { + type: "output_text", + text: "Hello world", + }, + ], + } as any, + }; + const completed: ResponseCompletedEvent = { + type: "response.completed", + sequence_number: 5, + response: { + id: "resp_123", + object: "response", + model: "gpt-5-preview", + created_at: 1710000000, + output_text: "Hello world", + error: null, + incomplete_details: null, + instructions: null, + metadata: null, + output: [], + parallel_tool_calls: false, + temperature: null, + tool_choice: null as any, + tools: [], + usage: { + input_tokens: 12, + input_tokens_details: { cached_tokens: 0 }, + output_tokens: 9, + output_tokens_details: { reasoning_tokens: 0 }, + total_tokens: 21, + }, + } as unknown as Response, + }; + + const chunks = collectChunks([ + messageAdded, + firstDelta, + secondDelta, + messageDone, + completed, + ]); + + expect(chunks[0].choices[0].delta.content).toBe("Hello"); + expect(chunks[1].choices[0].delta.content).toBe(" world"); + const finishChunk = chunks.find( + (chunk) => chunk.choices[0].finish_reason !== null, + ); + expect(finishChunk?.choices[0].finish_reason).toBe("stop"); + const usageChunk = chunks[chunks.length - 1]; + expect(usageChunk.usage).toMatchObject({ + prompt_tokens: 12, + completion_tokens: 9, + total_tokens: 21, + }); + }); + + it("tracks streaming tool call arguments and surfaces tool_calls deltas", () => { + const toolAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + sequence_number: 1, + output_index: 0, + item: { + id: "tool_item_1", + type: "function_call", + call_id: "call_99", + name: "searchDocs", + arguments: "", + status: "in_progress", + } as any, + }; + const toolDeltaA: ResponseFunctionCallArgumentsDeltaEvent = { + type: "response.function_call_arguments.delta", + sequence_number: 2, + item_id: "tool_item_1", + output_index: 0, + delta: '{"query":"vit', + }; + const toolDeltaB: ResponseFunctionCallArgumentsDeltaEvent = { + type: "response.function_call_arguments.delta", + sequence_number: 3, + item_id: "tool_item_1", + output_index: 0, + delta: 'est"}', + }; + const toolDone: ResponseFunctionCallArgumentsDoneEvent = { + type: "response.function_call_arguments.done", + sequence_number: 4, + item_id: "tool_item_1", + output_index: 0, + arguments: '{"query":"vitest"}', + }; + const toolOutputDone: ResponseOutputItemDoneEvent = { + type: "response.output_item.done", + sequence_number: 5, + output_index: 0, + item: { + id: "tool_item_1", + type: "function_call", + call_id: "call_99", + name: "searchDocs", + arguments: '{"query":"vitest"}', + status: "completed", + } as any, + }; + + const chunks = collectChunks([ + toolAdded, + toolDeltaA, + toolDeltaB, + toolDone, + toolOutputDone, + ]); + + expect(chunks[0].choices[0].delta.tool_calls?.[0].function?.arguments).toBe( + '{"query":"vit', + ); + expect(chunks[1].choices[0].delta.tool_calls?.[0].function?.arguments).toBe( + 'est"}', + ); + const toolFinish = chunks[chunks.length - 1]; + expect(toolFinish.choices[0].finish_reason).toBe("tool_calls"); + }); + + it("emits reasoning deltas when reasoning items stream", () => { + const reasoningAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + sequence_number: 1, + output_index: 0, + item: { + id: "reason_1", + type: "reasoning", + summary: [], + content: [], + } as any, + }; + const reasoningDelta: ResponseReasoningTextDeltaEvent = { + type: "response.reasoning_text.delta", + sequence_number: 2, + item_id: "reason_1", + output_index: 0, + content_index: 0, + delta: "First, inspect the repository structure.", + }; + + const chunks = collectChunks([reasoningAdded, reasoningDelta]); + expect(chunks).toHaveLength(1); + expect(chunks[0].choices[0].delta).toMatchObject({ + reasoning: { + content: [ + { + type: "reasoning_text", + text: "First, inspect the repository structure.", + }, + ], + }, + }); + }); +}); + +describe("responseToChatCompletion", () => { + it("converts a completed Responses payload into a ChatCompletion summary", () => { + const response = { + id: "resp_final", + object: "response", + model: "gpt-5-mini", + created_at: 1710000001, + output_text: "Tool call required.", + error: null, + incomplete_details: null, + instructions: null, + metadata: null, + parallel_tool_calls: false, + temperature: null, + tool_choice: null, + tools: [], + usage: { + input_tokens: 100, + input_tokens_details: { cached_tokens: 4 }, + output_tokens: 42, + output_tokens_details: { reasoning_tokens: 10 }, + total_tokens: 142, + }, + output: [ + { + id: "reason_final", + type: "reasoning", + summary: [], + content: [ + { + type: "reasoning_text", + text: "Identify missing unit tests first.", + }, + ], + }, + { + id: "tool_item_final", + type: "function_call", + call_id: "call_final", + name: "searchDocs", + arguments: '{"query":"unit tests"}', + status: "completed", + }, + { + id: "msg_final", + type: "message", + role: "assistant", + content: [ + { + type: "output_text", + text: "Triggering searchDocs tool with the provided query.", + }, + ], + }, + ], + } as unknown as Response; + + const result = responseToChatCompletion(response); + + expect(result.choices[0].message.content).toBe( + "Triggering searchDocs tool with the provided query.", + ); + expect(result.choices[0].message.tool_calls).toEqual([ + { + id: "call_final", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"unit tests"}', + }, + }, + ]); + expect(result.choices[0].finish_reason).toBe("tool_calls"); + expect(result.usage).toEqual({ + prompt_tokens: 100, + completion_tokens: 42, + total_tokens: 142, + }); + }); +});