Merge branch 'continuedev:main' into add-tool-call-support-for-moonshot-models
This commit is contained in:
commit
e4b32c0201
199 changed files with 10676 additions and 1781 deletions
10
.github/auto_assign.yml
vendored
10
.github/auto_assign.yml
vendored
|
|
@ -1,10 +0,0 @@
|
|||
# Reference: https://github.com/marketplace/actions/auto-assign-action
|
||||
addAssignees: true
|
||||
|
||||
assignees:
|
||||
- sestinj
|
||||
- Patrick-Erichsen
|
||||
- tomasz-stefaniak
|
||||
- RomneyDa
|
||||
|
||||
numberOfAssignees: 2
|
||||
10
.github/workflows/auto-assign-pr.yaml
vendored
10
.github/workflows/auto-assign-pr.yaml
vendored
|
|
@ -1,10 +0,0 @@
|
|||
name: PR assignment
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
add-reviews:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: kentaro-m/auto-assign-action@v2.0.0
|
||||
5
.github/workflows/auto-release.yml
vendored
5
.github/workflows/auto-release.yml
vendored
|
|
@ -4,8 +4,9 @@ on:
|
|||
push:
|
||||
branches:
|
||||
- nate/auto-main-release-draft
|
||||
schedule:
|
||||
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
|
||||
# Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases.
|
||||
# schedule:
|
||||
# - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
|
||||
workflow_dispatch: # Keep manual trigger option
|
||||
|
||||
jobs:
|
||||
|
|
|
|||
105
.github/workflows/main-build.yaml
vendored
Normal file
105
.github/workflows/main-build.yaml
vendored
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
name: Main Branch Build
|
||||
|
||||
# Download and republish VS Code extension artifacts when code is merged to main
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
test_pr_number:
|
||||
description: "PR number to test with"
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
republish-pr-artifacts:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [Linux, macOS]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2 # Get the last 2 commits to find the merge commit
|
||||
|
||||
- name: Get merged PR number
|
||||
id: get-pr
|
||||
run: |
|
||||
# Get the commit message of the merge commit
|
||||
COMMIT_MSG=$(git log --format=%B -n 1 HEAD)
|
||||
echo "Commit message: $COMMIT_MSG"
|
||||
|
||||
# Extract PR number from merge commit message (format: "Merge pull request #123 from...")
|
||||
PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723")
|
||||
|
||||
if [ -z "$PR_NUMBER" ]; then
|
||||
echo "❌ Could not extract PR number from commit message. This might not be a PR merge."
|
||||
echo "Commit message was: $COMMIT_MSG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Found PR number: $PR_NUMBER"
|
||||
echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Find PR workflow run
|
||||
id: find-run
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.get-pr.outputs.pr_number }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
echo "🔍 Getting branch name for PR #$PR_NUMBER..."
|
||||
|
||||
# Get the branch name for the PR
|
||||
BRANCH_NAME=$(gh pr view "$PR_NUMBER" --repo "${{ github.repository }}" --json headRefName --jq '.headRefName')
|
||||
|
||||
if [ -z "$BRANCH_NAME" ]; then
|
||||
echo "❌ Could not find PR #$PR_NUMBER"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Branch name: $BRANCH_NAME"
|
||||
|
||||
# Get the latest successful workflow run for the branch
|
||||
RUN_ID=$(gh run list \
|
||||
--repo "${{ github.repository }}" \
|
||||
--workflow="pr_checks.yaml" \
|
||||
--branch="$BRANCH_NAME" \
|
||||
--json databaseId,status,conclusion \
|
||||
--jq ".[] | select(.status == \"completed\" and .conclusion == \"success\") | .databaseId" \
|
||||
| head -1)
|
||||
|
||||
if [ -z "$RUN_ID" ]; then
|
||||
echo "❌ No successful workflow run found for PR #$PR_NUMBER (branch: $BRANCH_NAME)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Found successful workflow run: $RUN_ID"
|
||||
echo "run_id=$RUN_ID" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Download PR artifact
|
||||
env:
|
||||
RUN_ID: ${{ steps.find-run.outputs.run_id }}
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
echo "📥 Downloading vscode-extension-build-$PLATFORM artifact from run $RUN_ID..."
|
||||
|
||||
# Create temporary directory for download
|
||||
mkdir -p ./temp-download
|
||||
|
||||
# Download the artifact from the PR workflow run
|
||||
if ! gh run download "$RUN_ID" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--name "vscode-extension-build-$PLATFORM" \
|
||||
--dir "./temp-download"; then
|
||||
echo "❌ Failed to download artifact vscode-extension-build-$PLATFORM from run $RUN_ID"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Successfully downloaded artifact"
|
||||
|
||||
- name: Republish as main branch artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: vscode-extension-build-${{ matrix.platform }}
|
||||
path: ./temp-download/*
|
||||
7
.github/workflows/vscode-version-bump.yml
vendored
7
.github/workflows/vscode-version-bump.yml
vendored
|
|
@ -1,8 +1,9 @@
|
|||
name: Create VS Code main release draft
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
- cron: "0 15 * * 5"
|
||||
# Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases.
|
||||
# schedule:
|
||||
# # Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
# - cron: "0 15 * * 5"
|
||||
workflow_dispatch:
|
||||
# Allows manual triggering
|
||||
|
||||
|
|
|
|||
2
.idea/kotlinc.xml
generated
2
.idea/kotlinc.xml
generated
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.9.0" />
|
||||
<option name="version" value="1.8.0" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -22,7 +22,13 @@
|
|||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.vitest.ts"],
|
||||
"files": [
|
||||
"**/*.test.ts",
|
||||
"**/*.test.tsx",
|
||||
"**/*.spec.ts",
|
||||
"**/*.spec.tsx",
|
||||
"**/*.vitest.ts"
|
||||
],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off"
|
||||
}
|
||||
|
|
|
|||
31
core/config/json/loadRcConfigs.ts
Normal file
31
core/config/json/loadRcConfigs.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import * as JSONC from "comment-json";
|
||||
import { ContinueRcJson, FileType, IDE } from "../..";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
export async function getWorkspaceRcConfigs(
|
||||
ide: IDE,
|
||||
): Promise<ContinueRcJson[]> {
|
||||
try {
|
||||
const workspaces = await ide.getWorkspaceDirs();
|
||||
const rcFiles = await Promise.all(
|
||||
workspaces.map(async (dir) => {
|
||||
const ls = await ide.listDir(dir);
|
||||
const rcFiles = ls
|
||||
.filter(
|
||||
(entry) =>
|
||||
(entry[1] === (1 as FileType.File) ||
|
||||
entry[1] === (64 as FileType.SymbolicLink)) &&
|
||||
entry[0].endsWith(".continuerc.json"),
|
||||
)
|
||||
.map((entry) => joinPathsToUri(dir, entry[0]));
|
||||
return await Promise.all(rcFiles.map(ide.readFile));
|
||||
}),
|
||||
);
|
||||
return rcFiles
|
||||
.flat()
|
||||
.map((file) => JSONC.parse(file) as unknown as ContinueRcJson);
|
||||
} catch (e) {
|
||||
console.debug("Failed to load workspace configs: ", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -64,6 +64,7 @@ import { localPathToUri } from "../util/pathToUri";
|
|||
|
||||
import { getToolsForIde } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -877,7 +878,6 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
|
|||
|
||||
async function loadContinueConfigFromJson(
|
||||
ide: IDE,
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
|
|
@ -885,6 +885,7 @@ async function loadContinueConfigFromJson(
|
|||
workOsAccessToken: string | undefined,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const workspaceConfigs = await getWorkspaceRcConfigs(ide);
|
||||
// Serialized config
|
||||
let {
|
||||
config: serialized,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import {
|
|||
|
||||
import {
|
||||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
|
|
@ -86,7 +85,6 @@ export default async function doLoadConfig(options: {
|
|||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const workspaceConfigs = await getWorkspaceConfigs(ide);
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
const uniqueId = await ide.getUniqueId();
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
|
|
@ -126,7 +124,6 @@ export default async function doLoadConfig(options: {
|
|||
} else {
|
||||
const result = await loadContinueConfigFromJson(
|
||||
ide,
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
|
|
@ -365,21 +362,3 @@ async function injectControlPlaneProxyInfo(
|
|||
|
||||
return config;
|
||||
}
|
||||
|
||||
async function getWorkspaceConfigs(ide: IDE): Promise<ContinueRcJson[]> {
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
|
||||
try {
|
||||
workspaceConfigs = await ide.getWorkspaceConfigs();
|
||||
|
||||
// Config is sent over the wire from JB so we need to parse it
|
||||
if (ideInfo.ideType === "jetbrains") {
|
||||
workspaceConfigs = (workspaceConfigs as any).map(JSON.parse);
|
||||
}
|
||||
} catch (e) {
|
||||
console.debug("Failed to load workspace configs: ", e);
|
||||
}
|
||||
|
||||
return workspaceConfigs;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export const sharedConfigSchema = z
|
|||
useCurrentFileAsContext: z.boolean(),
|
||||
optInNextEditFeature: z.boolean(),
|
||||
enableExperimentalTools: z.boolean(),
|
||||
onlyUseSystemMessageTools: z.boolean(),
|
||||
codebaseToolCallingOnly: z.boolean(),
|
||||
enableStaticContextualization: z.boolean(),
|
||||
|
||||
|
|
@ -185,6 +186,11 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.optInNextEditFeature =
|
||||
sharedConfig.optInNextEditFeature;
|
||||
}
|
||||
if (sharedConfig.onlyUseSystemMessageTools !== undefined) {
|
||||
configCopy.experimental.onlyUseSystemMessageTools =
|
||||
sharedConfig.onlyUseSystemMessageTools;
|
||||
}
|
||||
|
||||
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
|
||||
configCopy.experimental.codebaseToolCallingOnly =
|
||||
sharedConfig.codebaseToolCallingOnly;
|
||||
|
|
|
|||
31
core/config/shouldAutoEnableSystemMessageTools.ts
Normal file
31
core/config/shouldAutoEnableSystemMessageTools.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { ModelDescription } from "../index.d";
|
||||
|
||||
/**
|
||||
* Determines if system message tools should be auto-enabled for the given model.
|
||||
* This is used to automatically enable system message tools for certain provider/model combinations
|
||||
* where we have a strong preference, taking priority over user manual settings.
|
||||
*
|
||||
* System message tools are an alternative to native tool calling where tool definitions and calls
|
||||
* are embedded in the system message as text rather than using the provider's native tool calling API.
|
||||
* This can be beneficial for providers/models that don't support native tool calling or have
|
||||
* poor tool calling performance.
|
||||
*
|
||||
* Current auto-enable rules:
|
||||
* - OpenRouter provider: true for all models except those containing "claude" (since Claude models
|
||||
* generally have good native tool calling support)
|
||||
* - All other providers: undefined (no auto-preference, use manual setting)
|
||||
*
|
||||
* @param model The model description to check
|
||||
* @returns true to force enable, false to force disable, undefined for no auto-preference
|
||||
*/
|
||||
export function shouldAutoEnableSystemMessageTools(
|
||||
model: ModelDescription,
|
||||
): boolean | undefined {
|
||||
// Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling
|
||||
if (model.provider === "openrouter") {
|
||||
return !model.model.toLowerCase().includes("claude");
|
||||
}
|
||||
|
||||
// No auto-preference for all other providers - use manual setting
|
||||
return undefined;
|
||||
}
|
||||
85
core/config/shouldAutoEnableSystemMessageTools.vitest.ts
Normal file
85
core/config/shouldAutoEnableSystemMessageTools.vitest.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
import { ModelDescription } from "../index.d";
|
||||
import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools";
|
||||
|
||||
describe("shouldAutoEnableSystemMessageTools", () => {
|
||||
const createModel = (provider: string, model: string): ModelDescription => ({
|
||||
title: "Test Model",
|
||||
provider,
|
||||
underlyingProviderName: provider,
|
||||
model,
|
||||
});
|
||||
|
||||
test("should return true for OpenRouter models that don't contain 'claude'", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "llama-3.3-70b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "qwen/qwen-2.5-72b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false for OpenRouter Claude models", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "claude-3-haiku"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("should return undefined for all other providers", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("anthropic", "claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("groq", "llama-3.3-70b-versatile"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
});
|
||||
|
||||
test("should be case insensitive for 'claude' detection", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "CLAUDE-models"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "Claude-3.5"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "some-model-Claude"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -682,8 +682,6 @@ declare global {
|
|||
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
|
||||
fileExists(filepath: string): Promise<boolean>;
|
||||
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
|
|
@ -1123,7 +1121,6 @@ declare global {
|
|||
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
|
||||
*/
|
||||
useChromiumForDocsCrawling?: boolean;
|
||||
useTools?: boolean;
|
||||
modelContextProtocolServers?: MCPOptions[];
|
||||
}
|
||||
|
||||
|
|
|
|||
62
core/config/yaml/loadLocalYamlBlocks.ts
Normal file
62
core/config/yaml/loadLocalYamlBlocks.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import {
|
||||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
unrollAssistantFromContent,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
||||
// This is a certain approach to unrolling local YAML where it
|
||||
// 1. creates an assistant out of all local blocks
|
||||
// 2. unrolls it like a local assistant
|
||||
export async function unrollLocalYamlBlocks(
|
||||
packageIdentifiers: PackageIdentifier[],
|
||||
ide: IDE,
|
||||
registryClient: RegistryClient,
|
||||
orgScopeId: string | null,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
try {
|
||||
const unrollResult = await unrollAssistantFromContent(
|
||||
{
|
||||
uriType: "file",
|
||||
filePath: "",
|
||||
},
|
||||
"name: FILLER\nschema: v1\nversion: 0.0.1",
|
||||
registryClient,
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
renderSecrets: true,
|
||||
injectBlocks: packageIdentifiers,
|
||||
},
|
||||
);
|
||||
const config =
|
||||
"config" in unrollResult ? unrollResult.config : unrollResult;
|
||||
const errors = "errors" in unrollResult ? unrollResult.errors : [];
|
||||
return {
|
||||
config,
|
||||
errors,
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
} catch (error) {
|
||||
let message = "An unknown error occurred while loading local YAML blocks";
|
||||
if (error instanceof Error) {
|
||||
message += ": " + error.message;
|
||||
}
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [{ message, fatal: false }],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -4,11 +4,10 @@ import {
|
|||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
isAssistantUnrolledNonNullable,
|
||||
MCPServer,
|
||||
mergeUnrolledAssistants,
|
||||
ModelRole,
|
||||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
Rule,
|
||||
TEMPLATE_VAR_REGEX,
|
||||
unrollAssistant,
|
||||
validateConfigYaml,
|
||||
|
|
@ -17,13 +16,11 @@ import { dirname } from "node:path";
|
|||
|
||||
import {
|
||||
ContinueConfig,
|
||||
ExperimentalMCPOptions,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
|
|
@ -41,41 +38,13 @@ import { getControlPlaneEnvSync } from "../../control-plane/env";
|
|||
import { getToolsForIde } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
|
||||
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
return {
|
||||
rule: rule,
|
||||
source: "rules-block",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
source: "rules-block",
|
||||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function convertYamlMcpToContinueMcp(
|
||||
server: MCPServer,
|
||||
): ExperimentalMCPOptions {
|
||||
return {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
cwd: server.cwd,
|
||||
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
|
||||
timeout: server.connectionTimeout,
|
||||
};
|
||||
}
|
||||
import {
|
||||
convertYamlMcpToContinueMcp,
|
||||
convertYamlRuleToContinueRule,
|
||||
} from "./yamlToContinueConfig";
|
||||
|
||||
async function loadConfigYaml(options: {
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
|
|
@ -95,46 +64,65 @@ async function loadConfigYaml(options: {
|
|||
} = options;
|
||||
|
||||
// Add local .continue blocks
|
||||
const allLocalBlocks: PackageIdentifier[] = [];
|
||||
for (const blockType of BLOCK_TYPES) {
|
||||
const localBlockPromises = BLOCK_TYPES.map(async (blockType) => {
|
||||
const localBlocks = await getAllDotContinueDefinitionFiles(
|
||||
ide,
|
||||
{ includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
|
||||
blockType,
|
||||
);
|
||||
allLocalBlocks.push(
|
||||
...localBlocks.map((b) => ({
|
||||
uriType: "file" as const,
|
||||
filePath: b.path,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const rootPath =
|
||||
packageIdentifier.uriType === "file"
|
||||
? dirname(getCleanUriPath(packageIdentifier.filePath))
|
||||
: undefined;
|
||||
return localBlocks.map((b) => ({
|
||||
uriType: "file" as const,
|
||||
filePath: b.path,
|
||||
}));
|
||||
});
|
||||
const localPackageIdentifiers: PackageIdentifier[] = (
|
||||
await Promise.all(localBlockPromises)
|
||||
).flat();
|
||||
|
||||
// logger.info(
|
||||
// `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
|
||||
// );
|
||||
|
||||
// Registry client is only used if local blocks are present, but logic same for hub/local assistants
|
||||
const getRegistryClient = async () => {
|
||||
const rootPath =
|
||||
packageIdentifier.uriType === "file"
|
||||
? dirname(getCleanUriPath(packageIdentifier.filePath))
|
||||
: undefined;
|
||||
return new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
|
||||
.CONTROL_PLANE_URL,
|
||||
rootPath,
|
||||
});
|
||||
};
|
||||
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
let config: AssistantUnrolled | undefined;
|
||||
|
||||
if (overrideConfigYaml) {
|
||||
config = overrideConfigYaml;
|
||||
if (localPackageIdentifiers.length > 0) {
|
||||
const unrolledLocal = await unrollLocalYamlBlocks(
|
||||
localPackageIdentifiers,
|
||||
ide,
|
||||
await getRegistryClient(),
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
);
|
||||
if (unrolledLocal.errors) {
|
||||
errors.push(...unrolledLocal.errors);
|
||||
}
|
||||
if (unrolledLocal.config) {
|
||||
config = mergeUnrolledAssistants(config, unrolledLocal.config);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is how we allow use of blocks locally
|
||||
const unrollResult = await unrollAssistant(
|
||||
packageIdentifier,
|
||||
new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
|
||||
.CONTROL_PLANE_URL,
|
||||
rootPath,
|
||||
}),
|
||||
await getRegistryClient(),
|
||||
{
|
||||
renderSecrets: true,
|
||||
currentUserSlug: "",
|
||||
|
|
@ -145,7 +133,7 @@ async function loadConfigYaml(options: {
|
|||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
injectBlocks: allLocalBlocks,
|
||||
injectBlocks: localPackageIdentifiers,
|
||||
},
|
||||
);
|
||||
config = unrollResult.config;
|
||||
|
|
|
|||
35
core/config/yaml/yamlToContinueConfig.ts
Normal file
35
core/config/yaml/yamlToContinueConfig.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { MCPServer, Rule } from "@continuedev/config-yaml";
|
||||
import { ExperimentalMCPOptions, RuleWithSource } from "../..";
|
||||
|
||||
export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
return {
|
||||
rule: rule,
|
||||
source: "rules-block",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
source: "rules-block",
|
||||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function convertYamlMcpToContinueMcp(
|
||||
server: MCPServer,
|
||||
): ExperimentalMCPOptions {
|
||||
return {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
cwd: server.cwd,
|
||||
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
|
||||
timeout: server.connectionTimeout,
|
||||
};
|
||||
}
|
||||
|
|
@ -400,7 +400,10 @@ export class Core {
|
|||
|
||||
on("controlPlane/openUrl", async (msg) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
let url = `${env.APP_URL}${msg.data.path}`;
|
||||
const urlPath = msg.data.path.startsWith("/")
|
||||
? msg.data.path.slice(1)
|
||||
: msg.data.path;
|
||||
let url = `${env.APP_URL}${urlPath}`;
|
||||
if (msg.data.orgSlug) {
|
||||
url += `?org=${msg.data.orgSlug}`;
|
||||
}
|
||||
|
|
|
|||
4
core/index.d.ts
vendored
4
core/index.d.ts
vendored
|
|
@ -806,8 +806,6 @@ export interface IDE {
|
|||
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
|
||||
fileExists(fileUri: string): Promise<boolean>;
|
||||
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
|
|
@ -1086,6 +1084,7 @@ export interface Tool {
|
|||
faviconUrl?: string;
|
||||
group: string;
|
||||
originalFunctionName?: string;
|
||||
systemMessageDescription?: string;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
@ -1516,6 +1515,7 @@ export interface ExperimentalConfig {
|
|||
defaultContext?: DefaultContextProvider[];
|
||||
promptPath?: string;
|
||||
enableExperimentalTools?: boolean;
|
||||
onlyUseSystemMessageTools?: boolean;
|
||||
|
||||
/**
|
||||
* Quick actions are a way to add custom commands to the Code Lens of
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
ModelCapability,
|
||||
ModelDescription,
|
||||
TemplateType,
|
||||
} from "../index.js";
|
||||
import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
|
||||
|
||||
import {
|
||||
anthropicTemplateMessages,
|
||||
|
|
@ -41,7 +36,6 @@ import {
|
|||
xWinCoderEditPrompt,
|
||||
zephyrEditPrompt,
|
||||
} from "./templates/edit.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
|
||||
|
||||
const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
||||
"lmstudio",
|
||||
|
|
@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
|
|||
"granite-vision",
|
||||
];
|
||||
|
||||
function modelSupportsTools(modelDescription: ModelDescription) {
|
||||
if (modelDescription.capabilities?.tools !== undefined) {
|
||||
return modelDescription.capabilities.tools;
|
||||
}
|
||||
const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider];
|
||||
if (!providerSupport) {
|
||||
return false;
|
||||
}
|
||||
return providerSupport(modelDescription.model) ?? false;
|
||||
}
|
||||
|
||||
function modelSupportsImages(
|
||||
provider: string,
|
||||
model: string,
|
||||
|
|
@ -401,5 +384,4 @@ export {
|
|||
autodetectTemplateType,
|
||||
llmCanGenerateInParallel,
|
||||
modelSupportsImages,
|
||||
modelSupportsTools,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -531,7 +531,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
let contentToShow = "";
|
||||
if (msg.role === "tool") {
|
||||
contentToShow = msg.content;
|
||||
} else if (msg.role === "assistant" && msg.toolCalls) {
|
||||
} else if (msg.role === "assistant" && msg.toolCalls?.length) {
|
||||
contentToShow = msg.toolCalls
|
||||
?.map(
|
||||
(toolCall) =>
|
||||
|
|
@ -539,10 +539,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
)
|
||||
.join("\n");
|
||||
} else if ("content" in msg) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
msg.content = renderChatMessage(msg);
|
||||
}
|
||||
contentToShow = msg.content;
|
||||
contentToShow = renderChatMessage(msg);
|
||||
}
|
||||
|
||||
return `<${msg.role}>\n${contentToShow}\n\n`;
|
||||
|
|
|
|||
|
|
@ -213,7 +213,7 @@ describe("LLM", () => {
|
|||
testToolCall: true,
|
||||
});
|
||||
testLLM(
|
||||
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }),
|
||||
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o3-mini" }),
|
||||
{ skip: false, timeout: 60000 },
|
||||
);
|
||||
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), {
|
||||
|
|
|
|||
|
|
@ -275,7 +275,7 @@ describe("OpenAI", () => {
|
|||
test("should handle O1 models correctly", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "o1-preview",
|
||||
model: "o3-mini",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
|
|
@ -296,7 +296,7 @@ describe("OpenAI", () => {
|
|||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "o1-preview",
|
||||
model: "o3-mini",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_completion_tokens: 100,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { parseProxyModelName } from "@continuedev/config-yaml";
|
||||
import { ModelDescription } from "..";
|
||||
|
||||
export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
||||
{
|
||||
|
|
@ -304,3 +305,31 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
export function isRecommendedAgentModel(modelName: string): boolean {
|
||||
// AND behavior
|
||||
const recs: RegExp[][] = [
|
||||
[/o[134]/],
|
||||
[/deepseek/, /r1|reasoner/],
|
||||
[/gemini/, /2\.5/, /pro/],
|
||||
[/gpt/, /4/],
|
||||
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
|
||||
[/claude/, /opus/, /-4/],
|
||||
];
|
||||
for (const combo of recs) {
|
||||
if (combo.every((regex) => modelName.toLowerCase().match(regex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function modelSupportsNativeTools(modelDescription: ModelDescription) {
|
||||
if (modelDescription.capabilities?.tools !== undefined) {
|
||||
return modelDescription.capabilities.tools;
|
||||
}
|
||||
const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider];
|
||||
if (!providerSupport) {
|
||||
return false;
|
||||
}
|
||||
return providerSupport(modelDescription.model) ?? false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import type {
|
||||
ContinueRcJson,
|
||||
FileStatsMap,
|
||||
FileType,
|
||||
IDE,
|
||||
|
|
@ -52,7 +51,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
|
||||
readRangeInFile: [{ filepath: string; range: Range }, string];
|
||||
getDiff: [{ includeUnstaged: boolean }, string[]];
|
||||
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
|
||||
getTerminalContents: [undefined, string];
|
||||
getDebugLocals: [{ threadIndex: number }, string];
|
||||
getTopLevelCallStackSources: [
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { FromIdeProtocol } from "..";
|
|||
import { ToIdeFromWebviewOrCoreProtocol } from "../ide";
|
||||
|
||||
import type {
|
||||
ContinueRcJson,
|
||||
FileStatsMap,
|
||||
FileType,
|
||||
IDE,
|
||||
|
|
@ -123,10 +122,6 @@ export class MessageIde implements IDE {
|
|||
return this.request("getUniqueId", undefined);
|
||||
}
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
|
||||
return this.request("getWorkspaceConfigs", undefined);
|
||||
}
|
||||
|
||||
async getDiff(includeUnstaged: boolean) {
|
||||
return await this.request("getDiff", { includeUnstaged });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,10 +89,6 @@ export class ReverseMessageIde {
|
|||
return this.ide.getUniqueId();
|
||||
});
|
||||
|
||||
this.on("getWorkspaceConfigs", () => {
|
||||
return this.ide.getWorkspaceConfigs();
|
||||
});
|
||||
|
||||
this.on("getIdeSettings", () => {
|
||||
return this.ide.getIdeSettings();
|
||||
});
|
||||
|
|
|
|||
2
core/tools/constants.ts
Normal file
2
core/tools/constants.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
|
||||
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const codebaseTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -26,4 +27,9 @@ export const codebaseTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.CodebaseTool,
|
||||
`To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,
|
||||
[["query", "How is user authentication handled in this codebase?"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const createNewFileTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -30,4 +31,12 @@ export const createNewFileTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.CreateNewFile,
|
||||
`To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,
|
||||
[
|
||||
["filepath", "path/to/the_file.txt"],
|
||||
["contents", "Contents of the file"],
|
||||
],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,20 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
const NAME_ARG_DESC =
|
||||
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')";
|
||||
const RULE_ARG_DESC =
|
||||
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.";
|
||||
const DESC_ARG_DESC =
|
||||
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.";
|
||||
const GLOB_ARG_DESC =
|
||||
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])";
|
||||
const REGEX_ARG_DESC =
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)";
|
||||
|
||||
const ALWAYS_APPLY_DESC =
|
||||
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.";
|
||||
|
||||
export const createRuleBlock: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -20,35 +35,54 @@ export const createRuleBlock: Tool = {
|
|||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
description:
|
||||
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
|
||||
description: NAME_ARG_DESC,
|
||||
},
|
||||
rule: {
|
||||
type: "string",
|
||||
description:
|
||||
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
|
||||
description: RULE_ARG_DESC,
|
||||
},
|
||||
description: {
|
||||
type: "string",
|
||||
description:
|
||||
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.",
|
||||
description: DESC_ARG_DESC,
|
||||
},
|
||||
globs: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
|
||||
description: GLOB_ARG_DESC,
|
||||
},
|
||||
regex: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
|
||||
description: REGEX_ARG_DESC,
|
||||
},
|
||||
alwaysApply: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.",
|
||||
description: ALWAYS_APPLY_DESC,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.CreateRuleBlock,
|
||||
`Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.
|
||||
This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules.
|
||||
To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments:
|
||||
- name: ${NAME_ARG_DESC}
|
||||
- rule: ${RULE_ARG_DESC}
|
||||
- description: ${DESC_ARG_DESC}
|
||||
- globs: ${GLOB_ARG_DESC}
|
||||
- alwaysApply: ${ALWAYS_APPLY_DESC}
|
||||
For example:`,
|
||||
[
|
||||
["name", "Use PropTypes"],
|
||||
[
|
||||
"rule",
|
||||
"Always use PropTypes when declaring React component properties",
|
||||
],
|
||||
[
|
||||
"description",
|
||||
"Ensure that all prop types are explicitly declared for better type safety and code maintainability in React components.",
|
||||
],
|
||||
["globs", "**/*.js"],
|
||||
["alwaysApply", "false"],
|
||||
],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
|
||||
|
||||
export interface EditToolArgs {
|
||||
|
|
@ -8,6 +9,9 @@ export interface EditToolArgs {
|
|||
changes: string;
|
||||
}
|
||||
|
||||
const CHANGES_DESCRIPTION =
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
|
|
@ -31,10 +35,24 @@ export const editFileTool: Tool = {
|
|||
},
|
||||
changes: {
|
||||
type: "string",
|
||||
description:
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'",
|
||||
description: CHANGES_DESCRIPTION,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.EditExistingFile,
|
||||
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
|
||||
- filepath: the relative filepath to the file.
|
||||
- changes: ${CHANGES_DESCRIPTION}
|
||||
Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first.
|
||||
For example:`,
|
||||
[
|
||||
["filepath", "path/to/the_file.ts"],
|
||||
[
|
||||
"changes",
|
||||
"// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...",
|
||||
],
|
||||
],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const fetchUrlContentTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -25,4 +26,9 @@ export const fetchUrlContentTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.FetchUrlContent,
|
||||
`To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
|
||||
[["url", "https://example.com"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const globSearchTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -25,4 +26,9 @@ export const globSearchTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.FileGlobSearch,
|
||||
`To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
|
||||
[["pattern", "*.py"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const grepSearchTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -26,4 +27,9 @@ export const grepSearchTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.GrepSearch,
|
||||
`To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
|
||||
[["query", ".*main_services.*"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const lsTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -30,4 +31,12 @@ export const lsTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.LSTool,
|
||||
`To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,
|
||||
[
|
||||
["dirPath", "path/to/dir"],
|
||||
["recursive", "false"],
|
||||
],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const readCurrentlyOpenFileTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -19,4 +20,10 @@ export const readCurrentlyOpenFileTool: Tool = {
|
|||
properties: {},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.ReadCurrentlyOpenFile,
|
||||
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
|
||||
If the user is asking about a file and you don't see any code, use this to check the current file`,
|
||||
[],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const readFileTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -26,4 +27,9 @@ export const readFileTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.ReadFile,
|
||||
`To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,
|
||||
[["filepath", "path/to/the_file.txt"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
expect(result).toBe(
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"No rules available.",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -69,7 +70,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Agent Rule 1: First agent-requested rule\n" +
|
||||
"Agent Rule 2: Second agent-requested rule";
|
||||
|
||||
|
|
@ -90,7 +91,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Rule Without Description: undefined";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
@ -110,7 +111,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"undefined: Rule without name";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
@ -130,7 +131,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Rule Without File: Rule without file path";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
@ -159,7 +160,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Valid Agent Rule: This should be included";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
@ -198,7 +199,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Valid Agent Rule: This should be included";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
@ -210,7 +211,8 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
expect(result).toBe(
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"No rules available.",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -229,7 +231,7 @@ describe("getRequestRuleDescription", () => {
|
|||
const result = getRequestRuleDescription(rules);
|
||||
|
||||
const expected =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
|
||||
"Single Rule: The only agent-requested rule";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
|
|
|
|||
|
|
@ -1,30 +1,41 @@
|
|||
import { ConfigDependentToolParams, GetTool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export interface RequestRuleArgs {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function getRequestRuleDescription(
|
||||
rules: ConfigDependentToolParams["rules"],
|
||||
): string {
|
||||
function getAvailableRules(rules: ConfigDependentToolParams["rules"]) {
|
||||
// Must be explicitly false and no globs
|
||||
const agentRequestedRules = rules.filter(
|
||||
(rule) => rule.alwaysApply === false && !rule.globs,
|
||||
);
|
||||
|
||||
const prefix =
|
||||
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n";
|
||||
|
||||
const body = agentRequestedRules
|
||||
.map((rule) => `${rule.name}: ${rule.description}`)
|
||||
.join("\n");
|
||||
|
||||
if (body.length === 0) {
|
||||
return prefix + "No rules available.";
|
||||
if (agentRequestedRules.length === 0) {
|
||||
return "No rules available.";
|
||||
}
|
||||
|
||||
return prefix + body;
|
||||
return agentRequestedRules
|
||||
.map((rule) => `${rule.name}: ${rule.description}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
export function getRequestRuleDescription(
|
||||
rules: ConfigDependentToolParams["rules"],
|
||||
): string {
|
||||
const prefix =
|
||||
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n";
|
||||
return prefix + getAvailableRules(rules);
|
||||
}
|
||||
|
||||
function getRequestRuleSystemMessageDescription(
|
||||
rules: ConfigDependentToolParams["rules"],
|
||||
): string {
|
||||
const prefix = `To retrieve "rules" that contain more context/instructions based on their descriptions, use the ${BuiltInToolNames.RequestRule} tool with the name of the rule. The available rules are:\n`;
|
||||
const availableRules = getAvailableRules(rules);
|
||||
const suffix = "\n\nFor example, you might respond with:";
|
||||
return prefix + availableRules + suffix;
|
||||
}
|
||||
|
||||
export const requestRuleTool: GetTool = ({ rules }) => ({
|
||||
|
|
@ -49,4 +60,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.RequestRule,
|
||||
getRequestRuleSystemMessageDescription(rules),
|
||||
[["name", "rule_name"]],
|
||||
),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import os from "os";
|
||||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
import os from "os";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
/**
|
||||
* Get the preferred shell for the current platform
|
||||
* @returns The preferred shell command or path
|
||||
*/
|
||||
export function getPreferredShell(): string {
|
||||
function getPreferredShell(): string {
|
||||
const platform = os.platform();
|
||||
|
||||
if (platform === "win32") {
|
||||
|
|
@ -20,7 +20,13 @@ export function getPreferredShell(): string {
|
|||
}
|
||||
}
|
||||
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
|
||||
const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
|
||||
|
||||
const RUN_COMMAND_NOTES = `The shell is not stateful and will not remember any previous commands.\
|
||||
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
|
||||
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
|
||||
Do NOT perform actions requiring special/admin privileges.\
|
||||
${PLATFORM_INFO}`;
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -32,12 +38,7 @@ export const runTerminalCommandTool: Tool = {
|
|||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.RunTerminalCommand,
|
||||
description: `Run a terminal command in the current directory.\
|
||||
The shell is not stateful and will not remember any previous commands.\
|
||||
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
|
||||
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
|
||||
Do NOT perform actions requiring special/admin privileges.\
|
||||
${PLATFORM_INFO}`,
|
||||
description: `Run a terminal command in the current directory.\n${RUN_COMMAND_NOTES}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
|
|
@ -55,4 +56,12 @@ export const runTerminalCommandTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.RunTerminalCommand,
|
||||
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
|
||||
${RUN_COMMAND_NOTES}
|
||||
You can also optionally include the waitForCompletion argument set to false to run the command in the background.
|
||||
For example, to see the git log, you could respond with:`,
|
||||
[["command", "git log"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export interface SearchAndReplaceInFileArgs {
|
||||
filepath: string;
|
||||
|
|
@ -10,46 +11,16 @@ export interface SearchAndReplaceInFileArgs {
|
|||
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
|
||||
"Note this tool CANNOT be called in parallel.";
|
||||
|
||||
/**
|
||||
* This tool is in an experimental state.
|
||||
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
|
||||
*/
|
||||
export const searchAndReplaceInFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SearchAndReplaceInFile,
|
||||
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "diffs"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to modify, relative to the root of the workspace.",
|
||||
},
|
||||
diffs: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
|
||||
\`\`\`
|
||||
------- SEARCH
|
||||
const SEARCH_AND_REPLACE_TOOL_DESCRIPTION = `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`;
|
||||
const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION =
|
||||
"The path of the file to modify, relative to the root of the workspace.";
|
||||
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
\`\`\`
|
||||
+++++++ REPLACE`;
|
||||
|
||||
Critical rules:
|
||||
const SEARCH_AND_REPLACE_RULES = `Critical rules:
|
||||
1. SEARCH content must match the associated file section to find EXACTLY:
|
||||
* Match character-for-character including whitespace, indentation, line endings
|
||||
* Include all comments, docstrings, etc.
|
||||
|
|
@ -69,26 +40,84 @@ Critical rules:
|
|||
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
|
||||
6. Special operations:
|
||||
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
|
||||
* To delete code: Use empty REPLACE section
|
||||
* To delete code: Use empty REPLACE section`;
|
||||
|
||||
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
|
||||
\`\`\`
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
\`\`\`
|
||||
|
||||
${SEARCH_AND_REPLACE_RULES}
|
||||
|
||||
Usage:
|
||||
\`\`\`
|
||||
------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
|
||||
------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
\`\`\`
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
\`\`\`
|
||||
|
||||
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
|
||||
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`;
|
||||
|
||||
/**
|
||||
* This tool is in an experimental state.
|
||||
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
|
||||
*/
|
||||
export const searchAndReplaceInFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SearchAndReplaceInFile,
|
||||
description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "diffs"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION,
|
||||
},
|
||||
diffs: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.SearchAndReplaceInFile,
|
||||
`To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
|
||||
Each block should follow this format:
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
|
||||
${SEARCH_AND_REPLACE_RULES}
|
||||
|
||||
For example, you could respond with:`,
|
||||
[
|
||||
["filepath", "path/to/file.ts"],
|
||||
[
|
||||
"diffs",
|
||||
`[
|
||||
"------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE",
|
||||
"------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE"
|
||||
]`,
|
||||
],
|
||||
],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const searchWebTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -25,4 +26,9 @@ export const searchWebTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.SearchWeb,
|
||||
`To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
|
||||
[["query", "What is the current weather in San Francisco?"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const viewDiffTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -19,4 +20,9 @@ export const viewDiffTool: Tool = {
|
|||
properties: {},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.ViewDiff,
|
||||
`To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
|
||||
[],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const viewRepoMapTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -19,4 +20,9 @@ export const viewRepoMapTool: Tool = {
|
|||
properties: {},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.ViewRepoMap,
|
||||
`To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
|
||||
[],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
|
||||
|
||||
export const viewSubdirectoryTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -25,4 +26,9 @@ export const viewSubdirectoryTool: Tool = {
|
|||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: createSystemMessageExampleCall(
|
||||
BuiltInToolNames.ViewSubdirectory,
|
||||
`To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,
|
||||
[["directory_path", "path/to/subdirectory"]],
|
||||
),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -10,7 +10,9 @@ export const readFileImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(`Could not find file ${filepath}`);
|
||||
throw new Error(
|
||||
`File "${filepath}" does not exist. You might want to check the path and try again.`,
|
||||
);
|
||||
}
|
||||
const content = await extras.ide.readFile(firstUriMatch);
|
||||
|
||||
|
|
|
|||
167
core/tools/systemMessageTools/buildToolsSystemMessage.ts
Normal file
167
core/tools/systemMessageTools/buildToolsSystemMessage.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import { Tool } from "../..";
|
||||
import { closeTag } from "./systemToolUtils";
|
||||
|
||||
export const TOOL_INSTRUCTIONS_TAG = "<tool_use_instructions>";
|
||||
export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION";
|
||||
export const TOOL_DESCRIPTION_TAG = "DESCRIPTION";
|
||||
|
||||
const EXAMPLE_DYNAMIC_TOOL = `
|
||||
\`\`\`tool_definition
|
||||
TOOL_NAME: example_tool
|
||||
TOOL_ARG: arg_1 (string, required)
|
||||
Description of the first argument
|
||||
END_ARG
|
||||
TOOL_ARG: arg_2 (number, optional)
|
||||
END_ARG
|
||||
\`\`\``.trim();
|
||||
|
||||
const EXAMPLE_DYNAMIC_TOOL_CALL = `
|
||||
\`\`\`tool
|
||||
TOOL_NAME: example_tool
|
||||
BEGIN_ARG: arg_1
|
||||
The value
|
||||
of arg 1
|
||||
END_ARG
|
||||
BEGIN_ARG: arg_2
|
||||
3
|
||||
END_ARG
|
||||
\`\`\``.trim();
|
||||
|
||||
export function createSystemMessageExampleCall(
|
||||
name: string,
|
||||
instructions: string,
|
||||
args: Array<[string, string]> = [],
|
||||
) {
|
||||
let callExample = `\`\`\`tool
|
||||
TOOL_NAME: ${name}`;
|
||||
|
||||
// Add each argument dynamically
|
||||
for (const [argName, argValue] of args) {
|
||||
callExample += `
|
||||
BEGIN_ARG: ${argName}
|
||||
${argValue}
|
||||
END_ARG`;
|
||||
}
|
||||
|
||||
callExample += `
|
||||
\`\`\``;
|
||||
|
||||
return `${instructions.trim()}
|
||||
${callExample}`;
|
||||
}
|
||||
|
||||
function toolToSystemToolDefinition(tool: Tool): string {
|
||||
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
|
||||
|
||||
if (tool.function.description) {
|
||||
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
|
||||
}
|
||||
|
||||
if (tool.function.parameters && "properties" in tool.function.parameters) {
|
||||
for (const [key, value] of Object.entries(
|
||||
tool.function.parameters.properties as object,
|
||||
)) {
|
||||
const isRequired = tool.function.parameters.required?.includes(key);
|
||||
const requiredText = isRequired ? "required" : "optional";
|
||||
|
||||
let argType = "string";
|
||||
if ("type" in value) {
|
||||
argType = value.type;
|
||||
}
|
||||
let argDescription = "";
|
||||
if ("description" in value) {
|
||||
argDescription = value.description;
|
||||
}
|
||||
|
||||
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
|
||||
if (argDescription) {
|
||||
toolDefinition += argDescription + "\n";
|
||||
}
|
||||
toolDefinition += `END_ARG\n`;
|
||||
}
|
||||
}
|
||||
|
||||
toolDefinition += `\`\`\``;
|
||||
return toolDefinition.trim();
|
||||
}
|
||||
|
||||
export const generateToolsSystemMessage = (tools: Tool[]): string => {
|
||||
if (tools.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const withPredefinedMessage = tools.filter(
|
||||
(tool) => !!tool.systemMessageDescription,
|
||||
);
|
||||
|
||||
const withDynamicMessage = tools.filter(
|
||||
(tool) => !tool.systemMessageDescription,
|
||||
);
|
||||
|
||||
const instructions: string[] = [];
|
||||
instructions.push(TOOL_INSTRUCTIONS_TAG);
|
||||
instructions.push(
|
||||
`You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`,
|
||||
);
|
||||
instructions.push(
|
||||
`To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`,
|
||||
);
|
||||
|
||||
if (withPredefinedMessage.length > 0) {
|
||||
instructions.push(`\nThe following tools are available to you:`);
|
||||
for (const tool of withPredefinedMessage) {
|
||||
instructions.push(`\n${tool.systemMessageDescription}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withDynamicMessage.length > 0) {
|
||||
instructions.push(
|
||||
`\nAlso, these additional tool definitions show other tools you can call with the same syntax:`,
|
||||
);
|
||||
|
||||
for (const tool of tools) {
|
||||
try {
|
||||
const definition = toolToSystemToolDefinition(tool);
|
||||
instructions.push(`\n${definition}`);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"Failed to convert tool to system message tool:\n" +
|
||||
JSON.stringify(tool),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
instructions.push(`\nFor example, this tool definition:\n`);
|
||||
instructions.push(EXAMPLE_DYNAMIC_TOOL);
|
||||
instructions.push("\nCan be called like this:\n");
|
||||
instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL);
|
||||
}
|
||||
|
||||
instructions.push(
|
||||
`\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`,
|
||||
);
|
||||
instructions.push(
|
||||
`Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`,
|
||||
);
|
||||
instructions.push(
|
||||
`Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`,
|
||||
);
|
||||
instructions.push(
|
||||
`You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`,
|
||||
);
|
||||
|
||||
instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`);
|
||||
return instructions.join("\n");
|
||||
};
|
||||
|
||||
export function addSystemMessageToolsToSystemMessage(
|
||||
baseSystemMessage: string,
|
||||
systemMessageTools: Tool[],
|
||||
): string {
|
||||
let systemMessage = baseSystemMessage;
|
||||
if (systemMessageTools.length > 0) {
|
||||
const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools);
|
||||
systemMessage += `\n\n${toolsSystemMessage}`;
|
||||
}
|
||||
|
||||
return systemMessage;
|
||||
}
|
||||
252
core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts
Normal file
252
core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { Tool } from "../..";
|
||||
import {
|
||||
TOOL_INSTRUCTIONS_TAG,
|
||||
addSystemMessageToolsToSystemMessage,
|
||||
createSystemMessageExampleCall,
|
||||
generateToolsSystemMessage,
|
||||
} from "./buildToolsSystemMessage";
|
||||
import { closeTag } from "./systemToolUtils";
|
||||
|
||||
const SHARED_TOOL_FIELDS = {
|
||||
displayTitle: "DUD",
|
||||
group: "DUD",
|
||||
readonly: true,
|
||||
type: "function" as const,
|
||||
};
|
||||
|
||||
describe("createSystemMessageExampleCall", () => {
|
||||
it("creates a system message example call with no args", () => {
|
||||
const result = createSystemMessageExampleCall(
|
||||
"test_tool",
|
||||
"Use this tool to test things",
|
||||
);
|
||||
expect(result).includes("Use this tool to test things");
|
||||
expect(result).includes("```tool");
|
||||
expect(result).includes("TOOL_NAME: test_tool");
|
||||
expect(result).includes("```");
|
||||
});
|
||||
|
||||
it("creates a system message example call with args", () => {
|
||||
const result = createSystemMessageExampleCall(
|
||||
"test_tool",
|
||||
"Use this tool to test things",
|
||||
[
|
||||
["arg1", "value1"],
|
||||
["arg2", "value2"],
|
||||
],
|
||||
);
|
||||
|
||||
expect(result).includes("Use this tool to test things");
|
||||
expect(result).includes("```tool");
|
||||
expect(result).includes("TOOL_NAME: test_tool");
|
||||
expect(result).includes("BEGIN_ARG: arg1");
|
||||
expect(result).includes("value1");
|
||||
expect(result).includes("END_ARG");
|
||||
expect(result).includes("BEGIN_ARG: arg2");
|
||||
expect(result).includes("value2");
|
||||
});
|
||||
|
||||
it("handles multiline arg values correctly", () => {
|
||||
const multilineValue = "value\nwith\nmultiple\nlines";
|
||||
const result = createSystemMessageExampleCall(
|
||||
"test_tool",
|
||||
"Use this tool to test things",
|
||||
[["arg1", multilineValue]],
|
||||
);
|
||||
|
||||
expect(result).includes("BEGIN_ARG: arg1");
|
||||
expect(result).includes(multilineValue);
|
||||
expect(result).includes("END_ARG");
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateToolsSystemMessage", () => {
|
||||
it("returns empty string for empty tools array", () => {
|
||||
const result = generateToolsSystemMessage([]);
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("generates system message for tools with system message descriptions", () => {
|
||||
const customDescription =
|
||||
"This is test tool 1's system message description";
|
||||
const tools: Tool[] = [
|
||||
{
|
||||
function: {
|
||||
name: "test_tool1",
|
||||
description: "Test tool 1 description",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
},
|
||||
systemMessageDescription: customDescription,
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
];
|
||||
|
||||
const result = generateToolsSystemMessage(tools);
|
||||
|
||||
// Check structure rather than exact text
|
||||
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
|
||||
expect(result).includes(customDescription);
|
||||
expect(result).includes(closeTag(TOOL_INSTRUCTIONS_TAG));
|
||||
|
||||
// Check for general section about available tools without requiring exact wording
|
||||
const hasToolsAvailableSection = /tools are available to you/i.test(result);
|
||||
expect(hasToolsAvailableSection).toBe(true);
|
||||
});
|
||||
|
||||
it("generates system message for tools without system message descriptions", () => {
|
||||
const toolName = "test_tool2";
|
||||
const toolDesc = "Test tool 2 description";
|
||||
const paramDesc = "Parameter 1 description";
|
||||
|
||||
const tools: Tool[] = [
|
||||
{
|
||||
function: {
|
||||
name: toolName,
|
||||
description: toolDesc,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
param1: {
|
||||
type: "string",
|
||||
description: paramDesc,
|
||||
},
|
||||
},
|
||||
required: ["param1"],
|
||||
},
|
||||
},
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
];
|
||||
|
||||
const result = generateToolsSystemMessage(tools);
|
||||
|
||||
// Check for key elements without requiring exact wording
|
||||
expect(result).includes(`TOOL_NAME: ${toolName}`);
|
||||
expect(result).includes("TOOL_DESCRIPTION:");
|
||||
expect(result).includes(toolDesc);
|
||||
expect(result).includes("TOOL_ARG: param1 (string, required)");
|
||||
expect(result).includes(paramDesc);
|
||||
|
||||
// Check for dynamic tool section without exact text matching
|
||||
const hasDynamicToolsSection = /additional tool definitions/i.test(result);
|
||||
expect(hasDynamicToolsSection).toBe(true);
|
||||
});
|
||||
|
||||
it("handles tools with and without system message descriptions", () => {
|
||||
const customMsg = "Custom system message";
|
||||
const tools: Tool[] = [
|
||||
{
|
||||
function: {
|
||||
name: "tool_with_description",
|
||||
description: "Tool description",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
},
|
||||
systemMessageDescription: customMsg,
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
{
|
||||
function: {
|
||||
name: "tool_without_description",
|
||||
description: "Another tool description",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
param1: {
|
||||
type: "string",
|
||||
description: "Parameter description",
|
||||
},
|
||||
},
|
||||
required: ["param1"],
|
||||
},
|
||||
},
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
];
|
||||
|
||||
const result = generateToolsSystemMessage(tools);
|
||||
|
||||
// Check for both types of tools
|
||||
expect(result).includes(customMsg);
|
||||
expect(result).includes("TOOL_NAME: tool_without_description");
|
||||
|
||||
// Verify structure without exact text matching
|
||||
const hasAvailableToolsSection = /tools are available to you/i.test(result);
|
||||
expect(hasAvailableToolsSection).toBe(true);
|
||||
|
||||
const hasDynamicToolsSection = /additional tool definitions/i.test(result);
|
||||
expect(hasDynamicToolsSection).toBe(true);
|
||||
});
|
||||
|
||||
it("includes example tool definition and call", () => {
|
||||
const tools: Tool[] = [
|
||||
{
|
||||
function: {
|
||||
name: "test_tool",
|
||||
description: "Test description",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
},
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
];
|
||||
|
||||
const result = generateToolsSystemMessage(tools);
|
||||
|
||||
// Check for example sections without exact text
|
||||
expect(result).includes("```tool_definition");
|
||||
expect(result).includes("TOOL_NAME: example_tool");
|
||||
expect(result).includes("```tool");
|
||||
|
||||
// Check for example format structure
|
||||
const hasExampleDefinition = /example.*tool definition/i.test(result);
|
||||
const hasExampleCall = /called like this/i.test(result);
|
||||
|
||||
expect(hasExampleDefinition).toBe(true);
|
||||
expect(hasExampleCall).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addSystemMessageToolsToSystemMessage", () => {
|
||||
it("returns original system message when no tools are provided", () => {
|
||||
const baseMessage = "This is the base system message";
|
||||
const result = addSystemMessageToolsToSystemMessage(baseMessage, []);
|
||||
expect(result).toBe(baseMessage);
|
||||
});
|
||||
|
||||
it("appends tools system message to base message", () => {
|
||||
const baseMessage = "This is the base system message";
|
||||
const toolName = "test_tool";
|
||||
const tools: Tool[] = [
|
||||
{
|
||||
function: {
|
||||
name: toolName,
|
||||
description: "Test description",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
},
|
||||
...SHARED_TOOL_FIELDS,
|
||||
},
|
||||
];
|
||||
|
||||
const result = addSystemMessageToolsToSystemMessage(baseMessage, tools);
|
||||
|
||||
expect(result.startsWith(baseMessage)).toBe(true);
|
||||
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
|
||||
expect(result).includes(`TOOL_NAME: ${toolName}`);
|
||||
});
|
||||
});
|
||||
95
core/tools/systemMessageTools/convertSystemTools.ts
Normal file
95
core/tools/systemMessageTools/convertSystemTools.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import {
|
||||
AssistantChatMessage,
|
||||
MessagePart,
|
||||
ToolCallState,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import {
|
||||
normalizeToMessageParts,
|
||||
renderContextItems,
|
||||
} from "../../util/messageContent";
|
||||
import {
|
||||
CANCELLED_TOOL_CALL_MESSAGE,
|
||||
NO_TOOL_CALL_OUTPUT_MESSAGE,
|
||||
} from "../constants";
|
||||
function toolCallStateToSystemToolCall(state: ToolCallState): string {
|
||||
let parts = ["```tool"];
|
||||
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
|
||||
try {
|
||||
for (const arg in state.parsedArgs) {
|
||||
parts.push(`BEGIN_ARG: ${arg}`);
|
||||
parts.push(JSON.stringify(state.parsedArgs[arg]));
|
||||
parts.push(`END_ARG`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Failed to stringify json args", state.parsedArgs);
|
||||
}
|
||||
// TODO - include tool call id for parallel. Confuses dumb models
|
||||
parts.push("```");
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
|
||||
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
|
||||
// TODO - include tool call id for parallel. Confuses dumb models
|
||||
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
|
||||
if (state.status === "canceled") {
|
||||
output += CANCELLED_TOOL_CALL_MESSAGE;
|
||||
} else if (state.output?.length) {
|
||||
output += renderContextItems(state.output);
|
||||
} else {
|
||||
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function convertToolCallStatesToSystemCallsAndOutput(
|
||||
originalAssistantMessage: AssistantChatMessage,
|
||||
toolCallStates: ToolCallState[],
|
||||
): {
|
||||
assistantMessage: AssistantChatMessage;
|
||||
userMessage: UserChatMessage;
|
||||
} {
|
||||
const parts = normalizeToMessageParts(originalAssistantMessage);
|
||||
if (originalAssistantMessage.toolCalls) {
|
||||
parts.push(
|
||||
...toolCallStates.map((state) => ({
|
||||
type: "text" as const,
|
||||
text: toolCallStateToSystemToolCall(state),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
// new message with tool calls moved to content
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
...originalAssistantMessage,
|
||||
content: parts,
|
||||
toolCalls: undefined, // remove tool calls from the assistant message
|
||||
};
|
||||
|
||||
const userParts: MessagePart[] = [];
|
||||
if (toolCallStates) {
|
||||
for (const state of toolCallStates) {
|
||||
userParts.push({
|
||||
type: "text",
|
||||
text: toolCallStateToSystemToolOutput(state),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (userParts.length === 0) {
|
||||
userParts.push({
|
||||
type: "text",
|
||||
text: "Error: no tool output for tool calls",
|
||||
});
|
||||
}
|
||||
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: userParts,
|
||||
};
|
||||
|
||||
return {
|
||||
assistantMessage,
|
||||
userMessage,
|
||||
};
|
||||
}
|
||||
33
core/tools/systemMessageTools/detectToolCallStart.ts
Normal file
33
core/tools/systemMessageTools/detectToolCallStart.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
let boundaryTypeIndex = 0;
|
||||
|
||||
// Poor models are really bad at following instructions
|
||||
// Give some leeway in how the initiate
|
||||
const acceptedToolStarts: [string, string][] = [
|
||||
["```tool\n", "```tool\n"],
|
||||
["tool_name:", "```tool\nTOOL_NAME:"],
|
||||
];
|
||||
|
||||
export function detectToolCallStart(buffer: string) {
|
||||
let modifiedBuffer = buffer;
|
||||
let isInToolCall = false;
|
||||
let isInPartialStart = false;
|
||||
const lowerCaseBuffer = buffer.toLowerCase();
|
||||
for (let i = 0; i < acceptedToolStarts.length; i++) {
|
||||
const [start, replacement] = acceptedToolStarts[i];
|
||||
if (lowerCaseBuffer.startsWith(start)) {
|
||||
// for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive
|
||||
if (i !== 0) {
|
||||
modifiedBuffer = buffer.replace(new RegExp(start, "i"), replacement);
|
||||
}
|
||||
isInToolCall = true;
|
||||
break;
|
||||
} else if (start.startsWith(lowerCaseBuffer)) {
|
||||
isInPartialStart = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
isInToolCall,
|
||||
isInPartialStart,
|
||||
modifiedBuffer,
|
||||
};
|
||||
}
|
||||
76
core/tools/systemMessageTools/detectToolCallStart.vitest.ts
Normal file
76
core/tools/systemMessageTools/detectToolCallStart.vitest.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { detectToolCallStart } from "./detectToolCallStart";
|
||||
|
||||
describe("detectToolCallStart", () => {
|
||||
it("detects standard tool call start", () => {
|
||||
const buffer = "```tool\nTOOL_NAME: example_tool";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(true);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
|
||||
it("detects tool_name start without codeblock", () => {
|
||||
const buffer = "tool_name: example_tool";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(true);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool");
|
||||
});
|
||||
|
||||
it("detects case-insensitive tool call start", () => {
|
||||
const buffer = "```ToOl\nTOOL_NAME: example_tool";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(true);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
|
||||
it("detects case-insensitive tool_name start", () => {
|
||||
const buffer = "ToOl_NaMe: example_tool";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(true);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool");
|
||||
});
|
||||
|
||||
it("identifies partial tool call start", () => {
|
||||
const buffer = "```to";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(false);
|
||||
expect(result.isInPartialStart).toBe(true);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
|
||||
it("identifies partial tool_name start", () => {
|
||||
const buffer = "tool_na";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(false);
|
||||
expect(result.isInPartialStart).toBe(true);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
|
||||
it("does not detect tool call in unrelated text", () => {
|
||||
const buffer = "This is some regular text.";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(false);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
|
||||
it("does not detect tool call in similar but different markdown block", () => {
|
||||
const buffer = "```javascript\nconst x = 10;";
|
||||
const result = detectToolCallStart(buffer);
|
||||
|
||||
expect(result.isInToolCall).toBe(false);
|
||||
expect(result.isInPartialStart).toBe(false);
|
||||
expect(result.modifiedBuffer).toBe(buffer);
|
||||
});
|
||||
});
|
||||
114
core/tools/systemMessageTools/interceptSystemToolCalls.ts
Normal file
114
core/tools/systemMessageTools/interceptSystemToolCalls.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { ChatMessage, PromptLog, TextMessagePart } from "../..";
|
||||
import { normalizeToMessageParts } from "../../util/messageContent";
|
||||
import { detectToolCallStart } from "./detectToolCallStart";
|
||||
import {
|
||||
getInitialTooLCallParseState,
|
||||
handleToolCallBuffer,
|
||||
ToolCallParseState,
|
||||
} from "./parseSystemToolCall";
|
||||
import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
|
||||
|
||||
/*
|
||||
Function to intercept tool calls in markdown code blocks format from a chat message stream
|
||||
1. Skips non-assistant messages
|
||||
2. Intercepts text that looks like a tool call in a markdown code block format:
|
||||
```tool
|
||||
TOOL_NAME: example_tool
|
||||
BEGIN_ARG: arg1
|
||||
value
|
||||
END_ARG
|
||||
```
|
||||
3. Parses tool calls line by line and generates proper tool call deltas
|
||||
4. Once the tool call is complete, resets state for potential future tool calls
|
||||
*/
|
||||
export async function* interceptSystemToolCalls(
|
||||
messageGenerator: AsyncGenerator<ChatMessage[], PromptLog | undefined>,
|
||||
abortController: AbortController,
|
||||
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
|
||||
let buffer = "";
|
||||
let parseState: ToolCallParseState | undefined;
|
||||
|
||||
while (true) {
|
||||
const result = await messageGenerator.next();
|
||||
if (result.done) {
|
||||
// Case: non-standard tool termination causes hanging args
|
||||
if (parseState && !parseState.done && parseState.processedArgNames.size) {
|
||||
yield [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [createDelta("", "}", parseState.toolCallId)],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return result.value;
|
||||
} else {
|
||||
for await (const message of result.value) {
|
||||
if (abortController.signal.aborted || parseState?.done) {
|
||||
break;
|
||||
}
|
||||
// Skip non-assistant messages or messages with native tool calls
|
||||
if (message.role !== "assistant" || message.toolCalls) {
|
||||
yield [message];
|
||||
continue;
|
||||
}
|
||||
|
||||
const parts = normalizeToMessageParts(message);
|
||||
|
||||
// Image output cannot be combined with tools
|
||||
if (parts.find((part) => part.type === "imageUrl")) {
|
||||
yield [message];
|
||||
continue;
|
||||
}
|
||||
|
||||
const chunks = (parts as TextMessagePart[])
|
||||
.map((part) => splitAtCodeblocksAndNewLines(part.text))
|
||||
.flat();
|
||||
|
||||
for (const chunk of chunks) {
|
||||
buffer += chunk;
|
||||
if (!parseState) {
|
||||
const { isInPartialStart, isInToolCall, modifiedBuffer } =
|
||||
detectToolCallStart(buffer);
|
||||
|
||||
if (isInPartialStart) {
|
||||
continue;
|
||||
}
|
||||
if (isInToolCall) {
|
||||
parseState = getInitialTooLCallParseState();
|
||||
buffer = modifiedBuffer;
|
||||
}
|
||||
}
|
||||
|
||||
if (parseState && !parseState.done) {
|
||||
const delta = handleToolCallBuffer(buffer, parseState);
|
||||
if (delta) {
|
||||
yield [
|
||||
{
|
||||
...message,
|
||||
content: "",
|
||||
toolCalls: [delta],
|
||||
},
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// Prevent content after tool calls for now
|
||||
if (parseState) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Yield normal assistant message
|
||||
yield [
|
||||
{
|
||||
...message,
|
||||
content: [{ type: "text", text: buffer }],
|
||||
},
|
||||
];
|
||||
}
|
||||
buffer = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
325
core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts
Normal file
325
core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { AssistantChatMessage, ChatMessage, PromptLog } from "../..";
|
||||
import { interceptSystemToolCalls } from "./interceptSystemToolCalls";
|
||||
|
||||
describe("interceptSystemToolCalls", () => {
|
||||
let abortController: AbortController;
|
||||
|
||||
beforeEach(() => {
|
||||
abortController = new AbortController();
|
||||
});
|
||||
|
||||
const createAsyncGenerator = async function* (
|
||||
messages: ChatMessage[][],
|
||||
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
|
||||
for (const messageGroup of messages) {
|
||||
yield messageGroup;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
it("passes through non-assistant messages unchanged", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "user", content: "Hello" }],
|
||||
[{ role: "system", content: "System message" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
let result = await generator.next();
|
||||
expect(result.value).toEqual([{ role: "user", content: "Hello" }]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{ role: "system", content: "System message" },
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.done).toBe(true);
|
||||
});
|
||||
|
||||
it("passes through assistant messages with existing tool calls", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "existing_tool",
|
||||
arguments: '{"arg1":"value1"}',
|
||||
},
|
||||
id: "existing_call_id",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
const result = await generator.next();
|
||||
expect(result.value).toEqual(messages[0]);
|
||||
});
|
||||
|
||||
it("passes through assistant messages with image URLs unchanged", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "text", text: "Here's an image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "https://example.com/image.png",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
const result = await generator.next();
|
||||
expect(result.value).toEqual(messages[0]);
|
||||
});
|
||||
|
||||
it("processes standard tool call format", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[
|
||||
{
|
||||
role: "assistant",
|
||||
content: "I'll help you with that. Let me use a tool:\n",
|
||||
},
|
||||
],
|
||||
[{ role: "assistant", content: "```tool\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
|
||||
[{ role: "assistant", content: "value1\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
[{ role: "assistant", content: "```" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
// First chunk should be normal text
|
||||
let result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "I'll help you with that. Let me use a tool:",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Tool name detection
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name,
|
||||
).toBe("test_tool");
|
||||
|
||||
// Begin argument
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toContain('{"arg1":');
|
||||
|
||||
// Argument value
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe('"value1"');
|
||||
|
||||
// End of tool call
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe("}");
|
||||
});
|
||||
|
||||
it("processes tool_name without codeblock format", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "assistant", content: "I'll help you with that.\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
|
||||
[{ role: "assistant", content: "value1\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
// First chunk should be normal text
|
||||
let result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "I'll help you with that." }],
|
||||
},
|
||||
]);
|
||||
|
||||
result = await generator.next();
|
||||
expect(result.value).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// The system should detect the tool_name format and convert it
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name,
|
||||
).toBe("test_tool");
|
||||
|
||||
// Rest of processing should work as normal
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe('{"arg1":');
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe('"value1"');
|
||||
|
||||
result = await generator.next();
|
||||
expect(
|
||||
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe("}");
|
||||
});
|
||||
|
||||
it("ignores content after a tool call", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "assistant", content: "```tool\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
|
||||
[{ role: "assistant", content: "value1\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
[{ role: "assistant", content: "```\n" }],
|
||||
[{ role: "assistant", content: "This content should be ignored" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
let result;
|
||||
// Process through all the tool call parts
|
||||
for (let i = 0; i < 6; i++) {
|
||||
result = await generator.next();
|
||||
}
|
||||
|
||||
// The content after the tool call should be ignored
|
||||
result = await generator.next();
|
||||
expect(result.value).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stops processing when aborted", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "assistant", content: "```tool\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
// Process the first part
|
||||
let result = await generator.next();
|
||||
|
||||
// Abort before processing the second part
|
||||
abortController.abort();
|
||||
|
||||
// The next value should be undefined
|
||||
result = await generator.next();
|
||||
expect(result.value).toBeUndefined();
|
||||
});
|
||||
|
||||
it("handles JSON parsing for argument values", async () => {
|
||||
const messages: ChatMessage[][] = [
|
||||
[{ role: "assistant", content: "```tool\n" }],
|
||||
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
|
||||
[{ role: "assistant", content: "BEGIN_ARG: number_arg\n" }],
|
||||
[{ role: "assistant", content: "123\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
[{ role: "assistant", content: "BEGIN_ARG: boolean_arg\n" }],
|
||||
[{ role: "assistant", content: "true\n" }],
|
||||
[{ role: "assistant", content: "END_ARG\n" }],
|
||||
[{ role: "assistant", content: "```" }],
|
||||
];
|
||||
|
||||
const generator = interceptSystemToolCalls(
|
||||
createAsyncGenerator(messages),
|
||||
abortController,
|
||||
);
|
||||
|
||||
// Skip to number arg end
|
||||
await generator.next();
|
||||
await generator.next();
|
||||
let result;
|
||||
result = await generator.next();
|
||||
|
||||
expect(
|
||||
(result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe("123");
|
||||
|
||||
// Skip to boolean arg end
|
||||
await generator.next();
|
||||
result = await generator.next();
|
||||
|
||||
expect(
|
||||
(result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function
|
||||
?.arguments,
|
||||
).toBe("true");
|
||||
});
|
||||
});
|
||||
143
core/tools/systemMessageTools/parseSystemToolCall.ts
Normal file
143
core/tools/systemMessageTools/parseSystemToolCall.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { ToolCallDelta } from "../..";
|
||||
import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils";
|
||||
|
||||
export type ToolCallParseState = {
|
||||
toolCallId: string;
|
||||
isOnArgBeginLine: boolean;
|
||||
currentArgName: string | undefined;
|
||||
currentArgLines: string[];
|
||||
processedArgNames: Set<string>;
|
||||
currentLineIndex: number;
|
||||
lineChunks: string[][];
|
||||
done: boolean;
|
||||
};
|
||||
|
||||
export const getInitialTooLCallParseState = (): ToolCallParseState => ({
|
||||
toolCallId: generateOpenAIToolCallId(),
|
||||
isOnArgBeginLine: false,
|
||||
currentArgName: undefined,
|
||||
currentArgLines: [],
|
||||
currentLineIndex: 0,
|
||||
processedArgNames: new Set(),
|
||||
lineChunks: [],
|
||||
done: false,
|
||||
});
|
||||
|
||||
/*
|
||||
Efficiently applies chunks to a tool call state as they come in
|
||||
Expects chunks to be broken so that new lines and codeblocks are alone
|
||||
For now, this parser collects entire arg before
|
||||
This is because support for JSON booleans is tricky otherwise
|
||||
|
||||
*/
|
||||
export function handleToolCallBuffer(
|
||||
chunk: string,
|
||||
state: ToolCallParseState,
|
||||
): ToolCallDelta | undefined {
|
||||
// Add chunks
|
||||
const lineIndex = state.currentLineIndex;
|
||||
if (!state.lineChunks[lineIndex]) {
|
||||
state.lineChunks[lineIndex] = [];
|
||||
}
|
||||
state.lineChunks[lineIndex].push(chunk);
|
||||
|
||||
const isNewLine = chunk === "\n";
|
||||
if (isNewLine) {
|
||||
state.currentLineIndex++;
|
||||
}
|
||||
|
||||
const line = state.lineChunks[lineIndex].join("");
|
||||
|
||||
switch (lineIndex) {
|
||||
// The first line will be skipped (e.g. ```tool\n)
|
||||
case 0:
|
||||
// non-standard start sequences will sometimes include stuff in the tool_name line
|
||||
const splitBuffer = line.split("\n");
|
||||
if (splitBuffer[0]) {
|
||||
state.lineChunks[0] = [splitBuffer[0], "\n"];
|
||||
}
|
||||
if (splitBuffer[1]) {
|
||||
state.lineChunks[1] = [splitBuffer[1]];
|
||||
}
|
||||
|
||||
state.currentLineIndex = 1;
|
||||
// Tool name line - process once line 2 is reached
|
||||
case 1:
|
||||
if (isNewLine) {
|
||||
const name = (line.split(/tool_?name:/i)[1] ?? "").trim();
|
||||
if (!name) {
|
||||
throw new Error("Invalid tool name");
|
||||
}
|
||||
return createDelta(name, "", state.toolCallId);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
if (state.isOnArgBeginLine) {
|
||||
if (isNewLine) {
|
||||
const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim();
|
||||
if (!argName) {
|
||||
throw new Error("Invalid begin arg line");
|
||||
}
|
||||
state.currentArgName = argName;
|
||||
state.isOnArgBeginLine = false;
|
||||
const argPrefix = state.processedArgNames.size === 0 ? "{" : ",";
|
||||
return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId);
|
||||
}
|
||||
} else if (state.currentArgName) {
|
||||
if (isNewLine) {
|
||||
const isEndArgTag = line.match(/end_?arg/i);
|
||||
if (isEndArgTag) {
|
||||
let trimmedValue = state.currentArgLines.join("").trim();
|
||||
state.currentArgLines.length = 0;
|
||||
state.processedArgNames.add(state.currentArgName);
|
||||
state.currentArgName = undefined;
|
||||
|
||||
try {
|
||||
if (
|
||||
trimmedValue.startsWith("[") ||
|
||||
trimmedValue.startsWith("{")
|
||||
) {
|
||||
trimmedValue = trimmedValue.replace(
|
||||
/"((?:\\[\s\S]|[^"\\])*?)"/g,
|
||||
(match) => {
|
||||
const content = match.slice(1, -1);
|
||||
// Replace unescaped newlines
|
||||
return (
|
||||
'"' +
|
||||
content
|
||||
.replace(/([^\\])\n/g, "$1\\n")
|
||||
.replace(/^\n/g, "\\n") +
|
||||
'"'
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
const parsed = JSON.parse(trimmedValue);
|
||||
const stringifiedArg = JSON.stringify(parsed);
|
||||
return createDelta("", stringifiedArg, state.toolCallId);
|
||||
} catch (e) {
|
||||
const stringifiedArg = JSON.stringify(trimmedValue);
|
||||
return createDelta("", stringifiedArg, state.toolCallId);
|
||||
}
|
||||
} else {
|
||||
state.currentArgLines.push(line);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Check for entry into arg
|
||||
const isBeginArgLine = line.match(/begin_?arg:/i);
|
||||
if (isBeginArgLine) {
|
||||
state.isOnArgBeginLine = true;
|
||||
}
|
||||
|
||||
// Check for exit
|
||||
if (line === "```" || isNewLine) {
|
||||
state.done = true;
|
||||
// finish args JSON if applicable
|
||||
if (state.processedArgNames.size > 0) {
|
||||
return createDelta("", "}", state.toolCallId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
301
core/tools/systemMessageTools/parseSystemToolCall.vitest.ts
Normal file
301
core/tools/systemMessageTools/parseSystemToolCall.vitest.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
ToolCallParseState,
|
||||
getInitialTooLCallParseState,
|
||||
handleToolCallBuffer,
|
||||
} from "./parseSystemToolCall";
|
||||
|
||||
describe("getInitialTooLCallParseState", () => {
|
||||
it("returns a properly initialized parse state", () => {
|
||||
const state = getInitialTooLCallParseState();
|
||||
|
||||
expect(state).toEqual({
|
||||
isOnArgBeginLine: false,
|
||||
currentArgName: undefined,
|
||||
currentArgLines: [],
|
||||
currentLineIndex: 0,
|
||||
processedArgNames: new Set(),
|
||||
lineChunks: [],
|
||||
done: false,
|
||||
toolCallId: expect.any(String),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleToolCallBuffer", () => {
|
||||
let state: ToolCallParseState;
|
||||
|
||||
beforeEach(() => {
|
||||
state = getInitialTooLCallParseState();
|
||||
});
|
||||
|
||||
it("handles the ```tool\ntool_name the name", () => {
|
||||
handleToolCallBuffer("```tool\ntool_name: my_name", state);
|
||||
expect(state.currentLineIndex).toBe(1);
|
||||
|
||||
const result = handleToolCallBuffer("\n", state);
|
||||
expect(result).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "my_name",
|
||||
arguments: "",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.currentLineIndex).toBe(2);
|
||||
});
|
||||
|
||||
it("handles the tool name line", () => {
|
||||
// Line 0 (```tool) is skipped internally
|
||||
state.currentLineIndex = 1;
|
||||
|
||||
const result = handleToolCallBuffer("TOOL_NAME: test_tool", state);
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: "",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.currentLineIndex).toBe(2);
|
||||
});
|
||||
|
||||
it("handles case-insensitive tool name line", () => {
|
||||
state.currentLineIndex = 1;
|
||||
|
||||
const result = handleToolCallBuffer("tool_name: test_tool", state);
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: "",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("begins an argument correctly", () => {
|
||||
state.currentLineIndex = 2;
|
||||
|
||||
const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state);
|
||||
expect(result).toBeUndefined();
|
||||
expect(state.isOnArgBeginLine).toBe(true);
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: '{"test_arg":',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.currentArgName).toBe("test_arg");
|
||||
expect(state.isOnArgBeginLine).toBe(false);
|
||||
});
|
||||
|
||||
it("handles case-insensitive begin arg", () => {
|
||||
state.currentLineIndex = 2;
|
||||
|
||||
const result = handleToolCallBuffer("begin_arg: test_arg", state);
|
||||
expect(result).toBeUndefined();
|
||||
expect(state.isOnArgBeginLine).toBe(true);
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: '{"test_arg":',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("collects arg value lines", () => {
|
||||
state.currentLineIndex = 3;
|
||||
state.currentArgName = "test_arg";
|
||||
|
||||
handleToolCallBuffer("line 1", state);
|
||||
const newLineResult1 = handleToolCallBuffer("\n", state);
|
||||
expect(newLineResult1).toBeUndefined();
|
||||
|
||||
handleToolCallBuffer("line 2", state);
|
||||
const newLineResult2 = handleToolCallBuffer("\n", state);
|
||||
expect(newLineResult2).toBeUndefined();
|
||||
|
||||
expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]);
|
||||
});
|
||||
|
||||
it("ends an argument correctly with string value", () => {
|
||||
state.currentLineIndex = 3;
|
||||
state.currentArgName = "test_arg";
|
||||
state.currentArgLines = ["string value"];
|
||||
|
||||
const result = handleToolCallBuffer("END_ARG", state);
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: '"string value"',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.currentArgName).toBeUndefined();
|
||||
expect(state.processedArgNames.has("test_arg")).toBe(true);
|
||||
});
|
||||
|
||||
it("handles case-insensitive end arg", () => {
|
||||
state.currentLineIndex = 3;
|
||||
state.currentArgName = "test_arg";
|
||||
state.currentArgLines = ["string value"];
|
||||
|
||||
const result = handleToolCallBuffer("end_arg", state);
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: '"string value"',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("attempts to parse JSON values", () => {
|
||||
state.currentLineIndex = 3;
|
||||
state.currentArgName = "test_arg";
|
||||
state.currentArgLines = ["123"];
|
||||
|
||||
handleToolCallBuffer("END_ARG", state);
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: "123",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("handles multiple arguments", () => {
|
||||
// Setup first arg
|
||||
state.currentLineIndex = 2;
|
||||
state.isOnArgBeginLine = true;
|
||||
state.lineChunks[2] = ["BEGIN_ARG: first_arg"];
|
||||
|
||||
handleToolCallBuffer("\n", state);
|
||||
handleToolCallBuffer("value1", state);
|
||||
handleToolCallBuffer("\n", state);
|
||||
handleToolCallBuffer("END_ARG", state);
|
||||
handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(state.processedArgNames.has("first_arg")).toBe(true);
|
||||
|
||||
// Setup second arg
|
||||
state.isOnArgBeginLine = true;
|
||||
handleToolCallBuffer("BEGIN_ARG: second_arg", state);
|
||||
handleToolCallBuffer("\n", state);
|
||||
handleToolCallBuffer("value2", state);
|
||||
handleToolCallBuffer("\n", state);
|
||||
handleToolCallBuffer("END_ARG", state);
|
||||
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: '"value2"',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.processedArgNames.has("second_arg")).toBe(true);
|
||||
});
|
||||
|
||||
it("finalizes JSON object at end of tool call", () => {
|
||||
state.currentLineIndex = 5;
|
||||
state.processedArgNames.add("test_arg");
|
||||
|
||||
const result = handleToolCallBuffer("```", state);
|
||||
|
||||
expect(result).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: "}",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.done).toBe(true);
|
||||
});
|
||||
|
||||
it("finalizes on newline after all args processed", () => {
|
||||
state.currentLineIndex = 5;
|
||||
state.processedArgNames.add("test_arg");
|
||||
|
||||
const result = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(result).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments: "}",
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
expect(state.done).toBe(true);
|
||||
});
|
||||
|
||||
it("handles JSON array args", () => {
|
||||
state.currentLineIndex = 3;
|
||||
state.currentArgName = "test_arg";
|
||||
state.currentArgLines = [
|
||||
"[\n",
|
||||
'"------- SEARCH\n',
|
||||
" subtract(number) {\n",
|
||||
" return this;\n",
|
||||
" }\n",
|
||||
"=======\n",
|
||||
" subtract(number) {\n",
|
||||
" this -= number\n",
|
||||
" return this;\n",
|
||||
" }\n",
|
||||
'+++++++ REPLACE"\n',
|
||||
"]\n",
|
||||
];
|
||||
|
||||
handleToolCallBuffer("END_ARG", state);
|
||||
const newLineResult = handleToolCallBuffer("\n", state);
|
||||
|
||||
expect(newLineResult).toEqual({
|
||||
type: "function",
|
||||
function: {
|
||||
name: "",
|
||||
arguments:
|
||||
'["------- SEARCH\\n subtract(number) {\\n return this;\\n }\\n=======\\n subtract(number) {\\n this -= number\\n return this;\\n }\\n+++++++ REPLACE"]',
|
||||
},
|
||||
id: expect.any(String),
|
||||
});
|
||||
});
|
||||
});
|
||||
38
core/tools/systemMessageTools/systemToolUtils.ts
Normal file
38
core/tools/systemMessageTools/systemToolUtils.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { ToolCallDelta } from "../..";
|
||||
|
||||
export function closeTag(openingTag: string): string {
|
||||
return `</${openingTag.slice(1)}`;
|
||||
}
|
||||
|
||||
export function splitAtCodeblocksAndNewLines(content: string) {
|
||||
return content.split(/(```|\n)/g).filter(Boolean);
|
||||
}
|
||||
|
||||
function randomLettersAndNumbers(length: number): string {
|
||||
const characters =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let result = "";
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += characters.charAt(Math.floor(Math.random() * characters.length));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function generateOpenAIToolCallId(): string {
|
||||
return `call_${randomLettersAndNumbers(24)}`;
|
||||
}
|
||||
|
||||
export function createDelta(
|
||||
name: string,
|
||||
args: string,
|
||||
id: string,
|
||||
): ToolCallDelta {
|
||||
return {
|
||||
type: "function",
|
||||
function: {
|
||||
name,
|
||||
arguments: args,
|
||||
},
|
||||
id,
|
||||
};
|
||||
}
|
||||
57
core/tools/systemMessageTools/systemToolUtils.vitest.ts
Normal file
57
core/tools/systemMessageTools/systemToolUtils.vitest.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
import { closeTag, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
|
||||
|
||||
describe("closeTag", () => {
|
||||
const testCases = [
|
||||
{
|
||||
input: "<div>",
|
||||
expectedOutput: "</div>",
|
||||
},
|
||||
{
|
||||
input: "<p>",
|
||||
expectedOutput: "</p>",
|
||||
},
|
||||
// Add more test cases as needed
|
||||
];
|
||||
|
||||
testCases.forEach((testCase) => {
|
||||
test(`closes tag "${testCase.input}" to "</${testCase.input.slice(1)}"`, () => {
|
||||
const result = closeTag(testCase.input);
|
||||
expect(result).toEqual(testCase.expectedOutput);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitAtCodeblocks", () => {
|
||||
test("doesn't split plain text without codeblocks", () => {
|
||||
expect(splitAtCodeblocksAndNewLines("hello world")).toEqual([
|
||||
"hello world",
|
||||
]);
|
||||
});
|
||||
|
||||
test("splits at codeblocks", () => {
|
||||
expect(splitAtCodeblocksAndNewLines("```<one>middle```<two>")).toEqual([
|
||||
"```",
|
||||
"<one>middle",
|
||||
"```",
|
||||
"<two>",
|
||||
]);
|
||||
});
|
||||
|
||||
test("splits at new lines", () => {
|
||||
expect(splitAtCodeblocksAndNewLines("hello\nhoware\n you\n")).toEqual([
|
||||
"hello",
|
||||
"\n",
|
||||
"howare",
|
||||
"\n",
|
||||
" you",
|
||||
"\n",
|
||||
]);
|
||||
});
|
||||
|
||||
test("splits at both codeblocks and new lines", () => {
|
||||
expect(splitAtCodeblocksAndNewLines("hello```\nho```ware\n you\n")).toEqual(
|
||||
["hello", "```", "\n", "ho", "```", "ware", "\n", " you", "\n"],
|
||||
);
|
||||
});
|
||||
});
|
||||
102
core/tools/systemMessageTools/textifySystemTools.ts
Normal file
102
core/tools/systemMessageTools/textifySystemTools.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import {
|
||||
AssistantChatMessage,
|
||||
MessagePart,
|
||||
ToolCallState,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import {
|
||||
normalizeToMessageParts,
|
||||
renderContextItems,
|
||||
} from "../../util/messageContent";
|
||||
import {
|
||||
CANCELLED_TOOL_CALL_MESSAGE,
|
||||
NO_TOOL_CALL_OUTPUT_MESSAGE,
|
||||
} from "../constants";
|
||||
function toolCallStateToSystemToolCall(state: ToolCallState): string {
|
||||
let parts = ["```tool"];
|
||||
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
|
||||
try {
|
||||
for (const arg in state.parsedArgs) {
|
||||
parts.push(`BEGIN_ARG: ${arg}`);
|
||||
parts.push(JSON.stringify(state.parsedArgs[arg]));
|
||||
parts.push(`END_ARG`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Failed to stringify json args", state.parsedArgs);
|
||||
}
|
||||
// TODO - include tool call id for parallel. Confuses dumb models
|
||||
parts.push("```");
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
|
||||
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
|
||||
// TODO - include tool call id for parallel. Confuses dumb models
|
||||
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
|
||||
if (state.status === "canceled") {
|
||||
output += CANCELLED_TOOL_CALL_MESSAGE;
|
||||
} else if (state.output?.length) {
|
||||
output += renderContextItems(state.output);
|
||||
} else {
|
||||
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function convertToolCallStatesToSystemCallsAndOutput(
|
||||
originalAssistantMessage: AssistantChatMessage,
|
||||
toolCallStates: ToolCallState[],
|
||||
): {
|
||||
assistantMessage: AssistantChatMessage;
|
||||
userMessage: UserChatMessage;
|
||||
} {
|
||||
const assistantParts = normalizeToMessageParts(originalAssistantMessage);
|
||||
if (originalAssistantMessage.toolCalls) {
|
||||
assistantParts.push(
|
||||
...toolCallStates.map((state) => ({
|
||||
type: "text" as const,
|
||||
text: toolCallStateToSystemToolCall(state),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const userParts: MessagePart[] = [];
|
||||
if (toolCallStates) {
|
||||
for (const state of toolCallStates) {
|
||||
userParts.push({
|
||||
type: "text",
|
||||
text: toolCallStateToSystemToolOutput(state),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (userParts.length === 0) {
|
||||
userParts.push({
|
||||
type: "text",
|
||||
text: "No tool output for tool calls",
|
||||
});
|
||||
}
|
||||
|
||||
const nonEmptyAssistantParts = assistantParts.filter(
|
||||
(p) => p.type !== "text" || !!p.text,
|
||||
);
|
||||
const nonEmptyUserParts = userParts.filter(
|
||||
(p) => p.type !== "text" || !!p.text,
|
||||
);
|
||||
|
||||
// new message with tool calls moved to content
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
...originalAssistantMessage,
|
||||
content: nonEmptyAssistantParts,
|
||||
toolCalls: undefined, // remove tool calls from the assistant message
|
||||
};
|
||||
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: nonEmptyUserParts,
|
||||
};
|
||||
|
||||
return {
|
||||
assistantMessage,
|
||||
userMessage,
|
||||
};
|
||||
}
|
||||
|
|
@ -2,7 +2,6 @@ import * as fs from "node:fs";
|
|||
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
ContinueRcJson,
|
||||
FileStatsMap,
|
||||
FileType,
|
||||
IDE,
|
||||
|
|
@ -145,10 +144,6 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve("NOT_UNIQUE");
|
||||
}
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
getDiff(includeUnstaged: boolean): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -988,6 +988,14 @@
|
|||
{
|
||||
"source": "/agent/context-selection",
|
||||
"destination": "/features/agent/context-selection"
|
||||
},
|
||||
{
|
||||
"source": "/customization/overview#codebase-context",
|
||||
"destination": "/customize/context/codebase"
|
||||
},
|
||||
{
|
||||
"source": "/customization/overview#documentation-context",
|
||||
"destination": "/customize/context/documentation"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,8 +51,8 @@ View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting
|
|||
|
||||
Learn more about how context providers work:
|
||||
|
||||
- [Codebase Context](/customization/overview#codebase-context)
|
||||
- [Documentation Context](/customization/overview#documentation-context)
|
||||
- [Codebase Context](/customize/context/codebase)
|
||||
- [Documentation Context](/customize/context/documentation)
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -110,6 +110,23 @@ You can selectively increase the log granularity (e.g., debug-level logs) as fol
|
|||
|
||||
You can find more information about this feature in [official docs](https://youtrack.jetbrains.com/articles/SUPPORT-A-43/How-to-enable-debug-logging-in-IntelliJ-IDEA).
|
||||
|
||||
### Developing `build.plugin.kts`
|
||||
|
||||
If in doubt, check out the
|
||||
official [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template).
|
||||
These templates are the most up-to-date examples of how to correctly customize the plugin build scripts.
|
||||
|
||||
Also, check out
|
||||
the [useful recipes](https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-recipes.html)
|
||||
for common problems.
|
||||
|
||||
### Adding new extensions in `plugin.xml`
|
||||
|
||||
There's a tool called [JetBrains Platform Explorer](https://plugins.jetbrains.com/intellij-platform-explorer) that
|
||||
aggregates plugin metadata and allows you to filter by specific
|
||||
extension points. If you're having trouble implementing a feature that's not officially documented,
|
||||
you can learn from other open source plugins.
|
||||
|
||||
### Reloading changes
|
||||
|
||||
- `extensions/intellij`: Attempt to reload changed classes by selecting
|
||||
|
|
|
|||
|
|
@ -1,77 +1,75 @@
|
|||
import org.jetbrains.changelog.markdownToHTML
|
||||
|
||||
fun properties(key: String) = providers.gradleProperty(key)
|
||||
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
|
||||
import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
|
||||
|
||||
fun environment(key: String) = providers.environmentVariable(key)
|
||||
|
||||
fun Sync.prepareSandbox() {
|
||||
from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") }
|
||||
}
|
||||
|
||||
val remoteRobotVersion = "0.11.23"
|
||||
val platformType: String by project
|
||||
val platformVersion: String by project
|
||||
val pluginGroup: String by project
|
||||
val pluginVersion: String by project
|
||||
val pluginSinceBuild: String by project
|
||||
val pluginRepositoryUrl: String by project
|
||||
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
|
||||
val pluginVersion = properties("pluginVersion").get()
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
kotlin("jvm") version "1.9.0"
|
||||
id("org.jetbrains.intellij") version "1.15.0"
|
||||
kotlin("jvm") version "1.8.0"
|
||||
id("org.jetbrains.intellij.platform") version "2.6.0"
|
||||
id("org.jetbrains.changelog") version "2.1.2"
|
||||
id("org.jetbrains.qodana") version "0.1.13"
|
||||
id("org.jetbrains.kotlinx.kover") version "0.7.3"
|
||||
kotlin("plugin.serialization") version "1.8.0"
|
||||
id("io.sentry.jvm.gradle") version "5.8.0"
|
||||
}
|
||||
|
||||
group = properties("pluginGroup").get()
|
||||
group = pluginGroup
|
||||
version = if (isEap) "$pluginVersion-eap" else pluginVersion
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") }
|
||||
intellijPlatform {
|
||||
defaultRepositories()
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
|
||||
implementation("com.posthog.java:posthog:1.+")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
|
||||
intellijPlatform {
|
||||
create(platformType, platformVersion)
|
||||
plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6"))
|
||||
testFramework(TestFrameworkType.Platform)
|
||||
}
|
||||
implementation("com.posthog.java:posthog:1.2.0")
|
||||
|
||||
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
|
||||
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
|
||||
testImplementation("io.mockk:mockk:1.14.2")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
|
||||
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
||||
testImplementation(kotlin("test"))
|
||||
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
|
||||
}
|
||||
|
||||
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
|
||||
// 2022.2+.
|
||||
kotlin { jvmToolchain(17) }
|
||||
|
||||
// Configure Gradle IntelliJ Plugin - read more:
|
||||
// https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html
|
||||
intellij {
|
||||
pluginName = properties("pluginName")
|
||||
version = properties("platformVersion")
|
||||
type = properties("platformType")
|
||||
|
||||
// Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
|
||||
plugins =
|
||||
properties("platformPlugins").map {
|
||||
it.split(',').map(String::trim).filter(String::isNotEmpty)
|
||||
intellijPlatform {
|
||||
pluginConfiguration {
|
||||
ideaVersion {
|
||||
sinceBuild = pluginSinceBuild
|
||||
}
|
||||
}
|
||||
pluginVerification {
|
||||
ides {
|
||||
ide("IC", "2025.1.4")
|
||||
ide("IC", "2022.3.3")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Gradle Changelog Plugin - read more:
|
||||
// https://github.com/JetBrains/gradle-changelog-plugin
|
||||
changelog {
|
||||
groups.empty()
|
||||
repositoryUrl = properties("pluginRepositoryUrl")
|
||||
repositoryUrl = pluginRepositoryUrl
|
||||
}
|
||||
|
||||
// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin
|
||||
qodana {
|
||||
cachePath = provider { file(".qodana").canonicalPath }
|
||||
reportPath = provider { file("build/reports/inspections").canonicalPath }
|
||||
|
|
@ -79,75 +77,52 @@ qodana {
|
|||
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
|
||||
}
|
||||
|
||||
// Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration
|
||||
koverReport { defaults { xml { onCheck = true } } }
|
||||
|
||||
intellijPlatformTesting {
|
||||
runIde {
|
||||
register("runIdeForUiTests") {
|
||||
task {
|
||||
environment(
|
||||
"CONTINUE_GLOBAL_DIR",
|
||||
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
|
||||
)
|
||||
jvmArgumentProviders += CommandLineArgumentProvider {
|
||||
listOf(
|
||||
"-Drobot-server.port=8082",
|
||||
"-Dide.mac.message.dialogs.as.sheets=false",
|
||||
"-Djb.privacy.policy.text=<!--999.999-->",
|
||||
"-Djb.consents.confirmation.enabled=false",
|
||||
"-Dide.mac.file.chooser.native=false",
|
||||
"-DjbScreenMenuBar.enabled=false",
|
||||
"-Dapple.laf.useScreenMenuBar=false",
|
||||
"-Didea.trust.all.projects=true",
|
||||
"-Dide.show.tips.on.startup.default.value=false",
|
||||
"-Dide.browser.jcef.jsQueryPoolSize=10000",
|
||||
"-Dide.browser.jcef.contextMenu.devTools.enabled=true"
|
||||
)
|
||||
}
|
||||
}
|
||||
plugins {
|
||||
robotServerPlugin()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks {
|
||||
downloadRobotServerPlugin {
|
||||
version = remoteRobotVersion
|
||||
}
|
||||
|
||||
prepareSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
prepareTestingSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
prepareUiTestingSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
wrapper {
|
||||
gradleVersion = properties("gradleVersion").get()
|
||||
withType<PrepareSandboxTask> {
|
||||
from("../../binary/bin") {
|
||||
into(pluginName.map { "$it/core" })
|
||||
}
|
||||
}
|
||||
|
||||
patchPluginXml {
|
||||
sinceBuild = properties("pluginSinceBuild")
|
||||
untilBuild = properties("pluginUntilBuild")
|
||||
pluginDescription =
|
||||
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
|
||||
val start = "<!-- Plugin description -->"
|
||||
val end = "<!-- Plugin description end -->"
|
||||
|
||||
with(it.lines()) {
|
||||
if (!containsAll(listOf(start, end))) {
|
||||
throw GradleException(
|
||||
"Plugin description section not found in README.md:\n$start ... $end"
|
||||
)
|
||||
}
|
||||
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure UI tests plugin
|
||||
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
|
||||
runIdeForUiTests {
|
||||
environment(
|
||||
"CONTINUE_GLOBAL_DIR",
|
||||
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
|
||||
)
|
||||
systemProperty("robot-server.port", "8082")
|
||||
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
|
||||
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
|
||||
systemProperty("jb.consents.confirmation.enabled", "false")
|
||||
systemProperty("ide.mac.file.chooser.native", "false")
|
||||
systemProperty("jbScreenMenuBar.enabled", "false")
|
||||
systemProperty("apple.laf.useScreenMenuBar", "false")
|
||||
systemProperty("idea.trust.all.projects", "true")
|
||||
systemProperty("ide.show.tips.on.startup.default.value", "false")
|
||||
systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
|
||||
systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
|
||||
|
||||
// This is to ensure we load the GUI with OSR enabled. We have logic that
|
||||
// renders with OSR disabled below a particular IDE version.
|
||||
// See ContinueExtensionSettingsService.kt for more info.
|
||||
// Currently commented out however since test fail in CI with this version
|
||||
// intellij {
|
||||
// version = "2024.1"
|
||||
// }
|
||||
pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.get()
|
||||
.substringAfter("<!-- Plugin description -->")
|
||||
.substringBefore("<!-- Plugin description end -->")
|
||||
.let(::markdownToHTML)
|
||||
check(pluginDescription.get().isNotEmpty()) { "Plugin description section not found in README.md" }
|
||||
}
|
||||
|
||||
signPlugin {
|
||||
|
|
@ -164,8 +139,10 @@ tasks {
|
|||
}
|
||||
|
||||
runIde {
|
||||
val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox"
|
||||
args = listOf(dir, "$dir/test.kt")
|
||||
val openProject = "$projectDir/../../manual-testing-sandbox"
|
||||
argumentProviders += CommandLineArgumentProvider {
|
||||
listOf(openProject, "$openProject/test.kt")
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
|
|
|
|||
|
|
@ -1,26 +1,9 @@
|
|||
# IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
|
||||
pluginGroup=com.github.continuedev.continueintellijextension
|
||||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.32
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginVersion=1.0.33
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
platformType=IC
|
||||
platformVersion=2022.3.3
|
||||
# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
#platformVersion = LATEST-EAP-SNAPSHOT
|
||||
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
|
||||
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
|
||||
platformPlugins=org.jetbrains.plugins.terminal
|
||||
# Gradle Releases -> https://github.com/gradle/gradle/releases
|
||||
gradleVersion=8.3
|
||||
# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
|
||||
kotlin.stdlib.default.dependency=false
|
||||
# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
|
||||
org.gradle.configuration-cache=true
|
||||
# Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
|
||||
org.gradle.caching=true
|
||||
# Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment
|
||||
systemProp.org.gradle.unsafe.kotlin.assignment=true
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1,8 +1,7 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
14
extensions/intellij/gradlew
vendored
14
extensions/intellij/gradlew
vendored
|
|
@ -145,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
|
|
@ -153,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
|
|
@ -202,11 +202,11 @@ fi
|
|||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ class MessageTypes {
|
|||
"readRangeInFile",
|
||||
"isTelemetryEnabled",
|
||||
"getUniqueId",
|
||||
"getWorkspaceConfigs",
|
||||
"getDiff",
|
||||
"getTerminalContents",
|
||||
"getWorkspaceDirs",
|
||||
|
|
|
|||
|
|
@ -196,11 +196,6 @@ class IdeProtocolClient(
|
|||
respond(tags)
|
||||
}
|
||||
|
||||
"getWorkspaceConfigs" -> {
|
||||
val configs = ide.getWorkspaceConfigs()
|
||||
respond(configs)
|
||||
}
|
||||
|
||||
"getTerminalContents" -> {
|
||||
val contents = ide.getTerminalContents()
|
||||
respond(contents)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
|
|||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
|
|
@ -38,9 +39,7 @@ import java.awt.Toolkit
|
|||
import java.awt.datatransfer.DataFlavor
|
||||
import java.io.BufferedReader
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.nio.charset.Charset
|
||||
|
||||
class IntelliJIDE(
|
||||
private val project: Project,
|
||||
|
|
@ -49,7 +48,7 @@ class IntelliJIDE(
|
|||
) : IDE {
|
||||
|
||||
private val gitService = GitService(project, continuePluginService)
|
||||
|
||||
private val fileUtils = FileUtils()
|
||||
private val ripgrep: String = getRipgrepPath()
|
||||
|
||||
init {
|
||||
|
|
@ -181,39 +180,11 @@ class IntelliJIDE(
|
|||
return workspaceDirectories().toList()
|
||||
}
|
||||
|
||||
override suspend fun getWorkspaceConfigs(): List<ContinueRcJson> {
|
||||
val workspaceDirs = this.getWorkspaceDirs()
|
||||
override suspend fun fileExists(filepath: String): Boolean =
|
||||
fileUtils.fileExists(filepath)
|
||||
|
||||
val configs = mutableListOf<String>()
|
||||
|
||||
for (workspaceDir in workspaceDirs) {
|
||||
val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir)
|
||||
if (dir != null) {
|
||||
val contents = dir.children.mapNotNull { it.toUriOrNull() }
|
||||
|
||||
// Find any .continuerc.json files
|
||||
for (file in contents) {
|
||||
if (file.endsWith(".continuerc.json")) {
|
||||
val fileContent = UriUtils.uriToFile(file).readText()
|
||||
configs.add(fileContent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return configs as List<ContinueRcJson>
|
||||
}
|
||||
|
||||
override suspend fun fileExists(filepath: String): Boolean {
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
return file.exists()
|
||||
}
|
||||
|
||||
override suspend fun writeFile(path: String, contents: String) {
|
||||
val file = UriUtils.uriToFile(path)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
override suspend fun writeFile(path: String, contents: String) =
|
||||
fileUtils.writeFile(path, contents)
|
||||
|
||||
override suspend fun showVirtualFile(title: String, contents: String) {
|
||||
val virtualFile = LightVirtualFile(title, contents)
|
||||
|
|
@ -321,39 +292,8 @@ class IntelliJIDE(
|
|||
}
|
||||
}
|
||||
|
||||
override suspend fun readFile(filepath: String): String {
|
||||
return try {
|
||||
val content = ApplicationManager.getApplication().runReadAction<String?> {
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
|
||||
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
|
||||
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
|
||||
}
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
if (content != null) {
|
||||
content
|
||||
} else {
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
withContext(Dispatchers.IO) {
|
||||
FileInputStream(file).use { fis ->
|
||||
val sizeToRead = minOf(100000, file.length()).toInt()
|
||||
val buffer = ByteArray(sizeToRead)
|
||||
val bytesRead = fis.read(buffer, 0, sizeToRead)
|
||||
if (bytesRead <= 0) return@use ""
|
||||
val content = String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
|
||||
// Remove `\r` characters but preserve trailing newlines to prevent line count discrepancies
|
||||
val contentWithoutCR = content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
contentWithoutCR
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
""
|
||||
}
|
||||
}
|
||||
override suspend fun readFile(filepath: String): String =
|
||||
fileUtils.readFile(filepath)
|
||||
|
||||
override suspend fun readRangeInFile(filepath: String, range: Range): String {
|
||||
val fullContents = readFile(filepath)
|
||||
|
|
@ -662,13 +602,8 @@ class IntelliJIDE(
|
|||
}
|
||||
}
|
||||
|
||||
override suspend fun listDir(dir: String): List<List<Any>> {
|
||||
val files = UriUtils.uriToFile(dir).listFiles()?.map {
|
||||
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
|
||||
} ?: emptyList()
|
||||
|
||||
return files
|
||||
}
|
||||
override suspend fun listDir(dir: String): List<List<Any>> =
|
||||
fileUtils.listDir(dir)
|
||||
|
||||
override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
|
||||
return files.associateWith { file ->
|
||||
|
|
|
|||
|
|
@ -0,0 +1,69 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.file
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FileType
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.FileInputStream
|
||||
import java.nio.charset.Charset
|
||||
|
||||
class FileUtils {
|
||||
// todo: use VFS (it's moved from IntellijIde)
|
||||
|
||||
fun fileExists(uri: String): Boolean {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
return file.exists()
|
||||
}
|
||||
|
||||
fun writeFile(uri: String, contents: String) {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
|
||||
fun listDir(dir: String): List<List<Any>> {
|
||||
val files = UriUtils.uriToFile(dir).listFiles()?.map {
|
||||
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
|
||||
} ?: emptyList()
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
fun readFile(uri: String): String {
|
||||
return try {
|
||||
val content = ApplicationManager.getApplication().runReadAction<String?> {
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(uri).path)
|
||||
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
|
||||
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
|
||||
}
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
if (content != null) {
|
||||
content
|
||||
} else {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
FileInputStream(file).use { fis ->
|
||||
val sizeToRead = minOf(100000, file.length()).toInt()
|
||||
val buffer = ByteArray(sizeToRead)
|
||||
val bytesRead = fis.read(buffer, 0, sizeToRead)
|
||||
if (bytesRead <= 0) return@use ""
|
||||
val content = String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
|
||||
// Remove `\r` characters but preserve trailing newlines to prevent line count discrepancies
|
||||
val contentWithoutCR = content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
contentWithoutCR
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
""
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -16,11 +16,6 @@ enum class FileType(val value: Int) {
|
|||
SYMBOLIC_LINK(64)
|
||||
}
|
||||
|
||||
enum class ConfigMergeType {
|
||||
MERGE,
|
||||
OVERWRITE
|
||||
}
|
||||
|
||||
data class Position(val line: Int, val character: Int)
|
||||
|
||||
data class Range(val start: Position, val end: Position)
|
||||
|
|
@ -149,10 +144,6 @@ data class IdeSettings(
|
|||
val continueTestEnvironment: String
|
||||
)
|
||||
|
||||
data class ContinueRcJson(
|
||||
val mergeBehavior: ConfigMergeType
|
||||
)
|
||||
|
||||
data class TerminalOptions(
|
||||
val reuseTerminal: Boolean?,
|
||||
val terminalName: String?,
|
||||
|
|
@ -187,8 +178,6 @@ interface IDE {
|
|||
|
||||
suspend fun getWorkspaceDirs(): List<String>
|
||||
|
||||
suspend fun getWorkspaceConfigs(): List<ContinueRcJson>
|
||||
|
||||
suspend fun fileExists(filepath: String): Boolean
|
||||
|
||||
suspend fun writeFile(path: String, contents: String)
|
||||
|
|
|
|||
|
|
@ -14,9 +14,6 @@
|
|||
com.intellij.modules.json
|
||||
</depends>
|
||||
|
||||
<!-- com.intellij.openapi.module.ModuleManager.Companion is only available since this build -->
|
||||
<idea-version since-build="223.7571.182"/>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<editorFactoryListener
|
||||
implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteEditorListener"/>
|
||||
|
|
|
|||
|
|
@ -12,13 +12,12 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
|
|||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import io.mockk.*
|
||||
import junit.framework.TestCase
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
@ExperimentalCoroutinesApi
|
||||
class ApplyToFileHandlerTest {
|
||||
class ApplyToFileHandlerTest : TestCase() {
|
||||
// Mock all dependencies
|
||||
private val mockProject = mockk<Project>(relaxed = true)
|
||||
private val mockContinuePluginService = mockk<ContinuePluginService>(relaxed = true)
|
||||
|
|
@ -39,8 +38,7 @@ class ApplyToFileHandlerTest {
|
|||
"tool-call-123"
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
override fun setUp() {
|
||||
// Common setup
|
||||
every { mockEditorUtils.editor } returns mockEditor
|
||||
every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
|
||||
|
|
@ -56,8 +54,7 @@ class ApplyToFileHandlerTest {
|
|||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should insert text directly when document is empty`() = runTest {
|
||||
fun `test should insert text directly when document is empty`() = runTest {
|
||||
// Given
|
||||
every { mockEditorUtils.isDocumentEmpty() } returns true
|
||||
|
||||
|
|
|
|||
|
|
@ -1,48 +1,39 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import com.github.continuedev.continueintellijextension.utils.checkFim
|
||||
import org.junit.jupiter.api.Disabled
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
import junit.framework.TestCase
|
||||
|
||||
class CheckFimTest {
|
||||
@Test
|
||||
fun testFim() {
|
||||
class CheckFimTest : TestCase() {
|
||||
fun `test FIM`() {
|
||||
val oldEditRange = "hello world"
|
||||
val newEditRange = "hello this world"
|
||||
val cursorPosition = Pair(0, 6)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMultilineFim() {
|
||||
fun `test multiline FIM`() {
|
||||
val oldEditRange = "hello {\n world\n}"
|
||||
val newEditRange = "hello {\n print()\n world\n}"
|
||||
val cursorPosition = Pair(1, 2)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNotFim() {
|
||||
fun `test not FIM`() {
|
||||
val oldEditRange = "hello world"
|
||||
val newEditRange = "hello this world"
|
||||
val cursorPosition = Pair(0, 8)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMultilineNotFim() {
|
||||
fun `test multiline not FIM`() {
|
||||
val oldEditRange = "hello {\n world\n}"
|
||||
val newEditRange = "hello {\n world\n}\nprint()"
|
||||
val cursorPosition = Pair(1, 2)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFimEdge() {
|
||||
fun `test FIM edge`() {
|
||||
val oldEditRange = ""
|
||||
val newEditRange = ""
|
||||
val cursorPosition = Pair(0, 0)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FileType
|
||||
import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
|
||||
import com.intellij.testFramework.UsefulTestCase
|
||||
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
|
||||
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
|
||||
|
||||
class FileUtilsTest : UsefulTestCase() {
|
||||
val fileUtils = FileUtils()
|
||||
val myFixture = setupRealFilesFixture()
|
||||
val tmpFixture get() = myFixture.tempDirFixture
|
||||
val tmpDir get() = myFixture.tempDirPath
|
||||
|
||||
override fun setUp() =
|
||||
myFixture.setUp()
|
||||
|
||||
override fun tearDown() =
|
||||
myFixture.tearDown()
|
||||
|
||||
fun `test fileExists`() {
|
||||
val file = tmpFixture.createFile("test.txt", "")
|
||||
val uri = "file://${file.path}"
|
||||
assertTrue(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test fileExists inside directory`() {
|
||||
val file = tmpFixture.createFile("dir/dir2/file.txt", "")
|
||||
val uri = "file://${file.path}"
|
||||
assertTrue(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test fileExists fails when file doesn't exists`() {
|
||||
val uri = "file:///tmp/aaaa.txt"
|
||||
assertFalse(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test readFile`() {
|
||||
val uri = "file://$tmpDir/bbbb.txt"
|
||||
tmpFixture.createFile("bbbb.txt", "contents")
|
||||
val text = fileUtils.readFile(uri)
|
||||
assertEquals("contents", text)
|
||||
}
|
||||
|
||||
fun `test listDir`() {
|
||||
tmpFixture.createFile("a.txt", "a")
|
||||
tmpFixture.createFile("b.txt", "b")
|
||||
tmpFixture.createFile("c.txt", "c")
|
||||
tmpFixture.createFile("dir/invisibleA.txt", "d")
|
||||
tmpFixture.createFile("dir/invisibleB.txt", "e")
|
||||
|
||||
val result = fileUtils.listDir("file://$tmpDir")
|
||||
|
||||
assertTrue(result.any { it[0] == "a.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "b.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "c.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
|
||||
assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
|
||||
assertFalse(result.any { it[0] == "invisibleA.txt" })
|
||||
assertFalse(result.any { it[0] == "invisibleB.txt" })
|
||||
assertEquals(4, result.size)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
// note: with this, files will actually exist inside /tmp/unitTest/ dir, otherwise it's virtual
|
||||
fun setupRealFilesFixture(): CodeInsightTestFixture {
|
||||
val factory = IdeaTestFixtureFactory.getFixtureFactory()
|
||||
return factory.createCodeInsightFixture(
|
||||
factory.createLightFixtureBuilder("my_continue_project").fixture,
|
||||
factory.createTempDirTestFixture()
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,64 +1,48 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import org.junit.jupiter.api.Disabled
|
||||
import org.junit.jupiter.api.Test
|
||||
import junit.framework.TestCase
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UriUtilsTest {
|
||||
@Test
|
||||
fun testUriToFile() {
|
||||
class UriUtilsTest : TestCase() {
|
||||
fun `test URI to File`() {
|
||||
val uri = "file:///path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Disabled("Not working")
|
||||
@Test
|
||||
fun testUriToFileWithWindowsPath() {
|
||||
val uri = "file:///C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("C:/path/to/file"), file)
|
||||
}
|
||||
// fixme it's not working
|
||||
// fun `test Windows path`() {
|
||||
// val uri = "file:///C:/path/to/file"
|
||||
// val file = UriUtils.uriToFile(uri)
|
||||
// assertEquals(File("C:/path/to/file"), file)
|
||||
// }
|
||||
|
||||
@Test
|
||||
fun shouldHandleAuthorityComponent() {
|
||||
val uri = "file://C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/C:/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpaces() {
|
||||
fun `test spaces`() {
|
||||
val uri = "file:///path/to/file%20with%20spaces"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file with spaces"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpecialCharacters() {
|
||||
fun `test special characters`() {
|
||||
val uri = "file:///path/to/file%23with%25special%26chars"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file#with%special&chars"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithQueryParams() {
|
||||
fun `test query params`() {
|
||||
val uri = "file:///path/to/file?param=value"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLPath() {
|
||||
fun `test WSL path`() {
|
||||
val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLLocalhostPath() {
|
||||
fun `test WSL localhost path`() {
|
||||
val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import {
|
|||
WebDriver,
|
||||
WebElement,
|
||||
WebView,
|
||||
until,
|
||||
until
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { GlobalActions } from "../actions/Global.actions";
|
||||
|
|
@ -299,8 +299,6 @@ describe("GUI Test", () => {
|
|||
expect(await statusMessage.getText()).contain(
|
||||
"Continue viewed the git diff",
|
||||
);
|
||||
// wait for 30 seconds, promise
|
||||
await new Promise((resolve) => setTimeout(resolve, 30000));
|
||||
}).timeout(DEFAULT_TIMEOUT.MD * 100);
|
||||
|
||||
it("should call tool after approval", async () => {
|
||||
|
|
@ -367,8 +365,9 @@ describe("GUI Test", () => {
|
|||
}).timeout(DEFAULT_TIMEOUT.MD);
|
||||
});
|
||||
|
||||
describe("Repeat back the system message", () => {
|
||||
describe("should repeat back the system message", () => {
|
||||
it("should repeat back the system message", async () => {
|
||||
await GUIActions.selectModeFromDropdown(view, "Chat");
|
||||
await GUIActions.selectModelFromDropdown(view, "SYSTEM MESSAGE MOCK LLM");
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
|
|
@ -376,8 +375,8 @@ describe("GUI Test", () => {
|
|||
await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getThreadMessageByText(view, "TEST_SYS_MSG"),
|
||||
);
|
||||
});
|
||||
});
|
||||
}).timeout(DEFAULT_TIMEOUT.XL * 1000);
|
||||
})
|
||||
|
||||
describe("Chat Paths", () => {
|
||||
it("Send many messages → chat auto scrolls → go to history → open previous chat → it is scrolled to the bottom", async () => {
|
||||
|
|
|
|||
7
extensions/vscode/package-lock.json
generated
7
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.63",
|
||||
"version": "1.1.68",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.63",
|
||||
"version": "1.1.68",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -129,6 +129,7 @@
|
|||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"ignore": "^5.3.1",
|
||||
"is-localhost-ip": "^2.0.0",
|
||||
"jinja-js": "0.1.8",
|
||||
|
|
@ -142,7 +143,7 @@
|
|||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.76.0",
|
||||
"openai": "^4.104.0",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.68",
|
||||
"version": "1.1.70",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -1,83 +1,40 @@
|
|||
const { fork } = require("child_process");
|
||||
const fs = require("fs");
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
|
||||
const { ProxyAgent } = require("undici");
|
||||
const { rimrafSync } = require("rimraf");
|
||||
|
||||
const { execCmdSync } = require("../../../scripts/util");
|
||||
|
||||
/**
|
||||
* download a file using nodejs http
|
||||
* download a file using fetch API
|
||||
* @param {string} url
|
||||
* @param {string} outputPath
|
||||
* @param {number} maxRedirects
|
||||
*/
|
||||
async function downloadFile(url, outputPath, maxRedirects = 5) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const downloadWithRedirects = (currentUrl, redirectCount = 0) => {
|
||||
if (redirectCount > maxRedirects) {
|
||||
return reject(new Error(`Too many redirects (${maxRedirects})`));
|
||||
}
|
||||
async function downloadFile(url, outputPath) {
|
||||
// Use proxy if set in environment variables
|
||||
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
|
||||
const agent = proxy ? new ProxyAgent(proxy) : undefined;
|
||||
|
||||
const request = https.get(currentUrl, (response) => {
|
||||
if (
|
||||
response.statusCode >= 300 &&
|
||||
response.statusCode < 400 &&
|
||||
response.headers.location
|
||||
) {
|
||||
return downloadWithRedirects(
|
||||
response.headers.location,
|
||||
redirectCount + 1,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
return reject(
|
||||
new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`),
|
||||
);
|
||||
}
|
||||
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
const writeStream = fs.createWriteStream(outputPath);
|
||||
|
||||
const totalSize = parseInt(response.headers["content-length"], 10);
|
||||
let downloadedSize = 0;
|
||||
|
||||
response.on("data", (chunk) => {
|
||||
downloadedSize += chunk.length;
|
||||
if (totalSize) {
|
||||
const percent = ((downloadedSize / totalSize) * 100).toFixed(1);
|
||||
process.stdout.write(
|
||||
`\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
response.pipe(writeStream);
|
||||
|
||||
writeStream.on("finish", () => {
|
||||
console.log(`\nDownload completed: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
});
|
||||
|
||||
writeStream.on("error", reject);
|
||||
response.on("error", reject);
|
||||
});
|
||||
|
||||
request.on("error", reject);
|
||||
request.setTimeout(30000, () => {
|
||||
request.destroy();
|
||||
reject(new Error("Request timeout"));
|
||||
});
|
||||
};
|
||||
|
||||
downloadWithRedirects(url);
|
||||
const response = await fetch(url, {
|
||||
redirect: "follow", // Automatically follow redirects
|
||||
dispatcher: agent,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download file, status code: ${response.status}`);
|
||||
}
|
||||
|
||||
// Create output directory if it doesn't exist
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Get the response as an array buffer and write it to the file
|
||||
const buffer = await response.arrayBuffer();
|
||||
fs.writeFileSync(outputPath, Buffer.from(buffer));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
|
|||
import { VsCodeWebviewProtocol } from "./webviewProtocol";
|
||||
|
||||
import type {
|
||||
ContinueRcJson,
|
||||
FileStatsMap,
|
||||
FileType,
|
||||
IDE,
|
||||
|
|
@ -266,32 +265,6 @@ class VsCodeIde implements IDE {
|
|||
return await this.ideUtils.getAvailableThreads();
|
||||
}
|
||||
|
||||
async getWorkspaceConfigs() {
|
||||
const workspaceDirs =
|
||||
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
|
||||
const configs: ContinueRcJson[] = [];
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const files = await this.ideUtils.readDirectory(workspaceDir);
|
||||
if (files === null) {
|
||||
//Unlikely, but just in case...
|
||||
continue;
|
||||
}
|
||||
for (const [filename, type] of files) {
|
||||
if (
|
||||
(type === vscode.FileType.File ||
|
||||
type === vscode.FileType.SymbolicLink) &&
|
||||
filename === ".continuerc.json"
|
||||
) {
|
||||
const contents = await this.readFile(
|
||||
vscode.Uri.joinPath(workspaceDir, filename).toString(),
|
||||
);
|
||||
configs.push(JSON.parse(contents));
|
||||
}
|
||||
}
|
||||
}
|
||||
return configs;
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,10 +6,6 @@ import * as vscode from "vscode";
|
|||
import { DiffChar, DiffLine } from "core";
|
||||
import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
|
||||
import { myersCharDiff } from "core/diff/myers";
|
||||
import {
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
} from "core/nextEdit/constants";
|
||||
import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
|
||||
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
|
||||
import { getThemeString } from "../util/getTheme";
|
||||
|
|
@ -117,6 +113,9 @@ export class NextEditWindowManager {
|
|||
// Track for logging purposes.
|
||||
private loggingService: NextEditLoggingService;
|
||||
private mostRecentCompletionId: string | null = null;
|
||||
// Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows.
|
||||
private editableRegionStartLine: number = 0;
|
||||
private editableRegionEndLine: number = 0;
|
||||
|
||||
// Disposables
|
||||
private disposables: vscode.Disposable[] = [];
|
||||
|
|
@ -261,6 +260,7 @@ export class NextEditWindowManager {
|
|||
editor: vscode.TextEditor,
|
||||
currCursorPos: vscode.Position,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
oldEditRangeSlice: string,
|
||||
newEditRangeSlice: string,
|
||||
diffLines: DiffLine[],
|
||||
|
|
@ -272,11 +272,15 @@ export class NextEditWindowManager {
|
|||
// Clear any existing decorations first (very important to prevent overlapping).
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
this.editableRegionStartLine = editableRegionStartLine;
|
||||
this.editableRegionEndLine = editableRegionEndLine;
|
||||
|
||||
// Store the current tooltip text for accepting later.
|
||||
this.currentTooltipText = newEditRangeSlice;
|
||||
|
||||
// How far away is the current line from the start of the editable region?
|
||||
const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
|
||||
const lineOffsetAtCursorPos =
|
||||
currCursorPos.line - this.editableRegionStartLine;
|
||||
|
||||
// How long is the line at the current cursor position?
|
||||
const lineContentAtCursorPos =
|
||||
|
|
@ -291,7 +295,7 @@ export class NextEditWindowManager {
|
|||
// Calculate the actual line number in the editor by adding the startPos offset
|
||||
// to the line number from the diff calculation.
|
||||
this.finalCursorPos = new vscode.Position(
|
||||
editableRegionStartLine + offset.line,
|
||||
this.editableRegionStartLine + offset.line,
|
||||
offset.character,
|
||||
);
|
||||
|
||||
|
|
@ -301,13 +305,13 @@ export class NextEditWindowManager {
|
|||
currCursorPos,
|
||||
oldEditRangeSlice,
|
||||
newEditRangeSlice,
|
||||
editableRegionStartLine,
|
||||
this.editableRegionStartLine,
|
||||
diffLines,
|
||||
);
|
||||
|
||||
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
|
||||
|
||||
this.renderDeletes(editor, editableRegionStartLine, diffChars);
|
||||
this.renderDeletions(editor, diffChars);
|
||||
|
||||
// Reserve tab and esc to either accept or reject the displayed next edit contents.
|
||||
await NextEditWindowManager.reserveTabAndEsc();
|
||||
|
|
@ -317,6 +321,8 @@ export class NextEditWindowManager {
|
|||
* Hide all tooltips in all editors.
|
||||
*/
|
||||
public async hideAllNextEditWindows() {
|
||||
await NextEditWindowManager.freeTabAndEsc();
|
||||
|
||||
if (this.currentDecoration) {
|
||||
vscode.window.visibleTextEditors.forEach((editor) => {
|
||||
editor.setDecorations(this.currentDecoration!, []);
|
||||
|
|
@ -339,12 +345,10 @@ export class NextEditWindowManager {
|
|||
// Clear the current tooltip text.
|
||||
this.currentTooltipText = null;
|
||||
}
|
||||
|
||||
await NextEditWindowManager.freeTabAndEsc();
|
||||
}
|
||||
|
||||
public async hideAllNextEditWindowsAndResetCompletionId() {
|
||||
this.hideAllNextEditWindows();
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
// Log with accept = false.
|
||||
await vscode.commands.executeCommand(
|
||||
|
|
@ -352,6 +356,7 @@ export class NextEditWindowManager {
|
|||
this.mostRecentCompletionId,
|
||||
this.loggingService,
|
||||
);
|
||||
|
||||
this.mostRecentCompletionId = null;
|
||||
}
|
||||
|
||||
|
|
@ -369,6 +374,10 @@ export class NextEditWindowManager {
|
|||
const position = editor.selection.active;
|
||||
|
||||
let success = false;
|
||||
|
||||
// Hide windows first for a snappier feel.
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
if (this.textApplier) {
|
||||
success = await this.textApplier.applyText(
|
||||
editor,
|
||||
|
|
@ -377,20 +386,15 @@ export class NextEditWindowManager {
|
|||
this.finalCursorPos,
|
||||
);
|
||||
} else {
|
||||
// Define the editable region.
|
||||
const editableRegionStartLine = Math.max(
|
||||
0,
|
||||
position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
);
|
||||
const editableRegionEndLine = Math.min(
|
||||
editor.document.lineCount - 1,
|
||||
position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
);
|
||||
const startPos = new vscode.Position(editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(editableRegionEndLine).text
|
||||
// Define the range to replace.
|
||||
const startPos = new vscode.Position(this.editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text
|
||||
.length;
|
||||
|
||||
const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
|
||||
const endPos = new vscode.Position(
|
||||
this.editableRegionEndLine,
|
||||
endPosChar,
|
||||
);
|
||||
const editRange = new vscode.Range(startPos, endPos);
|
||||
|
||||
success = await editor.edit((editBuilder) => {
|
||||
|
|
@ -405,23 +409,19 @@ export class NextEditWindowManager {
|
|||
.update("editor.inlineSuggest.enabled", false, true);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
if (success && this.finalCursorPos) {
|
||||
// Move cursor to the final position if available.
|
||||
if (this.finalCursorPos) {
|
||||
editor.selection = new vscode.Selection(
|
||||
this.finalCursorPos,
|
||||
this.finalCursorPos,
|
||||
);
|
||||
|
||||
// Reenable inline suggestions after we move the cursor.
|
||||
await vscode.workspace
|
||||
.getConfiguration()
|
||||
.update("editor.inlineSuggest.enabled", true, true);
|
||||
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
editor.selection = new vscode.Selection(
|
||||
this.finalCursorPos,
|
||||
this.finalCursorPos,
|
||||
);
|
||||
}
|
||||
|
||||
// Reenable inline suggestions.
|
||||
await vscode.workspace
|
||||
.getConfiguration()
|
||||
.update("editor.inlineSuggest.enabled", true, true);
|
||||
|
||||
// Log with accept = true.
|
||||
await vscode.commands.executeCommand(
|
||||
"continue.logNextEditOutcomeAccept",
|
||||
|
|
@ -454,7 +454,7 @@ export class NextEditWindowManager {
|
|||
*/
|
||||
private setupListeners() {
|
||||
// Theme change listener.
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
vscode.workspace.onDidChangeConfiguration(async (e) => {
|
||||
if (
|
||||
e.affectsConfiguration("workbench.colorTheme") ||
|
||||
e.affectsConfiguration("editor.fontSize") ||
|
||||
|
|
@ -467,7 +467,7 @@ export class NextEditWindowManager {
|
|||
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
|
||||
) {
|
||||
this.theme = getThemeString();
|
||||
this.codeRenderer.setTheme(this.theme);
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
"Theme updated:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
|
|
@ -479,9 +479,9 @@ export class NextEditWindowManager {
|
|||
});
|
||||
|
||||
// Listen for active color theme changes.
|
||||
vscode.window.onDidChangeActiveColorTheme(() => {
|
||||
vscode.window.onDidChangeActiveColorTheme(async () => {
|
||||
this.theme = getThemeString();
|
||||
this.codeRenderer.setTheme(this.theme);
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
"Active theme changed:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
|
|
@ -495,10 +495,11 @@ export class NextEditWindowManager {
|
|||
this.activeEditor &&
|
||||
!vscode.window.visibleTextEditors.includes(this.activeEditor)
|
||||
) {
|
||||
if (this.mostRecentCompletionId)
|
||||
if (this.mostRecentCompletionId) {
|
||||
this.loggingService.cancelRejectionTimeout(
|
||||
this.mostRecentCompletionId,
|
||||
);
|
||||
}
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
});
|
||||
|
|
@ -508,10 +509,11 @@ export class NextEditWindowManager {
|
|||
// If the selection changed in our active editor, hide the tooltip.
|
||||
if (this.activeEditor && e.textEditor === this.activeEditor) {
|
||||
// If the cursor moved because of something other than accepting next edit, stop logging it.
|
||||
if (!this.accepted && this.mostRecentCompletionId)
|
||||
if (!this.accepted && this.mostRecentCompletionId) {
|
||||
this.loggingService.cancelRejectionTimeout(
|
||||
this.mostRecentCompletionId,
|
||||
);
|
||||
}
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
});
|
||||
|
|
@ -747,7 +749,6 @@ export class NextEditWindowManager {
|
|||
}
|
||||
|
||||
// Store the decoration and editor.
|
||||
await this.hideAllNextEditWindows();
|
||||
this.currentDecoration = decoration; // TODO: This might be redundant.
|
||||
this.disposables.push(decoration);
|
||||
this.activeEditor = editor;
|
||||
|
|
@ -786,13 +787,7 @@ export class NextEditWindowManager {
|
|||
);
|
||||
}
|
||||
|
||||
private renderDeletes(
|
||||
editor: vscode.TextEditor,
|
||||
editableRegionStartLine: number,
|
||||
// oldEditRangeSlice: string,
|
||||
// newEditRangeSlice: string,
|
||||
oldDiffChars: DiffChar[],
|
||||
) {
|
||||
private renderDeletions(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) {
|
||||
const charsToDelete: vscode.DecorationOptions[] = [];
|
||||
|
||||
// const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
|
||||
|
|
@ -803,11 +798,11 @@ export class NextEditWindowManager {
|
|||
charsToDelete.push({
|
||||
range: new vscode.Range(
|
||||
new vscode.Position(
|
||||
editableRegionStartLine + diff.oldLineIndex!,
|
||||
this.editableRegionStartLine + diff.oldLineIndex!,
|
||||
diff.oldCharIndexInLine!,
|
||||
),
|
||||
new vscode.Position(
|
||||
editableRegionStartLine + diff.oldLineIndex!,
|
||||
this.editableRegionStartLine + diff.oldLineIndex!,
|
||||
diff.oldCharIndexInLine! + diff.char.length,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -420,6 +420,7 @@ export class ContinueCompletionProvider
|
|||
editor,
|
||||
currCursorPos,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
oldEditRangeSlice,
|
||||
newEditRangeSlice,
|
||||
diffLines,
|
||||
|
|
|
|||
|
|
@ -418,10 +418,6 @@ export class VsCodeMessenger {
|
|||
return await ide.isTelemetryEnabled();
|
||||
});
|
||||
|
||||
this.onWebviewOrCore("getWorkspaceConfigs", async (msg) => {
|
||||
return await ide.getWorkspaceConfigs();
|
||||
});
|
||||
|
||||
this.onWebviewOrCore("getUniqueId", async (msg) => {
|
||||
return await ide.getUniqueId();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,20 +15,34 @@ export class DownloadYamlExtensionCodeLensProvider
|
|||
if (!document.uri.fsPath.includes(".continue")) {
|
||||
return [];
|
||||
}
|
||||
if (this.yamlExtensionDownloaded()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const codeLens: vscode.CodeLens = {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
|
||||
// Always show documentation link
|
||||
const docCodeLens: vscode.CodeLens = {
|
||||
range: new vscode.Range(0, 0, 0, 0),
|
||||
command: {
|
||||
title: "Download YAML extension for Intellisense",
|
||||
command: "workbench.extensions.installExtension",
|
||||
arguments: ["redhat.vscode-yaml"],
|
||||
title: "📖 View Continue Reference",
|
||||
command: "vscode.open",
|
||||
arguments: [vscode.Uri.parse("https://docs.continue.dev/reference")],
|
||||
},
|
||||
isResolved: true,
|
||||
};
|
||||
codeLenses.push(docCodeLens);
|
||||
|
||||
return [codeLens];
|
||||
if (!this.yamlExtensionDownloaded()) {
|
||||
const codeLens: vscode.CodeLens = {
|
||||
range: new vscode.Range(0, 0, 0, 0),
|
||||
command: {
|
||||
title: "Download YAML extension for Intellisense",
|
||||
command: "workbench.extensions.installExtension",
|
||||
arguments: ["redhat.vscode-yaml"],
|
||||
},
|
||||
isResolved: true,
|
||||
};
|
||||
codeLenses.push(codeLens);
|
||||
}
|
||||
|
||||
return codeLenses;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
3
gui/package-lock.json
generated
3
gui/package-lock.json
generated
|
|
@ -140,6 +140,7 @@
|
|||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"ignore": "^5.3.1",
|
||||
"is-localhost-ip": "^2.0.0",
|
||||
"jinja-js": "0.1.8",
|
||||
|
|
@ -153,7 +154,7 @@
|
|||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.76.0",
|
||||
"openai": "^4.104.0",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
|
|
|
|||
|
|
@ -1,51 +0,0 @@
|
|||
import {
|
||||
ArrowRightEndOnRectangleIcon,
|
||||
UserCircleIcon as UserCircleIconOutline,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { ListboxOption, useFontSize } from "../ui";
|
||||
|
||||
interface AccountOptionProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function AccountOption({ onClose }: AccountOptionProps) {
|
||||
const { session, logout, login } = useAuth();
|
||||
const tinyFont = useFontSize(-4);
|
||||
|
||||
// No account option for on-prem deployments
|
||||
if (session && isOnPremSession(session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleClick() {
|
||||
if (session) {
|
||||
logout();
|
||||
} else {
|
||||
await login(false);
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
|
||||
return (
|
||||
<ListboxOption
|
||||
value={session ? "log-out" : "sign-in"}
|
||||
fontSizeModifier={-2}
|
||||
className="border-border border-b px-2 py-1.5"
|
||||
onClick={handleClick}
|
||||
>
|
||||
<div
|
||||
className="text-description flex flex-row items-center"
|
||||
style={{ fontSize: tinyFont }}
|
||||
>
|
||||
{session ? (
|
||||
<ArrowRightEndOnRectangleIcon className="mr-1 h-3 w-3" />
|
||||
) : (
|
||||
<UserCircleIconOutline className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{session ? "Log out" : "Sign in"}
|
||||
</div>
|
||||
</ListboxOption>
|
||||
);
|
||||
}
|
||||
|
|
@ -20,14 +20,20 @@ export function AssistantOptions({
|
|||
</div>
|
||||
|
||||
<div className="thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto">
|
||||
{profiles?.map((profile, idx) => (
|
||||
<AssistantOption
|
||||
key={idx}
|
||||
profile={profile}
|
||||
onClick={onClose}
|
||||
selected={profile.id === selectedProfileId}
|
||||
/>
|
||||
))}
|
||||
{profiles?.length === 0 ? (
|
||||
<div className="text-vsc-foreground px-3 py-2 opacity-70">
|
||||
No assistants found
|
||||
</div>
|
||||
) : (
|
||||
profiles?.map((profile, idx) => (
|
||||
<AssistantOption
|
||||
key={idx}
|
||||
profile={profile}
|
||||
onClick={onClose}
|
||||
selected={profile.id === selectedProfileId}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { ListboxButton } from "../ui";
|
|||
import { AssistantIcon } from "./AssistantIcon";
|
||||
|
||||
interface SelectedAssistantButtonProps {
|
||||
selectedProfile: ProfileDescription;
|
||||
selectedProfile: ProfileDescription | null;
|
||||
}
|
||||
|
||||
export function SelectedAssistantButton({
|
||||
|
|
@ -25,7 +25,9 @@ export function SelectedAssistantButton({
|
|||
style={{ fontSize: fontSize(-3) }}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
{configLoading ? (
|
||||
{selectedProfile === null ? (
|
||||
"Create your first assistant"
|
||||
) : configLoading ? (
|
||||
<span className="text-description flex flex-row items-center">
|
||||
<ArrowPathIcon
|
||||
className={cn(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ArrowPathIcon, PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { AuthType, isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useContext, useEffect, useRef } from "react";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
|
|
@ -18,7 +18,6 @@ import {
|
|||
Transition,
|
||||
useFontSize,
|
||||
} from "../ui";
|
||||
import { AccountOption } from "./AccountOption";
|
||||
import { AssistantOptions } from "./AssistantOptions";
|
||||
import { ScopeSelect } from "./ScopeSelect";
|
||||
import { SelectedAssistantButton } from "./SelectedAssistantButton";
|
||||
|
|
@ -34,6 +33,7 @@ export function AssistantAndOrgListbox() {
|
|||
selectedProfile,
|
||||
session,
|
||||
login,
|
||||
logout,
|
||||
organizations,
|
||||
refreshProfiles,
|
||||
} = useAuth();
|
||||
|
|
@ -57,6 +57,11 @@ export function AssistantAndOrgListbox() {
|
|||
close();
|
||||
}
|
||||
|
||||
function onLogout() {
|
||||
logout();
|
||||
close();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let lastToggleTime = 0;
|
||||
const DEBOUNCE_MS = 800;
|
||||
|
|
@ -98,49 +103,32 @@ export function AssistantAndOrgListbox() {
|
|||
};
|
||||
}, [currentOrg, selectedProfile]);
|
||||
|
||||
if (!selectedProfile) {
|
||||
return (
|
||||
<div
|
||||
onClick={() => {
|
||||
void ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "/new?type=assistant",
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
}}
|
||||
className="text-description flex cursor-pointer select-none items-center gap-1"
|
||||
style={{ fontSize: smallFont }}
|
||||
>
|
||||
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
|
||||
<span
|
||||
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
Create your first assistant
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Listbox>
|
||||
<div className="relative" ref={listboxRef}>
|
||||
<SelectedAssistantButton selectedProfile={selectedProfile} />
|
||||
<Transition>
|
||||
<ListboxOptions className="-translate-x-1.5 pb-0">
|
||||
{shouldRenderOrgInfo && (
|
||||
<div className="border-border border-x-0 border-t-0 border-solid px-2 py-3">
|
||||
<div className="flex flex-col gap-2 pb-1 pl-1">
|
||||
<div className="border-border border-x-0 border-t-0 border-solid px-2 py-3">
|
||||
<div className="flex flex-col gap-2 pb-1 pl-1">
|
||||
{session && session?.AUTH_TYPE !== AuthType.OnPrem && (
|
||||
<span className="text-description-muted flex items-center pb-1">
|
||||
{session.account.id}
|
||||
{session?.account.id}
|
||||
</span>
|
||||
<label className="text-vsc-foreground font-semibold">
|
||||
Organization
|
||||
</label>
|
||||
<ScopeSelect />
|
||||
</div>
|
||||
)}
|
||||
{shouldRenderOrgInfo && (
|
||||
<>
|
||||
<label className="text-vsc-foreground font-semibold">
|
||||
Organization
|
||||
</label>
|
||||
<ScopeSelect />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AssistantOptions
|
||||
selectedProfileId={selectedProfile.id}
|
||||
selectedProfileId={selectedProfile?.id}
|
||||
onClose={close}
|
||||
/>
|
||||
|
||||
|
|
@ -176,11 +164,25 @@ export function AssistantAndOrgListbox() {
|
|||
configLoading && "animate-spin-slow",
|
||||
)}
|
||||
/>
|
||||
Reload config
|
||||
Reload assistants
|
||||
</span>
|
||||
</ListboxOption>
|
||||
|
||||
<AccountOption onClose={close} />
|
||||
{session && (
|
||||
<ListboxOption
|
||||
value="log-out"
|
||||
fontSizeModifier={-2}
|
||||
className="border-border border-b px-3 py-1.5"
|
||||
onClick={onLogout}
|
||||
>
|
||||
<div
|
||||
className="text-description flex flex-row items-center"
|
||||
style={{ fontSize: tinyFont }}
|
||||
>
|
||||
Log out
|
||||
</div>
|
||||
</ListboxOption>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="text-description border-border flex items-center justify-between gap-1.5 border-x-0 border-b-0 border-t border-solid px-2 py-2"
|
||||
|
|
|
|||
|
|
@ -1,12 +1,18 @@
|
|||
import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ExclamationTriangleIcon,
|
||||
InformationCircleIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { MessageModes } from "core";
|
||||
import { modelSupportsTools } from "core/llm/autodetect";
|
||||
import {
|
||||
isRecommendedAgentModel,
|
||||
modelSupportsNativeTools,
|
||||
} from "core/llm/toolSupport";
|
||||
import { capitalize } from "lodash";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { selectUseSystemMessageTools } from "../../redux/selectors/selectUseSystemMessageTools";
|
||||
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
|
||||
import { setMode } from "../../redux/slices/sessionSlice";
|
||||
import { getFontSize, getMetaKeyLabel } from "../../util";
|
||||
|
|
@ -19,9 +25,22 @@ export function ModeSelect() {
|
|||
const dispatch = useAppDispatch();
|
||||
const mode = useAppSelector((store) => store.session.mode);
|
||||
const selectedModel = useAppSelector(selectSelectedChatModel);
|
||||
const agentModeSupported = useMemo(() => {
|
||||
return selectedModel && modelSupportsTools(selectedModel);
|
||||
const useSystemTools = useAppSelector(selectUseSystemMessageTools);
|
||||
|
||||
const isAgentSupported = useMemo(() => {
|
||||
if (!selectedModel) {
|
||||
return undefined;
|
||||
}
|
||||
return !!useSystemTools || modelSupportsNativeTools(selectedModel);
|
||||
}, [selectedModel, useSystemTools]);
|
||||
|
||||
const isGoodAtAgentMode = useMemo(() => {
|
||||
if (!selectedModel) {
|
||||
return undefined;
|
||||
}
|
||||
return isRecommendedAgentModel(selectedModel.model);
|
||||
}, [selectedModel]);
|
||||
|
||||
const { mainEditor } = useMainEditor();
|
||||
const metaKeyLabel = useMemo(() => {
|
||||
return getMetaKeyLabel();
|
||||
|
|
@ -32,10 +51,10 @@ export function ModeSelect() {
|
|||
if (!selectedModel) {
|
||||
return;
|
||||
}
|
||||
if (mode !== "chat" && !agentModeSupported) {
|
||||
if (mode !== "chat" && !isAgentSupported) {
|
||||
dispatch(setMode("chat"));
|
||||
}
|
||||
}, [mode, agentModeSupported, dispatch, selectedModel]);
|
||||
}, [mode, isAgentSupported, selectedModel]);
|
||||
|
||||
const cycleMode = useCallback(() => {
|
||||
if (mode === "chat") {
|
||||
|
|
@ -76,6 +95,25 @@ export function ModeSelect() {
|
|||
return () => document.removeEventListener("keydown", handleKeyDown);
|
||||
}, [cycleMode]);
|
||||
|
||||
const notSupported = <span>(Not supported)</span>;
|
||||
const notGreatAtAgent = (
|
||||
<>
|
||||
<ExclamationTriangleIcon
|
||||
data-tooltip-id="bad-at-agent-mode-tooltip"
|
||||
className="text-warning h-2.5 w-2.5"
|
||||
/>
|
||||
<ToolTip
|
||||
id="bad-at-agent-mode-tooltip"
|
||||
style={{
|
||||
zIndex: 200001, // in front of listbox
|
||||
}}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
{`${capitalize(mode)} might not work well with this model.`}
|
||||
</ToolTip>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<Listbox value={mode} onChange={selectMode}>
|
||||
<div className="relative">
|
||||
|
|
@ -117,11 +155,7 @@ export function ModeSelect() {
|
|||
</div>
|
||||
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
|
||||
</ListboxOption>
|
||||
<ListboxOption
|
||||
value="plan"
|
||||
disabled={!agentModeSupported}
|
||||
className={"gap-1"}
|
||||
>
|
||||
<ListboxOption value="plan" className={"gap-1"}>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<ModeIcon mode="plan" />
|
||||
<span className="">Plan</span>
|
||||
|
|
@ -138,19 +172,19 @@ export function ModeSelect() {
|
|||
Read-only/MCP tools available
|
||||
</ToolTip>
|
||||
</div>
|
||||
{agentModeSupported ? (
|
||||
<CheckIcon
|
||||
className={`ml-auto h-3 w-3 ${mode === "plan" ? "" : "opacity-0"}`}
|
||||
/>
|
||||
{isAgentSupported ? (
|
||||
<>
|
||||
{!isGoodAtAgentMode && notGreatAtAgent}
|
||||
<CheckIcon
|
||||
className={`ml-auto h-3 w-3 ${mode === "plan" ? "" : "opacity-0"}`}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<span>(Not supported)</span>
|
||||
notSupported
|
||||
)}
|
||||
</ListboxOption>
|
||||
<ListboxOption
|
||||
value="agent"
|
||||
disabled={!agentModeSupported}
|
||||
className={"gap-1"}
|
||||
>
|
||||
|
||||
<ListboxOption value="agent" className={"gap-1"}>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<ModeIcon mode="agent" />
|
||||
<span className="">Agent</span>
|
||||
|
|
@ -167,12 +201,15 @@ export function ModeSelect() {
|
|||
All tools available
|
||||
</ToolTip>
|
||||
</div>
|
||||
{agentModeSupported ? (
|
||||
<CheckIcon
|
||||
className={`ml-auto h-3 w-3 ${mode === "agent" ? "" : "opacity-0"}`}
|
||||
/>
|
||||
{isAgentSupported ? (
|
||||
<>
|
||||
{!isGoodAtAgentMode && notGreatAtAgent}
|
||||
<CheckIcon
|
||||
className={`ml-auto h-3 w-3 ${mode === "agent" ? "" : "opacity-0"}`}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<span>(Not supported)</span>
|
||||
notSupported
|
||||
)}
|
||||
</ListboxOption>
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,9 @@ export function OnboardingCardLanding({
|
|||
// A new assistant is created when the account is created
|
||||
// We want to switch to this immediately
|
||||
void dispatch(selectFirstHubProfile());
|
||||
|
||||
ideMessenger.post("showTutorial", undefined);
|
||||
ideMessenger.post("showToast", ["info", "🎉 Welcome to Continue!"]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
TrashIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ChatHistoryItem } from "core";
|
||||
import { modelSupportsTools } from "core/llm/autodetect";
|
||||
import { modelSupportsNativeTools } from "core/llm/toolSupport";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import { useMemo } from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
|
|
@ -41,7 +41,7 @@ export default function ResponseActions({
|
|||
);
|
||||
const isPruned = useAppSelector((state) => state.session.isPruned);
|
||||
const ruleGenerationSupported = useMemo(() => {
|
||||
return selectedModel && modelSupportsTools(selectedModel);
|
||||
return selectedModel && modelSupportsNativeTools(selectedModel);
|
||||
}, [selectedModel]);
|
||||
|
||||
const percent = Math.round((contextPercentage ?? 0) * 100);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
} from "@heroicons/react/24/outline";
|
||||
import { LightBulbIcon as LightBulbIconSolid } from "@heroicons/react/24/solid";
|
||||
import { InputModifiers } from "core";
|
||||
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
|
||||
import { modelSupportsImages } from "core/llm/autodetect";
|
||||
import { useContext, useRef } from "react";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
|
|
@ -57,8 +57,6 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
const isEnterDisabled =
|
||||
props.disabled || (isInEdit && codeToEdit.length === 0);
|
||||
|
||||
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
|
||||
|
||||
const supportsImages =
|
||||
defaultModel &&
|
||||
modelSupportsImages(
|
||||
|
|
@ -75,7 +73,7 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
<>
|
||||
<div
|
||||
onClick={props.onClick}
|
||||
className={`find-widget-skip bg-vsc-input-background flex select-none flex-row items-center justify-between gap-1 pt-1 ${props.hidden ? "pointer-events-none h-0 cursor-default opacity-0" : "pointer-events-auto cursor-text opacity-100"}`}
|
||||
className={`find-widget-skip bg-vsc-input-background flex select-none flex-row items-center justify-between gap-1 pt-1 ${props.hidden ? "pointer-events-none h-0 cursor-default opacity-0" : "pointer-events-auto mt-2 cursor-text opacity-100"}`}
|
||||
style={{
|
||||
fontSize: smallFont,
|
||||
}}
|
||||
|
|
@ -178,7 +176,7 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
{!isInEdit && <ContextStatus />}
|
||||
{!props.toolbarOptions?.hideUseCodebase && !isInEdit && (
|
||||
<div
|
||||
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
|
||||
className={`hover:underline" hidden transition-colors duration-200 md:flex`}
|
||||
>
|
||||
<HoverItem
|
||||
className={props.activeKey === "Alt" ? "underline" : ""}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ type SectionKey = Exclude<
|
|||
|
||||
interface EditBlockButtonProps<T extends SectionKey> {
|
||||
blockType: T;
|
||||
block?: NonNullable<ConfigYaml[T]>[number];
|
||||
block?: NonNullable<Omit<ConfigYaml, "env">[T]>[number];
|
||||
className?: string;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { beforeEach, describe, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "../../../../../util/test/render";
|
||||
import { CodeBlockPreview } from "./CodeBlockPreview";
|
||||
|
||||
const postIde = vi.fn();
|
||||
|
||||
vi.mock("../../../../../context/MockIdeMessenger", async (importOriginal) => {
|
||||
const original = (await importOriginal()) as any;
|
||||
return {
|
||||
...original,
|
||||
MockIdeMessenger: class MockedMockIdeMessenger extends original.MockIdeMessenger {
|
||||
post(...args: any[]) {
|
||||
postIde(...args);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe("CodeBlockPreview", () => {
|
||||
const createMockContextItem = (
|
||||
overrides: Partial<ContextItemWithId> = {},
|
||||
): ContextItemWithId => ({
|
||||
content: "console.log('test');",
|
||||
name: "test.ts",
|
||||
description: "Test file",
|
||||
id: {
|
||||
providerTitle: "file",
|
||||
itemId: "test-item-id",
|
||||
},
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "/test/test.ts",
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createMockNodeViewProps = (
|
||||
item: ContextItemWithId,
|
||||
selected = false,
|
||||
): NodeViewProps => ({
|
||||
node: {
|
||||
attrs: {
|
||||
item,
|
||||
},
|
||||
} as any,
|
||||
view: {} as any,
|
||||
getPos: vi.fn(() => 0),
|
||||
innerDecorations: {} as any,
|
||||
editor: {} as any,
|
||||
extension: {} as any,
|
||||
HTMLAttributes: {},
|
||||
decorations: [] as any,
|
||||
selected,
|
||||
updateAttributes: vi.fn(),
|
||||
deleteNode: vi.fn(),
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("opens file when title is clicked", async () => {
|
||||
const item = createMockContextItem({
|
||||
id: { providerTitle: "file", itemId: "test-id" },
|
||||
uri: { type: "file", value: "/test/file.ts" },
|
||||
name: "test.ts",
|
||||
});
|
||||
const props = createMockNodeViewProps(item);
|
||||
|
||||
await renderWithProviders(<CodeBlockPreview {...props} />);
|
||||
|
||||
const title = screen.getByText("test.ts");
|
||||
title.click();
|
||||
|
||||
expect(postIde).toHaveBeenCalled();
|
||||
expect(postIde).toHaveBeenCalledWith("showFile", {
|
||||
filepath: "/test/file.ts",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -42,7 +42,7 @@ export const CodeBlockPreview = ({
|
|||
});
|
||||
} else if (item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
void ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue