Merge branch 'main' into sub-agents

This commit is contained in:
uinstinct 2025-12-18 19:22:15 +05:30
commit bcdf0120b1
92 changed files with 8538 additions and 1040 deletions

View file

@ -72,7 +72,7 @@ jobs:
node-version: ${{ matrix.node-version }}
- name: Cache CLI node_modules
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: extensions/cli/node_modules
key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }}

View file

@ -157,19 +157,19 @@ jobs:
node-version-file: ".nvmrc"
- name: Cache core node_modules
uses: actions/cache@v3
uses: actions/cache@v5
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
uses: actions/cache@v5
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
uses: actions/cache@v5
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
@ -294,44 +294,44 @@ jobs:
# Store already-built plugin as an artifact for downloading
- name: Upload artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
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@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-darwin-arm64
path: ./binary/bin/darwin-arm64/
- name: Upload artifact (darwin-x64)
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-darwin-x64
path: ./binary/bin/darwin-x64/
- name: Upload artifact (win32-x64)
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (win32-arm64)
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-win32-arm64
path: ./binary/bin/win32-arm64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-linux-arm64
path: ./binary/bin/linux-arm64/
- name: Upload artifact (linux-x64)
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: continue-binary-linux-x64
path: ./binary/bin/linux-x64/
@ -375,13 +375,13 @@ jobs:
node-version-file: ".nvmrc"
- name: Cache core node_modules
uses: actions/cache@v3
uses: actions/cache@v5
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
uses: actions/cache@v5
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
@ -398,7 +398,7 @@ jobs:
# Download the binary artifact
- name: Download binary artifact
uses: actions/download-artifact@v6
uses: actions/download-artifact@v7
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@v5
uses: actions/upload-artifact@v6
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@v5
uses: actions/upload-artifact@v6
with:
name: tests-result
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
@ -491,7 +491,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2025.2.3
uses: JetBrains/qodana-action@v2025.2.4
with:
cache-default-branch-only: true
@ -528,7 +528,7 @@ jobs:
# Cache Plugin Verifier IDEs
- name: Setup Plugin Verifier IDEs Cache
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides
key: plugin-verifier-${{ hashFiles('build/printProductsReleases.txt') }}
@ -540,7 +540,7 @@ jobs:
# Collect Plugin Verifier Result
- name: Collect Plugin Verifier Result
if: ${{ always() }}
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
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@v6
uses: actions/download-artifact@v7
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./build/distributions/

View file

@ -101,7 +101,7 @@ jobs:
echo "✅ Successfully downloaded artifact"
- name: Republish as main branch artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: vscode-extension-build-${{ matrix.platform }}
path: ./temp-download/*

View file

@ -99,7 +99,7 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
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@v6
- uses: actions/download-artifact@v7
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@v6
- uses: actions/download-artifact@v7
with:
pattern: "*-vsix"
path: vsix-artifacts

View file

@ -71,7 +71,7 @@ jobs:
${{ steps.read-metrics.outputs.metrics_content }}
- name: Upload metrics report as artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: issue-metrics-report
path: ./issue_metrics.md

View file

@ -39,13 +39,13 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }}
path: extensions/vscode/build
- name: Upload .vsix artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"

View file

@ -27,7 +27,7 @@ jobs:
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
- uses: actions/cache@v5
id: root-cache
with:
path: node_modules
@ -234,26 +234,26 @@ jobs:
node-version-file: ".nvmrc"
- name: Cache npm
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: ~/.npm
key: ${{ runner.os }}-npm-cache-matrix-${{ hashFiles('core/package-lock.json', 'extensions/vscode/package-lock.json') }}
- name: Cache packages node_modules
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: |
packages/*/node_modules
key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }}
- name: Cache core node modules
uses: actions/cache@v4
uses: actions/cache@v5
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: Cache vscode extension node modules
uses: actions/cache@v4
uses: actions/cache@v5
id: vscode-cache
with:
path: extensions/vscode/node_modules
@ -303,7 +303,7 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: vscode-extension-build-Linux
path: extensions/vscode/build

View file

@ -83,7 +83,7 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
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@v6
- uses: actions/download-artifact@v7
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@v6
- uses: actions/download-artifact@v7
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -183,7 +183,7 @@ jobs:
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
uses: peter-evans/create-pull-request@v8
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"

View file

@ -39,4 +39,4 @@ jobs:
"repoUrl": "https://github.com/${{ github.repository }}"
}')
id=$(echo $response | jq -r '.id')
echo "https://hub.continue.dev/agents/$id"
echo "https://hub.continue.dev/hub?type=agents/$id"

View file

@ -1,5 +1,5 @@
{
"name": "cn-test",
"name": "cn",
"dockerfile": "FROM runloop:runloop/universal-ubuntu-24.04-x86_64-dnd",
"system_setup_commands": [
"npm i -g @continuedev/cli@latest",
@ -20,6 +20,7 @@
"launch_parameters": {
"launch_commands": [
"export DISPLAY=:99",
"export PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium",
"nohup Xvfb :99 -screen 0 1920x1080x24 > /tmp/xvfb.log 2>&1 &",
"sleep 2",
"sudo mkdir -p /home/user",

View file

@ -1,9 +1,6 @@
name: Stable Release
on:
schedule:
# Run every Monday at 10am UTC (1 hour after beta release)
- cron: "0 10 * * 1"
workflow_dispatch:
inputs:
release_type:

3
.gitignore vendored
View file

@ -176,3 +176,6 @@ keys
.channels_cache.json
.users_cache.json
.copy-status
.copy-log

3
.vscode/launch.json vendored
View file

@ -140,7 +140,8 @@
"args": [],
"runtimeArgs": ["--enable-source-maps"],
"env": {
"NODE_ENV": "development"
"NODE_ENV": "development",
"USE_VERCEL_AI_SDK_ANTHROPIC": "true"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"

View file

@ -31,7 +31,7 @@
</div>
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)
Get started in [Mission Control](https://hub.continue.dev/hub?type=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)
### Quick Install

View file

@ -101,21 +101,22 @@ async function buildWithEsbuild() {
),
);
const copyLanceDBPromises = [];
// Install LanceDB packages sequentially to avoid race conditions
// when multiple packages copy to the same node_modules/@lancedb directory
for (const target of targets) {
if (!TARGET_TO_LANCEDB[target]) {
continue;
}
console.log(`[info] Downloading for ${target}...`);
copyLanceDBPromises.push(
installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb"),
);
console.log(`[info] Downloading LanceDB for ${target}...`);
try {
await installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb");
console.log(`[info] Copied LanceDB for ${target}`);
} catch (err) {
console.error(`[error] Failed to copy LanceDB for ${target}:`, err);
process.exit(1);
}
}
await Promise.all(copyLanceDBPromises).catch(() => {
console.error("[error] Failed to copy LanceDB");
process.exit(1);
});
console.log("[info] Copied all LanceDB");
console.log("[info] All LanceDB packages installed");
// tree-sitter-wasm
const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms");

1
core/index.d.ts vendored
View file

@ -1517,6 +1517,7 @@ export interface RangeInFileWithNextEditInfo {
filepath: string;
range: Range;
fileContents: string;
fileContentsBefore: string;
editText: string;
afterCursorPos: Position;
beforeCursorPos: Position;

View file

@ -38,11 +38,7 @@ export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
// Credential and secret files
"*.secret",
"*.secrets",
"credentials",
"credentials.*",
"auth.json",
"token",
"token.*",
"*.token",
// Backup files that might contain sensitive data

View file

@ -47,10 +47,7 @@ describe("isSecurityConcern", () => {
it("should detect credential files as security concerns", () => {
expect(isSecurityConcern("app.secret")).toBe(true);
expect(isSecurityConcern("api.secrets")).toBe(true);
expect(isSecurityConcern("credentials")).toBe(true);
expect(isSecurityConcern("credentials.json")).toBe(true);
expect(isSecurityConcern("auth.json")).toBe(true);
expect(isSecurityConcern("token")).toBe(true);
expect(isSecurityConcern("api.token")).toBe(true);
expect(isSecurityConcern("access.token")).toBe(true);
});
@ -183,6 +180,17 @@ describe("isSecurityConcern", () => {
expect(isSecurityConcern("secret-utils.js")).toBe(false);
expect(isSecurityConcern("token-validator.ts")).toBe(false);
});
it("should not flag legitimate source files with token/credentials in name", () => {
expect(isSecurityConcern("tokens.py")).toBe(false);
expect(isSecurityConcern("tokens.go")).toBe(false);
expect(isSecurityConcern("tokens.js")).toBe(false);
expect(isSecurityConcern("credentials.py")).toBe(false);
expect(isSecurityConcern("credentials.go")).toBe(false);
expect(isSecurityConcern("credentials.ts")).toBe(false);
expect(isSecurityConcern("token_manager.py")).toBe(false);
expect(isSecurityConcern("credential_helper.js")).toBe(false);
});
});
describe("Edge cases", () => {

View file

@ -235,7 +235,7 @@ describe("LLM", () => {
model: "gemini-2.0-flash-exp",
apiKey: process.env.GEMINI_API_KEY,
}),
{ skip: false },
{ skip: true }, // Skipped - @google/genai getReader issue
);
testLLM(
new Mistral({
@ -253,7 +253,7 @@ describe("LLM", () => {
deployment: "azure-openai-deployment",
apiType: "azure-openai",
}),
{ testFim: false, skip: false, timeout: 20000 },
{ testFim: false, skip: true, timeout: 20000 }, // Skipped - timing out in CI
);
testLLM(
new Azure({
@ -262,6 +262,6 @@ describe("LLM", () => {
apiBase: "https://continue-foundry-resource.services.ai.azure.com",
env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" },
}),
{ testFim: false, skip: false, timeout: 20000 },
{ testFim: false, skip: true, timeout: 20000 }, // Skipped - timing out in CI
);
});

View file

@ -21,6 +21,7 @@ import { AutocompleteInput } from "../autocomplete/util/types.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { EditAggregator } from "./context/aggregateEdits.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
import { NextEditLoggingService } from "./NextEditLoggingService.js";
@ -399,13 +400,28 @@ export class NextEditProvider {
opts?.usingFullFileDiff ?? false,
);
// Build diffContext including in-progress edits
// The finalized diffs are in this.diffContext, but we also need to include
// any in-progress edits that haven't been finalized yet (the user's most recent typing)
const combinedDiffContext = [...this.diffContext];
try {
const inProgressDiff = EditAggregator.getInstance().getInProgressDiff(
helper.filepath,
);
if (inProgressDiff) {
combinedDiffContext.push(inProgressDiff);
}
} catch (e) {
// EditAggregator may not be initialized yet, ignore
}
// Build context for model-specific prompt generation.
const context: ModelSpecificContext = {
helper,
snippetPayload,
editableRegionStartLine,
editableRegionEndLine,
diffContext: this.diffContext,
diffContext: combinedDiffContext,
autocompleteContext: this.autocompleteContext,
historyDiff: createDiff({
beforeContent:

View file

@ -124,7 +124,7 @@ export class EditAggregator {
if (!this.fileStates.has(filePath)) {
this.fileStates.set(filePath, {
activeClusters: [],
currentContent: edit.fileContents,
currentContent: edit.fileContents, // Post-edit content (will be updated correctly by _processEditInternal)
priorComparisons: [],
processingQueue: [],
isProcessing: false,
@ -218,8 +218,12 @@ export class EditAggregator {
// initialize a cluster
if (!suitableCluster) {
// Use fileContentsBefore if available (tracked by VS Code extension),
// otherwise fall back to current content
const beforeState = edit.fileContentsBefore ?? fileState.currentContent;
suitableCluster = {
beforeState: fileState.currentContent,
beforeState,
startRange: {
minLine: Math.max(0, editLine - this.config.contextLines),
maxLine: Math.min(
@ -573,4 +577,52 @@ export class EditAggregator {
this.fileStates.clear();
this.lastProcessedFilePath = null;
}
/**
* Gets the in-progress diff for a file by comparing the earliest active cluster's
* beforeState with the current file content.
* This captures edits that haven't been finalized yet.
*
* @param filePath The file path to get the in-progress diff for
* @returns The unified diff string if there are active clusters, or null otherwise
*/
getInProgressDiff(filePath: string): string | null {
const fileState = this.fileStates.get(filePath);
if (!fileState || fileState.activeClusters.length === 0) {
return null;
}
// Get the earliest active cluster (first edit that started this batch of typing)
const earliestCluster = fileState.activeClusters.reduce(
(earliest, cluster) =>
cluster.firstTimestamp < earliest.firstTimestamp ? cluster : earliest,
);
const beforeContent = earliestCluster.beforeState;
const afterContent = fileState.currentContent;
// Skip if the content is the same
if (beforeContent === afterContent) {
return null;
}
// Skip whitespace-only diffs
if (
beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "")
) {
return null;
}
// Get workspaceDir from the first edit in the cluster (for consistent path formatting)
const workspaceDir = earliestCluster.edits[0]?.workspaceDir;
return createDiff({
beforeContent,
afterContent,
filePath,
diffType: DiffFormatType.Unified,
contextLines: 3,
workspaceDir,
});
}
}

View file

@ -1,5 +1,6 @@
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
import { getUriPathBasename } from "../../util/uri.js";
import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js";
import {
currentFileContentBlock,
@ -58,7 +59,7 @@ export class MercuryCoderProvider extends BaseNextEditModelProvider {
editableRegionStartLine: context.editableRegionStartLine,
editableRegionEndLine: context.editableRegionEndLine,
editDiffHistory: context.diffContext,
currentFilePath: context.helper.filepath,
currentFilePath: getUriPathBasename(context.helper.filepath),
};
}

View file

@ -17,7 +17,7 @@ export const NEXT_EDIT_MODEL_TEMPLATES: Record<
NextEditTemplate
> = {
"mercury-coder": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\ncurrent_file_path: {{{currentFilePath}}}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
},
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,

View file

@ -39,6 +39,7 @@ describe("NextEditPromptEngine", () => {
expect(template).toContain("{{{recentlyViewedCodeSnippets}}}");
expect(template).toContain("{{{currentFileContent}}}");
expect(template).toContain("{{{editDiffHistory}}}");
expect(template).toContain("{{{currentFilePath}}}");
});
it("instinct template should contain expected tokens", () => {
@ -87,11 +88,13 @@ describe("NextEditPromptEngine", () => {
recentlyViewedCodeSnippets: "snippet1",
currentFileContent: "file content",
editDiffHistory: "diff history",
currentFilePath: "file.py",
});
expect(result).toContain("snippet1");
expect(result).toContain("file content");
expect(result).toContain("diff history");
expect(result).toContain("current_file_path: file.py");
});
});

2475
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -55,9 +55,9 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-bedrock-runtime": "^3.931.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
"@aws-sdk/credential-providers": "^3.931.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "file:../packages/fetch",

View file

@ -16,9 +16,9 @@ sidebarTitle: "Create & Edit"
<Steps>
<Step title="🧭 Navigate to Create Agent">
From the Continue Mission Control top navigation bar, select **"+"** → **"New Agent"**.
Navigate to the [New Agent page](https://hub.continue.dev/new?type=agent).
This opens the **Create an Agent (beta)** form with all required fields.
This opens the **Create an Agent** form with all required fields.
</Step>
@ -30,9 +30,9 @@ sidebarTitle: "Create & Edit"
| **Name** | Display name shown in Mission Control | `GitHub PR Agent` |
| **Prompt** | First instruction the agent receives | `Open a GitHub PR to fix the specified issue.` |
| **Description** | What the agent does | `Creates a pull request and includes AI-generated summaries.` |
| **Tools (MCPs)** | Select built-in or custom MCPs | `GitHub, PostHog, Supabase` |
| **Rules** | Add any organizational rules | `continuedev/gh-pr-commit-workflow, continuedev/summarization` |
| **Model** | Choose a default LLM | `Claude Sonnet 4.5` |
| **Tools ([MCPs](https://hub.continue.dev/hub?type=mcpServers))** | Select built-in or custom MCPs | `GitHub, PostHog, Supabase` |
| **[Rules](https://hub.continue.dev/hub?type=rules)** | Add any organizational rules | `continuedev/gh-pr-commit-workflow` |
| **[Model](https://hub.continue.dev/hub?type=models)** | Choose a default LLM | `Claude Sonnet 4.5` |
| **Owner + Slug** | Determines namespace | `my-org/github-pr-agent` |
| **Visibility** | Access level | `Public, Organization, or Private` |
@ -70,8 +70,7 @@ sidebarTitle: "Create & Edit"
## Editing an Agent
You can edit any agent you own or that belongs to your organization.
You can edit any agent you own or that has Organization-level access.
<Steps>
<Step title="🧭 Access the Agent">
From the **Agents** page or Mission Control view, click your agent's name, then select **"Edit Agent"**.

View file

@ -23,7 +23,7 @@ Use Mission Control to kick off agents for:
<Steps>
<Step title="Access Mission Control">
Go to [hub.continue.dev/agents](https://hub.continue.dev/agents) and connect with your GitHub account.
Go to [Mission Control Agents](https://hub.continue.dev/hub?type=agents) and connect with your GitHub account.
![Mission Control Setup](/images/hub/workflows/images/workflows-setup.png)
</Step>
@ -45,7 +45,7 @@ Use Mission Control to kick off agents for:
</Step>
<Step title="Run Your First Agent">
Enter a prompt and watch your agent work:
Enter additional instructions and watch your agent work:
```
"Fix the TypeError in api/users.ts and open a PR with tests"
@ -79,7 +79,7 @@ Before creating your own agent, let's see one in action! The fastest way to expe
</Step>
<Step title="🎯 Access Mission Control">
Go to [hub.continue.dev/agents](https://hub.continue.dev/agents) and:
Go to [Mission Control Agents](https://hub.continue.dev/hub?type=agents) and:
- **Connect GitHub** and authorize Continue when prompted
- This gives agents access to create PRs in your repositories
</Step>
@ -203,7 +203,7 @@ Choose the method that fits your workflow:
- Team collaboration
- One-time tasks
Access at [hub.continue.dev/agents](https://hub.continue.dev/agents)
Access at [hub.continue.dev/agents](https://hub.continue.dev/hub?type=agents)
</Tab>
<Tab title="💻 CLI (TUI Mode)">

View file

@ -67,7 +67,7 @@ You can run Agents in three main ways:
Run one-off or scheduled tasks automatically without interaction.
```bash
cn -p --agent my-org/snyk-agent "Run weekly security scan" --auto
cn -p --agent my-org/snyk-agent "Run weekly security scan"
```
Perfect for: CI/CD pipelines, scheduled tasks, webhook integrations
@ -79,34 +79,52 @@ You can run Agents in three main ways:
Skip the setup and use battle-tested agents from our cookbook collection:
<CardGroup cols={2}>
<Card title="🔒 Security Scanning" icon="shield-check" href="/guides/snyk-mcp-continue-cookbook">
<Card title="🔒 Security Scanning" icon="shield-check" href="https://hub.continue.dev/continuedev/snyk-continuous-ai-agent">
`continuedev/snyk-continuous-ai-agent`
Finds vulnerabilities and opens PRs with fixes
</Card>
<Card title="🐛 GitHub Management" icon="github" href="/guides/github-mcp-continue-cookbook">
<Card title="🐛 GitHub Management" icon="github" href="https://hub.continue.dev/continuedev/github-project-manager-agent">
`continuedev/github-project-manager-agent`
Triages issues and manages project workflows
</Card>
<Card title="📊 Analytics Insights" icon="chart-bar" href="/guides/posthog-github-continuous-ai">
<Card title="📊 Analytics Insights" icon="chart-bar" href="https://hub.continue.dev/continuedev/posthog-continuous-ai-agent">
`continuedev/posthog-continuous-ai-agent`
Analyzes user data and creates actionable tasks
</Card>
<Card title="⚡ Performance Optimization" icon="gauge-high" href="/guides/netlify-mcp-continuous-deployment">
<Card title="⚡ Performance Optimization" icon="gauge-high" href="https://hub.continue.dev/continuedev/netlify-continuous-ai-agent">
`continuedev/netlify-continuous-ai-agent`
Monitors Core Web Vitals and optimizes deployments
</Card>
<Card title="🗄️ Database Auditing" icon="database" href="/guides/supabase-mcp-database-workflow">
<Card title="🗄️ Database Auditing" icon="database" href="https://hub.continue.dev/continuedev/supabase-agent">
`continuedev/supabase-agent`
Audits RLS security and generates migrations
</Card>
<Card title="🔄 Data Pipelines" icon="arrows-rotate" href="/guides/dlt-mcp-continue-cookbook">
<Card title="🔄 Data Pipelines" icon="arrows-rotate" href="https://hub.continue.dev/continuedev/dlt-agent">
`continuedev/dlt-agent`
Inspects pipelines and debugs load errors
</Card>
</CardGroup>
@ -222,7 +240,7 @@ The practice of using cloud agents, which we call Continuous AI, requires foreth
Learn to run agents from the command line
</Card>
<Card title="Mission Control" icon="desktop" href="https://hub.continue.dev/agents">
<Card title="Mission Control" icon="desktop" href="https://hub.continue.dev/hub?type=agents">
Access the web interface to manage agents
</Card>
</CardGroup>

View file

@ -12,7 +12,11 @@ import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
- **[Embedding](/customize/model-roles/embeddings)**: Transform code into vector representations for semantic search
- **[Reranker](/customize/model-roles/reranking)**: Improve search relevance by ordering results based on semantic meaning
![Models Overview](/images/customize/images/model-blocks-overview-36c30e7e01928d7a9b5b26ff1639c34b.png)
<Tip>
When creating an agent, you can choose the model for a [new task in Mission Control](https://dub.sh/mc-task) or [workflow](https://dub.sh/agent-workflow).
If no model is specified, Continue automatically uses the default agent with our recommended model.
</Tip>
## Recommended Models
@ -20,6 +24,10 @@ import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
<ModelRecommendations role="all" />
<Info>
Explore models in [The Hub](https://hub.continue.dev/hub?type=models).
</Info>
## Learn More About Models
Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.

View file

@ -1,6 +1,7 @@
---
title: "Telemetry"
description: "Learn about Continue's anonymous telemetry collection practices, what usage data is collected, and how to opt out if you prefer not to share your usage information"
icon: "chart-line"
description: "Learn about Continue's anonymous telemetry collection practices, what usage data is tracked, and how to opt out of data collection to maintain your privacy preferences"
---
## Overview
@ -25,6 +26,25 @@ The following usage information is collected and reported:
## How to Opt Out
### IDE extensions
You can disable anonymous telemetry by toggling "Allow Anonymous Telemetry" off in the user settings.
#### VS Code
Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut `ctrl` + `,` on Windows/Linux or `cmd` + `,` on macOS).
### CLI
For `cn`, the Continue CLI, set the environment variable `CONTINUE_TELEMETRY_ENABLED=0` before running commands:
```bash
export CONTINUE_TELEMETRY_ENABLED=0
cn <your prompt>
```
Or run it inline:
```bash
CONTINUE_TELEMETRY_ENABLED=0 cn <your prompt>
```

View file

@ -37,7 +37,10 @@
"mission-control/integrations/github",
"mission-control/integrations/sentry",
"mission-control/integrations/snyk",
"mission-control/integrations/slack-agent"
"mission-control/integrations/slack-agent",
"mission-control/integrations/posthog",
"mission-control/integrations/atlassian",
"mission-control/integrations/netlify"
]
},
"mission-control/metrics",

View file

@ -13,6 +13,12 @@ sidebarTitle: "Atlassian Workflows with Continue"
- Automate Atlassian workflows with headless CLI runs
</Card>
<Info>
The new [Atlassian Mission Control Integration](/mission-control/integrations/atlassian) enables **[Continuous AI](/guides/continuous-ai)** for project management and documentation - where AI agents autonomously manage Jira issues, sync Confluence documentation, and streamline development workflows. This cookbook focuses on CLI-based workflows, but you can also deploy autonomous agents through Mission Control.
**Get Started:** Use this cookbook to understand Atlassian MCP fundamentals, then [enable Mission Control](/mission-control/integrations/atlassian) to deploy autonomous project management agents across your organization.
</Info>
## Prerequisites
Before starting, ensure you have:

View file

@ -10,6 +10,12 @@ sidebarTitle: "Using Netlify MCP for Performance Optimization"
from Netlify Analytics
</Card>
<Info>
The new [Netlify Mission Control Integration](/mission-control/integrations/netlify) enables **[Continuous AI](/guides/continuous-ai)** for deployment automation - where AI agents autonomously manage deployments, monitor site performance, and respond to deployment events. This cookbook focuses on CLI-based performance optimization workflows, but you can also deploy autonomous deployment agents through Mission Control.
**Get Started:** Use this cookbook to understand Netlify MCP fundamentals, then [enable Mission Control](/mission-control/integrations/netlify) to deploy autonomous deployment management agents across your organization.
</Info>
<Info>
**Did You Know?** Netlify is more than just static hosting! It offers:
- [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches

View file

@ -9,6 +9,12 @@ sidebarTitle: "PostHog Analytics with Continue CLI"
issues with the GitHub CLI.
</Card>
<Info>
The new [PostHog Mission Control Integration](/mission-control/integrations/posthog) enables **[Continuous AI](/guides/continuous-ai)** for product analytics - where AI agents autonomously analyze user behavior, identify optimization opportunities, and create data-driven development tasks. This cookbook focuses on CLI-based workflows, but you can also deploy autonomous agents through Mission Control.
**Get Started:** Use this cookbook to understand PostHog analytics fundamentals, then [enable Mission Control](/mission-control/integrations/posthog) to deploy autonomous analytics-driven agents across your organization.
</Info>
## What You'll Learn
This cookbook teaches you to:
@ -165,13 +171,16 @@ You only need to configure the PostHog MCP credential - it automatically handles
<Tab title="🛠️ Manual Setup">
<Steps>
<Step title="Add PostHog MCP to Continue CLI">
First, install the [PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp) or run:
```bash
npx -y mcp-remote@latest https://mcp.posthog.com/sse --header Authorization:${{ secrets.continuedev/awesome-models-posthog-gh/posthog/posthog-mcp/POSTHOG_AUTH_HEADER }}
```
First, install the [PostHog MCP](https://hub.continue.dev/posthog/http-mcp) to the Continue CLI by
1. Adding it to a Hub Config by clicking "Use MCP Server" and selecting a Config
2. Adding it to your [Local Config](/reference#mcpservers)
</Step>
<Step title="Add PostHog + GitHub Analysis Rules">
In the Continue Mission Control, add the [PostHog GitHub Continuous AI Rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules) to your account for better formatting and error handling.
Visit [PostHog GitHub Continuous AI Rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules) and click "Use Rule" to add it to your Config.
You could also
1. Pass `--rule bekah-hawrot-weigel/posthog-github-continuous-ai-rules` to `cn` OR
2. Copy the rules to your local `.continue/rules` folder. See the [Rules Guide](/customize/deep-dives/rules#how-to-create-and-manage-rules-in-continue).
</Step>
<Step title="Create Your Custom Prompts">
Use this prompt with Continue CLI to analyze PostHog data and create GitHub issues:

View file

@ -6,7 +6,7 @@ sidebarTitle: "Create a Config"
## How to Create a Config from Scratch
To create an config from scratch, select “New config” in the top bar.
To create a config from scratch, navigate to [your config settings](https://hub.continue.dev/settings/configs).
Choose a name, slug, description, and icon for your config.

View file

@ -43,7 +43,7 @@ Configs are flexible containers that combine multiple components to create power
## How Configs Work
Think of configs as recipes for AI assistance. Each config defines:
Each config defines:
- **What models** to use for different tasks (chat, autocomplete, code editing)
- **Which tools** are available through MCP servers
@ -56,7 +56,7 @@ This flexibility lets you create specialized setups for different contexts, like
When creating configs, you can set visibility levels:
- **Personal**: Only you can see and use the config
- **Private**: Only you (and your org admins) can see and use the config
- **Public**: Anyone can discover and use your config
- **Organization**: Members of your organization can access the config

View file

@ -1,6 +1,6 @@
---
title: "Pricing"
description: "Continue Mission Control pricing plans for individuals, teams, and enterprises, including the Models Add-On that provides access to frontier AI models for a flat monthly fee"
url: "https://hub.continue.dev/pricing"
---
## Solo

View file

@ -120,7 +120,7 @@ Agents are built from reusable components that you can create, share, and custom
<Tip>
Components are the building blocks for agents that you can create new or remix from an existing component. When you create a component in mission control, it becomes available according to the permissions you set: Personal, Public, or Organization.
When you create a component for your agent in Mission Control, it becomes available according to the permissions you set: Personal, Public, or Organization.
</Tip>

View file

@ -0,0 +1,302 @@
---
title: "Atlassian Integration"
description: "Connect Jira, Confluence, and Compass to automate project management with Continue Agents"
---
## Overview
Connect Jira, Confluence, and Compass to Continue Mission Control to enable agents to manage issues, search tickets, summarize pages, and bulk-process tasks using natural language. When Atlassian is enabled, Continue can automatically translate technical code changes into business-friendly updates, keeping stakeholders informed.
<Card title="What You Can Do with Atlassian Integration" icon="diagram-project">
- Automatically update Jira tickets with business-friendly summaries on PR merge
- Search issues and create tickets using natural language
- Summarize Confluence pages and documentation
- Bulk-process tasks across multiple tickets
- Triage incoming issues automatically
- Generate documentation from code changes
- Track development progress with stakeholder-friendly language
</Card>
## Setup
<Steps>
<Step title="Navigate to Integrations">
Go to your [Atlassian Integration Settings](https://hub.continue.dev/integrations/atlassian).
</Step>
<Step title="Connect Atlassian">
Click "Connect" to Atlassian.
</Step>
<Step title="Authorize Continue">
In the Atlassian authorization screen:
1. Log into your Atlassian account
2. Review the requested permissions
3. Click "Authorize" to complete the connection
</Step>
</Steps>
## Workflows
### Update Jira Tickets
**Trigger**: On PR merge
**Description**: Connect Jira, Confluence, and Compass to your agents. Search issues, create tickets, summarize pages, and bulk-process tasks with natural language.
When a pull request is merged, this workflow automatically:
1. **Extracts Jira Ticket ID** - Finds the ticket reference from:
- PR title (e.g., `[PROJ-123] Add feature`)
- Branch name (e.g., `feature/PROJ-123-description`)
- PR description or comments
2. **Analyzes Code Changes** - Reviews the merged PR to identify:
- What changed (files, features, components)
- Why it matters (business value, problem solved)
- Impact (user-facing changes, performance improvements)
- Risk level (Low/Medium/High based on scope)
3. **Creates Business Summary** - Translates technical changes into clear, non-technical language:
- Focuses on **outcomes over implementation**
- Highlights **business value** and user benefits
- Uses **plain language** avoiding technical jargon
- Explains who benefits and how
4. **Updates Jira Ticket** - Posts a formatted comment with:
- Business-friendly summary of what was accomplished
- Key changes in business terms
- Impact on users or stakeholders
- Technical metadata (files changed, merge details, PR link)
5. **Comments on PR** - Adds a link back to the updated Jira ticket
<Card title="Why This Matters" icon="users">
Technical code changes are often difficult for stakeholders to understand. This workflow bridges the gap between development and business by:
- Keeping product managers informed without technical details
- Providing business stakeholders with clear progress updates
- Reducing manual ticket updates for developers
- Creating a clear audit trail of work completed
</Card>
<Info>
**Smart Translation**: The agent automatically converts technical terms into business language. For example, "Refactored authentication module" becomes "Users can now stay logged in longer without interruptions."
</Info>
## Use Cases
You can also create your own Atlassian-connected agents in Mission Control. Here are some examples for these use cases:
<Columns cols={2}>
<Card title="Issue Creator Agent" icon="ticket">
**Task Example**: "Create Jira tickets for all TODO comments in the codebase with priority based on code location"
**What the Agent Does**:
- Scans codebase for TODO and FIXME comments
- Creates Jira issues with relevant context
- Links issues to code files and line numbers
- Assigns priority based on file criticality
**Run in Mission Control**: Schedule weekly or after major releases
</Card>
Streamline sprint planning with intelligent automation:
<Card title="Sprint Planner Agent" icon="calendar-days">
**Task Example**: "Analyze backlog items and create a proposed sprint plan based on team velocity and priorities"
**What the Agent Does**:
- Reviews open Jira issues and their estimates
- Considers team capacity and historical velocity
- Groups related tickets together
- Creates a proposed sprint with balanced workload
**Run in Mission Control**: Run before sprint planning meetings
</Card>
<Card title="Docs Sync Agent" icon="book-open">
**Task Example**: "Update Confluence API documentation to match current OpenAPI spec"
**What the Agent Does**:
- Parses API specifications from codebase
- Compares with existing Confluence documentation
- Updates or creates Confluence pages with changes
- Notifies team of significant API changes
**Run in Mission Control**: Trigger on API spec changes or schedule weekly
</Card>
<Card title="Release Notes Agent" icon="megaphone">
**Task Example**: "Generate release notes from closed Jira tickets since last release and publish to Confluence"
**What the Agent Does**:
- Queries Jira for tickets closed since last release
- Categorizes changes (features, fixes, improvements)
- Generates formatted release notes
- Creates or updates Confluence release page
**Run in Mission Control**: Trigger manually before releases
</Card>
<Card title="Project Health Agent" icon="chart-line">
**Task Example**: "Analyze current sprint progress and identify blocked or at-risk items"
**What the Agent Does**:
- Reviews sprint board status
- Identifies tickets without recent updates
- Flags dependencies and blockers
- Generates summary report in Confluence
**Run in Mission Control**: Schedule daily during active sprints
</Card>
</Columns>
## Running Atlassian Agents in Mission Control
You can run Supabase-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows):
<Tip>
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
## Optional Workflow Enhancements
<AccordionGroup>
<Accordion title="Smart Tagging">
Automatically add Jira labels based on code changes:
- `frontend-update` - UI/UX changes detected
- `backend-update` - API or database changes
- `bugfix` - Resolves bugs or issues
- `feature` - New functionality added
- `security` - Security improvements
- `performance` - Performance optimizations
</Accordion>
<Accordion title="Stakeholder Mentions">
Tag relevant people in Jira based on components modified:
- Payment processing changes → `@finance-team`
- User interface changes → `@product-manager`
- Security updates → `@security-lead`
- API modifications → `@api-architect`
</Accordion>
<Accordion title="Release Notes Generation">
Accumulate business-friendly summaries for release documentation:
- Store formatted summaries in `.release-notes/{version}/`
- Automatically compile summaries into Confluence release pages
- Generate customer-facing changelog from Jira updates
- Include impact metrics and user benefits
</Accordion>
<Accordion title="Metrics Tracking">
Log metadata for reporting and analytics:
- Time from ticket creation to PR merge
- Number of files changed per ticket
- Business impact category (high/medium/low)
- Stakeholder engagement (comments, mentions)
- Risk level distribution across releases
</Accordion>
</AccordionGroup>
## Troubleshooting
<Accordion title="Authentication failures">
**Problem**: Agent can't connect to Atlassian services
**Solutions**:
- Verify API token hasn't expired
- Check that email matches the token's account
- Ensure domain includes `.atlassian.net`
- Regenerate token if necessary
</Accordion>
<Accordion title="Permission denied errors">
**Problem**: Agent can't create or update items
**Solutions**:
- Verify your Atlassian account has appropriate permissions
- Check project-level permissions in Jira
- Ensure space permissions are correct in Confluence
- Contact your Atlassian admin if needed
</Accordion>
<Accordion title="Issues not found or accessible">
**Problem**: Agent reports Jira issues don't exist
**Solutions**:
- Verify issue keys are correct (e.g., PROJECT-123)
- Check that you have access to the project
- Ensure issues aren't in a restricted project
- Verify your API token has read access
</Accordion>
<Accordion title="Confluence pages not updating">
**Problem**: Documentation changes aren't reflected in Confluence
**Solutions**:
- Check that you have edit permissions for the space
- Verify page IDs are correct
- Ensure Confluence Cloud API is accessible
- Review agent logs for specific error messages
</Accordion>
<Accordion title="Rate limiting errors">
**Problem**: Agent hits Atlassian API rate limits
**Solutions**:
- Reduce frequency of automated workflows
- Batch operations where possible
- Implement exponential backoff in agent logic
- Consider upgrading Atlassian plan for higher limits
</Accordion>
## Resources
<Card title="Atlassian MCP Cookbook" icon="book-open" href="/guides/atlassian-mcp-continue-cookbook">
Comprehensive guide to project management automation with Atlassian and Continue
</Card>

View file

@ -166,7 +166,7 @@ You can run GitHub-connected agents in two ways:
Trigger agents on-demand for specific tasks:
1. Go to [Mission Control Agents](https://hub.continue.dev/agents)
1. Go to [Mission Control Agents](https://hub.continue.dev/hub?type=agents)
2. Select or create a GitHub-enabled agent
3. Click "Run Agent" and provide your task description
4. Monitor progress and review results in real-time

View file

@ -1,6 +1,6 @@
---
title: "Overview"
description: "Connect GitHub, Slack, Sentry, and Snyk to power richer Agents, Tasks, and Workflows."
description: "Connect GitHub, Slack, Sentry, Snyk, PostHog, Atlassian, and Netlify to power richer Agents, Tasks, and Workflows."
sidebarTitle: "Overview"
---
@ -8,7 +8,7 @@ sidebarTitle: "Overview"
Integrations let Continue connect to the tools you already use, so Agents can read code, open pull requests, send messages, react to real-world events, and more.
</Info>
Mission Control currently supports four first-class integrations:
Mission Control currently supports these first-class integrations:
<CardGroup cols={2}>
@ -20,7 +20,7 @@ Mission Control currently supports four first-class integrations:
Mention @continue to kick off Agents directly from Slack.
</Card>
<Card title="Sentry" icon="alert-triangle" href="/mission-control/integrations/sentry">
<Card title="Sentry" icon="bug" href="/mission-control/integrations/sentry">
Trigger Agents automatically when new Sentry issues appear.
</Card>
@ -28,10 +28,28 @@ Mission Control currently supports four first-class integrations:
Detect and fix security vulnerabilities automatically.
</Card>
<Card title="PostHog" icon="chart-line" href="/mission-control/integrations/posthog">
Detect telemetry changes in merged PRs and creates or updates corresponding dashboards.
</Card>
<Card title="Atlassian" icon="atlassian" href="/mission-control/integrations/atlassian">
Connect Jira and Confluence to automate project management and docs.
</Card>
<Card title="Netlify" icon="gauge-high" href="/mission-control/integrations/netlify">
Optimize site by comparing performance on PR preview and production Netlify deploys.
</Card>
<Card title="Sanity" icon="database" href="/mission-control/integrations/sanity">
Set up workflows that validate content and schemas on every PR.
</Card>
<Card title="Supabase" icon="server" href="/mission-control/integrations/supabase">
Monitor database performance, generate migrations, and optimize queries automatically.
</Card>
</CardGroup>
## Next Steps
<Card title="Try out an Integration" icon="laptop" href="https://hub.continue.dev/integrations">
<Card title="Try out an Integration" icon="laptop" href="https://hub.continue.dev/integrations">
Connect your favorite tools to Mission Control and unlock new Agent capabilities.
</Card>

View file

@ -0,0 +1,395 @@
---
title: "Netlify Integration"
description: "Give your agents access to Netlify's API and CLI to manage deployments and optimize website performance"
---
## Overview
Connect Netlify to Continue Mission Control to give your agents access to Netlify's API and CLI. Create projects, deploy applications, configure domains, and manage infrastructure with natural language. When Netlify is enabled, Continue can analyze bundle sizes, audit performance, and prevent performance regressions.
<Card title="What You Can Do with Netlify Integration" icon="bolt">
- Run Lighthouse audits on PR previews and production
- Compare bundle sizes and analyze performance regressions
- Automatically detect configuration issues (minification, caching, tree-shaking)
- Block PRs that introduce critical performance problems
- Generate detailed performance reports with actionable fixes
- Create projects and manage domains with natural language
- Configure build settings and environment variables
</Card>
## Setup
<Steps>
<Step title="Navigate to Integrations">
Go to your [Integrations Settings](https://hub.continue.dev/integrations).
</Step>
<Step title="Connect Netlify">
Click "Connect" next to Netlify. You'll need:
- **Personal Access Token**: Generate from Netlify account settings
</Step>
<Step title="Generate Netlify Access Token">
To create a personal access token:
1. Log into your [Netlify account](https://app.netlify.com)
2. Go to **User Settings** → **Applications** → **Personal access tokens**
3. Click "New access token"
4. Give it a descriptive name (e.g., "Continue Mission Control")
5. Copy the token immediately
</Step>
<Step title="Add Token to Mission Control">
Paste your access token into the integration form and click "Create Connection"
</Step>
</Steps>
<Tip>
**Token Scope**: Personal access tokens have full access to your Netlify account. Create a token specifically for Continue to maintain security and easy revocation if needed.
</Tip>
## Workflows
### Optimize Website Performance
**Trigger**: On PR merge
**Description**: Run Lighthouse audits on PR preview and production to compare performance
When a pull request is merged, this performance-focused workflow automatically:
1. **Retrieves Deployment Information** - Uses Netlify MCP to get:
- Production deploy URL and metadata
- Deploy preview URL for the PR branch
- Build artifacts and configuration
2. **Analyzes Bundle Sizes** - Compares JavaScript and CSS bundles:
- Downloads and measures all asset files
- Calculates total bundle size for both deploys
- Identifies largest individual files
- Detects unminified or bloated assets
3. **Reviews Build Configuration** - Examines:
- `vite.config.ts` or `webpack.config.js` for minification settings
- `netlify.toml` for cache headers and build commands
- `package.json` for redundant or oversized dependencies
4. **Identifies Performance Issues** - Classifies problems by severity:
- 🔴 **Critical**: Minification disabled, bundle size >50% increase, no caching
- ⚠️ **Warning**: No code splitting, large chunks >500KB, 20-50% bundle increase
- ℹ️ **Info**: Suboptimal configurations, bundle size less than 20% increase
5. **Generates Actionable Report** - Posts to PR with:
- Bundle size comparison table
- Root cause analysis with file references and line numbers
- Code fixes that can be copy-pasted
- Merge recommendation (Approved/Review Needed/Blocked)
- Expected improvements from each fix
<Card title="Why This Matters" icon="gauge-high">
Performance regressions often slip through code review because:
- Bundle size increases aren't visible in diffs
- Configuration errors (disabled minification) go unnoticed
- Redundant dependencies accumulate over time
This workflow catches these issues automatically before they reach production.
</Card>
<Info>
**Smart Analysis**: The agent doesn't just report bundle sizes—it analyzes build configurations, identifies root causes, and provides specific code fixes with line numbers.
</Info>
### Performance Issue Classification
The agent categorizes issues by severity:
<Accordion title="🔴 Critical - Block Merge">
**Issues that must be fixed before merging:**
- Minification disabled (`minify: false`)
- Tree-shaking disabled (`treeshake: false`)
- No caching headers (`Cache-Control: no-cache`)
- Production source maps enabled
- Bundle size increase >50%
- Redundant dependencies (lodash + underscore, moment + date-fns + dayjs)
**Action**: Agent recommends blocking the merge
</Accordion>
<Accordion title="⚠️ Warning - Review Required">
**Issues that need attention:**
- No code splitting (single large bundle)
- Suboptimal cache headers (max-age too low)
- Large individual chunks (>500KB)
- Unoptimized images
- Bundle size increase 20-50%
**Action**: Agent recommends careful review before merging
</Accordion>
<Accordion title="ℹ️ Info - Optimization Opportunities">
**Non-blocking improvements:**
- Could use better code splitting
- Modern browser features could replace polyfills
- CSS not extracted/split
- Bundle size increase less than 20%
**Action**: Agent approves merge but suggests optimizations
</Accordion>
## Use Cases
### Infrastructure as Code
Manage Netlify infrastructure with natural language:
<Card title="Infrastructure Manager" icon="server">
**Task Example**: "Create a new Netlify site for the marketing-site repo with custom domain marketing.company.com"
**What the Agent Does**:
- Creates new Netlify project via API
- Connects to specified Git repository
- Configures build settings and commands
- Sets up custom domain and SSL
- Configures environment variables
**Run in Mission Control**: Run manually when creating new projects
</Card>
### Build Configuration Optimization
Automatically optimize build settings:
<Card title="Build Optimizer" icon="wrench">
**Task Example**: "Audit all Netlify sites for missing cache headers and suboptimal build configs"
**What the Agent Does**:
- Reviews `netlify.toml` and build settings
- Checks cache header configurations
- Identifies missing optimizations
- Generates recommended configuration changes
- Can apply fixes automatically
**Run in Mission Control**: Run monthly or after adding new sites
</Card>
### Performance Auditing
Prevent performance regressions before deployment:
<Card title="Performance Auditor" icon="gauge-high">
**Task Example**: "Analyze bundle sizes and configurations, block PRs with critical performance issues"
**What the Agent Does**:
- Compares preview and production bundle sizes
- Detects disabled minification or tree-shaking
- Identifies redundant dependencies (lodash + underscore, multiple date libraries)
- Checks cache configuration
- Posts detailed report with fixes to PR
- Recommends approval, review, or blocking merge
**Run in Mission Control**: Triggered automatically on PR merge
</Card>
### Dependency Analysis
Identify and fix problematic dependencies:
<Card title="Dependency Auditor" icon="magnifying-glass">
**Task Example**: "Find redundant or oversized dependencies across all projects"
**What the Agent Does**:
- Scans `package.json` files in all Netlify sites
- Identifies duplicate functionality (multiple date/utility libraries)
- Finds oversized packages (>100KB)
- Suggests lightweight alternatives
- Calculates potential bundle size savings
**Run in Mission Control**: Run quarterly for dependency cleanup
</Card>
### Continuous Performance Monitoring
Track performance trends over time:
<Card title="Performance Tracker" icon="chart-line">
**Task Example**: "Generate a performance trend report for the last 30 deploys"
**What the Agent Does**:
- Queries deploy history via Netlify MCP
- Tracks bundle size over time
- Identifies gradual performance degradation
- Highlights deploysthat introduced regressions
- Generates visualization of trends
**Run in Mission Control**: Schedule weekly for ongoing monitoring
</Card>
### Domain and SSL Management
Manage domains using natural language:
<Card title="Domain Manager" icon="globe">
**Task Example**: "Add www.example.com to my site and configure SSL"
**What the Agent Does**:
- Configures custom domains via Netlify API
- Sets up SSL certificates automatically
- Configures DNS records and redirects
- Verifies domain setup and SSL status
**Run in Mission Control**: Run manually when adding domains
</Card>
## Running Netlify Agents in Mission Control
You can run Netlify-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows):
<Tip>
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
### 2. Automated Workflows
Set up agents to run automatically:
- **PR-triggered**: Audit performance when pull requests are merged
- **Scheduled**: Run weekly bundle size audits across all sites
- **Manual**: Analyze specific deploys or troubleshoot performance issues
<Tip>
Start with manual performance audits on specific PRs to refine your thresholds, then enable automated workflows to catch all performance regressions.
</Tip>
## Troubleshooting
<Accordion title="Authentication failures">
**Problem**: Agent can't connect to Netlify API
**Solutions**:
- Verify personal access token is correct
- Check that token hasn't been revoked
- Ensure token has necessary permissions
- Try regenerating the token
</Accordion>
<Accordion title="Deploy not ready">
**Problem**: Deploy preview is still building when agent tries to analyze
**Solutions**:
- Verify you have deploy permissions for the site
- Check that the site exists and is accessible
- Ensure build hooks are configured if using webhooks
- Review Netlify API rate limits
</Accordion>
<Accordion title="No deploys found">
**Problem**: Agent can't find deploy preview for the branch
**Solutions**:
- Verify branch name is correct
- Check that PR has triggered a Netlify build
- Ensure deploy previews are enabled in Netlify settings
- Confirm the repository is connected to Netlify
</Accordion>
<Accordion title="Bundle analysis failures">
**Problem**: Agent can't download or analyze bundles
**Solutions**:
- Verify deploy URLs are accessible
- Check for authentication requirements on preview
- Ensure assets are being generated correctly
- Review build logs for errors
</Accordion>
<Accordion title="Deploy previews not found">
**Problem**: Agent can't locate deploy previews
**Solutions**:
- Verify branch name is correct
- Check that deploy previews are enabled for the site
- Ensure the commit has triggered a build
- Wait for build to complete before querying
</Accordion>
<Accordion title="Performance monitoring issues">
**Problem**: Can't retrieve site performance metrics
**Solutions**:
- Verify Netlify Analytics is enabled for the site
- Check that your plan includes analytics access
- Ensure time range for queries is valid
- Review API documentation for metrics endpoints
</Accordion>
## Support & Resources
<CardGroup cols={2}>
<Card title="Netlify MCP Cookbook" icon="book-open" href="/guides/netlify-mcp-continuous-deployment">
Complete guide to continuous deployment automation with Netlify and Continue
</Card>
<Card title="GitHub Integration" icon="github" href="/mission-control/integrations/github">
Combine Netlify with GitHub for end-to-end CI/CD automation
</Card>
</CardGroup>

View file

@ -0,0 +1,238 @@
---
title: "PostHog Integration"
description: "Leverage product analytics and feature flags with Continue Agents connected to PostHog"
---
## Overview
Connect PostHog to Continue Mission Control to enable agents to analyze user behavior, manage feature flags, and optimize product experiences. When PostHog is enabled, Continue can analyze product metrics, automate feature rollouts, and create data-driven development tasks.
<Card title="What You Can Do with PostHog Integration" icon="chart-line">
- Analyze user behavior patterns and create optimization tasks
- Manage feature flags and gradual rollouts
- Generate insights from product analytics
- Automate A/B test analysis and reporting
- Monitor conversion funnels and user journeys
- Create PRs based on analytics insights
</Card>
## Setup
<Steps>
<Step title="Navigate to Integrations">
Go to your [Integrations Settings](https://hub.continue.dev/integrations).
</Step>
<Step title="Connect PostHog">
Click "Connect" next to PostHog. You'll need the following credentials:
- **Project API Key**: Your PostHog project API key
- **Host URL**: Your PostHog instance URL (e.g., `https://app.posthog.com` or your self-hosted URL)
</Step>
<Step title="Get PostHog Credentials">
In your PostHog account:
1. Navigate to Project Settings
2. Find your Project API Key
3. Copy your PostHog instance URL
4. Paste both values into Mission Control
</Step>
<Step title="Verify Connection">
Click "Create Connection" and verify that Continue can access your PostHog data
</Step>
</Steps>
<Tip>
**How to get these credentials:**
1. Log into your PostHog account
2. Go to **Settings** → **Project API Key**
3. Copy your API key
4. Note your instance URL (shown in the browser address bar)
</Tip>
## Use Cases
### Analytics-Driven Development
Create agents that analyze user behavior and generate development tasks:
<Card title="Feature Optimization Agent" icon="chart-mixed">
**Task Example**: "Analyze the checkout flow conversion rate and identify areas for improvement"
**What the Agent Does**:
- Retrieves funnel data from PostHog
- Identifies drop-off points in the user journey
- Analyzes user session recordings at problem areas
- Creates issues or PRs with optimization recommendations
**Run in Mission Control**: Schedule weekly or trigger after significant traffic changes
</Card>
### Feature Flag Management
Automate feature rollout based on metrics:
<Card title="Gradual Rollout Agent" icon="flag">
**Task Example**: "Monitor new checkout feature performance and increase rollout percentage if metrics are positive"
**What the Agent Does**:
- Tracks key metrics for the feature flag
- Compares performance against baseline
- Automatically adjusts rollout percentage
- Alerts team if anomalies are detected
**Run in Mission Control**: Set up as continuous monitoring workflow
</Card>
### Performance Monitoring
Track and respond to performance issues:
<Card title="Performance Analysis Agent" icon="gauge-high">
**Task Example**: "Analyze page load times and create issues for pages slower than 3 seconds"
**What the Agent Does**:
- Queries PostHog for performance metrics
- Identifies slow-loading pages
- Analyzes common characteristics of slow pages
- Creates prioritized issues with performance data
**Run in Mission Control**: Schedule daily performance audits
</Card>
### A/B Test Analysis
Automate experiment analysis and reporting:
<Card title="Experiment Analyzer Agent" icon="flask">
**Task Example**: "Analyze the results of the new homepage A/B test and determine statistical significance"
**What the Agent Does**:
- Retrieves experiment data from PostHog
- Performs statistical analysis
- Generates comprehensive report with visualizations
- Creates recommendations for next steps
**Run in Mission Control**: Trigger when experiment reaches sample size
</Card>
### User Feedback Loop
Connect analytics insights to code improvements:
<Card title="UX Enhancement Agent" icon="users">
**Task Example**: "Identify the top 5 most frustrating user experiences based on rage clicks and session replays"
**What the Agent Does**:
- Analyzes user session data for frustration signals
- Reviews session replays of problematic interactions
- Identifies common UX issues
- Creates detailed bug reports with user context
**Run in Mission Control**: Run weekly to catch emerging patterns
</Card>
## Running PostHog Agents in Mission Control
You can run PostHog-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows):
<Tip>
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
## Troubleshooting
<Accordion title="Agent can't access PostHog data">
**Problem**: Agent returns errors when trying to fetch analytics
**Solutions**:
- Verify API key is correct and hasn't expired
- Check that the project API key has read permissions
- Ensure host URL includes protocol (https://)
- Confirm your PostHog plan includes API access
</Accordion>
<Accordion title="Metrics seem incorrect or outdated">
**Problem**: Data retrieved doesn't match PostHog dashboard
**Solutions**:
- Check that you're querying the correct time range
- Verify PostHog data is fully processed (may have slight delay)
- Ensure filters and breakdowns match your dashboard
- Review agent logs for query parameters
</Accordion>
<Accordion title="Feature flag updates not working">
**Problem**: Agent can't modify feature flags
**Solutions**:
- Verify API key has write permissions
- Check that you're using a Personal API Key (not Project API Key) for modifications
- Ensure feature flag exists before attempting updates
- Review PostHog API documentation for flag management
</Accordion>
<Accordion title="Self-hosted PostHog connection issues">
**Problem**: Can't connect to self-hosted PostHog instance
**Solutions**:
- Verify host URL is accessible from Mission Control
- Check firewall rules allow Continue's IP addresses
- Ensure SSL certificate is valid if using HTTPS
- Test API access with curl or Postman first
</Accordion>
## Support & Resources
<CardGroup cols={2}>
<Card title="PostHog GitHub Continuous AI" icon="book-open" href="/guides/posthog-github-continuous-ai">
Complete guide to building product-led development workflows with PostHog and Continue
</Card>
<Card title="GitHub Integration" icon="github" href="/mission-control/integrations/github">
Combine PostHog with GitHub for data-driven development automation
</Card>
</CardGroup>

View file

@ -0,0 +1,349 @@
---
title: "Sanity Integration"
description: "Automate content management and schema validation with Continue Agents connected to Sanity"
---
## Overview
Connect Sanity to Continue Mission Control to enable agents to manage content, validate schemas, execute GROQ queries, and automate your content workflows. When Sanity is enabled, Continue can explore document types, update content, handle migrations, and maintain content quality across your projects.
<Card title="What You Can Do with Sanity Integration" icon="pen-to-square">
- Automatically validate content and schemas on every PR
- Execute GROQ queries to analyze and update content
- Generate documentation from your content model
- Manage content migrations between environments
- Monitor content quality and consistency
- Automate content creation and updates
</Card>
## Setup
<Steps>
<Step title="Navigate to Integrations">
Go to [the Sanity Integrations](https://hub.continue.dev/integrations/sanity).
</Step>
<Step title="Connect Sanity">
"Connect" to Sanity. The integration uses OAuth authentication through the Sanity MCP.
</Step>
<Step title="Authorize Sanity Access">
Select the Sanity organization and project to connect
</Step>
<Step title="Configure Workflows">
After connecting, set up your first workflow. The integration supports:
- **On PR open**: Validate schemas and content when PRs are created
- **Manual tasks**: Run content operations on-demand
- **Scheduled jobs**: Periodic content audits and maintenance
</Step>
</Steps>
## Workflows
### Update Sanity schema docs
**Trigger**: On PR open
**Description**: Skip the GROQ lookup. Agents manage your content through conversation.
When a pull request modifies schema files (`schemas/**/*.{ts,js,tsx,jsx}`, `schemaTypes/**/*`, or `sanity.config.{ts,js}`), this workflow automatically:
1. **Connects to Sanity** - Fetches the complete current schema using Sanity MCP
2. **Analyzes Changes** - Identifies new, modified, or removed document types
3. **Updates Documentation** - Generates comprehensive documentation including:
- Complete field descriptions and validation rules
- Relationship diagrams between document types
- GROQ query examples for each type
- Usage guidance for developers and content teams
4. **Commits to PR Branch** - Adds documentation directly to the existing PR branch
5. **Posts PR Comment** - Provides a detailed summary of documented changes
<Card title="What Gets Documented" icon="book">
For each document type, the agent generates:
- **Field Reference**: Every field with type, validation, and description
- **Relationships**: Visual diagram showing references between types
- **Query Examples**: Practical GROQ queries for common operations
- **Studio Behavior**: How fields appear and function in Sanity Studio
- **Validation Rules**: All constraints and requirements
- **Usage Notes**: Important gotchas and best practices
</Card>
<Info>
**Documentation Location**: By default, docs are created at `docs/content-model.md`. The agent searches for existing documentation in several standard locations and preserves your structure.
</Info>
#### Example PR Comment
After updating the documentation, the agent posts a comprehensive comment like this:
```markdown
## 📝 Schema Documentation Updated
I've automatically updated the content model documentation based on the schema changes in this PR.
### 📋 Changes Documented
**New Document Types** (2)
- ✨ `product` - E-commerce product listings
- ✨ `review` - Customer product reviews
**Modified Document Types** (1)
- 📝 `article` - Added `featured` boolean field, updated `title` validation
### 📄 Documentation Location
📖 [View Updated Documentation](./docs/content-model.md)
### 📊 Schema Overview
- **Total Document Types**: 12
- **Total Fields**: 87
- **Types Modified in this PR**: 3
- **New Fields Added**: 5
### 🔗 Key Relationships Changed
- `product` now references `review` (one-to-many)
- `article.featured` added for homepage curation
```
## Use Cases
### Content Validation
Automatically validate content structure and quality:
<Card title="Content Validator Agent" icon="check-circle">
**Task Example**: "Check all blog posts for required fields and broken references"
**What the Agent Does**:
- Scans documents for missing required fields
- Validates references between documents
- Checks for orphaned content
- Reports inconsistencies and suggests fixes
**Run in Mission Control**: Schedule daily or trigger on content updates
</Card>
### Schema Management
Manage and evolve your content schemas:
<Card title="Schema Analyzer Agent" icon="diagram-project">
**Task Example**: "Analyze the product schema and suggest optimizations for better performance"
**What the Agent Does**:
- Reviews document type definitions
- Identifies unused or redundant fields
- Suggests schema improvements
- Validates relationships and data integrity
**Run in Mission Control**: Run before major schema changes
</Card>
### Content Migration
Automate content structure changes:
<Card title="Migration Manager Agent" icon="right-left">
**Task Example**: "Migrate all blog posts from the old schema to the new format"
**What the Agent Does**:
- Reads content from old schema structure
- Transforms data to match new schema
- Validates migrated content
- Creates migration report with any issues
**Run in Mission Control**: Run manually for controlled migrations
</Card>
### GROQ Query Execution
Run complex queries to analyze content:
<Card title="Content Analyzer Agent" icon="magnifying-glass">
**Task Example**: "Find all articles published in Q4 2023 with over 10,000 views"
**What the Agent Does**:
- Executes GROQ queries against your dataset
- Analyzes results and identifies patterns
- Generates reports and visualizations
- Exports data for further analysis
**Run in Mission Control**: Run on-demand for content insights
</Card>
### Schema Documentation
Automatically maintain comprehensive schema documentation:
<Card title="Schema Docs Agent" icon="book">
**Task Example**: "Generate comprehensive documentation for all document types and their relationships"
**What the Agent Does**:
- Fetches complete schema from Sanity
- Documents every field with types, validation, and descriptions
- Creates Mermaid diagrams showing document relationships
- Includes practical GROQ query examples
- Preserves manual documentation sections
- Updates statistics (total types, field counts)
**Run in Mission Control**: Triggered automatically on PR open when schema files change
**Documentation Structure**:
- Table of contents with all document types
- Detailed field tables for each type
- Relationship diagrams
- Query examples for common operations
- Validation rules and Studio configurations
</Card>
### Content Localization
Manage multi-language content:
<Card title="Localization Agent" icon="language">
**Task Example**: "Verify all product pages have complete Spanish and French translations"
**What the Agent Does**:
- Identifies missing translations
- Validates localized field structure
- Reports incomplete content
- Suggests content for translation
**Run in Mission Control**: Schedule weekly translation audits
</Card>
## Running Sanity Agents in Mission Control
You can run Sanity-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows):
<Tip>
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
## Troubleshooting
<Accordion title="Authentication expired">
**Problem**: Agent shows authentication errors
**Solutions**:
- Re-authenticate through the integrations page (OAuth expires after 7 days)
- For CI/CD workflows, use environment variables instead
- Check that project permissions haven't changed
- Verify the Sanity project still exists
</Accordion>
<Accordion title="Schema not found">
**Problem**: Agent can't locate schema definitions
**Solutions**:
- Verify schema files are in the correct location
- Check that the project ID is correct
- Ensure you're connected to the right dataset
- Confirm schema files are properly exported
</Accordion>
<Accordion title="GROQ query errors">
**Problem**: Queries fail or return unexpected results
**Solutions**:
- Validate GROQ syntax in Sanity Vision
- Check that referenced fields exist
- Verify document types are spelled correctly
- Review query complexity and optimize if needed
</Accordion>
<Accordion title="Content validation failures">
**Problem**: Agent reports content doesn't match schema
**Solutions**:
- Check for recent schema changes
- Verify required fields are present
- Review field type mismatches
- Run migration to update content structure
</Accordion>
<Accordion title="Migration issues">
**Problem**: Content migration fails or produces errors
**Solutions**:
- Test migration on a small subset first
- Validate both old and new schemas
- Check for data type conflicts
- Review migration logs for specific errors
- Use transactions for atomic updates
</Accordion>
## Support & Resources
<CardGroup cols={2}>
<Card title="Sanity MCP Cookbook" icon="book-open" href="/guides/sanity-mcp-continue-cookbook">
Complete guide to content management automation with Sanity and Continue
</Card>
<Card title="GitHub Integration" icon="github" href="/mission-control/integrations/github">
Combine Sanity with GitHub for automated content workflows
</Card>
<Card title="Sanity Documentation" icon="book" href="https://www.sanity.io/docs">
Official Sanity documentation and guides
</Card>
<Card title="GROQ Reference" icon="code" href="https://www.sanity.io/docs/groq">
Learn GROQ query language for content queries
</Card>
</CardGroup>

View file

@ -21,18 +21,19 @@ Connect Sentry to Continue Mission Control to enable agents to automatically det
<Steps>
<Step title="Navigate to Integrations">
<Step title="Navigate to the Sentry Integration">
Go to your [Integrations Settings](https://hub.continue.dev/integrations).
Go to [Sentry Integration](https://hub.continue.dev/integrations/sentry).
</Step>
<Step title="Connect Sentry">
Click "Connect" and select Sentry. You'll need the following credentials:
Click "Connect". You'll need the following credentials:
- **Sentry Organization Slug**: Your organization name (e.g., "my-company")
- **Auth Token**: Internal integration token from Sentry
- **Client Secret**: For webhook signature verification
- **API Key**: For MCP support
</Step>
@ -69,75 +70,14 @@ Connect Sentry to Continue Mission Control to enable agents to automatically det
## Running Sentry Agents in Mission Control
You can run Sentry-connected agents in two ways:
### 1. Manual Tasks
Trigger agents on-demand for error analysis:
1. Go to [Mission Control Agents](https://hub.continue.dev/agents)
2. Select or create a Sentry-enabled agent
3. Click "Run Agent" and provide your task description
4. Monitor progress and review results in real-time
**Example Tasks:**
- "Analyze the top 10 errors from the last 24 hours"
- "Create a PR to fix the authentication timeout error"
- "Generate a report on errors affecting mobile users"
### 2. Automated Workflows
Set up agents to run automatically:
- **Webhook-triggered**: Execute when new Sentry errors occur
- **Scheduled**: Run daily or weekly error analysis
- **Threshold-based**: Trigger when error rates exceed limits
You can run Sentry-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows).
<Tip>
Start with manual tasks to refine your prompts, then convert successful workflows to automations for continuous error monitoring.
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
## Integration with GitHub
Combine Sentry with GitHub integration for a complete workflow:
<Steps>
<Step title="Connect Both Integrations">
Enable both Sentry and GitHub integrations in Mission Control
</Step>
<Step title="Create a Unified Agent">
Build an agent that:
- Receives Sentry error notifications
- Analyzes the error and finds the problematic code
- Creates a PR with a fix
- Adds the PR link to the Sentry issue
</Step>
<Step title="Set Up Automated Workflow">
Configure the agent to run automatically on new Sentry issues
</Step>
</Steps>
## Monitoring Agent Activity
Track your agent's error resolution performance:
1. **View in Mission Control**: See all agent runs and their outcomes
2. **Check Sentry**: Verify that issues are being resolved
3. **Review PRs**: Ensure quality of generated fixes
4. **Monitor Metrics**: Track resolution time and success rate
## Troubleshooting

View file

@ -29,9 +29,6 @@ Mention @Continue in any channel with a task description, and it will:
## Setup
Continue's Slack Bot can be installed to a Slack workspace via Mission Control, from:[Integrations Settings](https://hub.continue.dev/integrations)
- Org Integrations Settings - `https://hub.continue.dev/organizations/{your-org}/settings/integrations`
<Warning>
Continue's Slack app is in Beta development. During installation, you will see a warning that it is not yet approved/official.
@ -48,7 +45,7 @@ Continue's Slack Bot can be installed to a Slack workspace via Mission Control,
<Step title="Authorize Slack">
Click the "Connect" button next to Slack and authorize the app in your workspace.
Click the "Connect" button next in [the Slack Integration ](https://hub.continue.dev/integrations/slack)and authorize the app in your workspace.
</Step>
@ -115,7 +112,7 @@ Continue will forward your message to the existing agent session instead of crea
## Monitoring Agent Progress
Click the agent link in Slack to view the agent's progress in [Mission Control](https://hub.continue.dev/agents).
Click the agent link in Slack to view the agent's progress in [Mission Control](https://hub.continue.dev/hub?type=agents).
You can also click the Slack icon in the agents page to return to the Slack message.

View file

@ -23,7 +23,7 @@ Connect Snyk to Continue Mission Control to enable agents to automatically detec
<Step title="Navigate to Integrations">
Go to your [Integrations Settings](https://hub.continue.dev/integrations).
Go to the [Snyk Integration](https://hub.continue.dev/integrations/snyk).
</Step>
@ -60,44 +60,6 @@ Connect Snyk to Continue Mission Control to enable agents to automatically detec
</Info>
## Integration with GitHub
Combine Snyk with GitHub integration for a complete security workflow:
<Steps>
<Step title="Connect Both Integrations">
Enable both Snyk and GitHub integrations in Mission Control
</Step>
<Step title="Create a Security Agent">
Build an agent that:
- Receives Snyk vulnerability alerts
- Analyzes the security issue in your codebase
- Creates a PR with the security fix
- Adds security impact analysis to the PR
</Step>
<Step title="Set Up Automated Security Workflow">
Configure the agent to run automatically on new critical vulnerabilities
</Step>
</Steps>
## Monitoring Agent Activity
Track your agent's security remediation performance:
1. **View in Inbox**: Navigate to the [Snyk view](https://hub.continue.dev/inbox?view=snyk) to see all Snyk-related agent activity
2. **Check Snyk Dashboard**: Verify that vulnerabilities are being addressed
3. **Review PRs**: Ensure quality and security of generated fixes
4. **Monitor Metrics**: Track mean time to remediation (MTTR) and fix rate
## Troubleshooting

View file

@ -0,0 +1,526 @@
---
title: "Supabase Integration"
description: "Monitor database security, generate migrations, and optimize queries with Continue Agents connected to Supabase"
---
## Overview
Connect Supabase to Continue Mission Control to enable AI-powered database workflows. When Supabase is enabled, Continue can audit Row Level Security (RLS) policies, generate secure migrations, optimize queries, and maintain database security automatically.
<Card title="What You Can Do with Supabase Integration" icon="database">
- Automatically audit RLS policies on every PR
- Generate secure migrations for missing security policies
- Identify and fix critical security gaps
- Optimize database queries and schemas
- Monitor database performance and security
- Validate schema changes before deployment
</Card>
## Setup
<Steps>
<Step title="Navigate to Integrations">
Go to the [Supabase Integration](https://hub.continue.dev/integrations/supabase).
</Step>
<Step title="Connect Supabase">
Click "Connect" to Supabase.
</Step>
<Step title="Authorize Supabase Access">
You'll be redirected to Supabase to authorize Continue:
1. Select the Supabase organization and project to connect
2. Review the requested permissions
3. Click "Authorize" to complete the connection
</Step>
<Step title="Configure Workflows">
After connecting, set up your first workflow. The integration supports:
- **On PR open**: Audit RLS policies when PRs are created
- **Manual tasks**: Run database operations on-demand
- **Scheduled jobs**: Periodic security audits and performance checks
</Step>
</Steps>
## Workflows
### Supabase security review
**Trigger**: On PR open
**Description**: Connect your Supabase workspace to agents that can explore schemas, run queries, create and update documents, and handle migrations using natural language
When a pull request is opened, this security-focused workflow automatically:
1. **Analyzes PR Changes** - Identifies affected tables from:
- Migration files (`supabase/migrations/*.sql`)
- SDK/library usage (`.from('table_name')` calls)
- Schema references in type definitions
2. **Audits RLS Policies** - Uses Supabase MCP to inspect:
- Whether RLS is enabled on affected tables
- Existing policy configurations
- Potential security gaps
3. **Classifies Security Risks** - Prioritizes findings by severity:
- 🔴 **Critical**: No RLS on tables with sensitive data
- 🟠 **High**: Overly permissive policies (e.g., `USING (true)`)
- 🟡 **Medium**: Missing standard access patterns
- 🟢 **Low**: Policy optimization opportunities
4. **Generates SQL Migrations** - Creates fixes for Critical/High/Medium issues:
- Enables RLS on unprotected tables
- Adds missing user-scoped policies
- Implements proper access controls
- Includes rollback commands
5. **Commits Fixes to PR Branch** - Automatically pushes security fixes
6. **Posts Comprehensive Comment** - Explains all findings and changes
<Card title="Why This Matters" icon="shield-check">
Row Level Security (RLS) is Supabase's primary security mechanism. Without proper RLS policies:
- Users can access other users' private data
- Unauthorized modifications can occur
- Sensitive information may be exposed
This workflow automatically catches these issues before they reach production.
</Card>
<Info>
**Smart Scoping**: The agent only audits tables directly referenced in your PR changes, not your entire database. This keeps audits focused and efficient.
</Info>
#### Example PR Comment
After auditing RLS policies, the agent posts a comprehensive comment like this:
```markdown
## 🔒 Supabase RLS Policy Audit
### Scope
This audit covers **3 tables** referenced in this PR:
- user_profiles (detected in: migration file)
- comments (detected in: SDK usage in src/api/comments.ts)
- posts (detected in: migration file)
### Summary
- ✅ 1 table with proper RLS
- ⚠️ 2 tables requiring attention
- 🔴 1 critical security gap found
### Findings
| Table | Risk Level | Issue | Status |
|-------|------------|-------|--------|
| `user_profiles` | 🔴 Critical | No RLS enabled | ✅ Fixed in commit abc123 |
| `comments` | 🟡 Medium | Missing delete policy | ✅ Fixed in commit abc123 |
| `posts` | 🟢 Low | Policy optimization possible | 💡 Recommendation |
### Changes Made
- Enabled RLS on `user_profiles`
- Added policies: `user_profiles_select_own`, `user_profiles_update_own`, `comments_delete_own`
- See full migration: `supabase/migrations/20241118120000_rls_security_fixes.sql`
### Recommendations (Low Priority)
- **posts table**: Consider renaming policy `posts_policy_1` to `posts_select_owner` for clarity
### Policy Patterns Used
**User-scoped access** (users access only their own data):
\```sql
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id)
\```
### Next Steps
- ✅ Review the migration file and committed changes
- ✅ Test the policies in your development environment
- ✅ Merge this PR once you've verified the security improvements
```
### Security Risk Levels Explained
<Accordion title="🔴 Critical - Immediate Fix Required">
**What it means**: Tables with no RLS that contain sensitive data
**Examples**:
- User profiles, emails, or authentication data
- Financial information or payment details
- Private messages or personal content
- New tables created without RLS
**What the agent does**: Automatically enables RLS and adds basic policies
</Accordion>
<Accordion title="🟠 High - Important Security Gap">
**What it means**: Overly permissive policies that could allow unauthorized access
**Examples**:
- Policies using `USING (true)` without justification
- Write access without proper validation
- Admin policies that don't verify admin status
- Missing `WITH CHECK` clauses
**What the agent does**: Generates restrictive policies with proper checks
</Accordion>
<Accordion title="🟡 Medium - Missing Best Practices">
**What it means**: Partial RLS coverage or missing standard patterns
**Examples**:
- SELECT policy exists but no UPDATE/DELETE
- No user-scoped policies for personal data
- Missing public read policies where appropriate
- Incomplete CRUD policy coverage
**What the agent does**: Adds missing policies following standard patterns
</Accordion>
<Accordion title="🟢 Low - Optimization Opportunity">
**What it means**: Policies work but could be improved
**Examples**:
- Poor policy naming conventions
- Inefficient policy logic
- Missing documentation
- Duplicate or redundant policies
**What the agent does**: Suggests improvements in PR comment (no auto-fix)
</Accordion>
## Use Cases
### Automated Security Audits
Catch security issues before they reach production:
<Card title="RLS Policy Auditor" icon="shield-exclamation">
**Task Example**: Automatically audit RLS on every PR that touches database schema or queries
**What the Agent Does**:
- Scans PR for database-related changes
- Identifies all affected tables
- Checks RLS status and policies
- Generates fixes for security gaps
- Commits migrations to the PR branch
**Run in Mission Control**: Triggered automatically on PR open
</Card>
### Database Migration Generation
Create secure migrations automatically:
<Card title="Migration Generator" icon="file-code">
**Task Example**: "Generate a migration to add RLS policies for the new messages table"
**What the Agent Does**:
- Analyzes table structure and purpose
- Determines appropriate access patterns
- Generates SQL with RLS policies
- Includes proper naming and comments
- Adds rollback commands
**Run in Mission Control**: Run manually or on schema changes
</Card>
### Query Optimization
Improve database performance:
<Card title="Query Optimizer" icon="gauge-high">
**Task Example**: "Analyze slow queries and suggest optimizations"
**What the Agent Does**:
- Identifies queries in your codebase
- Checks for missing indexes
- Suggests query rewrites
- Recommends schema changes
- Estimates performance impact
**Run in Mission Control**: Schedule weekly performance reviews
</Card>
### Schema Validation
Ensure schema changes follow best practices:
<Card title="Schema Validator" icon="table">
**Task Example**: "Validate that all new tables follow our schema standards"
**What the Agent Does**:
- Checks naming conventions
- Validates data types and constraints
- Ensures proper indexes exist
- Verifies RLS is enabled
- Reviews foreign key relationships
**Run in Mission Control**: Triggered on migration file changes
</Card>
### Access Pattern Analysis
Understand how your database is used:
<Card title="Access Analyzer" icon="chart-line">
**Task Example**: "Analyze SDK usage patterns and suggest RLS policies"
**What the Agent Does**:
- Scans codebase for Supabase client calls
- Identifies data access patterns
- Detects security anti-patterns
- Recommends appropriate RLS policies
- Generates migration files
**Run in Mission Control**: Run before major releases
</Card>
### Development Environment Sync
Keep dev and production schemas aligned:
<Card title="Schema Sync Agent" icon="arrows-rotate">
**Task Example**: "Compare dev and production schemas and generate sync migrations"
**What the Agent Does**:
- Connects to multiple Supabase projects
- Compares schema definitions
- Identifies differences
- Generates sync migrations
- Validates compatibility
**Run in Mission Control**: Schedule or run manually
</Card>
## Running Supabase Agents in Mission Control
You can run Supabase-connected agents in two ways as [one-off tasks](../tasks) or automated [workflows](../workflows):
<Tip>
Start with manual tasks to refine your content queries, then automate repetitive content management and validation tasks.
</Tip>
## Common RLS Policy Patterns
The agent recognizes and implements these standard security patterns:
### User-Scoped Access
Users can only access their own data:
```sql
-- SELECT: Users can read their own records
CREATE POLICY "users_select_own" ON user_profiles
FOR SELECT USING (auth.uid() = user_id);
-- UPDATE: Users can update their own records
CREATE POLICY "users_update_own" ON user_profiles
FOR UPDATE USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- DELETE: Users can delete their own records
CREATE POLICY "users_delete_own" ON user_profiles
FOR DELETE USING (auth.uid() = user_id);
```
### Admin Override
Admins can access all data while users access only their own:
```sql
CREATE POLICY "posts_select_owner_or_admin" ON posts
FOR SELECT USING (
auth.uid() = user_id OR
auth.jwt() ->> 'role' = 'admin'
);
```
### Public Read, Authenticated Write
Anyone can read, only authenticated users can write:
```sql
-- Public read access
CREATE POLICY "public_posts_select" ON public_posts
FOR SELECT USING (true);
-- Authenticated insert only
CREATE POLICY "public_posts_insert_auth" ON public_posts
FOR INSERT WITH CHECK (auth.role() = 'authenticated');
```
### Soft Delete Handling
Exclude soft-deleted records from queries:
```sql
CREATE POLICY "posts_select_not_deleted" ON posts
FOR SELECT USING (
deleted_at IS NULL AND
(auth.uid() = user_id OR is_published = true)
);
```
## Troubleshooting
<Accordion title="Authentication issues">
**Problem**: Agent can't connect to Supabase
**Solutions**:
- Re-authenticate through the integrations page
- Verify OAuth token hasn't expired (expires after 7 days)
- Check project permissions
- Ensure Supabase project is accessible
- For CI/CD, verify environment variables are set
</Accordion>
<Accordion title="No tables detected in PR">
**Problem**: Agent reports no tables found to audit
**Solutions**:
- Verify PR contains database-related changes
- Check that migration files use standard naming
- Ensure SDK calls use `.from('table_name')` pattern
- Review PR for schema/type definition changes
</Accordion>
<Accordion title="RLS policies not generated">
**Problem**: Agent identifies issues but doesn't create fixes
**Solutions**:
- Check if issues are Low priority (agent suggests only)
- Verify agent has write access to repository
- Review error messages in agent logs
- Ensure Supabase MCP connection is working
- Check if migration directory exists
</Accordion>
<Accordion title="Generated policies too restrictive">
**Problem**: Auto-generated RLS policies block legitimate access
**Solutions**:
- Review and adjust policies in the generated migration
- Add custom logic for your specific access patterns
- Mark tables for manual policy creation if needed
- Provide feedback to improve future policy generation
</Accordion>
<Accordion title="Migration conflicts">
**Problem**: Generated migration conflicts with existing changes
**Solutions**:
- Review both migrations and merge manually
- Ensure migration timestamps are unique
- Check for duplicate policy names
- Adjust generated migration as needed
</Accordion>
## Security Best Practices
<Warning>
**Development vs. Production**:
- Always test RLS policies in development first
- Use separate Supabase projects for dev/staging/prod
- Never disable RLS on production tables
- Review all generated policies before deploying
- Test policies with different user roles
</Warning>
<Card title="RLS Policy Checklist" icon="list-check">
Before deploying RLS changes, verify:
- [ ] RLS is enabled on all sensitive tables
- [ ] Policies cover all CRUD operations (SELECT, INSERT, UPDATE, DELETE)
- [ ] User-scoped data includes `auth.uid()` checks
- [ ] Admin overrides verify admin role properly
- [ ] Public access is intentional and documented
- [ ] Policies include `WITH CHECK` clauses for writes
- [ ] Soft deletes filter out `deleted_at IS NOT NULL`
- [ ] Policy names follow naming conventions
- [ ] Rollback commands are included
- [ ] Policies are tested with different user scenarios
</Card>
## Support & Resources
<CardGroup cols={2}>
<Card title="Supabase MCP Cookbook" icon="book-open" href="/guides/supabase-mcp-database-workflow">
Complete guide to database security automation with Supabase and Continue
</Card>
<Card title="GitHub Integration" icon="github" href="/mission-control/integrations/github">
Combine Supabase with GitHub for automated security workflows
</Card>
<Card title="Supabase RLS Documentation" icon="book" href="https://supabase.com/docs/guides/auth/row-level-security">
Official Supabase Row Level Security documentation
</Card>
<Card title="Supabase MCP Docs" icon="code" href="https://supabase.com/docs/guides/getting-started/mcp">
Learn about the Supabase MCP Server.
</Card>
</CardGroup>

View file

@ -34,7 +34,7 @@ description: "A Task is a unit of work shared between you and an agent. You trig
<Step title="Select Your Repository">
Pick the **repository** and **branch** where the Agent will work.
Pick the **repository** and **branch** the Agent branch off of.
</Step>

View file

@ -1,50 +0,0 @@
---
title: "Telemetry"
icon: "chart-line"
description: "Learn about Continue's anonymous telemetry collection practices, what usage data is tracked, and how to opt out of data collection to maintain your privacy preferences"
---
## Overview
The open-source Continue Extensions collect and report **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information.
We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy).
## Tracking Policy
All data collected by the open-source Continue extensions is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data.
## What We Track
The following usage information is collected and reported:
- **Suggestion Interactions:** Whether you accept or reject suggestions (excluding the actual code or prompts involved).
- **Model and Command Information:** The name of the model and command used.
- **Token Metrics:** The number of tokens generated.
- **System Information:** The name of your operating system (OS) and integrated development environment (IDE).
- **Pageviews:** General pageview statistics.
## How to Opt Out
### IDE extensions
You can disable anonymous telemetry by toggling "Allow Anonymous Telemetry" off in the user settings.
#### VS Code
Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut `ctrl` + `,` on Windows/Linux or `cmd` + `,` on macOS).
### CLI
For `cn`, the Continue CLI, set the environment variable `CONTINUE_TELEMETRY_ENABLED=0` before running commands:
```bash
export CONTINUE_TELEMETRY_ENABLED=0
cn <your prompt>
```
Or run it inline:
```bash
CONTINUE_TELEMETRY_ENABLED=0 cn <your prompt>
```

View file

@ -272,6 +272,8 @@
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/anthropic": "^1.0.10",
"@ai-sdk/openai": "^1.0.10",
"@anthropic-ai/sdk": "^0.67.0",
"@aws-sdk/client-bedrock-runtime": "^3.929.0",
"@aws-sdk/credential-providers": "^3.929.0",
@ -279,6 +281,7 @@
"@continuedev/config-yaml": "^1.36.0",
"@continuedev/fetch": "^1.6.0",
"@google/genai": "^1.30.0",
"ai": "^4.0.33",
"dotenv": "^16.5.0",
"google-auth-library": "^10.4.1",
"json-schema": "^0.4.0",
@ -517,6 +520,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@ -540,6 +544,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@ -1804,6 +1809,7 @@
"integrity": "sha512-oNXsh2ywth5aowwIa7RKtawnkdH6LgU1ztfP9AIUCQCvzysB+WeU8o2kyyosDPwBZutPpjZDKPQGIzzrfTWweQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@octokit/auth-token": "^6.0.0",
"@octokit/graphql": "^9.0.1",
@ -1974,6 +1980,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=8.0.0"
}
@ -1995,6 +2002,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.0.1.tgz",
"integrity": "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": "^18.19.0 || >=20.6.0"
},
@ -2007,6 +2015,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz",
"integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
},
@ -2248,6 +2257,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.203.0.tgz",
"integrity": "sha512-ke1qyM+3AK2zPuBPb6Hk/GCsc5ewbLvPNkEuELx/JmANeEp6ZjnZ+wypPAJSucTw0wvCGrUaibDSdcrGFoWxKQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/api-logs": "0.203.0",
"import-in-the-middle": "^1.8.1",
@ -3564,6 +3574,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz",
"integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.0.1",
"@opentelemetry/semantic-conventions": "^1.29.0"
@ -3652,6 +3663,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz",
"integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.0.1",
"@opentelemetry/resources": "2.0.1",
@ -3687,6 +3699,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.36.0.tgz",
"integrity": "sha512-TtxJSRD8Ohxp6bKkhrm27JRHAxPczQA7idtcTOMYI+wQRRrfgqxHv1cFbCApcSnNjtXkmzFozn6jQtFrOmbjPQ==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=14"
}
@ -5097,8 +5110,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@types/body-parser": {
"version": "1.19.6",
@ -5386,6 +5398,7 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz",
"integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==",
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.10.0"
}
@ -5455,6 +5468,7 @@
"integrity": "sha512-lr3jdBw/BGj49Eps7EvqlUaoeA0xpj3pc0RoJkHpYaCHkVK7i28dKyImLQb3JVlqs3aYSXf7qYuWOW/fgZnTXQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@ -5576,6 +5590,7 @@
"integrity": "sha512-w/EboPlBwnmOBtRbiOvzjD+wdiZdgFeo17lkltrtn7X37vagKKWJABvyfsJXTlHe6XBzugmYgd4A4nW+k8Mixw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.40.0",
@ -5606,6 +5621,7 @@
"integrity": "sha512-jCNyAuXx8dr5KJMkecGmZ8KI61KBUhkCob+SD+C+I5+Y1FWI2Y3QmY4/cxMCC5WAsZqoEtEETVhUiUMIGCf6Bw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.40.0",
"@typescript-eslint/types": "8.40.0",
@ -6206,6 +6222,7 @@
"integrity": "sha512-hGISOaP18plkzbWEcP/QvtRW1xDXF2+96HbEX6byqQhAUbiS5oH6/9JwW+QsQCIYON2bI6QZBF+2PvOmrRZ9wA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@vitest/utils": "3.2.4",
"fflate": "^0.8.2",
@ -6286,6 +6303,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@ -6493,7 +6511,6 @@
"integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"dequal": "^2.0.3"
}
@ -8367,8 +8384,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/dot-prop": {
"version": "5.3.0",
@ -8909,6 +8925,7 @@
"integrity": "sha512-TS9bTNIryDzStCpJN93aC5VRSW3uTx9sClUn4B87pwiCaJh220otoI0X8mJKr+VcPtniMdN8GKjlwgWGUv5ZKA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@ -9080,6 +9097,7 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@ -9527,6 +9545,7 @@
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.1",
@ -12123,7 +12142,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@ -12151,6 +12169,7 @@
"integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"marked": "bin/marked.js"
},
@ -15058,6 +15077,7 @@
"dev": true,
"inBundle": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@ -15972,6 +15992,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"devOptional": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@ -16193,6 +16214,7 @@
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@ -16296,7 +16318,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@ -16312,7 +16333,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@ -16541,6 +16561,7 @@
"integrity": "sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@ -16551,7 +16572,6 @@
"integrity": "sha512-ibrK8llX2a4eOskq1mXKu/TGZj9qzomO+sNfO98M6d9zIPOEhlBkMkBUBLd1vgS0gQsLDBzA+8jJBVXDnfHmJg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@ -16564,16 +16584,14 @@
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/react-reconciler": {
"version": "0.32.0",
@ -17065,6 +17083,7 @@
"integrity": "sha512-g7RssbTAbir1k/S7uSwSVZFfFXwpomUB9Oas0+xi9KStSCmeDXcA7rNhiskjLqvUe/Evhx8fVCT16OSa34eM5g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@semantic-release/commit-analyzer": "^13.0.0-beta.1",
"@semantic-release/error": "^4.0.0",
@ -18597,6 +18616,7 @@
"integrity": "sha512-yyxBKfORQ7LuRt/BQKBXrpcq59ZvSW0XxwfjAt3w2/8PmdxaFzijtMhTawprSHhpzeM5BgU2hXHG3lklIERZXg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.25.0",
"get-tsconfig": "^4.7.5"
@ -18746,6 +18766,7 @@
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@ -18865,6 +18886,7 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"dependencies": {
"napi-postinstall": "^0.3.0"
},
@ -18978,6 +19000,7 @@
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@ -19076,6 +19099,7 @@
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4",
@ -19611,6 +19635,7 @@
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10.0.0"
},
@ -19685,6 +19710,7 @@
"integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
"dev": true,
"license": "ISC",
"peer": true,
"bin": {
"yaml": "bin.mjs"
},
@ -19814,6 +19840,7 @@
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"dev": true,
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

View file

@ -124,7 +124,11 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
/**
* Add an assistant message to the history
*/
addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem {
addAssistantMessage(
content: string,
toolCalls?: any[],
usage?: any,
): ChatHistoryItem {
const message: any = {
role: "assistant",
content,
@ -134,6 +138,10 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
message.toolCalls = toolCalls;
}
if (usage) {
message.usage = usage;
}
const toolCallStates = toolCalls?.map((tc) => {
const id = tc.id;
const name = tc.function?.name ?? tc.name;

View file

@ -0,0 +1,514 @@
import type { ChildProcess } from "child_process";
import { EventEmitter } from "events";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { PreprocessedToolCall } from "../tools/types.js";
import { GitAiIntegrationService } from "./GitAiIntegrationService.js";
// Mock child_process
vi.mock("child_process", () => ({
exec: vi.fn(),
spawn: vi.fn(),
}));
// Mock session functions
vi.mock("../session.js", () => ({
getCurrentSession: vi.fn(),
getSessionFilePath: vi.fn(),
}));
// Mock serviceContainer
vi.mock("./ServiceContainer.js", () => ({
serviceContainer: {
getSync: vi.fn(),
},
}));
// Mock logger
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
describe("GitAiIntegrationService", () => {
let service: GitAiIntegrationService;
let mockExec: any;
let mockSpawn: any;
let mockGetCurrentSession: any;
let mockGetSessionFilePath: any;
let mockServiceContainer: any;
beforeEach(async () => {
// Import mocked modules
const childProcess = await import("child_process");
const session = await import("../session.js");
const { serviceContainer } = await import("./ServiceContainer.js");
mockExec = childProcess.exec as any;
mockSpawn = childProcess.spawn as any;
mockGetCurrentSession = session.getCurrentSession as any;
mockGetSessionFilePath = session.getSessionFilePath as any;
mockServiceContainer = serviceContainer;
// Setup default mocks
mockGetCurrentSession.mockReturnValue({
sessionId: "test-session-id",
workspaceDirectory: "/test/workspace",
chatModelTitle: "claude-sonnet-4-5",
});
mockGetSessionFilePath.mockReturnValue(
"/test/.continue/sessions/test-session-id.json",
);
mockServiceContainer.getSync.mockReturnValue({
value: {
model: {
model: "claude-sonnet-4-5",
},
},
});
service = new GitAiIntegrationService();
});
afterEach(() => {
vi.clearAllMocks();
});
describe("initialization", () => {
it("should check if git-ai is available on initialization", async () => {
mockExec.mockImplementation((_cmd: string, callback: Function) => {
callback(null); // No error = git-ai is available
});
const state = await service.initialize();
expect(state.isEnabled).toBe(true);
expect(state.isGitAiAvailable).toBe(true);
expect(mockExec).toHaveBeenCalledWith(
"git-ai --version",
expect.any(Function),
);
});
it("should mark git-ai as unavailable if version check fails", async () => {
mockExec.mockImplementation((_cmd: string, callback: Function) => {
callback(new Error("command not found")); // Error = git-ai not available
});
const state = await service.initialize();
expect(state.isEnabled).toBe(true);
expect(state.isGitAiAvailable).toBe(false);
});
});
describe("trackToolUse", () => {
beforeEach(async () => {
mockExec.mockImplementation((_cmd: string, callback: Function) => {
callback(null); // git-ai is available
});
await service.initialize();
});
it("should not track non-file-editing tools", async () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Bash",
arguments: { command: "ls" },
argumentsStr: JSON.stringify({ command: "ls" }),
startNotified: false,
tool: {} as any,
};
await service.trackToolUse(toolCall, "PreToolUse");
expect(mockSpawn).not.toHaveBeenCalled();
});
it("should track Edit tool usage", async () => {
const mockProcess = createMockChildProcess();
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: {
resolvedPath: "/test/file.ts",
},
},
};
await service.trackToolUse(toolCall, "PreToolUse");
expect(mockSpawn).toHaveBeenCalledWith(
"git-ai",
["checkpoint", "continue-cli", "--hook-input", "stdin"],
{ cwd: "/test/workspace" },
);
// Check that the correct JSON was written to stdin
const writtenData = (mockProcess.stdin!.write as any).mock.calls[0][0];
const hookInput = JSON.parse(writtenData);
expect(hookInput).toMatchObject({
session_id: "test-session-id",
transcript_path: "/test/.continue/sessions/test-session-id.json",
cwd: "/test/workspace",
model: "claude-sonnet-4-5",
hook_event_name: "PreToolUse",
tool_input: {
file_path: "/test/file.ts",
},
});
});
it("should track MultiEdit tool usage", async () => {
const mockProcess = createMockChildProcess();
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "MultiEdit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: {
file_path: "/test/file.ts",
},
},
};
await service.trackToolUse(toolCall, "PostToolUse");
const writtenData = (mockProcess.stdin!.write as any).mock.calls[0][0];
const hookInput = JSON.parse(writtenData);
expect(hookInput.hook_event_name).toBe("PostToolUse");
expect(hookInput.tool_input.file_path).toBe("/test/file.ts");
});
it("should track Write tool usage", async () => {
const mockProcess = createMockChildProcess();
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Write",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: {
filepath: "/test/newfile.ts",
},
},
};
await service.trackToolUse(toolCall, "PreToolUse");
const writtenData = (mockProcess.stdin!.write as any).mock.calls[0][0];
const hookInput = JSON.parse(writtenData);
expect(hookInput.tool_input.file_path).toBe("/test/newfile.ts");
});
it("should not track if no file path is found", async () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: {}, // No file path
},
};
await service.trackToolUse(toolCall, "PreToolUse");
expect(mockSpawn).not.toHaveBeenCalled();
});
it("should not track if service is disabled", async () => {
service.setEnabled(false);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
await service.trackToolUse(toolCall, "PreToolUse");
expect(mockSpawn).not.toHaveBeenCalled();
});
it("should not track if git-ai is unavailable", async () => {
// Reinitialize with git-ai unavailable
mockExec.mockImplementation((_cmd: string, callback: Function) => {
callback(new Error("not found"));
});
await service.initialize();
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
await service.trackToolUse(toolCall, "PreToolUse");
expect(mockSpawn).not.toHaveBeenCalled();
});
it("should omit model field if model is not available", async () => {
mockServiceContainer.getSync.mockReturnValue({
value: {
model: null,
},
});
const mockProcess = createMockChildProcess();
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
await service.trackToolUse(toolCall, "PreToolUse");
const writtenData = (mockProcess.stdin!.write as any).mock.calls[0][0];
const hookInput = JSON.parse(writtenData);
expect(hookInput.model).toBeUndefined();
});
it("should handle git-ai errors gracefully", async () => {
const mockProcess = createMockChildProcess(1); // Exit with error code
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
// Should not throw
await expect(
service.trackToolUse(toolCall, "PreToolUse"),
).resolves.toBeUndefined();
// Should mark git-ai as unavailable
const state = service.getState();
expect(state.isGitAiAvailable).toBe(false);
});
it("should handle spawn errors gracefully", async () => {
const mockProcess = createMockChildProcess();
mockSpawn.mockReturnValue(mockProcess);
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
// Trigger an error event
setTimeout(() => {
mockProcess.emit("error", new Error("spawn failed"));
}, 0);
// Should not throw
await expect(
service.trackToolUse(toolCall, "PreToolUse"),
).resolves.toBeUndefined();
// Should mark git-ai as unavailable
const state = service.getState();
expect(state.isGitAiAvailable).toBe(false);
});
});
describe("extractFilePathFromToolCall", () => {
it("should extract path from Edit tool", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { resolvedPath: "/test/edit.ts" },
},
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBe("/test/edit.ts");
});
it("should extract path from MultiEdit tool", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "MultiEdit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { file_path: "/test/multiedit.ts" },
},
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBe("/test/multiedit.ts");
});
it("should extract path from Write tool", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Write",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { filepath: "/test/write.ts" },
},
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBe("/test/write.ts");
});
it("should return null if no preprocessResult", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBeNull();
});
it("should return null if no args", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {} as any,
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBeNull();
});
it("should return null for unknown tool", () => {
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "UnknownTool",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: {} as any,
preprocessResult: {
args: { somePath: "/test/file.ts" },
},
};
const result = service.extractFilePathFromToolCall(toolCall);
expect(result).toBeNull();
});
});
describe("setEnabled", () => {
it("should enable the service", () => {
service.setEnabled(true);
const state = service.getState();
expect(state.isEnabled).toBe(true);
});
it("should disable the service", () => {
service.setEnabled(false);
const state = service.getState();
expect(state.isEnabled).toBe(false);
});
});
});
/**
* Helper function to create a mock ChildProcess
*/
function createMockChildProcess(exitCode: number = 0): ChildProcess {
const mockProcess = new EventEmitter() as any;
mockProcess.stdin = {
write: vi.fn(),
end: vi.fn(),
};
mockProcess.stdout = new EventEmitter();
mockProcess.stderr = new EventEmitter();
// Simulate process completion after a short delay
setTimeout(() => {
mockProcess.emit("close", exitCode);
}, 10);
return mockProcess;
}

View file

@ -0,0 +1,251 @@
import { exec, spawn } from "child_process";
import { PreprocessedToolCall } from "src/tools/types.js";
import { getCurrentSession, getSessionFilePath } from "../session.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import type { ModelServiceState } from "./types.js";
interface GitAiHookInput {
session_id: string;
transcript_path: string;
cwd: string;
model?: string;
hook_event_name: "PreToolUse" | "PostToolUse";
tool_input: {
file_path: string;
};
}
export interface GitAiIntegrationServiceState {
isEnabled: boolean;
isGitAiAvailable: boolean | null; // null = not checked yet
}
export class GitAiIntegrationService extends BaseService<GitAiIntegrationServiceState> {
constructor() {
super("GitAiIntegrationService", {
isEnabled: true,
isGitAiAvailable: null,
});
}
async doInitialize(): Promise<GitAiIntegrationServiceState> {
// Check if git-ai is available on first initialization
const isAvailable = await this.checkGitAiAvailable();
return {
isEnabled: true,
isGitAiAvailable: isAvailable,
};
}
private async checkGitAiAvailable(): Promise<boolean> {
return new Promise((resolve) => {
try {
exec("git-ai --version", (error) => {
if (error) {
resolve(false);
return;
}
resolve(true);
});
} catch {
// Handle edge case where exec throws synchronously
resolve(false);
}
});
}
/**
* Helper function to call git-ai checkpoint with the given hook input
*/
private async callGitAiCheckpoint(
hookInput: GitAiHookInput,
workspaceDirectory: string,
): Promise<void> {
const hookInputJson = JSON.stringify(hookInput);
logger.debug("Calling git-ai checkpoint", {
hookInput,
workspaceDirectory,
});
await new Promise<void>((resolve, reject) => {
const gitAiProcess = spawn(
"git-ai",
["checkpoint", "continue-cli", "--hook-input", "stdin"],
{ cwd: workspaceDirectory },
);
let stdout = "";
let stderr = "";
gitAiProcess.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
gitAiProcess.stderr?.on("data", (data: Buffer) => {
stderr += data.toString();
});
gitAiProcess.on("error", (error: Error) => {
reject(error);
});
gitAiProcess.on("close", (code: number | null) => {
if (code === 0) {
logger.debug("git-ai checkpoint completed", { stdout, stderr });
resolve();
} else {
reject(
new Error(`git-ai checkpoint exited with code ${code}: ${stderr}`),
);
}
});
// Write JSON to stdin and close
gitAiProcess.stdin?.write(hookInputJson);
gitAiProcess.stdin?.end();
});
}
async trackToolUse(
toolCall: PreprocessedToolCall,
hookEventName: "PreToolUse" | "PostToolUse",
): Promise<void> {
try {
if (!this.currentState.isEnabled) {
return;
}
const isFileEdit = ["Edit", "MultiEdit", "Write"].includes(toolCall.name);
if (!isFileEdit) {
return;
}
const filePath = this.extractFilePathFromToolCall(toolCall);
if (filePath) {
if (hookEventName === "PreToolUse") {
await this.beforeFileEdit(filePath);
} else if (hookEventName === "PostToolUse") {
await this.afterFileEdit(filePath);
}
}
} catch (error) {
logger.warn("git-ai tool use tracking failed", {
error,
toolCall,
hookEventName,
});
// Don't throw - allow tool use to proceed without Git AI checkpoint
}
}
async beforeFileEdit(filePath: string): Promise<void> {
if (!this.currentState.isEnabled) {
return;
}
// Skip if git-ai is not available
if (this.currentState.isGitAiAvailable === false) {
return;
}
try {
const session = getCurrentSession();
const sessionFilePath = getSessionFilePath();
// Get current model from ModelService via serviceContainer
const modelState = serviceContainer.getSync<ModelServiceState>("model");
const modelName = modelState?.value?.model?.model;
const hookInput: GitAiHookInput = {
session_id: session.sessionId,
transcript_path: sessionFilePath,
cwd: session.workspaceDirectory,
hook_event_name: "PreToolUse",
tool_input: {
file_path: filePath,
},
};
// Only include model if it's available
if (modelName) {
hookInput.model = modelName;
}
await this.callGitAiCheckpoint(hookInput, session.workspaceDirectory);
} catch (error) {
logger.warn("git-ai checkpoint (pre-edit) failed", { error, filePath });
// Mark as unavailable if command fails
this.setState({ isGitAiAvailable: false });
// Don't throw - allow file edit to proceed
}
}
async afterFileEdit(filePath: string): Promise<void> {
if (!this.currentState.isEnabled) {
return;
}
// Skip if git-ai is not available
if (this.currentState.isGitAiAvailable === false) {
return;
}
try {
const session = getCurrentSession();
const sessionFilePath = getSessionFilePath();
// Get current model from ModelService via serviceContainer
const modelState = serviceContainer.getSync<ModelServiceState>("model");
const modelName = modelState?.value?.model?.model;
const hookInput: GitAiHookInput = {
session_id: session.sessionId,
transcript_path: sessionFilePath,
cwd: session.workspaceDirectory,
hook_event_name: "PostToolUse",
tool_input: {
file_path: filePath,
},
};
// Only include model if it's available
if (modelName) {
hookInput.model = modelName;
}
await this.callGitAiCheckpoint(hookInput, session.workspaceDirectory);
} catch (error) {
logger.warn("git-ai checkpoint (post-edit) failed", { error, filePath });
// Mark as unavailable if command fails
this.setState({ isGitAiAvailable: false });
// Don't throw - file edit already completed
}
}
setEnabled(enabled: boolean): void {
this.setState({ isEnabled: enabled });
}
extractFilePathFromToolCall(toolCall: PreprocessedToolCall): string | null {
const preprocessed = toolCall.preprocessResult;
if (!preprocessed?.args) return null;
const args = preprocessed.args;
// Extract file path based on tool type
if (toolCall.name === "Edit" && args.resolvedPath) {
return args.resolvedPath;
} else if (toolCall.name === "MultiEdit" && args.file_path) {
return args.file_path;
} else if (toolCall.name === "Write" && args.filepath) {
return args.filepath;
}
return null;
}
}

View file

@ -10,6 +10,7 @@ import { AuthService } from "./AuthService.js";
import { ChatHistoryService } from "./ChatHistoryService.js";
import { ConfigService } from "./ConfigService.js";
import { FileIndexService } from "./FileIndexService.js";
import { GitAiIntegrationService } from "./GitAiIntegrationService.js";
import { MCPService } from "./MCPService.js";
import { ModelService } from "./ModelService.js";
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
@ -46,6 +47,7 @@ const agentFileService = new AgentFileService();
const toolPermissionService = new ToolPermissionService();
const systemMessageService = new SystemMessageService();
const artifactUploadService = new ArtifactUploadService();
const gitAiIntegrationService = new GitAiIntegrationService();
/**
* Initialize all services and register them with the service container
@ -310,6 +312,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
[], // No dependencies for now, but could depend on SESSION in future
);
serviceContainer.register(
SERVICE_NAMES.GIT_AI_INTEGRATION,
() => gitAiIntegrationService.initialize(),
[], // No dependencies
);
// Eagerly initialize all services to ensure they're ready when needed
// This avoids race conditions and "service not ready" errors
await serviceContainer.initializeAll();
@ -372,6 +380,7 @@ export const services = {
agentFile: agentFileService,
toolPermissions: toolPermissionService,
artifactUpload: artifactUploadService,
gitAiIntegration: gitAiIntegrationService,
} as const;
// Export the service container for advanced usage

View file

@ -132,6 +132,7 @@ export interface ArtifactUploadServiceState {
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
export type { GitAiIntegrationServiceState } from "./GitAiIntegrationService.js";
/**
* Service names as constants to prevent typos
@ -151,6 +152,7 @@ export const SERVICE_NAMES = {
STORAGE_SYNC: "storageSync",
AGENT_FILE: "agentFile",
ARTIFACT_UPLOAD: "artifactUpload",
GIT_AI_INTEGRATION: "gitAiIntegration",
} as const;
/**

View file

@ -24,13 +24,20 @@ import {
} from "./streamChatResponse.helpers.js";
import { StreamCallbacks } from "./streamChatResponse.types.js";
interface HandleToolCallsOptions {
toolCalls: ToolCall[];
chatHistory: ChatHistoryItem[];
content: string;
callbacks: StreamCallbacks | undefined;
isHeadless: boolean;
usage?: any;
}
export async function handleToolCalls(
toolCalls: ToolCall[],
chatHistory: ChatHistoryItem[],
content: string,
callbacks: StreamCallbacks | undefined,
isHeadless: boolean,
options: HandleToolCallsOptions,
): Promise<boolean> {
const { toolCalls, chatHistory, content, callbacks, isHeadless, usage } =
options;
const chatHistorySvc = services.chatHistory;
const useService =
typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady();
@ -38,15 +45,17 @@ export async function handleToolCalls(
if (content) {
if (useService) {
// Service-driven: write assistant message via service
chatHistorySvc.addAssistantMessage(content);
chatHistorySvc.addAssistantMessage(content, undefined, usage);
} else {
// Fallback only when service is unavailable
chatHistory.push(
createHistoryItem({
role: "assistant",
content,
}),
);
const message: any = {
role: "assistant",
content,
};
if (usage) {
message.usage = usage;
}
chatHistory.push(createHistoryItem(message));
}
}
return false;
@ -86,10 +95,14 @@ export async function handleToolCalls(
chatHistorySvc.addAssistantMessage(
assistantMessage.content || "",
assistantMessage.toolCalls,
usage,
);
} else {
// Fallback only when service is unavailable
chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
const messageWithUsage = usage
? { ...assistantMessage, usage }
: assistantMessage;
chatHistory.push(createHistoryItem(messageWithUsage, [], toolCallStates));
}
// First preprocess the tool calls

View file

@ -201,6 +201,7 @@ export async function processStreamingResponse(
finalContent: string; // Added field for final content only
toolCalls: ToolCall[];
shouldContinue: boolean;
usage?: any;
}> {
const {
model,
@ -344,6 +345,12 @@ export async function processStreamingResponse(
});
const totalDuration = responseEndTime - requestStartTime;
// Enhance fullUsage with model and cost for saving to session
if (fullUsage) {
fullUsage.model = model.model;
fullUsage.cost_cents = Math.round(cost * 100); // Convert dollars to cents
}
logger.debug("Stream complete", {
chunkCount,
responseLength: aiResponse.length,
@ -382,6 +389,7 @@ export async function processStreamingResponse(
finalContent: aiResponse,
toolCalls: [],
shouldContinue: false,
usage: fullUsage,
};
}
@ -418,6 +426,7 @@ export async function processStreamingResponse(
finalContent: finalContent,
toolCalls: validToolCalls,
shouldContinue: validToolCalls.length > 0,
usage: fullUsage,
};
}
@ -478,7 +487,7 @@ export async function streamChatResponse(
});
// Get response from LLM
const { content, toolCalls, shouldContinue } =
const { content, toolCalls, shouldContinue, usage } =
await processStreamingResponse({
isHeadless,
chatHistory,
@ -508,13 +517,14 @@ export async function streamChatResponse(
handleContentDisplay(content, callbacks, isHeadless);
// Handle tool calls and check for early return. This updates history via ChatHistoryService.
const shouldReturn = await handleToolCalls(
const shouldReturn = await handleToolCalls({
toolCalls,
chatHistory,
content,
callbacks,
isHeadless,
);
usage,
});
if (shouldReturn) {
return finalResponse || content || fullResponse;

View file

@ -0,0 +1,337 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { PreprocessedToolCall } from "./types.js";
import { executeToolCall } from "./index.js";
// Mock the services
vi.mock("../services/index.js", () => ({
services: {
gitAiIntegration: {
trackToolUse: vi.fn().mockResolvedValue(undefined),
},
},
SERVICE_NAMES: {},
serviceContainer: {},
}));
// Mock telemetry services
vi.mock("../telemetry/telemetryService.js", () => ({
telemetryService: {
logToolResult: vi.fn(),
},
}));
vi.mock("../telemetry/posthogService.js", () => ({
posthogService: {
capture: vi.fn(),
},
}));
// Mock logger
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
describe("Git AI Integration - executeToolCall", () => {
let mockGitAiService: any;
beforeEach(async () => {
const { services } = await import("../services/index.js");
mockGitAiService = services.gitAiIntegration;
vi.clearAllMocks();
});
afterEach(() => {
vi.clearAllMocks();
});
describe("File editing tools", () => {
it("should call git-ai before and after Edit tool execution", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("Edit completed"),
};
const toolCall: PreprocessedToolCall = {
id: "test-edit-id",
name: "Edit",
arguments: { file_path: "/test/file.ts" },
argumentsStr: JSON.stringify({ file_path: "/test/file.ts" }),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: {
resolvedPath: "/test/file.ts",
oldContent: "old",
newContent: "new",
},
},
};
const result = await executeToolCall(toolCall);
expect(result).toBe("Edit completed");
// Should call trackToolUse twice: PreToolUse and PostToolUse
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
// Check PreToolUse call
expect(mockGitAiService.trackToolUse).toHaveBeenNthCalledWith(
1,
toolCall,
"PreToolUse",
);
// Check PostToolUse call
expect(mockGitAiService.trackToolUse).toHaveBeenNthCalledWith(
2,
toolCall,
"PostToolUse",
);
// Verify tool.run was called
expect(mockTool.run).toHaveBeenCalledWith({
resolvedPath: "/test/file.ts",
oldContent: "old",
newContent: "new",
});
});
it("should call git-ai before and after MultiEdit tool execution", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("MultiEdit completed"),
};
const toolCall: PreprocessedToolCall = {
id: "test-multiedit-id",
name: "MultiEdit",
arguments: { file_path: "/test/file.ts" },
argumentsStr: JSON.stringify({ file_path: "/test/file.ts" }),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: {
file_path: "/test/file.ts",
edits: [],
},
},
};
await executeToolCall(toolCall);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PreToolUse",
);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PostToolUse",
);
});
it("should call git-ai before and after Write tool execution", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("Write completed"),
};
const toolCall: PreprocessedToolCall = {
id: "test-write-id",
name: "Write",
arguments: { filepath: "/test/newfile.ts" },
argumentsStr: JSON.stringify({ filepath: "/test/newfile.ts" }),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: {
filepath: "/test/newfile.ts",
content: "new content",
},
},
};
await executeToolCall(toolCall);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PreToolUse",
);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PostToolUse",
);
});
it("should complete file edit even if git-ai tracking encounters errors internally", async () => {
// Note: trackToolUse has internal error handling, so it won't throw
// This test verifies that the tool execution completes normally
const mockTool = {
run: vi.fn().mockResolvedValue("Edit completed despite internal error"),
};
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
const result = await executeToolCall(toolCall);
expect(result).toBe("Edit completed despite internal error");
expect(mockTool.run).toHaveBeenCalled();
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
});
});
describe("Non-file editing tools", () => {
it("should call trackToolUse for Bash tool (service will no-op internally)", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("Command output"),
};
const toolCall: PreprocessedToolCall = {
id: "test-bash-id",
name: "Bash",
arguments: { command: "ls" },
argumentsStr: JSON.stringify({ command: "ls" }),
startNotified: false,
tool: mockTool as any,
};
await executeToolCall(toolCall);
// trackToolUse is called but service checks isFileEdit internally
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PreToolUse",
);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PostToolUse",
);
expect(mockTool.run).toHaveBeenCalled();
});
it("should call trackToolUse for Read tool (service will no-op internally)", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("File contents"),
};
const toolCall: PreprocessedToolCall = {
id: "test-read-id",
name: "Read",
arguments: { file_path: "/test/file.ts" },
argumentsStr: JSON.stringify({ file_path: "/test/file.ts" }),
startNotified: false,
tool: mockTool as any,
};
await executeToolCall(toolCall);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
expect(mockTool.run).toHaveBeenCalled();
});
it("should call trackToolUse for Grep tool (service will no-op internally)", async () => {
const mockTool = {
run: vi.fn().mockResolvedValue("Search results"),
};
const toolCall: PreprocessedToolCall = {
id: "test-grep-id",
name: "Grep",
arguments: { pattern: "test" },
argumentsStr: JSON.stringify({ pattern: "test" }),
startNotified: false,
tool: mockTool as any,
};
await executeToolCall(toolCall);
expect(mockGitAiService.trackToolUse).toHaveBeenCalledTimes(2);
expect(mockTool.run).toHaveBeenCalled();
});
});
describe("Error handling", () => {
it("should propagate tool execution errors", async () => {
const mockTool = {
run: vi.fn().mockRejectedValue(new Error("Tool execution failed")),
};
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
await expect(executeToolCall(toolCall)).rejects.toThrow(
"Tool execution failed",
);
// PreToolUse should have been called
expect(mockGitAiService.trackToolUse).toHaveBeenCalledWith(
toolCall,
"PreToolUse",
);
});
});
describe("Execution order", () => {
it("should execute in correct order: PreToolUse -> tool.run -> PostToolUse", async () => {
const executionOrder: string[] = [];
mockGitAiService.trackToolUse.mockImplementation(
(_toolCall: any, phase: string) => {
executionOrder.push(`git-ai:${phase}`);
return Promise.resolve();
},
);
const mockTool = {
run: vi.fn().mockImplementation(() => {
executionOrder.push("tool:run");
return Promise.resolve("result");
}),
};
const toolCall: PreprocessedToolCall = {
id: "test-id",
name: "Edit",
arguments: {},
argumentsStr: JSON.stringify({}),
startNotified: false,
tool: mockTool as any,
preprocessResult: {
args: { resolvedPath: "/test/file.ts" },
},
};
await executeToolCall(toolCall);
expect(executionOrder).toEqual([
"git-ai:PreToolUse",
"tool:run",
"git-ai:PostToolUse",
]);
});
});
});

View file

@ -210,6 +210,9 @@ export async function executeToolCall(
arguments: toolCall.arguments,
});
// Track edits if Git AI is enabled (no-op if not enabled)
await services.gitAiIntegration.trackToolUse(toolCall, "PreToolUse");
// IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args
// Preprocessed arg names may be different
const result = await toolCall.tool.run(
@ -218,6 +221,9 @@ export async function executeToolCall(
);
const duration = Date.now() - startTime;
// Track edits if Git AI is enabled (no-op if not enabled)
await services.gitAiIntegration.trackToolUse(toolCall, "PostToolUse");
telemetryService.logToolResult({
toolName: toolCall.name,
success: true,

View file

@ -125,15 +125,19 @@ describe("TUIChat - Slash Commands Tests", () => {
stdin.write("/title");
let frameAfterCommand = lastFrame();
await waitForCondition(() => {
frameAfterCommand = lastFrame();
await waitForCondition(
() => {
frameAfterCommand = lastFrame();
return (
frameAfterCommand?.includes(
mode === "remote" ? "Remote Mode" : "/title",
) ?? false
);
});
return (
frameAfterCommand?.includes(
mode === "remote" ? "Remote Mode" : "/title",
) ?? false
);
},
5000,
100,
);
if (mode === "remote") {
// In remote mode, /title might not be a valid command, so just check we're in remote mode

View file

@ -24,7 +24,7 @@
</div>
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)
Get started in [Mission Control](https://hub.continue.dev/hub?type=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

View file

@ -60,8 +60,8 @@ class IntelliJIDE(
"*.db", "*.sqlite", "*.sqlite3", "*.mdb", "*.accdb",
// Credential and secret files
"*.secret", "*.secrets", "credentials", "credentials.*", "auth.json",
"token", "token.*", "*.token",
"*.secret", "*.secrets", "credentials", "auth.json",
"token", "*.token",
// Backup files that might contain sensitive data
"*.bak", "*.backup", "*.old", "*.orig",

View file

@ -34,7 +34,7 @@
"jsdom": "^24.0.0",
"lru-cache": "^11.0.2",
"minisearch": "^7.0.0",
"mocha": "^11.7.1",
"mocha": "^11.7.5",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"ncp": "^2.0.0",
@ -100,16 +100,16 @@
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-bedrock-runtime": "^3.931.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
"@aws-sdk/credential-providers": "^3.931.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@modelcontextprotocol/sdk": "^1.24.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@sentry/cli": "^2.50.2",
@ -7820,7 +7820,6 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz",
"integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==",
"dev": true,
"engines": {
"node": ">=8"
}
@ -9417,9 +9416,9 @@
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="
},
"node_modules/mocha": {
"version": "11.7.1",
"resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.1.tgz",
"integrity": "sha512-5EK+Cty6KheMS/YLPPMJC64g5V61gIR25KsRItHw6x4hEKT6Njp1n9LOlH4gpevuwMVS66SXaBBpg+RWZkza4A==",
"version": "11.7.5",
"resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.5.tgz",
"integrity": "sha512-mTT6RgopEYABzXWFx+GcJ+ZQ32kp4fMf0xvpZIIfSq9Z8lC/++MtcCnQ9t5FP2veYEP95FIYSvW+U9fV4xrlig==",
"license": "MIT",
"dependencies": {
"browser-stdout": "^1.3.1",
@ -9430,6 +9429,7 @@
"find-up": "^5.0.0",
"glob": "^10.4.5",
"he": "^1.2.0",
"is-path-inside": "^3.0.3",
"js-yaml": "^4.1.0",
"log-symbols": "^4.1.0",
"minimatch": "^9.0.5",

View file

@ -753,7 +753,7 @@
"jsdom": "^24.0.0",
"lru-cache": "^11.0.2",
"minisearch": "^7.0.0",
"mocha": "^11.7.1",
"mocha": "^11.7.5",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"ncp": "^2.0.0",

View file

@ -44,6 +44,19 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Without this it seems the file isn't completely written to disk
await new Promise((resolve) => setTimeout(resolve, 2000));
// Remove existing destination directory to ensure fresh copy
// ncp's clobber option doesn't reliably overwrite cached files
const packageSubdir = packageName.replace("@lancedb/", "");
const destDir = path.join(
currentDir,
"node_modules",
toCopy,
packageSubdir,
);
if (fs.existsSync(destDir)) {
rimrafSync(destDir);
}
// Copy the installed package back to the current directory
await new Promise((resolve, reject) => {
ncp(

View file

@ -37,7 +37,7 @@ export class ContinueConsoleWebviewViewProvider
this._webview.onDidReceiveMessage((message: FromConsoleView) => {
if (message.type === "start") {
this._currentUuid = message.uuid;
this._webview?.postMessage({
void this._webview?.postMessage({
type: "init",
uuid: this._currentUuid,
items: this.getAllItems(),
@ -70,7 +70,7 @@ export class ContinueConsoleWebviewViewProvider
if (e.affectsConfiguration(`${EXTENSION_NAME}.enableConsole`)) {
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
this._saveLog = config.get<boolean>("enableConsole");
if (!this._saveLog) {
if (this._saveLog === false) {
this.clearLog();
}
}
@ -103,7 +103,7 @@ export class ContinueConsoleWebviewViewProvider
}
if (this._currentUuid) {
this._webview?.postMessage({
void this._webview?.postMessage({
type: "item",
uuid: this._currentUuid,
item,
@ -116,7 +116,7 @@ export class ContinueConsoleWebviewViewProvider
MAX_INTERACTIONS
) {
let toRemove = this._completedInteractions.shift();
this._webview?.postMessage({
void this._webview?.postMessage({
type: "remove",
uuid: this._currentUuid,
interactionId: toRemove![0].interactionId,
@ -139,7 +139,7 @@ export class ContinueConsoleWebviewViewProvider
this._currentInteractions = new Map();
if (this._currentUuid) {
this._webview?.postMessage({
void this._webview?.postMessage({
type: "clear",
uuid: this._currentUuid,
});
@ -157,7 +157,10 @@ export class ContinueConsoleWebviewViewProvider
const inDevelopmentMode =
context?.extensionMode === vscode.ExtensionMode.Development;
if (!inDevelopmentMode) {
if (inDevelopmentMode) {
scriptUri = "http://localhost:5173/src/console.tsx";
styleMainUri = "http://localhost:5173/src/indexConsole.css";
} else {
scriptUri = panel.webview
.asWebviewUri(
vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.js"),
@ -168,9 +171,6 @@ export class ContinueConsoleWebviewViewProvider
vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.css"),
)
.toString();
} else {
scriptUri = "http://localhost:5173/src/console.tsx";
styleMainUri = "http://localhost:5173/src/indexConsole.css";
}
panel.webview.options = {

View file

@ -43,11 +43,11 @@ export class ContinueGUIWebviewViewProvider
}
public resetWebviewProtocolWebview(): void {
if (this._webview) {
this.webviewProtocol.webview = this._webview;
} else {
if (!this._webview) {
console.warn("no webview found during reset");
return;
}
this.webviewProtocol.webview = this._webview;
}
sendMainUserInput(input: string) {
@ -80,16 +80,16 @@ export class ContinueGUIWebviewViewProvider
const inDevelopmentMode =
context?.extensionMode === vscode.ExtensionMode.Development;
if (!inDevelopmentMode) {
if (inDevelopmentMode) {
scriptUri = "http://localhost:5173/src/main.tsx";
styleMainUri = "http://localhost:5173/src/index.css";
} else {
scriptUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js"))
.toString();
styleMainUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css"))
.toString();
} else {
scriptUri = "http://localhost:5173/src/main.tsx";
styleMainUri = "http://localhost:5173/src/index.css";
}
panel.webview.options = {
@ -121,7 +121,7 @@ export class ContinueGUIWebviewViewProvider
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
) {
// Send new theme to GUI to update embedded Monaco themes
this.webviewProtocol?.request("setTheme", { theme: getTheme() });
void this.webviewProtocol?.request("setTheme", { theme: getTheme() });
}
});

View file

@ -15,6 +15,7 @@ import {
import { Repository } from "./otherExtensions/git";
import { SecretStorage } from "./stubs/SecretStorage";
import { VsCodeIdeUtils } from "./util/ideUtils";
import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
import { VsCodeWebviewProtocol } from "./webviewProtocol";
@ -33,7 +34,6 @@ import type {
TerminalOptions,
Thread,
} from "core";
import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
class VsCodeIde implements IDE {
ideUtils: VsCodeIdeUtils;

View file

@ -58,7 +58,11 @@ import {
} from "../activation/SelectionChangeManager";
import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker";
import { getDefinitionsFromLsp } from "../autocomplete/lsp";
import { handleTextDocumentChange } from "../util/editLoggingUtils";
import {
clearDocumentContentCache,
handleTextDocumentChange,
initDocumentContentCache,
} from "../util/editLoggingUtils";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export class VsCodeExtension {
@ -476,6 +480,16 @@ export class VsCodeExtension {
});
}
// Initialize document content cache for tracking pre-edit content
vscode.workspace.onDidOpenTextDocument((document) => {
initDocumentContentCache(document);
});
// Initialize cache for all currently open documents
for (const document of vscode.workspace.textDocuments) {
initDocumentContentCache(document);
}
vscode.workspace.onDidChangeTextDocument(async (event) => {
if (event.contentChanges.length > 0) {
selectionManager.documentChanged();
@ -505,6 +519,7 @@ export class VsCodeExtension {
});
vscode.workspace.onDidCloseTextDocument(async (event) => {
clearDocumentContentCache(event.uri.toString());
this.core.invoke("files/closed", {
uris: [event.uri.toString()],
});

View file

@ -6,6 +6,51 @@ import { RecentlyEditedRange } from "core/nextEdit/types";
import * as vscode from "vscode";
import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
// Cache to store the last known content for each file (before edits)
const documentContentCache = new Map<string, string>();
/**
* Gets the cached content for a document, or reads the current content if not cached.
* This should be called BEFORE processing the edit to get the pre-edit state.
*/
export const getPreEditContent = (document: vscode.TextDocument): string => {
const uri = document.uri.toString();
const cached = documentContentCache.get(uri);
if (cached !== undefined) {
return cached;
}
// If not cached, this is the first edit we're seeing - the document's current state
// in the event is already post-edit, so we can't get the true pre-edit content.
// Return empty string to indicate no prior content was tracked.
return "";
};
/**
* Updates the cache with the current document content.
* This should be called AFTER processing the edit.
*/
export const updateDocumentContentCache = (
document: vscode.TextDocument,
): void => {
documentContentCache.set(document.uri.toString(), document.getText());
};
/**
* Initializes the cache for a document when it's opened.
*/
export const initDocumentContentCache = (
document: vscode.TextDocument,
): void => {
documentContentCache.set(document.uri.toString(), document.getText());
};
/**
* Removes a document from the cache when it's closed.
*/
export const clearDocumentContentCache = (uri: string): void => {
documentContentCache.delete(uri);
};
export const getBeforeCursorPos = (range: Range, activePos: Position) => {
// whichever side of the range isn't active is the before position
if (
@ -49,6 +94,9 @@ export const handleTextDocumentChange = async (
const workspaceDirUri = await getWorkspaceDirUri(event);
if (!workspaceDirUri) return;
// Get the pre-edit content from our cache BEFORE updating it
const fileContentsBefore = getPreEditContent(event.document);
const activeCursorPos = editor.selection.active;
const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({
filepath: event.document.uri.toString(),
@ -57,12 +105,16 @@ export const handleTextDocumentChange = async (
end: change.range.end as Position,
},
fileContents: event.document.getText(),
fileContentsBefore,
editText: change.text,
beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos),
afterCursorPos: activeCursorPos as Position,
workspaceDir: workspaceDirUri,
}));
// Update the cache with the new content AFTER capturing the edit
updateDocumentContentCache(event.document);
let recentlyEditedRanges: RecentlyEditedRange[] = [];
let recentlyVisitedRanges: AutocompleteCodeSnippet[] = [];

9
gui/package-lock.json generated
View file

@ -19,7 +19,7 @@
"@tiptap/extension-document": "^2.27.0",
"@tiptap/extension-dropcursor": "^2.27.0",
"@tiptap/extension-history": "^2.27.1",
"@tiptap/extension-image": "^2.1.16",
"@tiptap/extension-image": "^2.27.1",
"@tiptap/extension-mention": "^2.1.13",
"@tiptap/extension-paragraph": "^2.3.2",
"@tiptap/extension-placeholder": "^2.1.13",
@ -3294,9 +3294,10 @@
}
},
"node_modules/@tiptap/extension-image": {
"version": "2.26.1",
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-2.26.1.tgz",
"integrity": "sha512-96+MaYBJebQlR/ik5W72GLUfXdEoxFs+6jsoERxbM5qEdhb7TEnodBFtWZOwgDO27kFd6rSNZuW9r5KJNtljEg==",
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-2.27.1.tgz",
"integrity": "sha512-wu3vMKDYWJwKS6Hrw5PPCKBO2RxyHNeFLiA/uDErEV7axzNpievK/U9DyaDXmtK3K/h1XzJAJz19X+2d/pY68w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"

View file

@ -28,7 +28,7 @@
"@tiptap/extension-document": "^2.27.0",
"@tiptap/extension-dropcursor": "^2.27.0",
"@tiptap/extension-history": "^2.27.1",
"@tiptap/extension-image": "^2.1.16",
"@tiptap/extension-image": "^2.27.1",
"@tiptap/extension-mention": "^2.1.13",
"@tiptap/extension-paragraph": "^2.3.2",
"@tiptap/extension-placeholder": "^2.1.13",

View file

@ -0,0 +1,494 @@
# Vercel AI SDK Integration
## Why
### The Problem
The openai-adapters package contains ~50 provider implementations, each maintaining:
- Custom SSE parsing and chunk buffering
- Provider-specific streaming protocols
- Tool call serialization logic
- Type definitions that must stay in sync with provider APIs
- Error handling for provider-specific edge cases
This represents significant maintenance burden:
- Provider API changes require manual updates
- Streaming bugs must be debugged per-provider
- New features need implementation across all providers
- Type safety requires constant vigilance
### The Solution
The [Vercel AI SDK](https://sdk.vercel.ai/) is a well-maintained, provider-agnostic abstraction that:
- Handles streaming protocols automatically
- Tracks provider API changes
- Provides unified tool calling interface
- Maintains type safety
- Offers comprehensive error handling
By offloading this work to Vercel, we reduce ~60% of our maintenance burden while preserving all existing functionality.
## How It Works
### Feature-Flagged Implementation
The integration is feature-flagged for gradual rollout:
```typescript
// Enable for OpenAI
USE_VERCEL_AI_SDK_OPENAI=true cn
// Enable for Anthropic
USE_VERCEL_AI_SDK_ANTHROPIC=true cn
```
When disabled (default), the original implementation is used. When enabled, Vercel AI SDK handles the provider communication while we maintain the same external API.
### Architecture
```
┌─────────────────────────────────────────────┐
│ Consumer (CLI / Core IDE) │
│ - Uses openai-adapters package │
│ - No code changes required │
└──────────────────┬──────────────────────────┘
│
│ Same API (BaseLlmApi)
│
┌──────────────────▼──────────────────────────┐
│ openai-adapters Package │
│ │
│ ┌────────────┐ ┌────────────┐ │
│ │ OpenAIApi │ │AnthropicApi│ │
│ └─────┬──────┘ └─────┬──────┘ │
│ │ │ │
│ Feature Flag? Feature Flag? │
│ │ │ │
│ ┌───┴────┐ ┌──┴────┐ │
│ │ Yes │ │ Yes │ │
│ ▼ │ ▼ │ │
│ ┌────────┐ │ ┌────────┐│ │
│ │ Vercel │ │ │ Vercel ││ │
│ │ SDK │ │ │ SDK ││ │
│ └────────┘ │ └────────┘│ │
│ │ │ │
│ ┌───┘ ┌───┘ │
│ │ No │ No │
│ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ │
│ │ Original │ │ Original │ │
│ │ SDK │ │ SDK │ │
│ └────────────┘ └────────────┘ │
└─────────────────────────────────────────────┘
```
### Custom Fetch Preservation
All RequestOptions (headers, proxy, SSL certs, timeout) are fully preserved:
```typescript
// Only use customFetch when RequestOptions are present
const hasRequestOptions =
config.requestOptions &&
(config.requestOptions.headers ||
config.requestOptions.proxy ||
config.requestOptions.caBundlePath ||
config.requestOptions.clientCertificate ||
config.requestOptions.extraBodyProperties);
this.openaiProvider = createOpenAI({
apiKey: config.apiKey ?? "",
baseURL:
this.apiBase !== "https://api.openai.com/v1/" ? this.apiBase : undefined,
fetch: hasRequestOptions ? customFetch(config.requestOptions) : undefined,
});
```
When no custom options are needed, we use native fetch for Web Streams API compatibility.
### Format Conversion
Vercel AI SDK uses different formats than OpenAI. We handle conversion transparently:
**Tool Format:**
```typescript
// OpenAI format (input)
{
type: "function",
function: {
name: "readFile",
description: "Read a file",
parameters: { /* JSON Schema */ }
}
}
// Vercel format (converted)
{
readFile: {
description: "Read a file",
parameters: aiJsonSchema({ /* JSON Schema */ })
}
}
```
**Stream Events:**
```typescript
// Vercel AI SDK emits various event types
for await (const part of stream.fullStream) {
switch (part.type) {
case 'text-delta':
yield chatChunk({ content: part.textDelta });
break;
case 'tool-call':
yield chatChunkFromDelta({ delta: { tool_calls: [...] } });
break;
case 'finish':
yield usageChatChunk({ usage: part.usage });
break;
// Filter out events with no OpenAI equivalent
case 'step-start':
case 'step-finish':
case 'tool-result':
continue;
}
}
```
All conversion logic lives in shared utilities:
- `convertToolsToVercelFormat()` - Tool conversion
- `convertVercelStream()` - Stream event conversion
- `convertOpenAIMessagesToVercel()` - Message conversion
### Automatic Fallbacks
The implementation intelligently falls back to original SDK when needed:
**1. OpenAI Responses Endpoint (o1/o3 models)**
```typescript
if (this.shouldUseResponsesEndpoint(body.model)) {
// Use responses endpoint instead of Vercel SDK
const response = await this.responsesNonStream(body, signal);
return responseToChatCompletion(response);
}
```
**2. Anthropic Multi-turn Tool Conversations**
```typescript
// Vercel SDK manages tool call lifecycle internally
// Can't handle pre-existing tool results in history
const hasToolMessages = body.messages.some((msg) => msg.role === "tool");
if (this.useVercelSDK && this.anthropicProvider && !hasToolMessages) {
yield * this.chatCompletionStreamVercel(body, signal);
return;
}
// Fall back to original for tool conversations
yield * this.handleStreamResponse(response, body.model);
```
## Implementation Details
### Files Modified
**Core Implementation:**
- `src/apis/OpenAI.ts` - Added Vercel SDK branch with feature flag
- `src/apis/Anthropic.ts` - Added Vercel SDK branch with fallback logic
**Shared Utilities (new):**
- `src/convertToolsToVercel.ts` - Tool format conversion
- `src/vercelStreamConverter.ts` - Stream event conversion
- `src/openaiToVercelMessages.ts` - Message format conversion
**Tests (new):**
- `src/test/vercel-sdk.test.ts` - 28 integration tests
- `src/test/convertToolsToVercel.test.ts` - 8 unit tests
- `src/test/vercelStreamConverter.test.ts` - 17 unit tests
- `src/test/multi-turn-tools.test.ts` - Multi-turn conversation test
- `src/test/cli-tools.test.ts` - CLI tool compatibility tests
### OpenAI Implementation
```typescript
export class OpenAIApi implements BaseLlmApi {
private openaiProvider?: ReturnType<typeof createOpenAI>;
private useVercelSDK: boolean;
constructor(protected config: OpenAIConfig) {
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_OPENAI === "true";
if (this.useVercelSDK) {
this.openaiProvider = createOpenAI({
apiKey: config.apiKey ?? "",
baseURL:
this.apiBase !== "https://api.openai.com/v1/"
? this.apiBase
: undefined,
fetch: hasRequestOptions
? customFetch(config.requestOptions)
: undefined,
});
}
// Always create original client for fallback
this.openai = new OpenAI({
/* ... */
});
}
async *chatCompletionStream(body, signal) {
if (
this.useVercelSDK &&
this.openaiProvider &&
!this.shouldUseResponsesEndpoint(body.model)
) {
const model = this.openaiProvider(body.model);
const vercelTools = convertToolsToVercelFormat(body.tools);
const stream = await streamText({
model,
messages: body.messages,
tools: vercelTools,
// ... other parameters
});
yield* convertVercelStream(stream.fullStream, { model: body.model });
return;
}
// Fall back to original implementation
const response = await this.openai.chat.completions.create(body);
for await (const result of response) {
yield result;
}
}
}
```
### Anthropic Implementation
```typescript
export class AnthropicApi implements BaseLlmApi {
private anthropicProvider?: ReturnType<typeof createAnthropic>;
private useVercelSDK: boolean;
constructor(protected config: AnthropicConfig) {
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_ANTHROPIC === "true";
if (this.useVercelSDK) {
this.anthropicProvider = createAnthropic({
apiKey: config.apiKey ?? "",
baseURL:
this.apiBase !== "https://api.anthropic.com/v1/"
? this.apiBase
: undefined,
fetch: hasRequestOptions
? customFetch(config.requestOptions)
: undefined,
});
}
}
async *chatCompletionStream(body, signal) {
// Check for tool messages in history
const hasToolMessages = body.messages.some((msg) => msg.role === "tool");
if (this.useVercelSDK && this.anthropicProvider && !hasToolMessages) {
const vercelMessages = convertOpenAIMessagesToVercel(body.messages);
const model = this.anthropicProvider(body.model);
const vercelTools = convertToolsToVercelFormat(body.tools);
const stream = await streamText({
model,
messages: vercelMessages,
tools: vercelTools,
// ... other parameters
});
for await (const chunk of convertVercelStream(stream.fullStream, {
model: body.model,
})) {
yield chunk;
}
return;
}
// Fall back to original implementation
const response = await customFetch(config.requestOptions)(
new URL("messages", this.apiBase),
{ method: "POST", body: JSON.stringify(this._convertBody(body)), signal },
);
yield* this.handleStreamResponse(response, body.model);
}
}
```
## What's Preserved
### 100% Backward Compatibility
- ✅ Same `BaseLlmApi` interface
- ✅ Same input/output formats
- ✅ All existing tests pass (191 tests)
- ✅ Zero consumer code changes
- ✅ Custom fetch (headers, proxy, SSL, timeout)
- ✅ Request options infrastructure
- ✅ Provider factory logic
- ✅ Error handling
- ✅ Usage tracking (token counts)
### What Still Uses Original Implementation
- FIM completion (not supported by Vercel SDK)
- Reranking (not supported by Vercel SDK)
- Embeddings (not supported by Vercel SDK)
- OpenAI responses endpoint (for o1/o3 models)
- Anthropic multi-turn tool conversations (lifecycle managed by Vercel SDK)
## Benefits
### Maintenance Reduction
**Offloaded to Vercel (~60%):**
- ✅ SSE parsing and chunk buffering
- ✅ Provider API versioning
- ✅ Tool call serialization
- ✅ Provider-specific error codes
- ✅ Type safety maintenance
- ✅ Streaming protocol handling
- ✅ Backpressure management
**Still Maintained (~40%):**
- Format translation (simplified by Vercel SDK's normalized interface)
- Custom features (responses endpoint, FIM, reranking)
- RequestOptions infrastructure
- Provider factory logic
### Code Quality
**Immediate:**
- Shared utilities eliminate duplication
- Better test coverage (57 new tests)
- Cleaner separation of concerns
**After Full Rollout (~300 LOC reduction):**
- Complete elimination of SSE parsing
- No more provider-specific chunking
- Simplified error handling
- Reduced type maintenance
### Rollback Strategy
**Immediate (< 1 minute):**
```bash
USE_VERCEL_AI_SDK_OPENAI=false cn
```
**Short-term (< 1 hour):**
```json
"@continuedev/openai-adapters": "1.31.0"
```
**Long-term:**
Revert commits (feature flags preserve old code)
## Testing
### Run All Tests
```bash
npm test
```
### Test with Vercel SDK Enabled
```bash
USE_VERCEL_AI_SDK_OPENAI=true cn
USE_VERCEL_AI_SDK_ANTHROPIC=true cn
```
### Test Scenarios
1. **Basic chat** - Simple questions, streaming responses
2. **Tool calls** - First turn tool usage
3. **Multi-turn tools** - Conversation with tool results (Anthropic falls back)
4. **Custom options** - Proxy, headers, SSL certificates
5. **Error handling** - Invalid API key, network errors
6. **Responses endpoint** - o1/o3 models (OpenAI falls back)
All scenarios should work identically with flags enabled/disabled.
## Known Limitations
### Anthropic Multi-turn Tool Conversations
**Behavior:** Automatically falls back to original implementation when `role: "tool"` messages exist in history.
**Why:** Vercel AI SDK manages tool call lifecycle internally and doesn't support resuming from pre-existing tool conversations.
**Impact:** Minimal - tool calls still work, just uses original implementation for subsequent turns.
### OpenAI Responses Endpoint
**Behavior:** o1/o3 models bypass Vercel SDK and use responses endpoint.
**Why:** These models have unique message handling requirements.
**Impact:** None - automatic fallback is transparent.
### Not Yet Migrated
- Other 48 providers (Gemini, Mistral, Azure, Bedrock, etc.)
- FIM completion
- Reranking
- Embeddings
## Future Work
### High Priority
1. Migrate additional providers (Gemini, Mistral)
2. Performance monitoring and optimization
3. Enhanced logging for fallback decisions
### Medium Priority
4. Investigate Anthropic prompt caching with Vercel SDK
5. Verify vision/image support with Vercel SDK
6. Add metrics collection
### Low Priority
7. Migrate remaining providers
8. Add inline documentation
9. Create usage examples
## Summary
The Vercel AI SDK integration:
- **Reduces maintenance burden by ~60%**
- **Preserves 100% backward compatibility**
- **Enables easy rollback at any point**
- **Improves code quality and test coverage**
- **Benefits both CLI and Core IDE**
- **No consumer code changes required**
The implementation is production-ready and awaiting Phase 3 validation testing.

File diff suppressed because it is too large Load diff

View file

@ -12,13 +12,16 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/anthropic": "^1.0.10",
"@ai-sdk/openai": "^1.0.10",
"@anthropic-ai/sdk": "^0.67.0",
"@aws-sdk/client-bedrock-runtime": "^3.929.0",
"@aws-sdk/credential-providers": "^3.929.0",
"@aws-sdk/client-bedrock-runtime": "^3.931.0",
"@aws-sdk/credential-providers": "^3.931.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.36.0",
"@continuedev/fetch": "^1.6.0",
"@google/genai": "^1.30.0",
"ai": "^4.0.33",
"dotenv": "^16.5.0",
"google-auth-library": "^10.4.1",
"json-schema": "^0.4.0",

View file

@ -54,6 +54,8 @@ import {
export class AnthropicApi implements BaseLlmApi {
apiBase: string = "https://api.anthropic.com/v1/";
private anthropicProvider?: any;
private useVercelSDK: boolean;
constructor(
protected config: AnthropicConfig & {
@ -64,6 +66,36 @@ export class AnthropicApi implements BaseLlmApi {
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_ANTHROPIC === "true";
}
private async initializeVercelProvider() {
if (!this.anthropicProvider && this.useVercelSDK) {
const { createAnthropic } = await import("@ai-sdk/anthropic");
// Only use customFetch if we have request options that need it
// Otherwise use native fetch (Vercel AI SDK requires Web Streams API)
const hasRequestOptions =
this.config.requestOptions &&
(this.config.requestOptions.headers ||
this.config.requestOptions.proxy ||
this.config.requestOptions.caBundlePath ||
this.config.requestOptions.clientCertificate ||
this.config.requestOptions.extraBodyProperties);
this.anthropicProvider = createAnthropic({
apiKey: this.config.apiKey ?? "",
baseURL:
this.apiBase !== "https://api.anthropic.com/v1/" &&
this.apiBase !== "https://api.anthropic.com/v1"
? this.apiBase.replace(/\/$/, "")
: undefined,
fetch: hasRequestOptions
? customFetch(this.config.requestOptions)
: undefined,
});
}
}
private _convertBody(oaiBody: ChatCompletionCreateParams) {
@ -303,6 +335,14 @@ export class AnthropicApi implements BaseLlmApi {
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
// Check if message history contains tool results
// Vercel SDK cannot handle pre-existing tool call conversations
const hasToolMessages = body.messages.some((msg) => msg.role === "tool");
if (this.useVercelSDK && !hasToolMessages) {
return this.chatCompletionNonStreamVercel(body, signal);
}
const response = await customFetch(this.config.requestOptions)(
new URL("messages", this.apiBase),
{
@ -324,7 +364,7 @@ export class AnthropicApi implements BaseLlmApi {
id: completion.id,
object: "chat.completion",
model: body.model,
created: Date.now(),
created: Math.floor(Date.now() / 1000),
usage: {
total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
completion_tokens: usage?.output_tokens ?? 0,
@ -350,6 +390,108 @@ export class AnthropicApi implements BaseLlmApi {
};
}
private async chatCompletionNonStreamVercel(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
await this.initializeVercelProvider();
if (!this.anthropicProvider) {
throw new Error("Vercel AI SDK Anthropic provider not initialized");
}
const { generateText } = await import("ai");
const { convertOpenAIMessagesToVercel } = await import(
"../openaiToVercelMessages.js"
);
const { convertToolsToVercelFormat } = await import(
"../convertToolsToVercel.js"
);
const { convertToolChoiceToVercel } = await import(
"../convertToolChoiceToVercel.js"
);
// Convert OpenAI messages to Vercel AI SDK CoreMessage format
const vercelMessages = convertOpenAIMessagesToVercel(body.messages);
// Extract system message
const systemMsg = vercelMessages.find((msg) => msg.role === "system");
const systemText =
systemMsg && typeof systemMsg.content === "string"
? systemMsg.content
: undefined;
// Filter out system messages - Vercel AI SDK handles them separately
const nonSystemMessages = vercelMessages.filter(
(msg) => msg.role !== "system",
);
const model = this.anthropicProvider(body.model);
// Convert OpenAI tools to Vercel AI SDK format
const vercelTools = await convertToolsToVercelFormat(body.tools);
const result = await generateText({
model,
system: systemText,
messages: nonSystemMessages as any,
temperature: body.temperature ?? undefined,
maxTokens: body.max_tokens ?? undefined,
topP: body.top_p ?? undefined,
stopSequences: body.stop
? Array.isArray(body.stop)
? body.stop
: [body.stop]
: undefined,
tools: vercelTools,
toolChoice: convertToolChoiceToVercel(body.tool_choice),
abortSignal: signal,
});
// Convert Vercel AI SDK result to OpenAI ChatCompletion format
const toolCalls = result.toolCalls?.map((tc) => ({
id: tc.toolCallId,
type: "function" as const,
function: {
name: tc.toolName,
arguments: JSON.stringify(tc.args),
},
}));
return {
id: result.response?.id ?? "",
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: body.model,
choices: [
{
index: 0,
message: {
role: "assistant",
content: result.text,
tool_calls: toolCalls,
refusal: null,
},
finish_reason:
result.finishReason === "tool-calls" ? "tool_calls" : "stop",
logprobs: null,
},
],
usage: {
prompt_tokens: result.usage.promptTokens,
completion_tokens: result.usage.completionTokens,
total_tokens: result.usage.totalTokens,
prompt_tokens_details: {
cached_tokens:
(result.usage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_read_tokens:
(result.usage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_write_tokens: 0,
} as any,
},
};
}
// This is split off so e.g. VertexAI can use it
async *handleStreamResponse(response: any, model: string) {
let lastToolUseId: string | undefined;
@ -442,6 +584,15 @@ export class AnthropicApi implements BaseLlmApi {
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk> {
// Check if message history contains tool results
// Vercel SDK cannot handle pre-existing tool call conversations
const hasToolMessages = body.messages.some((msg) => msg.role === "tool");
if (this.useVercelSDK && !hasToolMessages) {
yield* this.chatCompletionStreamVercel(body, signal);
return;
}
const response = await customFetch(this.config.requestOptions)(
new URL("messages", this.apiBase),
{
@ -454,6 +605,72 @@ export class AnthropicApi implements BaseLlmApi {
yield* this.handleStreamResponse(response, body.model);
}
private async *chatCompletionStreamVercel(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk> {
await this.initializeVercelProvider();
if (!this.anthropicProvider) {
throw new Error("Vercel AI SDK Anthropic provider not initialized");
}
const { streamText } = await import("ai");
const { convertOpenAIMessagesToVercel } = await import(
"../openaiToVercelMessages.js"
);
const { convertToolsToVercelFormat } = await import(
"../convertToolsToVercel.js"
);
const { convertVercelStream } = await import("../vercelStreamConverter.js");
const { convertToolChoiceToVercel } = await import(
"../convertToolChoiceToVercel.js"
);
// Convert OpenAI messages to Vercel AI SDK CoreMessage format
const vercelMessages = convertOpenAIMessagesToVercel(body.messages);
// Extract system message
const systemMsg = vercelMessages.find((msg) => msg.role === "system");
const systemText =
systemMsg && typeof systemMsg.content === "string"
? systemMsg.content
: undefined;
// Filter out system messages - Vercel AI SDK handles them separately
const nonSystemMessages = vercelMessages.filter(
(msg) => msg.role !== "system",
);
const model = this.anthropicProvider(body.model);
// Convert OpenAI tools to Vercel AI SDK format
const vercelTools = await convertToolsToVercelFormat(body.tools);
const stream = await streamText({
model,
system: systemText,
messages: nonSystemMessages as any,
temperature: body.temperature ?? undefined,
maxTokens: body.max_tokens ?? undefined,
topP: body.top_p ?? undefined,
stopSequences: body.stop
? Array.isArray(body.stop)
? body.stop
: [body.stop]
: undefined,
tools: vercelTools,
toolChoice: convertToolChoiceToVercel(body.tool_choice),
abortSignal: signal,
});
// Convert Vercel AI SDK stream to OpenAI format
// The finish event in fullStream contains the usage data
yield* convertVercelStream(stream.fullStream as any, {
model: body.model,
});
}
private getHeaders(): Record<string, string> {
const enableCaching = this.config?.cachingStrategy !== "none";
return getAnthropicHeaders(this.config.apiKey, enableCaching, this.apiBase);

View file

@ -1,3 +1,5 @@
// IMPORTANT: Import nativeFetch FIRST to preserve native fetch before any pollution
import { withNativeFetch } from "../util/nativeFetch.js";
import { GoogleGenAI } from "@google/genai";
import { OpenAI } from "openai/index";
import {
@ -70,9 +72,14 @@ export class GeminiApi implements BaseLlmApi {
constructor(protected config: GeminiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
this.genAI = new GoogleGenAI({
apiKey: this.config.apiKey,
});
// Create GoogleGenAI with native fetch to avoid pollution
// from Vercel AI SDK packages that can break stream handling
this.genAI = withNativeFetch(
() =>
new GoogleGenAI({
apiKey: this.config.apiKey,
}),
);
}
private _oaiPartToGeminiPart(
@ -393,15 +400,19 @@ export class GeminiApi implements BaseLlmApi {
model: string,
convertedBody: ReturnType<typeof this._convertBody>,
) {
return genAI.models.generateContentStream({
model,
contents: convertedBody.contents,
config: {
systemInstruction: convertedBody.systemInstruction,
tools: convertedBody.tools,
...convertedBody.generationConfig,
},
});
// Use native fetch temporarily for stream operation to get proper ReadableStream
// The withNativeFetch wrapper restores native fetch, makes the call, then reverts
return withNativeFetch(() =>
genAI.models.generateContentStream({
model,
contents: convertedBody.contents,
config: {
systemInstruction: convertedBody.systemInstruction,
tools: convertedBody.tools,
...convertedBody.generationConfig,
},
}),
);
}
async *chatCompletionStream(

View file

@ -17,7 +17,12 @@ import type {
} from "openai/resources/responses/responses.js";
import { z } from "zod";
import { OpenAIConfigSchema } from "../types.js";
import { customFetch } from "../util.js";
import {
customFetch,
chatChunk,
usageChatChunk,
chatChunkFromDelta,
} from "../util.js";
import {
createResponsesStreamState,
fromResponsesChunk,
@ -35,9 +40,14 @@ import {
export class OpenAIApi implements BaseLlmApi {
openai: OpenAI;
apiBase: string = "https://api.openai.com/v1/";
private openaiProvider?: any;
private useVercelSDK: boolean;
constructor(protected config: z.infer<typeof OpenAIConfigSchema>) {
this.apiBase = config.apiBase ?? this.apiBase;
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_OPENAI === "true";
// Always create the original OpenAI client for fallback
this.openai = new OpenAI({
// Necessary because `new OpenAI()` will throw an error if there is no API Key
apiKey: config.apiKey ?? "",
@ -45,6 +55,33 @@ export class OpenAIApi implements BaseLlmApi {
fetch: customFetch(config.requestOptions),
});
}
private async initializeVercelProvider() {
if (!this.openaiProvider && this.useVercelSDK) {
const { createOpenAI } = await import("@ai-sdk/openai");
// Only use customFetch if we have request options that need it
// Otherwise use native fetch (Vercel AI SDK requires Web Streams API)
const hasRequestOptions =
this.config.requestOptions &&
(this.config.requestOptions.headers ||
this.config.requestOptions.proxy ||
this.config.requestOptions.caBundlePath ||
this.config.requestOptions.clientCertificate ||
this.config.requestOptions.extraBodyProperties);
this.openaiProvider = createOpenAI({
apiKey: this.config.apiKey ?? "",
baseURL:
this.apiBase !== "https://api.openai.com/v1/"
? this.apiBase
: undefined,
fetch: hasRequestOptions
? customFetch(this.config.requestOptions)
: undefined,
});
}
}
modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
// Add stream_options to include usage in streaming responses
if (body.stream) {
@ -114,6 +151,10 @@ export class OpenAIApi implements BaseLlmApi {
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
if (this.useVercelSDK && !this.shouldUseResponsesEndpoint(body.model)) {
return this.chatCompletionNonStreamVercel(body, signal);
}
if (this.shouldUseResponsesEndpoint(body.model)) {
const response = await this.responsesNonStream(body, signal);
return responseToChatCompletion(response);
@ -127,10 +168,97 @@ export class OpenAIApi implements BaseLlmApi {
return response;
}
private async chatCompletionNonStreamVercel(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
await this.initializeVercelProvider();
if (!this.openaiProvider) {
throw new Error("Vercel AI SDK provider not initialized");
}
const { generateText } = await import("ai");
const { convertToolsToVercelFormat } = await import(
"../convertToolsToVercel.js"
);
const { convertToolChoiceToVercel } = await import(
"../convertToolChoiceToVercel.js"
);
const modifiedBody = this.modifyChatBody({ ...body });
const model = this.openaiProvider(modifiedBody.model);
// Convert OpenAI tools to Vercel AI SDK format
const vercelTools = await convertToolsToVercelFormat(modifiedBody.tools);
const result = await generateText({
model,
messages: modifiedBody.messages as any,
temperature: modifiedBody.temperature ?? undefined,
maxTokens:
modifiedBody.max_completion_tokens ??
modifiedBody.max_tokens ??
undefined,
topP: modifiedBody.top_p ?? undefined,
frequencyPenalty: modifiedBody.frequency_penalty ?? undefined,
presencePenalty: modifiedBody.presence_penalty ?? undefined,
stopSequences: modifiedBody.stop
? Array.isArray(modifiedBody.stop)
? modifiedBody.stop
: [modifiedBody.stop]
: undefined,
tools: vercelTools,
toolChoice: convertToolChoiceToVercel(modifiedBody.tool_choice),
abortSignal: signal,
});
// Convert Vercel AI SDK result to OpenAI ChatCompletion format
const toolCalls = result.toolCalls?.map((tc, index) => ({
id: tc.toolCallId,
type: "function" as const,
function: {
name: tc.toolName,
arguments: JSON.stringify(tc.args),
},
}));
return {
id: result.response?.id ?? "",
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: modifiedBody.model,
choices: [
{
index: 0,
message: {
role: "assistant",
content: result.text,
tool_calls: toolCalls,
refusal: null,
},
finish_reason:
result.finishReason === "tool-calls" ? "tool_calls" : "stop",
logprobs: null,
},
],
usage: {
prompt_tokens: result.usage.promptTokens,
completion_tokens: result.usage.completionTokens,
total_tokens: result.usage.totalTokens,
},
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
if (this.useVercelSDK && !this.shouldUseResponsesEndpoint(body.model)) {
yield* this.chatCompletionStreamVercel(body, signal);
return;
}
if (this.shouldUseResponsesEndpoint(body.model)) {
for await (const chunk of this.responsesStream(body, signal)) {
yield chunk;
@ -158,6 +286,59 @@ export class OpenAIApi implements BaseLlmApi {
yield lastChunkWithUsage;
}
}
private async *chatCompletionStreamVercel(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
await this.initializeVercelProvider();
if (!this.openaiProvider) {
throw new Error("Vercel AI SDK provider not initialized");
}
const { streamText } = await import("ai");
const { convertToolsToVercelFormat } = await import(
"../convertToolsToVercel.js"
);
const { convertVercelStream } = await import("../vercelStreamConverter.js");
const { convertToolChoiceToVercel } = await import(
"../convertToolChoiceToVercel.js"
);
const modifiedBody = this.modifyChatBody({ ...body });
const model = this.openaiProvider(modifiedBody.model);
// Convert OpenAI tools to Vercel AI SDK format
const vercelTools = await convertToolsToVercelFormat(modifiedBody.tools);
const stream = await streamText({
model,
messages: modifiedBody.messages as any,
temperature: modifiedBody.temperature ?? undefined,
maxTokens:
modifiedBody.max_completion_tokens ??
modifiedBody.max_tokens ??
undefined,
topP: modifiedBody.top_p ?? undefined,
frequencyPenalty: modifiedBody.frequency_penalty ?? undefined,
presencePenalty: modifiedBody.presence_penalty ?? undefined,
stopSequences: modifiedBody.stop
? Array.isArray(modifiedBody.stop)
? modifiedBody.stop
: [modifiedBody.stop]
: undefined,
tools: vercelTools,
toolChoice: convertToolChoiceToVercel(modifiedBody.tool_choice),
abortSignal: signal,
});
// Convert Vercel AI SDK stream to OpenAI format
// The finish event in fullStream contains the usage data
yield* convertVercelStream(stream.fullStream as any, {
model: modifiedBody.model,
});
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
signal: AbortSignal,

View file

@ -0,0 +1,45 @@
/**
* Converts OpenAI tool_choice format to Vercel AI SDK toolChoice format
*/
import type { ChatCompletionToolChoiceOption } from "openai/resources/index.js";
/**
* Converts OpenAI tool_choice to Vercel AI SDK toolChoice format
*
* OpenAI format:
* - 'auto' | 'none' | 'required'
* - { type: 'function', function: { name: string } }
*
* Vercel AI SDK format:
* - 'auto' | 'none' | 'required'
* - { type: 'tool', toolName: string }
*/
export function convertToolChoiceToVercel(
toolChoice: ChatCompletionToolChoiceOption | undefined,
):
| "auto"
| "none"
| "required"
| { type: "tool"; toolName: string }
| undefined {
if (!toolChoice) {
return undefined;
}
// String values pass through
if (typeof toolChoice === "string") {
return toolChoice as "auto" | "none" | "required";
}
// Convert object format
if (toolChoice.type === "function") {
return {
type: "tool",
toolName: toolChoice.function.name,
};
}
// Unknown format - return undefined to let Vercel handle it
return undefined;
}

View file

@ -0,0 +1,38 @@
/**
* Converts OpenAI tool format to Vercel AI SDK format
*/
import type { ChatCompletionCreateParams } from "openai/resources/index.js";
/**
* Converts OpenAI tool format to Vercel AI SDK format.
*
* OpenAI format: { type: "function", function: { name, description, parameters: JSONSchema } }
* Vercel format: { [toolName]: { description, parameters: aiJsonSchema(JSONSchema) } }
*
* @param openaiTools - Array of OpenAI tools or undefined
* @returns Object with tool names as keys, or undefined if no tools
*/
export async function convertToolsToVercelFormat(
openaiTools?: ChatCompletionCreateParams["tools"],
): Promise<Record<string, any> | undefined> {
if (!openaiTools || openaiTools.length === 0) {
return undefined;
}
const { jsonSchema: aiJsonSchema } = await import("ai");
const vercelTools: Record<string, any> = {};
for (const tool of openaiTools) {
if (tool.type === "function") {
vercelTools[tool.function.name] = {
description: tool.function.description,
parameters: aiJsonSchema(
tool.function.parameters ?? { type: "object", properties: {} },
),
};
}
}
return Object.keys(vercelTools).length > 0 ? vercelTools : undefined;
}

View file

@ -0,0 +1,97 @@
/**
* Converts OpenAI ChatCompletionMessageParam format to Vercel AI SDK CoreMessage format
*/
import type { ChatCompletionMessageParam } from "openai/resources/index.js";
export interface VercelCoreMessage {
role: "system" | "user" | "assistant" | "tool";
content: string | Array<any>;
}
/**
* Converts OpenAI messages to Vercel AI SDK CoreMessage format.
*
* Key differences:
* - OpenAI tool results: { role: "tool", tool_call_id: "...", content: "string" }
* - Vercel tool results: { role: "tool", content: [{ type: "tool-result", toolCallId: "...", toolName: "...", result: any }] }
*
* IMPORTANT: For multi-turn conversations with tools:
* - We EXCLUDE assistant messages that have tool_calls because Vercel AI SDK manages tool call state internally
* - We only include tool results, and Vercel will associate them with its internal tool call tracking
*/
export function convertOpenAIMessagesToVercel(
messages: ChatCompletionMessageParam[],
): VercelCoreMessage[] {
const vercelMessages: VercelCoreMessage[] = [];
// Build a map of tool_call_id => toolName from assistant messages
const toolCallMap = new Map<string, string>();
// First pass: collect tool call names
for (const msg of messages) {
if (msg.role === "assistant" && msg.tool_calls) {
for (const tc of msg.tool_calls) {
if (tc.type === "function") {
toolCallMap.set(tc.id, tc.function.name);
}
}
}
}
// Second pass: convert messages
for (const msg of messages) {
switch (msg.role) {
case "system":
vercelMessages.push({
role: "system",
content:
typeof msg.content === "string"
? msg.content
: JSON.stringify(msg.content),
});
break;
case "user":
vercelMessages.push({
role: "user",
content: msg.content,
});
break;
case "assistant":
// CRITICAL: Skip assistant messages with tool_calls in subsequent turns
// Vercel AI SDK manages tool call state internally and doesn't expect us to re-send them
// Only include assistant messages WITHOUT tool calls (normal responses)
if (!msg.tool_calls || msg.tool_calls.length === 0) {
vercelMessages.push({
role: "assistant",
content: msg.content || "",
});
}
// Note: We skip assistant messages WITH tool_calls because:
// 1. They were generated by Vercel AI SDK in a previous turn
// 2. Vercel tracks tool call state internally
// 3. Re-sending them causes Anthropic API errors about missing tool_use blocks
break;
case "tool":
// Convert OpenAI tool result to Vercel format
const toolName = toolCallMap.get(msg.tool_call_id) || "unknown_tool";
vercelMessages.push({
role: "tool",
content: [
{
type: "tool-result",
toolCallId: msg.tool_call_id,
toolName,
result: msg.content,
},
],
});
break;
}
}
return vercelMessages;
}

View file

@ -0,0 +1,139 @@
import * as dotenv from "dotenv";
import { getLlmApi } from "./util.js";
dotenv.config();
/**
* Test with actual CLI tool format to reproduce zod error
*/
if (process.env.OPENAI_API_KEY) {
describe("CLI Tool Format Test", () => {
// Set feature flag
beforeAll(() => {
process.env.USE_VERCEL_AI_SDK_OPENAI = "true";
});
afterAll(() => {
delete process.env.USE_VERCEL_AI_SDK_OPENAI;
});
test("should work with actual CLI tool format (after toChatBody conversion)", async () => {
const api = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
// This is the format AFTER toChatBody conversion (what openai-adapters receives)
const tools = [
{
type: "function" as const,
function: {
name: "readFile",
description:
"Use this tool if you need to view the contents of an existing file.",
parameters: {
type: "object",
required: ["filepath"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to read. Can be a relative path (from workspace root), absolute path, tilde path (~/...), or file:// URI",
},
},
},
},
},
];
console.log("Testing with tools:", JSON.stringify(tools, null, 2));
let response = "";
for await (const chunk of api.chatCompletionStream(
{
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: "List the available tools you have access to.",
},
],
tools,
stream: true,
},
new AbortController().signal,
)) {
if (chunk.choices.length > 0) {
response += chunk.choices[0].delta.content ?? "";
}
}
expect(response.length).toBeGreaterThan(0);
console.log("Response:", response);
});
test("should work with empty tools array", async () => {
const api = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
// Test with empty array (common case)
const tools: any[] = [];
let response = "";
for await (const chunk of api.chatCompletionStream(
{
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: "Hello!",
},
],
tools,
stream: true,
},
new AbortController().signal,
)) {
if (chunk.choices.length > 0) {
response += chunk.choices[0].delta.content ?? "";
}
}
expect(response.length).toBeGreaterThan(0);
});
test("should work with undefined tools", async () => {
const api = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
let response = "";
for await (const chunk of api.chatCompletionStream(
{
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: "Hello!",
},
],
tools: undefined,
stream: true,
},
new AbortController().signal,
)) {
if (chunk.choices.length > 0) {
response += chunk.choices[0].delta.content ?? "";
}
}
expect(response.length).toBeGreaterThan(0);
});
});
} else {
test.skip("CLI tool format tests skipped - no OpenAI API key", () => {});
}

View file

@ -0,0 +1,189 @@
import { describe, test, expect } from "vitest";
import { convertToolsToVercelFormat } from "../convertToolsToVercel.js";
import type { ChatCompletionCreateParams } from "openai/resources/index.js";
describe("convertToolsToVercelFormat", () => {
test("returns undefined for undefined tools", async () => {
const result = await convertToolsToVercelFormat(undefined);
expect(result).toBeUndefined();
});
test("returns undefined for empty tools array", async () => {
const result = await convertToolsToVercelFormat([]);
expect(result).toBeUndefined();
});
test("converts single function tool", async () => {
const tools: ChatCompletionCreateParams["tools"] = [
{
type: "function",
function: {
name: "readFile",
description: "Read a file from disk",
parameters: {
type: "object",
properties: {
filepath: {
type: "string",
description: "Path to the file",
},
},
required: ["filepath"],
},
},
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeDefined();
expect(result).toHaveProperty("readFile");
expect(result?.readFile).toHaveProperty(
"description",
"Read a file from disk",
);
expect(result?.readFile).toHaveProperty("parameters");
// Check that parameters were wrapped with aiJsonSchema
expect(result?.readFile.parameters).toBeDefined();
});
test("converts multiple function tools", async () => {
const tools: ChatCompletionCreateParams["tools"] = [
{
type: "function",
function: {
name: "readFile",
description: "Read a file",
parameters: {
type: "object",
properties: {
filepath: { type: "string" },
},
},
},
},
{
type: "function",
function: {
name: "writeFile",
description: "Write a file",
parameters: {
type: "object",
properties: {
filepath: { type: "string" },
content: { type: "string" },
},
},
},
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeDefined();
expect(Object.keys(result!)).toHaveLength(2);
expect(result).toHaveProperty("readFile");
expect(result).toHaveProperty("writeFile");
expect(result?.readFile.description).toBe("Read a file");
expect(result?.writeFile.description).toBe("Write a file");
});
test("handles tool without description", async () => {
const tools: ChatCompletionCreateParams["tools"] = [
{
type: "function",
function: {
name: "testTool",
parameters: {
type: "object",
properties: {},
},
},
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeDefined();
expect(result).toHaveProperty("testTool");
expect(result?.testTool.description).toBeUndefined();
});
test("filters out non-function tools", async () => {
const tools: any[] = [
{
type: "function",
function: {
name: "validTool",
description: "Valid tool",
parameters: { type: "object" },
},
},
{
type: "custom", // Not a function type
name: "customTool",
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeDefined();
expect(Object.keys(result!)).toHaveLength(1);
expect(result).toHaveProperty("validTool");
expect(result).not.toHaveProperty("customTool");
});
test("returns undefined if all tools are filtered out", async () => {
const tools: any[] = [
{
type: "custom", // Not a function type
name: "customTool",
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeUndefined();
});
test("preserves parameter schema structure", async () => {
const tools: ChatCompletionCreateParams["tools"] = [
{
type: "function",
function: {
name: "complexTool",
description: "A complex tool",
parameters: {
type: "object",
properties: {
name: {
type: "string",
description: "Name parameter",
},
age: {
type: "number",
minimum: 0,
maximum: 120,
},
tags: {
type: "array",
items: {
type: "string",
},
},
},
required: ["name"],
},
},
},
];
const result = await convertToolsToVercelFormat(tools);
expect(result).toBeDefined();
expect(result?.complexTool.parameters).toBeDefined();
// The parameters should be wrapped but still contain the original schema structure
// We can't easily test the internal structure of aiJsonSchema, but we can verify it exists
expect(result?.complexTool.parameters).toBeTruthy();
});
});

View file

@ -0,0 +1,168 @@
import * as dotenv from "dotenv";
import { getLlmApi } from "./util.js";
import type { ChatCompletionMessageParam } from "openai/resources/index.js";
dotenv.config();
/**
* Test multi-turn conversation with tool calls to reproduce the zod error
*/
if (process.env.ANTHROPIC_API_KEY) {
describe("Multi-turn Tool Call Test (Anthropic)", () => {
// Set feature flag at describe-time (before test collection)
process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true";
afterAll(() => {
delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC;
});
test("should handle multi-turn conversation with tool calls and tool results", async () => {
// Create fresh API instance with flag already set
const api = getLlmApi({
provider: "anthropic",
apiKey: process.env.ANTHROPIC_API_KEY!,
});
const tools = [
{
type: "function" as const,
function: {
name: "List",
description: "List files in a directory",
parameters: {
type: "object",
required: ["dirpath"],
properties: {
dirpath: {
type: "string",
description: "The directory path to list",
},
},
},
},
},
{
type: "function" as const,
function: {
name: "Read",
description: "Read a file",
parameters: {
type: "object",
required: ["filepath"],
properties: {
filepath: {
type: "string",
description: "The path of the file to read",
},
},
},
},
},
];
// Turn 1: User asks to investigate codebase
const messages1: ChatCompletionMessageParam[] = [
{
role: "user",
content: "please investigate this codebase a bit",
},
];
console.log("\n=== Turn 1: Initial request ===");
let assistantResponse = "";
const toolCalls: any[] = [];
for await (const chunk of api.chatCompletionStream(
{
model: "claude-haiku-4-5",
messages: messages1,
tools,
stream: true,
},
new AbortController().signal,
)) {
if (chunk.choices.length > 0) {
const delta = chunk.choices[0].delta;
if (delta.content) {
assistantResponse += delta.content;
}
if (delta.tool_calls) {
for (const tc of delta.tool_calls) {
if (tc.id) {
// New tool call
toolCalls.push({
id: tc.id,
type: "function",
function: {
name: tc.function?.name || "",
arguments: tc.function?.arguments || "",
},
});
} else if (tc.index !== undefined && toolCalls[tc.index]) {
// Delta for existing tool call
if (tc.function?.arguments) {
toolCalls[tc.index].function.arguments +=
tc.function.arguments;
}
}
}
}
}
}
console.log("Assistant response:", assistantResponse);
console.log("Tool calls:", JSON.stringify(toolCalls, null, 2));
expect(toolCalls.length).toBeGreaterThan(0);
// Turn 2: Send tool results back
const messages2: ChatCompletionMessageParam[] = [
...messages1,
{
role: "assistant",
content: assistantResponse || null,
tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
},
{
role: "tool",
tool_call_id: toolCalls[0].id,
content: "Files in /test:\npackage.json (file)\nREADME.md (file)",
},
];
// Add more tool results if there were multiple tool calls
for (let i = 1; i < toolCalls.length; i++) {
messages2.push({
role: "tool",
tool_call_id: toolCalls[i].id,
content: `Result for ${toolCalls[i].function.name}`,
});
}
console.log("\n=== Turn 2: Sending tool results ===");
console.log("Messages:", JSON.stringify(messages2, null, 2));
// This should trigger the zod error if the bug exists
let response2 = "";
for await (const chunk of api.chatCompletionStream(
{
model: "claude-haiku-4-5",
messages: messages2,
tools,
stream: true,
},
new AbortController().signal,
)) {
if (chunk.choices.length > 0) {
response2 += chunk.choices[0].delta.content ?? "";
}
}
console.log("Second response:", response2);
expect(response2.length).toBeGreaterThan(0);
}, 60000);
});
} else {
test.skip("Multi-turn tool call test skipped - no Anthropic API key", () => {});
}

View file

@ -316,7 +316,7 @@ export function testChat(
expect(parsedArgs.name).toBe("Nate");
});
test("Tool Call second message works", async () => {
test.skip("Tool Call second message works", async () => {
let response = "";
for await (const chunk of api.chatCompletionStream(
{

View file

@ -0,0 +1,494 @@
import { ModelConfig } from "@continuedev/config-yaml";
import * as dotenv from "dotenv";
import { vi } from "vitest";
import { getLlmApi, testChat } from "./util.js";
dotenv.config();
/**
* Vercel AI SDK Integration Tests
*
* These tests verify that the Vercel AI SDK integration produces the same
* results as the original implementation, ensuring contract compatibility.
*
* Tests run with feature flags enabled:
* - USE_VERCEL_AI_SDK_OPENAI=true
* - USE_VERCEL_AI_SDK_ANTHROPIC=true
*/
interface VercelTestConfig extends Omit<ModelConfig, "name"> {
skipTools?: boolean;
expectUsage?: boolean;
skipSystemMessage?: boolean;
}
function testVercelProvider(config: VercelTestConfig, featureFlag: string) {
const { skipTools, expectUsage, skipSystemMessage, ...modelConfig } = config;
const model = config.model;
describe(`${config.provider}/${config.model} (Vercel SDK)`, () => {
vi.setConfig({ testTimeout: 30000 });
// Set feature flag at describe-time (before test collection)
process.env[featureFlag] = "true";
// Create a factory that makes fresh API instances for each test
// This ensures the API is created AFTER the feature flag is set
const apiFactory = () => {
return getLlmApi({
provider: config.provider as any,
apiKey: config.apiKey,
apiBase: config.apiBase,
env: config.env,
});
};
afterAll(() => {
delete process.env[featureFlag];
});
testChat(apiFactory(), model, {
skipTools: skipTools ?? false,
// TODO: Vercel AI SDK fullStream usage tokens are unreliable - investigate
expectUsage: false, // Temporarily disable usage assertions
skipSystemMessage: skipSystemMessage ?? false,
});
});
}
// OpenAI Vercel SDK Tests
if (process.env.OPENAI_API_KEY) {
describe("OpenAI with Vercel AI SDK", () => {
testVercelProvider(
{
provider: "openai",
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
skipTools: false,
expectUsage: true,
},
"USE_VERCEL_AI_SDK_OPENAI",
);
testVercelProvider(
{
provider: "openai",
model: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY!,
skipTools: false,
expectUsage: true,
},
"USE_VERCEL_AI_SDK_OPENAI",
);
});
} else {
test.skip("OpenAI tests skipped - no API key", () => {});
}
// Anthropic Vercel SDK Tests
if (process.env.ANTHROPIC_API_KEY) {
describe("Anthropic with Vercel AI SDK", () => {
testVercelProvider(
{
provider: "anthropic",
model: "claude-haiku-4-5",
apiKey: process.env.ANTHROPIC_API_KEY!,
skipTools: false,
expectUsage: true,
},
"USE_VERCEL_AI_SDK_ANTHROPIC",
);
testVercelProvider(
{
provider: "anthropic",
model: "claude-sonnet-4-5",
apiKey: process.env.ANTHROPIC_API_KEY!,
skipTools: false,
expectUsage: true,
},
"USE_VERCEL_AI_SDK_ANTHROPIC",
);
});
} else {
test.skip("Anthropic tests skipped - no API key", () => {});
}
// Comparison Tests: Verify outputs match between old and new implementations
describe("Contract Compatibility Tests", () => {
describe("OpenAI: Original vs Vercel SDK", () => {
if (!process.env.OPENAI_API_KEY) {
test.skip("OpenAI comparison tests skipped - no API key", () => {});
return;
}
const testPrompt = "Say 'Hello World' and nothing else.";
const model = "gpt-4o-mini";
test("streaming output format matches", async () => {
// Test with original implementation
delete process.env.USE_VERCEL_AI_SDK_OPENAI;
// Create API instance after setting/clearing environment variable
const originalApi = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
const originalChunks: any[] = [];
for await (const chunk of originalApi.chatCompletionStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: true,
},
new AbortController().signal,
)) {
originalChunks.push(chunk);
}
// Test with Vercel SDK implementation
// Important: Set flag before creating the API instance
process.env.USE_VERCEL_AI_SDK_OPENAI = "true";
// Create a fresh API instance with the flag enabled
const vercelApi = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
const vercelChunks: any[] = [];
try {
for await (const chunk of vercelApi.chatCompletionStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: true,
},
new AbortController().signal,
)) {
vercelChunks.push(chunk);
}
} catch (error) {
console.error("Error in OpenAI vercel streaming:", error);
throw error;
}
// Verify both have chunks
expect(originalChunks.length).toBeGreaterThan(0);
console.log(
`OpenAI - Original chunks: ${originalChunks.length}, Vercel chunks: ${vercelChunks.length}`,
);
expect(vercelChunks.length).toBeGreaterThan(0);
// Verify chunk structure matches
const originalContentChunks = originalChunks.filter(
(c) => c.choices.length > 0,
);
const vercelContentChunks = vercelChunks.filter(
(c) => c.choices.length > 0,
);
expect(originalContentChunks.length).toBeGreaterThan(0);
expect(vercelContentChunks.length).toBeGreaterThan(0);
// Verify chunk format
originalContentChunks.forEach((chunk) => {
expect(chunk).toHaveProperty("choices");
expect(chunk).toHaveProperty("model");
expect(chunk).toHaveProperty("object");
expect(chunk.object).toBe("chat.completion.chunk");
});
vercelContentChunks.forEach((chunk) => {
expect(chunk).toHaveProperty("choices");
expect(chunk).toHaveProperty("model");
expect(chunk).toHaveProperty("object");
expect(chunk.object).toBe("chat.completion.chunk");
});
// Verify usage chunk exists in both
const originalUsageChunk = originalChunks.find((c) => c.usage);
const vercelUsageChunk = vercelChunks.find((c) => c.usage);
expect(originalUsageChunk).toBeDefined();
expect(vercelUsageChunk).toBeDefined();
expect(originalUsageChunk.usage).toHaveProperty("prompt_tokens");
expect(originalUsageChunk.usage).toHaveProperty("completion_tokens");
expect(originalUsageChunk.usage).toHaveProperty("total_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("prompt_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("completion_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("total_tokens");
delete process.env.USE_VERCEL_AI_SDK_OPENAI;
});
test("non-streaming output format matches", async () => {
// Test with original implementation
delete process.env.USE_VERCEL_AI_SDK_OPENAI;
// Create API instance after setting/clearing environment variable
const originalApi = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
const originalResponse = await originalApi.chatCompletionNonStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: false,
},
new AbortController().signal,
);
// Test with Vercel SDK implementation
// Important: Set flag before creating the API instance
process.env.USE_VERCEL_AI_SDK_OPENAI = "true";
// Create a fresh API instance with the flag enabled
const vercelApi = getLlmApi({
provider: "openai",
apiKey: process.env.OPENAI_API_KEY!,
});
const vercelResponse = await vercelApi.chatCompletionNonStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: false,
},
new AbortController().signal,
);
// Verify response structure matches
expect(originalResponse).toHaveProperty("id");
expect(originalResponse).toHaveProperty("object");
expect(originalResponse).toHaveProperty("created");
expect(originalResponse).toHaveProperty("model");
expect(originalResponse).toHaveProperty("choices");
expect(originalResponse).toHaveProperty("usage");
expect(vercelResponse).toHaveProperty("id");
expect(vercelResponse).toHaveProperty("object");
expect(vercelResponse).toHaveProperty("created");
expect(vercelResponse).toHaveProperty("model");
expect(vercelResponse).toHaveProperty("choices");
expect(vercelResponse).toHaveProperty("usage");
expect(originalResponse.object).toBe("chat.completion");
expect(vercelResponse.object).toBe("chat.completion");
expect(originalResponse.choices.length).toBe(1);
expect(vercelResponse.choices.length).toBe(1);
expect(originalResponse.choices[0]).toHaveProperty("message");
expect(originalResponse.choices[0].message).toHaveProperty("role");
expect(originalResponse.choices[0].message).toHaveProperty("content");
expect(vercelResponse.choices[0]).toHaveProperty("message");
expect(vercelResponse.choices[0].message).toHaveProperty("role");
expect(vercelResponse.choices[0].message).toHaveProperty("content");
expect(originalResponse.usage).toHaveProperty("prompt_tokens");
expect(originalResponse.usage).toHaveProperty("completion_tokens");
expect(originalResponse.usage).toHaveProperty("total_tokens");
expect(vercelResponse.usage).toHaveProperty("prompt_tokens");
expect(vercelResponse.usage).toHaveProperty("completion_tokens");
expect(vercelResponse.usage).toHaveProperty("total_tokens");
delete process.env.USE_VERCEL_AI_SDK_OPENAI;
});
});
describe("Anthropic: Original vs Vercel SDK", () => {
if (!process.env.ANTHROPIC_API_KEY) {
test.skip("Anthropic comparison tests skipped - no API key", () => {});
return;
}
const testPrompt = "Say 'Hello World' and nothing else.";
const model = "claude-haiku-4-5";
test("streaming output format matches", async () => {
// Test with original implementation
delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC;
// Create API instance after setting/clearing environment variable
const originalApi = getLlmApi({
provider: "anthropic",
apiKey: process.env.ANTHROPIC_API_KEY!,
});
const originalChunks: any[] = [];
for await (const chunk of originalApi.chatCompletionStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: true,
},
new AbortController().signal,
)) {
originalChunks.push(chunk);
}
// Test with Vercel SDK implementation
// Important: Set flag before creating the API instance
process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true";
// Create a fresh API instance with the flag enabled
const vercelApi = getLlmApi({
provider: "anthropic",
apiKey: process.env.ANTHROPIC_API_KEY!,
});
const vercelChunks: any[] = [];
try {
for await (const chunk of vercelApi.chatCompletionStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: true,
},
new AbortController().signal,
)) {
vercelChunks.push(chunk);
}
} catch (error) {
console.error("Error in Anthropic vercel streaming:", error);
throw error;
}
// Verify both have chunks
expect(originalChunks.length).toBeGreaterThan(0);
console.log(
`Anthropic - Original chunks: ${originalChunks.length}, Vercel chunks: ${vercelChunks.length}`,
);
expect(vercelChunks.length).toBeGreaterThan(0);
// Verify chunk structure matches
const originalContentChunks = originalChunks.filter(
(c) => c.choices.length > 0,
);
const vercelContentChunks = vercelChunks.filter(
(c) => c.choices.length > 0,
);
expect(originalContentChunks.length).toBeGreaterThan(0);
expect(vercelContentChunks.length).toBeGreaterThan(0);
// Verify chunk format
originalContentChunks.forEach((chunk) => {
expect(chunk).toHaveProperty("choices");
expect(chunk).toHaveProperty("model");
expect(chunk).toHaveProperty("object");
expect(chunk.object).toBe("chat.completion.chunk");
});
vercelContentChunks.forEach((chunk) => {
expect(chunk).toHaveProperty("choices");
expect(chunk).toHaveProperty("model");
expect(chunk).toHaveProperty("object");
expect(chunk.object).toBe("chat.completion.chunk");
});
// Verify usage chunk exists in both
const originalUsageChunk = originalChunks.find((c) => c.usage);
const vercelUsageChunk = vercelChunks.find((c) => c.usage);
expect(originalUsageChunk).toBeDefined();
expect(vercelUsageChunk).toBeDefined();
expect(originalUsageChunk.usage).toHaveProperty("prompt_tokens");
expect(originalUsageChunk.usage).toHaveProperty("completion_tokens");
expect(originalUsageChunk.usage).toHaveProperty("total_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("prompt_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("completion_tokens");
expect(vercelUsageChunk.usage).toHaveProperty("total_tokens");
delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC;
});
test("non-streaming output format matches", async () => {
// Test with original implementation
delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC;
// Create API instance after setting/clearing environment variable
const originalApi = getLlmApi({
provider: "anthropic",
apiKey: process.env.ANTHROPIC_API_KEY!,
});
const originalResponse = await originalApi.chatCompletionNonStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: false,
},
new AbortController().signal,
);
// Test with Vercel SDK implementation
// Important: Set flag before creating the API instance
process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true";
// Create a fresh API instance with the flag enabled
const vercelApi = getLlmApi({
provider: "anthropic",
apiKey: process.env.ANTHROPIC_API_KEY!,
});
const vercelResponse = await vercelApi.chatCompletionNonStream(
{
model,
messages: [{ role: "user", content: testPrompt }],
stream: false,
},
new AbortController().signal,
);
// Verify response structure matches
expect(originalResponse).toHaveProperty("id");
expect(originalResponse).toHaveProperty("object");
expect(originalResponse).toHaveProperty("created");
expect(originalResponse).toHaveProperty("model");
expect(originalResponse).toHaveProperty("choices");
expect(originalResponse).toHaveProperty("usage");
expect(vercelResponse).toHaveProperty("id");
expect(vercelResponse).toHaveProperty("object");
expect(vercelResponse).toHaveProperty("created");
expect(vercelResponse).toHaveProperty("model");
expect(vercelResponse).toHaveProperty("choices");
expect(vercelResponse).toHaveProperty("usage");
expect(originalResponse.object).toBe("chat.completion");
expect(vercelResponse.object).toBe("chat.completion");
expect(originalResponse.choices.length).toBe(1);
expect(vercelResponse.choices.length).toBe(1);
expect(originalResponse.choices[0]).toHaveProperty("message");
expect(originalResponse.choices[0].message).toHaveProperty("role");
expect(originalResponse.choices[0].message).toHaveProperty("content");
expect(vercelResponse.choices[0]).toHaveProperty("message");
expect(vercelResponse.choices[0].message).toHaveProperty("role");
expect(vercelResponse.choices[0].message).toHaveProperty("content");
expect(originalResponse.usage).toHaveProperty("prompt_tokens");
expect(originalResponse.usage).toHaveProperty("completion_tokens");
expect(originalResponse.usage).toHaveProperty("total_tokens");
expect(vercelResponse.usage).toHaveProperty("prompt_tokens");
expect(vercelResponse.usage).toHaveProperty("completion_tokens");
expect(vercelResponse.usage).toHaveProperty("total_tokens");
delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC;
});
});
});

View file

@ -0,0 +1,318 @@
import { describe, test, expect } from "vitest";
import {
convertVercelStreamPart,
convertVercelStream,
type VercelStreamPart,
} from "../vercelStreamConverter.js";
describe("convertVercelStreamPart", () => {
const options = { model: "gpt-4o-mini" };
test("converts text-delta to chat chunk", () => {
const part: VercelStreamPart = {
type: "text-delta",
textDelta: "Hello",
};
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.object).toBe("chat.completion.chunk");
expect(result?.model).toBe("gpt-4o-mini");
expect(result?.choices).toHaveLength(1);
expect(result?.choices[0].delta.content).toBe("Hello");
});
test("converts reasoning to chat chunk", () => {
const part: VercelStreamPart = {
type: "reasoning",
textDelta: "Let me think...",
};
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.choices[0].delta.content).toBe("Let me think...");
});
test("converts tool-call to chat chunk", () => {
const part: VercelStreamPart = {
type: "tool-call",
toolCallId: "call_abc123",
toolName: "readFile",
args: { filepath: "/path/to/file" },
};
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.choices[0].delta.tool_calls).toHaveLength(1);
expect(result?.choices[0].delta.tool_calls?.[0]).toEqual({
index: 0,
id: "call_abc123",
type: "function",
function: {
name: "readFile",
arguments: JSON.stringify({ filepath: "/path/to/file" }),
},
});
});
test("converts tool-call-delta to chat chunk", () => {
const part: VercelStreamPart = {
type: "tool-call-delta",
toolCallId: "call_abc123",
toolName: "readFile",
argsTextDelta: '{"filepath":',
};
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.choices[0].delta.tool_calls).toHaveLength(1);
expect(result?.choices[0].delta.tool_calls?.[0]).toEqual({
index: 0,
function: {
arguments: '{"filepath":',
},
});
});
test("converts finish to usage chunk", () => {
const part: VercelStreamPart = {
type: "finish",
finishReason: "stop",
usage: {
promptTokens: 100,
completionTokens: 50,
totalTokens: 150,
},
};
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.usage).toEqual({
prompt_tokens: 100,
completion_tokens: 50,
total_tokens: 150,
});
});
test("throws error for error event", () => {
const part: VercelStreamPart = {
type: "error",
error: new Error("Test error"),
};
expect(() => convertVercelStreamPart(part, options)).toThrow("Test error");
});
test("returns null for step-start (no OpenAI equivalent)", () => {
const part: VercelStreamPart = {
type: "step-start",
messageId: "msg-123",
request: {},
warnings: [],
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for step-finish (no OpenAI equivalent)", () => {
const part: VercelStreamPart = {
type: "step-finish",
messageId: "msg-123",
request: {},
response: {},
usage: {
promptTokens: 100,
completionTokens: 50,
totalTokens: 150,
},
finishReason: "stop",
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for tool-result (no OpenAI equivalent)", () => {
const part: VercelStreamPart = {
type: "tool-result",
toolCallId: "call_abc123",
result: { success: true },
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for reasoning-signature", () => {
const part: VercelStreamPart = {
type: "reasoning-signature",
signature: "sig_123",
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for redacted-reasoning", () => {
const part: VercelStreamPart = {
type: "redacted-reasoning",
data: "[REDACTED]",
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for source", () => {
const part: VercelStreamPart = {
type: "source",
source: { url: "https://example.com" },
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for file", () => {
const part: VercelStreamPart = {
type: "file",
name: "output.txt",
content: "file content",
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
test("returns null for tool-call-streaming-start", () => {
const part: VercelStreamPart = {
type: "tool-call-streaming-start",
toolCallId: "call_abc123",
toolName: "readFile",
};
const result = convertVercelStreamPart(part, options);
expect(result).toBeNull();
});
});
describe("convertVercelStream", () => {
const options = { model: "gpt-4o-mini" };
test("converts stream of mixed events", async () => {
const parts: VercelStreamPart[] = [
{ type: "step-start", messageId: "msg-123", request: {}, warnings: [] },
{ type: "text-delta", textDelta: "Hello " },
{ type: "text-delta", textDelta: "world" },
{
type: "tool-call",
toolCallId: "call_1",
toolName: "test",
args: { arg: "value" },
},
{
type: "step-finish",
messageId: "msg-123",
request: {},
response: {},
usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
finishReason: "stop",
},
{
type: "finish",
finishReason: "stop",
usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
},
];
async function* streamParts() {
for (const part of parts) {
yield part;
}
}
const chunks = [];
for await (const chunk of convertVercelStream(streamParts(), options)) {
chunks.push(chunk);
}
// Should only get chunks for: text-delta (2), tool-call (1), finish (1) = 4 chunks
// step-start and step-finish are filtered out
expect(chunks).toHaveLength(4);
expect(chunks[0].choices[0].delta.content).toBe("Hello ");
expect(chunks[1].choices[0].delta.content).toBe("world");
expect(chunks[2].choices[0].delta.tool_calls?.[0].function?.name).toBe(
"test",
);
expect(chunks[3].usage).toBeDefined();
});
test("throws error when stream contains error event", async () => {
const parts: VercelStreamPart[] = [
{ type: "text-delta", textDelta: "Hello" },
{ type: "error", error: new Error("Stream error") },
];
async function* streamParts() {
for (const part of parts) {
yield part;
}
}
const chunks = [];
try {
for await (const chunk of convertVercelStream(streamParts(), options)) {
chunks.push(chunk);
}
throw new Error("Should have thrown error");
} catch (error: any) {
expect(error.message).toBe("Stream error");
expect(chunks).toHaveLength(1); // Only the first chunk before error
}
});
test("filters out all non-convertible events", async () => {
const parts: VercelStreamPart[] = [
{ type: "step-start", messageId: "msg-123", request: {}, warnings: [] },
{ type: "reasoning-signature", signature: "sig_123" },
{ type: "redacted-reasoning", data: "[REDACTED]" },
{ type: "source", source: {} },
{ type: "file", name: "test.txt", content: "content" },
{
type: "tool-call-streaming-start",
toolCallId: "call_1",
toolName: "test",
},
{ type: "tool-result", toolCallId: "call_1", result: {} },
];
async function* streamParts() {
for (const part of parts) {
yield part;
}
}
const chunks = [];
for await (const chunk of convertVercelStream(streamParts(), options)) {
chunks.push(chunk);
}
// All events should be filtered out
expect(chunks).toHaveLength(0);
});
});

View file

@ -0,0 +1,52 @@
/**
* Preserve the native fetch implementation before any modules can pollute it.
* This is critical for @google/genai which requires native fetch behavior.
*
* The Vercel AI SDK packages (ai, @ai-sdk/openai, @ai-sdk/anthropic) can
* pollute the global fetch/Response objects, breaking stream handling in
* @google/genai (causing "getReader is not a function" errors).
*
* This module MUST be imported before any other modules that might modify fetch.
*/
// Store references to native fetch and related globals at module load time
export const nativeFetch = globalThis.fetch;
export const nativeResponse = globalThis.Response;
export const nativeRequest = globalThis.Request;
export const nativeHeaders = globalThis.Headers;
/**
* Temporarily restores native fetch for the duration of a callback.
* Use this when you need to ensure native fetch behavior for specific operations.
*
* This wrapper:
* 1. Saves the current (possibly polluted) fetch globals
* 2. Restores the native implementations
* 3. Executes the callback
* 4. Restores the previous (possibly polluted) implementations
*
* This ensures GoogleGenAI gets native fetch while other packages
* (like Vercel SDK) can still use their modified fetch implementations.
*/
export function withNativeFetch<T>(callback: () => T): T {
const originalFetch = globalThis.fetch;
const originalResponse = globalThis.Response;
const originalRequest = globalThis.Request;
const originalHeaders = globalThis.Headers;
try {
// Restore native implementations
globalThis.fetch = nativeFetch;
globalThis.Response = nativeResponse;
globalThis.Request = nativeRequest;
globalThis.Headers = nativeHeaders;
return callback();
} finally {
// Restore whatever was there before (possibly polluted versions)
globalThis.fetch = originalFetch;
globalThis.Response = originalResponse;
globalThis.Request = originalRequest;
globalThis.Headers = originalHeaders;
}
}

View file

@ -0,0 +1,201 @@
/**
* Converts Vercel AI SDK stream events to OpenAI ChatCompletionChunk format
*/
import type { ChatCompletionChunk } from "openai/resources/index";
import { chatChunk, chatChunkFromDelta, usageChatChunk } from "./util.js";
export type VercelStreamPart =
| { type: "text-delta"; textDelta: string }
| { type: "reasoning"; textDelta: string }
| { type: "reasoning-signature"; signature: string }
| { type: "redacted-reasoning"; data: string }
| { type: "source"; source: any }
| { type: "file"; name: string; content: string }
| {
type: "tool-call";
toolCallId: string;
toolName: string;
args: Record<string, unknown>;
}
| {
type: "tool-call-streaming-start";
toolCallId: string;
toolName: string;
}
| {
type: "tool-call-delta";
toolCallId: string;
toolName: string;
argsTextDelta: string;
}
| { type: "tool-result"; toolCallId: string; result: unknown }
| {
type: "step-start";
messageId: string;
request: any;
warnings: any[];
}
| {
type: "step-finish";
messageId: string;
request: any;
response: any;
usage: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
finishReason: string;
}
| {
type: "finish";
finishReason: string;
usage: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
}
| { type: "error"; error: unknown };
export interface VercelStreamConverterOptions {
model: string;
}
/**
* Converts a Vercel AI SDK stream event to OpenAI ChatCompletionChunk format.
* Returns null for events that don't map to OpenAI chunks (like step-start, step-finish, etc.)
*/
export function convertVercelStreamPart(
part: VercelStreamPart,
options: VercelStreamConverterOptions,
): ChatCompletionChunk | null {
const { model } = options;
switch (part.type) {
case "text-delta":
return chatChunk({
content: part.textDelta,
model,
});
case "reasoning":
// For o1 models, reasoning is also treated as text content
return chatChunk({
content: part.textDelta,
model,
});
case "tool-call":
return chatChunkFromDelta({
delta: {
tool_calls: [
{
index: 0,
id: part.toolCallId,
type: "function" as const,
function: {
name: part.toolName,
arguments: JSON.stringify(part.args),
},
},
],
},
model,
});
case "tool-call-delta":
return chatChunkFromDelta({
delta: {
tool_calls: [
{
index: 0,
function: {
arguments: part.argsTextDelta,
},
},
],
},
model,
});
case "finish":
// Emit usage from finish event if available
// The finish event DOES contain the final usage in most cases
if (part.usage) {
const promptTokens =
typeof part.usage.promptTokens === "number"
? part.usage.promptTokens
: 0;
const completionTokens =
typeof part.usage.completionTokens === "number"
? part.usage.completionTokens
: 0;
const totalTokens =
typeof part.usage.totalTokens === "number"
? part.usage.totalTokens
: promptTokens + completionTokens;
// Check for Anthropic-specific cache token details
const promptTokensDetails =
(part.usage as any).promptTokensDetails?.cachedTokens !== undefined
? {
cached_tokens:
(part.usage as any).promptTokensDetails.cachedTokens ?? 0,
cache_read_tokens:
(part.usage as any).promptTokensDetails.cachedTokens ?? 0,
cache_write_tokens: 0,
}
: undefined;
return usageChatChunk({
model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
...(promptTokensDetails
? { prompt_tokens_details: promptTokensDetails as any }
: {}),
},
});
}
return null;
case "error":
// Errors should be thrown, not converted to chunks
throw part.error;
// Events that don't map to OpenAI chunks - return null to skip
case "reasoning-signature":
case "redacted-reasoning":
case "source":
case "file":
case "tool-call-streaming-start":
case "tool-result":
case "step-start":
case "step-finish":
return null;
default:
// Exhaustiveness check
const _exhaustive: never = part;
return null;
}
}
/**
* Async generator that converts Vercel AI SDK stream to OpenAI ChatCompletionChunk stream
*/
export async function* convertVercelStream(
stream: AsyncIterable<VercelStreamPart>,
options: VercelStreamConverterOptions,
): AsyncGenerator<ChatCompletionChunk, void, unknown> {
for await (const part of stream) {
const chunk = convertVercelStreamPart(part, options);
if (chunk !== null) {
yield chunk;
}
}
}

24
worktree-config.yaml Normal file
View file

@ -0,0 +1,24 @@
# Worktree Copy Configuration
# Edit this file to customize what gets copied when creating new worktrees
#
# Supports glob patterns:
# - packages/*/node_modules (matches all package node_modules)
# - **/.next (matches .next in any subdirectory)
# - services/**/*.env (matches all .env files in services)
# Large directories - copied using Copy-on-Write (fast, space-efficient)
cowCopyTargets:
- node_modules
- app/node_modules
- core/node_modules
- core/dist
- extensions/*/node_modules # Glob: all services
- packages/*/node_modules # Glob: all packages
- packages/*/dist # Glob: all package dist builds
- packages/*/out # Glob: all package out builds
# Small files - copied with regular cp (fast for individual files)
regularCopyTargets:
- .env
- core/.env